path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
ajax/libs/pdf.js/2.0.112/pdf.js
cdnjs/cdnjs
/* Copyright 2017 Mozilla Foundation * * 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 webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("pdfjs-dist/build/pdf", [], factory); else if(typeof exports === 'object') exports["pdfjs-dist/build/pdf"] = factory(); else root["pdfjs-dist/build/pdf"] = root.pdfjsDistBuildPdf = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __w_pdfjs_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __w_pdfjs_require__.m = modules; /******/ /******/ // expose the module cache /******/ __w_pdfjs_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __w_pdfjs_require__.d = function(exports, name, getter) { /******/ if(!__w_pdfjs_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __w_pdfjs_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __w_pdfjs_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __w_pdfjs_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __w_pdfjs_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __w_pdfjs_require__(__w_pdfjs_require__.s = 63); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unreachable = exports.warn = exports.utf8StringToString = exports.stringToUTF8String = exports.stringToPDFString = exports.stringToBytes = exports.string32 = exports.shadow = exports.setVerbosityLevel = exports.ReadableStream = exports.removeNullCharacters = exports.readUint32 = exports.readUint16 = exports.readInt8 = exports.log2 = exports.loadJpegStream = exports.isEvalSupported = exports.isLittleEndian = exports.createValidAbsoluteUrl = exports.isSameOrigin = exports.isNodeJS = exports.isSpace = exports.isString = exports.isNum = exports.isEmptyObj = exports.isBool = exports.isArrayBuffer = exports.info = exports.getVerbosityLevel = exports.getLookupTableFactory = exports.deprecated = exports.createObjectURL = exports.createPromiseCapability = exports.createBlob = exports.bytesToString = exports.assert = exports.arraysToBytes = exports.arrayByteLength = exports.FormatError = exports.XRefParseException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.StatTimer = exports.PasswordResponses = exports.PasswordException = exports.PageViewport = exports.NotImplementedException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.MessageHandler = exports.InvalidPDFException = exports.AbortException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VERBOSITY_LEVELS = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = undefined; 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; }; __w_pdfjs_require__(64); var _streams_polyfill = __w_pdfjs_require__(111); var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var NativeImageDecoding = { NONE: 'none', DECODE: 'decode', DISPLAY: 'display' }; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationFieldFlag = { READONLY: 0x0000001, REQUIRED: 0x0000002, NOEXPORT: 0x0000004, MULTILINE: 0x0001000, PASSWORD: 0x0002000, NOTOGGLETOOFF: 0x0004000, RADIO: 0x0008000, PUSHBUTTON: 0x0010000, COMBO: 0x0020000, EDIT: 0x0040000, SORT: 0x0080000, FILESELECT: 0x0100000, MULTISELECT: 0x0200000, DONOTSPELLCHECK: 0x0400000, DONOTSCROLL: 0x0800000, COMB: 0x1000000, RICHTEXT: 0x2000000, RADIOSINUNISON: 0x2000000, COMMITONSELCHANGE: 0x4000000 }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; var VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; var CMapCompressionType = { NONE: 0, BINARY: 1, STREAM: 2 }; var OPS = { dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; var verbosity = VERBOSITY_LEVELS.warnings; function setVerbosityLevel(level) { verbosity = level; } function getVerbosityLevel() { return verbosity; } function info(msg) { if (verbosity >= VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } function warn(msg) { if (verbosity >= VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } function deprecated(details) { console.log('Deprecated API usage: ' + details); } function unreachable(msg) { throw new Error(msg); } function assert(cond, msg) { if (!cond) { unreachable(msg); } } var UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; function isSameOrigin(baseUrl, otherUrl) { try { var base = new URL(baseUrl); if (!base.origin || base.origin === 'null') { return false; } } catch (e) { return false; } var other = new URL(otherUrl, base); return base.origin === other.origin; } function isValidProtocol(url) { if (!url) { return false; } switch (url.protocol) { case 'http:': case 'https:': case 'ftp:': case 'mailto:': case 'tel:': return true; default: return false; } } function createValidAbsoluteUrl(url, baseUrl) { if (!url) { return null; } try { var absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url); if (isValidProtocol(absoluteUrl)) { return absoluteUrl; } } catch (ex) {} return null; } function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } function getLookupTableFactory(initializer) { var lookup; return function () { if (initializer) { lookup = Object.create(null); initializer(lookup); initializer = null; } return lookup; }; } var PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; }(); var UnknownErrorException = function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; }(); var InvalidPDFException = function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; }(); var MissingPDFException = function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; }(); var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; }(); var NotImplementedException = function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; }(); var MissingDataException = function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; }(); var XRefParseException = function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; }(); var FormatError = function FormatErrorClosure() { function FormatError(msg) { this.message = msg; } FormatError.prototype = new Error(); FormatError.prototype.name = 'FormatError'; FormatError.constructor = FormatError; return FormatError; }(); var AbortException = function AbortExceptionClosure() { function AbortException(msg) { this.name = 'AbortException'; this.message = msg; } AbortException.prototype = new Error(); AbortException.constructor = AbortException; return AbortException; }(); var NullCharactersRegExp = /\x00/g; function removeNullCharacters(str) { if (typeof str !== 'string') { warn('The argument for removeNullCharacters must be a string.'); return str; } return str.replace(NullCharactersRegExp, ''); } function bytesToString(bytes) { assert(bytes !== null && (typeof bytes === 'undefined' ? 'undefined' : _typeof(bytes)) === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function arrayByteLength(arr) { if (arr.length !== undefined) { return arr.length; } assert(arr.byteLength !== undefined); return arr.byteLength; } function arraysToBytes(arr) { if (arr.length === 1 && arr[0] instanceof Uint8Array) { return arr[0]; } var resultLength = 0; var i, ii = arr.length; var item, itemLength; for (i = 0; i < ii; i++) { item = arr[i]; itemLength = arrayByteLength(item); resultLength += itemLength; } var pos = 0; var data = new Uint8Array(resultLength); for (i = 0; i < ii; i++) { item = arr[i]; if (!(item instanceof Uint8Array)) { if (typeof item === 'string') { item = stringToBytes(item); } else { item = new Uint8Array(item); } } itemLength = item.byteLength; data.set(item, pos); pos += itemLength; } return data; } function string32(value) { return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return data[start] << 24 >> 24; } function readUint16(data, offset) { return data[offset] << 8 | data[offset + 1]; } function readUint32(data, offset) { return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0; } function isLittleEndian() { var buffer8 = new Uint8Array(4); buffer8[0] = 1; var view32 = new Uint32Array(buffer8.buffer, 0, 1); return view32[0] === 1; } function isEvalSupported() { try { new Function(''); return true; } catch (e) { return false; } } var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; Util.transform = function Util_transform(m1, m2) { return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]]; }; Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]]; }; Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; return [Math.sqrt(sx), Math.sqrt(sy)]; }; Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) { result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) { result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; var ROMAN_NUMBER_MAP = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; Util.toRoman = function Util_toRoman(number, lowerCase) { assert(Number.isInteger(number) && number > 0, 'The number should be a positive integer.'); var pos, romanBuf = []; while (number >= 1000) { number -= 1000; romanBuf.push('M'); } pos = number / 100 | 0; number %= 100; romanBuf.push(ROMAN_NUMBER_MAP[pos]); pos = number / 10 | 0; number %= 10; romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]); romanBuf.push(ROMAN_NUMBER_MAP[20 + number]); var romanStr = romanBuf.join(''); return lowerCase ? romanStr.toLowerCase() : romanStr; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return getArray ? dict.getArray(name) : dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function () { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; }(); var PageViewport = function PageViewportClosure() { function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = { clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; }(); var PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isArrayBuffer(v) { return (typeof v === 'undefined' ? 'undefined' : _typeof(v)) === 'object' && v !== null && v.byteLength !== undefined; } function isSpace(ch) { return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A; } function isNodeJS() { return (typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && process + '' === '[object process]'; } function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } var StatTimer = function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = Object.create(null); this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; }(); var createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } throw new Error('The "Blob" constructor is not supported.'); }; var createObjectURL = function createObjectURLClosure() { var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { var forceDataSchema = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (!forceDataSchema && URL.createObjectURL) { var blob = createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4; var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64; var d4 = i + 2 < ii ? b3 & 0x3F : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; }(); function resolveCall(fn, args) { var thisArg = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (!fn) { return Promise.resolve(undefined); } return new Promise(function (resolve, reject) { resolve(fn.apply(thisArg, args)); }); } function wrapReason(reason) { if ((typeof reason === 'undefined' ? 'undefined' : _typeof(reason)) !== 'object') { return reason; } switch (reason.name) { case 'AbortException': return new AbortException(reason.message); case 'MissingPDFException': return new MissingPDFException(reason.message); case 'UnexpectedResponseException': return new UnexpectedResponseException(reason.message, reason.status); default: return new UnknownErrorException(reason.message, reason.details); } } function makeReasonSerializable(reason) { if (!(reason instanceof Error) || reason instanceof AbortException || reason instanceof MissingPDFException || reason instanceof UnexpectedResponseException || reason instanceof UnknownErrorException) { return reason; } return new UnknownErrorException(reason.message, reason.toString()); } function resolveOrReject(capability, success, reason) { if (success) { capability.resolve(); } else { capability.reject(reason); } } function finalize(promise) { return Promise.resolve(promise).catch(function () {}); } function MessageHandler(sourceName, targetName, comObj) { var _this = this; this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackId = 1; this.streamId = 1; this.postMessageTransfers = true; this.streamSinks = Object.create(null); this.streamControllers = Object.create(null); var callbacksCapabilities = this.callbacksCapabilities = Object.create(null); var ah = this.actionHandler = Object.create(null); this._onComObjOnMessage = function (event) { var data = event.data; if (data.targetName !== _this.sourceName) { return; } if (data.stream) { _this._processStreamMessage(data); } else if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(wrapReason(data.error)); } else { callback.resolve(data.data); } } else { throw new Error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var _sourceName = _this.sourceName; var _targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: _sourceName, targetName: _targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { comObj.postMessage({ sourceName: _sourceName, targetName: _targetName, isReply: true, callbackId: data.callbackId, error: makeReasonSerializable(reason) }); }); } else if (data.streamId) { _this._createStreamSink(data); } else { action[0].call(action[1], data.data); } } else { throw new Error('Unknown action from worker: ' + data.action); } }; comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function on(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { throw new Error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, send: function send(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, sendWithPromise: function sendWithPromise(actionName, data, transfers) { var callbackId = this.callbackId++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, sendWithStream: function sendWithStream(actionName, data, queueingStrategy, transfers) { var _this2 = this; var streamId = this.streamId++; var sourceName = this.sourceName; var targetName = this.targetName; return new _streams_polyfill.ReadableStream({ start: function start(controller) { var startCapability = createPromiseCapability(); _this2.streamControllers[streamId] = { controller: controller, startCall: startCapability, isClosed: false }; _this2.postMessage({ sourceName: sourceName, targetName: targetName, action: actionName, streamId: streamId, data: data, desiredSize: controller.desiredSize }); return startCapability.promise; }, pull: function pull(controller) { var pullCapability = createPromiseCapability(); _this2.streamControllers[streamId].pullCall = pullCapability; _this2.postMessage({ sourceName: sourceName, targetName: targetName, stream: 'pull', streamId: streamId, desiredSize: controller.desiredSize }); return pullCapability.promise; }, cancel: function cancel(reason) { var cancelCapability = createPromiseCapability(); _this2.streamControllers[streamId].cancelCall = cancelCapability; _this2.streamControllers[streamId].isClosed = true; _this2.postMessage({ sourceName: sourceName, targetName: targetName, stream: 'cancel', reason: reason, streamId: streamId }); return cancelCapability.promise; } }, queueingStrategy); }, _createStreamSink: function _createStreamSink(data) { var _this3 = this; var self = this; var action = this.actionHandler[data.action]; var streamId = data.streamId; var desiredSize = data.desiredSize; var sourceName = this.sourceName; var targetName = data.sourceName; var capability = createPromiseCapability(); var sendStreamRequest = function sendStreamRequest(_ref) { var stream = _ref.stream, chunk = _ref.chunk, transfers = _ref.transfers, success = _ref.success, reason = _ref.reason; _this3.postMessage({ sourceName: sourceName, targetName: targetName, stream: stream, streamId: streamId, chunk: chunk, success: success, reason: reason }, transfers); }; var streamSink = { enqueue: function enqueue(chunk) { var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var transfers = arguments[2]; if (this.isCancelled) { return; } var lastDesiredSize = this.desiredSize; this.desiredSize -= size; if (lastDesiredSize > 0 && this.desiredSize <= 0) { this.sinkCapability = createPromiseCapability(); this.ready = this.sinkCapability.promise; } sendStreamRequest({ stream: 'enqueue', chunk: chunk, transfers: transfers }); }, close: function close() { if (this.isCancelled) { return; } this.isCancelled = true; sendStreamRequest({ stream: 'close' }); delete self.streamSinks[streamId]; }, error: function error(reason) { if (this.isCancelled) { return; } this.isCancelled = true; sendStreamRequest({ stream: 'error', reason: reason }); }, sinkCapability: capability, onPull: null, onCancel: null, isCancelled: false, desiredSize: desiredSize, ready: null }; streamSink.sinkCapability.resolve(); streamSink.ready = streamSink.sinkCapability.promise; this.streamSinks[streamId] = streamSink; resolveCall(action[0], [data.data, streamSink], action[1]).then(function () { sendStreamRequest({ stream: 'start_complete', success: true }); }, function (reason) { sendStreamRequest({ stream: 'start_complete', success: false, reason: reason }); }); }, _processStreamMessage: function _processStreamMessage(data) { var _this4 = this; var sourceName = this.sourceName; var targetName = data.sourceName; var streamId = data.streamId; var sendStreamResponse = function sendStreamResponse(_ref2) { var stream = _ref2.stream, success = _ref2.success, reason = _ref2.reason; _this4.comObj.postMessage({ sourceName: sourceName, targetName: targetName, stream: stream, success: success, streamId: streamId, reason: reason }); }; var deleteStreamController = function deleteStreamController() { Promise.all([_this4.streamControllers[data.streamId].startCall, _this4.streamControllers[data.streamId].pullCall, _this4.streamControllers[data.streamId].cancelCall].map(function (capability) { return capability && finalize(capability.promise); })).then(function () { delete _this4.streamControllers[data.streamId]; }); }; switch (data.stream) { case 'start_complete': resolveOrReject(this.streamControllers[data.streamId].startCall, data.success, wrapReason(data.reason)); break; case 'pull_complete': resolveOrReject(this.streamControllers[data.streamId].pullCall, data.success, wrapReason(data.reason)); break; case 'pull': if (!this.streamSinks[data.streamId]) { sendStreamResponse({ stream: 'pull_complete', success: true }); break; } if (this.streamSinks[data.streamId].desiredSize <= 0 && data.desiredSize > 0) { this.streamSinks[data.streamId].sinkCapability.resolve(); } this.streamSinks[data.streamId].desiredSize = data.desiredSize; resolveCall(this.streamSinks[data.streamId].onPull).then(function () { sendStreamResponse({ stream: 'pull_complete', success: true }); }, function (reason) { sendStreamResponse({ stream: 'pull_complete', success: false, reason: reason }); }); break; case 'enqueue': assert(this.streamControllers[data.streamId], 'enqueue should have stream controller'); if (!this.streamControllers[data.streamId].isClosed) { this.streamControllers[data.streamId].controller.enqueue(data.chunk); } break; case 'close': assert(this.streamControllers[data.streamId], 'close should have stream controller'); if (this.streamControllers[data.streamId].isClosed) { break; } this.streamControllers[data.streamId].isClosed = true; this.streamControllers[data.streamId].controller.close(); deleteStreamController(); break; case 'error': assert(this.streamControllers[data.streamId], 'error should have stream controller'); this.streamControllers[data.streamId].controller.error(wrapReason(data.reason)); deleteStreamController(); break; case 'cancel_complete': resolveOrReject(this.streamControllers[data.streamId].cancelCall, data.success, wrapReason(data.reason)); deleteStreamController(); break; case 'cancel': if (!this.streamSinks[data.streamId]) { break; } resolveCall(this.streamSinks[data.streamId].onCancel, [wrapReason(data.reason)]).then(function () { sendStreamResponse({ stream: 'cancel_complete', success: true }); }, function (reason) { sendStreamResponse({ stream: 'cancel_complete', success: false, reason: reason }); }); this.streamSinks[data.streamId].sinkCapability.reject(wrapReason(data.reason)); this.streamSinks[data.streamId].isCancelled = true; delete this.streamSinks[data.streamId]; break; default: throw new Error('Unexpected stream case'); } }, postMessage: function postMessage(message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function destroy() { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = function loadJpegStream_onloadClosure() { objs.resolve(id, img); }; img.onerror = function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }; img.src = imageUrl; } exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; exports.OPS = OPS; exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS; exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; exports.AnnotationBorderStyleType = AnnotationBorderStyleType; exports.AnnotationFieldFlag = AnnotationFieldFlag; exports.AnnotationFlag = AnnotationFlag; exports.AnnotationType = AnnotationType; exports.FontType = FontType; exports.ImageKind = ImageKind; exports.CMapCompressionType = CMapCompressionType; exports.AbortException = AbortException; exports.InvalidPDFException = InvalidPDFException; exports.MessageHandler = MessageHandler; exports.MissingDataException = MissingDataException; exports.MissingPDFException = MissingPDFException; exports.NativeImageDecoding = NativeImageDecoding; exports.NotImplementedException = NotImplementedException; exports.PageViewport = PageViewport; exports.PasswordException = PasswordException; exports.PasswordResponses = PasswordResponses; exports.StatTimer = StatTimer; exports.StreamType = StreamType; exports.TextRenderingMode = TextRenderingMode; exports.UnexpectedResponseException = UnexpectedResponseException; exports.UnknownErrorException = UnknownErrorException; exports.Util = Util; exports.XRefParseException = XRefParseException; exports.FormatError = FormatError; exports.arrayByteLength = arrayByteLength; exports.arraysToBytes = arraysToBytes; exports.assert = assert; exports.bytesToString = bytesToString; exports.createBlob = createBlob; exports.createPromiseCapability = createPromiseCapability; exports.createObjectURL = createObjectURL; exports.deprecated = deprecated; exports.getLookupTableFactory = getLookupTableFactory; exports.getVerbosityLevel = getVerbosityLevel; exports.info = info; exports.isArrayBuffer = isArrayBuffer; exports.isBool = isBool; exports.isEmptyObj = isEmptyObj; exports.isNum = isNum; exports.isString = isString; exports.isSpace = isSpace; exports.isNodeJS = isNodeJS; exports.isSameOrigin = isSameOrigin; exports.createValidAbsoluteUrl = createValidAbsoluteUrl; exports.isLittleEndian = isLittleEndian; exports.isEvalSupported = isEvalSupported; exports.loadJpegStream = loadJpegStream; exports.log2 = log2; exports.readInt8 = readInt8; exports.readUint16 = readUint16; exports.readUint32 = readUint32; exports.removeNullCharacters = removeNullCharacters; exports.ReadableStream = _streams_polyfill.ReadableStream; exports.setVerbosityLevel = setVerbosityLevel; exports.shadow = shadow; exports.string32 = string32; exports.stringToBytes = stringToBytes; exports.stringToPDFString = stringToPDFString; exports.stringToUTF8String = stringToUTF8String; exports.utf8StringToString = utf8StringToString; exports.warn = warn; exports.unreachable = unreachable; /***/ }), /* 1 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; 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; }; module.exports = function (it) { return (typeof it === 'undefined' ? 'undefined' : _typeof(it)) === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 2 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var store = __w_pdfjs_require__(42)('wks'); var uid = __w_pdfjs_require__(20); var _Symbol = __w_pdfjs_require__(3).Symbol; var USE_SYMBOL = typeof _Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && _Symbol[name] || (USE_SYMBOL ? _Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /* 3 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if (typeof __g == 'number') __g = global; /***/ }), /* 4 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = __w_pdfjs_require__(3); var core = __w_pdfjs_require__(5); var hide = __w_pdfjs_require__(11); var redefine = __w_pdfjs_require__(9); var ctx = __w_pdfjs_require__(10); var PROTOTYPE = 'prototype'; var $export = function $export(type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); var key, own, out, exp; if (IS_GLOBAL) source = name; for (key in source) { own = !IS_FORCED && target && target[key] !== undefined; out = (own ? target : source)[key]; exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; if (target) redefine(target, key, out, type & $export.U); if (exports[key] != out) hide(exports, key, exp); if (IS_PROTO && expProto[key] != out) expProto[key] = out; } }; global.core = core; $export.F = 1; $export.G = 2; $export.S = 4; $export.P = 8; $export.B = 16; $export.W = 32; $export.U = 64; $export.R = 128; module.exports = $export; /***/ }), /* 5 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var core = module.exports = { version: '2.5.1' }; if (typeof __e == 'number') __e = core; /***/ }), /* 6 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /* 7 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /* 8 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SimpleXMLParser = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.getDefaultSetting = exports.LinkTarget = exports.getFilenameFromUrl = exports.isExternalLinkTargetSet = exports.addLinkAttributes = exports.RenderingCancelledException = exports.CustomStyle = undefined; 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 _util = __w_pdfjs_require__(0); var _global_scope = __w_pdfjs_require__(14); var _global_scope2 = _interopRequireDefault(_global_scope); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DEFAULT_LINK_REL = 'noopener noreferrer nofollow'; var SVG_NS = 'http://www.w3.org/2000/svg'; var DOMCanvasFactory = function () { function DOMCanvasFactory() { _classCallCheck(this, DOMCanvasFactory); } _createClass(DOMCanvasFactory, [{ key: 'create', value: function create(width, height) { if (width <= 0 || height <= 0) { throw new Error('invalid canvas size'); } var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = width; canvas.height = height; return { canvas: canvas, context: context }; } }, { key: 'reset', value: function reset(canvasAndContext, width, height) { if (!canvasAndContext.canvas) { throw new Error('canvas is not specified'); } if (width <= 0 || height <= 0) { throw new Error('invalid canvas size'); } canvasAndContext.canvas.width = width; canvasAndContext.canvas.height = height; } }, { key: 'destroy', value: function destroy(canvasAndContext) { if (!canvasAndContext.canvas) { throw new Error('canvas is not specified'); } canvasAndContext.canvas.width = 0; canvasAndContext.canvas.height = 0; canvasAndContext.canvas = null; canvasAndContext.context = null; } }]); return DOMCanvasFactory; }(); var DOMCMapReaderFactory = function () { function DOMCMapReaderFactory(_ref) { var _ref$baseUrl = _ref.baseUrl, baseUrl = _ref$baseUrl === undefined ? null : _ref$baseUrl, _ref$isCompressed = _ref.isCompressed, isCompressed = _ref$isCompressed === undefined ? false : _ref$isCompressed; _classCallCheck(this, DOMCMapReaderFactory); this.baseUrl = baseUrl; this.isCompressed = isCompressed; } _createClass(DOMCMapReaderFactory, [{ key: 'fetch', value: function fetch(_ref2) { var _this = this; var name = _ref2.name; if (!this.baseUrl) { return Promise.reject(new Error('CMap baseUrl must be specified, ' + 'see "PDFJS.cMapUrl" (and also "PDFJS.cMapPacked").')); } if (!name) { return Promise.reject(new Error('CMap name must be specified.')); } return new Promise(function (resolve, reject) { var url = _this.baseUrl + name + (_this.isCompressed ? '.bcmap' : ''); var request = new XMLHttpRequest(); request.open('GET', url, true); if (_this.isCompressed) { request.responseType = 'arraybuffer'; } request.onreadystatechange = function () { if (request.readyState !== XMLHttpRequest.DONE) { return; } if (request.status === 200 || request.status === 0) { var data = void 0; if (_this.isCompressed && request.response) { data = new Uint8Array(request.response); } else if (!_this.isCompressed && request.responseText) { data = (0, _util.stringToBytes)(request.responseText); } if (data) { resolve({ cMapData: data, compressionType: _this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE }); return; } } reject(new Error('Unable to load ' + (_this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url)); }; request.send(null); }); } }]); return DOMCMapReaderFactory; }(); var DOMSVGFactory = function () { function DOMSVGFactory() { _classCallCheck(this, DOMSVGFactory); } _createClass(DOMSVGFactory, [{ key: 'create', value: function create(width, height) { (0, _util.assert)(width > 0 && height > 0, 'Invalid SVG dimensions'); var svg = document.createElementNS(SVG_NS, 'svg:svg'); svg.setAttribute('version', '1.1'); svg.setAttribute('width', width + 'px'); svg.setAttribute('height', height + 'px'); svg.setAttribute('preserveAspectRatio', 'none'); svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height); return svg; } }, { key: 'createElement', value: function createElement(type) { (0, _util.assert)(typeof type === 'string', 'Invalid SVG element type'); return document.createElementNS(SVG_NS, type); } }]); return DOMSVGFactory; }(); var SimpleDOMNode = function () { function SimpleDOMNode(nodeName, nodeValue) { _classCallCheck(this, SimpleDOMNode); this.nodeName = nodeName; this.nodeValue = nodeValue; Object.defineProperty(this, 'parentNode', { value: null, writable: true }); } _createClass(SimpleDOMNode, [{ key: 'hasChildNodes', value: function hasChildNodes() { return this.childNodes && this.childNodes.length > 0; } }, { key: 'firstChild', get: function get() { return this.childNodes[0]; } }, { key: 'nextSibling', get: function get() { var index = this.parentNode.childNodes.indexOf(this); return this.parentNode.childNodes[index + 1]; } }, { key: 'textContent', get: function get() { if (!this.childNodes) { return this.nodeValue || ''; } return this.childNodes.map(function (child) { return child.textContent; }).join(''); } }]); return SimpleDOMNode; }(); var SimpleXMLParser = function () { function SimpleXMLParser() { _classCallCheck(this, SimpleXMLParser); } _createClass(SimpleXMLParser, [{ key: 'parseFromString', value: function parseFromString(data) { var _this2 = this; var nodes = []; data = data.replace(/<\?[\s\S]*?\?>|<!--[\s\S]*?-->/g, '').trim(); data = data.replace(/<!DOCTYPE[^>\[]+(\[[^\]]+)?[^>]+>/g, '').trim(); data = data.replace(/>([^<][\s\S]*?)</g, function (all, text) { var length = nodes.length; var node = new SimpleDOMNode('#text', _this2._decodeXML(text)); nodes.push(node); if (node.textContent.trim().length === 0) { return '><'; } return '>' + length + ',<'; }); data = data.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, function (all, text) { var length = nodes.length; var node = new SimpleDOMNode('#text', text); nodes.push(node); return length + ','; }); var regex = /<([\w\:]+)((?:[\s\w:=]|'[^']*'|"[^"]*")*)(?:\/>|>([\d,]*)<\/[^>]+>)/g; var lastLength = void 0; do { lastLength = nodes.length; data = data.replace(regex, function (all, name, attrs, data) { var length = nodes.length; var node = new SimpleDOMNode(name); var children = []; if (data) { data = data.split(','); data.pop(); data.forEach(function (child) { var childNode = nodes[+child]; childNode.parentNode = node; children.push(childNode); }); } node.childNodes = children; nodes.push(node); return length + ','; }); } while (lastLength < nodes.length); return { documentElement: nodes.pop() }; } }, { key: '_decodeXML', value: function _decodeXML(text) { if (text.indexOf('&') < 0) { return text; } return text.replace(/&(#(x[0-9a-f]+|\d+)|\w+);/gi, function (all, entityName, number) { if (number) { if (number[0] === 'x') { number = parseInt(number.substring(1), 16); } else { number = +number; } return String.fromCharCode(number); } switch (entityName) { case 'amp': return '&'; case 'lt': return '<'; case 'gt': return '>'; case 'quot': return '\"'; case 'apos': return '\''; } return '&' + entityName + ';'; }); } }]); return SimpleXMLParser; }(); var CustomStyle = function CustomStyleClosure() { var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = Object.create(null); function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; if (typeof style[propName] === 'string') { return _cache[propName] = propName; } uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return _cache[propName] = prefixed; } } return _cache[propName] = 'undefined'; }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; }(); var RenderingCancelledException = function RenderingCancelledException() { function RenderingCancelledException(msg, type) { this.message = msg; this.type = type; } RenderingCancelledException.prototype = new Error(); RenderingCancelledException.prototype.name = 'RenderingCancelledException'; RenderingCancelledException.constructor = RenderingCancelledException; return RenderingCancelledException; }(); var LinkTarget = { NONE: 0, SELF: 1, BLANK: 2, PARENT: 3, TOP: 4 }; var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top']; function addLinkAttributes(link, params) { var url = params && params.url; link.href = link.title = url ? (0, _util.removeNullCharacters)(url) : ''; if (url) { var target = params.target; if (typeof target === 'undefined') { target = getDefaultSetting('externalLinkTarget'); } link.target = LinkTargetStringMap[target]; var rel = params.rel; if (typeof rel === 'undefined') { rel = getDefaultSetting('externalLinkRel'); } link.rel = rel; } } function getFilenameFromUrl(url) { var anchor = url.indexOf('#'); var query = url.indexOf('?'); var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length); return url.substring(url.lastIndexOf('/', end) + 1, end); } function getDefaultSetting(id) { var globalSettings = _global_scope2.default.PDFJS; switch (id) { case 'pdfBug': return globalSettings ? globalSettings.pdfBug : false; case 'disableAutoFetch': return globalSettings ? globalSettings.disableAutoFetch : false; case 'disableStream': return globalSettings ? globalSettings.disableStream : false; case 'disableRange': return globalSettings ? globalSettings.disableRange : false; case 'disableFontFace': return globalSettings ? globalSettings.disableFontFace : false; case 'disableCreateObjectURL': return globalSettings ? globalSettings.disableCreateObjectURL : false; case 'disableWebGL': return globalSettings ? globalSettings.disableWebGL : true; case 'cMapUrl': return globalSettings ? globalSettings.cMapUrl : null; case 'cMapPacked': return globalSettings ? globalSettings.cMapPacked : false; case 'postMessageTransfers': return globalSettings ? globalSettings.postMessageTransfers : true; case 'workerPort': return globalSettings ? globalSettings.workerPort : null; case 'workerSrc': return globalSettings ? globalSettings.workerSrc : null; case 'disableWorker': return globalSettings ? globalSettings.disableWorker : false; case 'maxImageSize': return globalSettings ? globalSettings.maxImageSize : -1; case 'imageResourcesPath': return globalSettings ? globalSettings.imageResourcesPath : ''; case 'isEvalSupported': return globalSettings ? globalSettings.isEvalSupported : true; case 'externalLinkTarget': if (!globalSettings) { return LinkTarget.NONE; } switch (globalSettings.externalLinkTarget) { case LinkTarget.NONE: case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return globalSettings.externalLinkTarget; } (0, _util.warn)('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget); globalSettings.externalLinkTarget = LinkTarget.NONE; return LinkTarget.NONE; case 'externalLinkRel': return globalSettings ? globalSettings.externalLinkRel : DEFAULT_LINK_REL; case 'enableStats': return !!(globalSettings && globalSettings.enableStats); default: throw new Error('Unknown default setting: ' + id); } } function isExternalLinkTargetSet() { var externalLinkTarget = getDefaultSetting('externalLinkTarget'); switch (externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } } exports.CustomStyle = CustomStyle; exports.RenderingCancelledException = RenderingCancelledException; exports.addLinkAttributes = addLinkAttributes; exports.isExternalLinkTargetSet = isExternalLinkTargetSet; exports.getFilenameFromUrl = getFilenameFromUrl; exports.LinkTarget = LinkTarget; exports.getDefaultSetting = getDefaultSetting; exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL; exports.DOMCanvasFactory = DOMCanvasFactory; exports.DOMCMapReaderFactory = DOMCMapReaderFactory; exports.DOMSVGFactory = DOMSVGFactory; exports.SimpleXMLParser = SimpleXMLParser; /***/ }), /* 9 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = __w_pdfjs_require__(3); var hide = __w_pdfjs_require__(11); var has = __w_pdfjs_require__(7); var SRC = __w_pdfjs_require__(20)('src'); var TO_STRING = 'toString'; var $toString = Function[TO_STRING]; var TPL = ('' + $toString).split(TO_STRING); __w_pdfjs_require__(5).inspectSource = function (it) { return $toString.call(it); }; (module.exports = function (O, key, val, safe) { var isFunction = typeof val == 'function'; if (isFunction) has(val, 'name') || hide(val, 'name', key); if (O[key] === val) return; if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if (O === global) { O[key] = val; } else if (!safe) { delete O[key]; hide(O, key, val); } else if (O[key]) { O[key] = val; } else { hide(O, key, val); } })(Function.prototype, TO_STRING, function toString() { return typeof this == 'function' && this[SRC] || $toString.call(this); }); /***/ }), /* 10 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var aFunction = __w_pdfjs_require__(16); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function () { return fn.apply(that, arguments); }; }; /***/ }), /* 11 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var dP = __w_pdfjs_require__(15); var createDesc = __w_pdfjs_require__(25); module.exports = __w_pdfjs_require__(12) ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /* 12 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = !__w_pdfjs_require__(13)(function () { return Object.defineProperty({}, 'a', { get: function get() { return 7; } }).a != 7; }); /***/ }), /* 13 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /* 14 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = typeof window !== 'undefined' && window.Math === Math ? window : typeof global !== 'undefined' && global.Math === Math ? global : typeof self !== 'undefined' && self.Math === Math ? self : {}; /***/ }), /* 15 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var anObject = __w_pdfjs_require__(6); var IE8_DOM_DEFINE = __w_pdfjs_require__(39); var toPrimitive = __w_pdfjs_require__(40); var dP = Object.defineProperty; exports.f = __w_pdfjs_require__(12) ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) {} if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /* 16 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 17 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var IObject = __w_pdfjs_require__(26); var defined = __w_pdfjs_require__(27); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /* 18 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /* 19 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = {}; /***/ }), /* 20 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /* 21 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $keys = __w_pdfjs_require__(68); var enumBugKeys = __w_pdfjs_require__(43); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /* 22 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var def = __w_pdfjs_require__(15).f; var has = __w_pdfjs_require__(7); var TAG = __w_pdfjs_require__(2)('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /* 23 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var ctx = __w_pdfjs_require__(10); var call = __w_pdfjs_require__(87); var isArrayIter = __w_pdfjs_require__(88); var anObject = __w_pdfjs_require__(6); var toLength = __w_pdfjs_require__(28); var getIterFn = __w_pdfjs_require__(89); var BREAK = {}; var RETURN = {}; var _exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; _exports.BREAK = BREAK; _exports.RETURN = RETURN; /***/ }), /* 24 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); var document = __w_pdfjs_require__(3).document; var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /* 25 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /* 26 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var cof = __w_pdfjs_require__(18); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /* 27 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /* 28 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var toInteger = __w_pdfjs_require__(29); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; }; /***/ }), /* 29 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /* 30 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var shared = __w_pdfjs_require__(42)('keys'); var uid = __w_pdfjs_require__(20); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /* 31 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; exports.f = {}.propertyIsEnumerable; /***/ }), /* 32 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var cof = __w_pdfjs_require__(18); var TAG = __w_pdfjs_require__(2)('toStringTag'); var ARG = cof(function () { return arguments; }()) == 'Arguments'; var tryGet = function tryGet(it, key) { try { return it[key]; } catch (e) {} }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T : ARG ? cof(O) : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /* 33 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var defined = __w_pdfjs_require__(27); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /* 34 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || forbiddenField !== undefined && forbiddenField in it) { throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }), /* 35 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var aFunction = __w_pdfjs_require__(16); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /* 36 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var redefine = __w_pdfjs_require__(9); module.exports = function (target, src, safe) { for (var key in src) { redefine(target, key, src[key], safe); }return target; }; /***/ }), /* 37 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; 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 META = __w_pdfjs_require__(20)('meta'); var isObject = __w_pdfjs_require__(1); var has = __w_pdfjs_require__(7); var setDesc = __w_pdfjs_require__(15).f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__w_pdfjs_require__(13)(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function setMeta(it) { setDesc(it, META, { value: { i: 'O' + ++id, w: {} } }); }; var fastKey = function fastKey(it, create) { if (!isObject(it)) return (typeof it === 'undefined' ? 'undefined' : _typeof(it)) == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { if (!isExtensible(it)) return 'F'; if (!create) return 'E'; setMeta(it); } return it[META].i; }; var getWeak = function getWeak(it, create) { if (!has(it, META)) { if (!isExtensible(it)) return true; if (!create) return false; setMeta(it); } return it[META].w; }; var onFreeze = function onFreeze(it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /* 38 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateResponseStatus = exports.validateRangeRequestCapabilities = exports.createResponseStatusError = undefined; var _util = __w_pdfjs_require__(0); function validateRangeRequestCapabilities(_ref) { var getResponseHeader = _ref.getResponseHeader, isHttp = _ref.isHttp, rangeChunkSize = _ref.rangeChunkSize, disableRange = _ref.disableRange; (0, _util.assert)(rangeChunkSize > 0); var returnValues = { allowRangeRequests: false, suggestedLength: undefined }; if (disableRange || !isHttp) { return returnValues; } if (getResponseHeader('Accept-Ranges') !== 'bytes') { return returnValues; } var contentEncoding = getResponseHeader('Content-Encoding') || 'identity'; if (contentEncoding !== 'identity') { return returnValues; } var length = parseInt(getResponseHeader('Content-Length'), 10); if (!Number.isInteger(length)) { return returnValues; } returnValues.suggestedLength = length; if (length <= 2 * rangeChunkSize) { return returnValues; } returnValues.allowRangeRequests = true; return returnValues; } function createResponseStatusError(status, url) { if (status === 404 || status === 0 && /^file:/.test(url)) { return new _util.MissingPDFException('Missing PDF "' + url + '".'); } return new _util.UnexpectedResponseException('Unexpected server response (' + status + ') while retrieving PDF "' + url + '".', status); } function validateResponseStatus(status) { return status === 200 || status === 206; } exports.createResponseStatusError = createResponseStatusError; exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities; exports.validateResponseStatus = validateResponseStatus; /***/ }), /* 39 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = !__w_pdfjs_require__(12) && !__w_pdfjs_require__(13)(function () { return Object.defineProperty(__w_pdfjs_require__(24)('div'), 'a', { get: function get() { return 7; } }).a != 7; }); /***/ }), /* 40 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /* 41 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var toIObject = __w_pdfjs_require__(17); var toLength = __w_pdfjs_require__(28); var toAbsoluteIndex = __w_pdfjs_require__(69); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; if (value != value) return true; } else for (; length > index; index++) { if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } }return !IS_INCLUDES && -1; }; }; /***/ }), /* 42 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = __w_pdfjs_require__(3); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); module.exports = function (key) { return store[key] || (store[key] = {}); }; /***/ }), /* 43 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'.split(','); /***/ }), /* 44 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var UNSCOPABLES = __w_pdfjs_require__(2)('unscopables'); var ArrayProto = Array.prototype; if (ArrayProto[UNSCOPABLES] == undefined) __w_pdfjs_require__(11)(ArrayProto, UNSCOPABLES, {}); module.exports = function (key) { ArrayProto[UNSCOPABLES][key] = true; }; /***/ }), /* 45 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var classof = __w_pdfjs_require__(32); var test = {}; test[__w_pdfjs_require__(2)('toStringTag')] = 'z'; if (test + '' != '[object z]') { __w_pdfjs_require__(9)(Object.prototype, 'toString', function toString() { return '[object ' + classof(this) + ']'; }, true); } /***/ }), /* 46 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var LIBRARY = __w_pdfjs_require__(47); var $export = __w_pdfjs_require__(4); var redefine = __w_pdfjs_require__(9); var hide = __w_pdfjs_require__(11); var has = __w_pdfjs_require__(7); var Iterators = __w_pdfjs_require__(19); var $iterCreate = __w_pdfjs_require__(80); var setToStringTag = __w_pdfjs_require__(22); var getPrototypeOf = __w_pdfjs_require__(83); var ITERATOR = __w_pdfjs_require__(2)('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function returnThis() { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function getMethod(kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = $native || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { setToStringTag(IteratorPrototype, TAG, true); if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis); } } if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /* 47 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = false; /***/ }), /* 48 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var document = __w_pdfjs_require__(3).document; module.exports = document && document.documentElement; /***/ }), /* 49 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $iterators = __w_pdfjs_require__(84); var getKeys = __w_pdfjs_require__(21); var redefine = __w_pdfjs_require__(9); var global = __w_pdfjs_require__(3); var hide = __w_pdfjs_require__(11); var Iterators = __w_pdfjs_require__(19); var wks = __w_pdfjs_require__(2); var ITERATOR = wks('iterator'); var TO_STRING_TAG = wks('toStringTag'); var ArrayValues = Iterators.Array; var DOMIterables = { CSSRuleList: true, CSSStyleDeclaration: false, CSSValueList: false, ClientRectList: false, DOMRectList: false, DOMStringList: false, DOMTokenList: true, DataTransferItemList: false, FileList: false, HTMLAllCollection: false, HTMLCollection: false, HTMLFormElement: false, HTMLSelectElement: false, MediaList: true, MimeTypeArray: false, NamedNodeMap: false, NodeList: true, PaintRequestList: false, Plugin: false, PluginArray: false, SVGLengthList: false, SVGNumberList: false, SVGPathSegList: false, SVGPointList: false, SVGStringList: false, SVGTransformList: false, SourceBufferList: false, StyleSheetList: true, TextTrackCueList: false, TextTrackList: false, TouchList: false }; for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { var NAME = collections[i]; var explicit = DOMIterables[NAME]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; var key; if (proto) { if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; if (explicit) for (key in $iterators) { if (!proto[key]) redefine(proto, key, $iterators[key], true); } } } /***/ }), /* 50 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var anObject = __w_pdfjs_require__(6); var aFunction = __w_pdfjs_require__(16); var SPECIES = __w_pdfjs_require__(2)('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }), /* 51 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var ctx = __w_pdfjs_require__(10); var invoke = __w_pdfjs_require__(90); var html = __w_pdfjs_require__(48); var cel = __w_pdfjs_require__(24); var global = __w_pdfjs_require__(3); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; var MessageChannel = global.MessageChannel; var Dispatch = global.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function run() { var id = +this; if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function listener(event) { run.call(event.data); }; if (!setTask || !clearTask) { setTask = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) { args.push(arguments[i++]); }queue[++counter] = function () { invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id) { delete queue[id]; }; if (__w_pdfjs_require__(18)(process) == 'process') { defer = function defer(id) { process.nextTick(ctx(run, id, 1)); }; } else if (Dispatch && Dispatch.now) { defer = function defer(id) { Dispatch.now(ctx(run, id, 1)); }; } else if (MessageChannel) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { defer = function defer(id) { global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); } else if (ONREADYSTATECHANGE in cel('script')) { defer = function defer(id) { html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run.call(id); }; }; } else { defer = function defer(id) { setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }), /* 52 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (exec) { try { return { e: false, v: exec() }; } catch (e) { return { e: true, v: e }; } }; /***/ }), /* 53 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var anObject = __w_pdfjs_require__(6); var isObject = __w_pdfjs_require__(1); var newPromiseCapability = __w_pdfjs_require__(35); module.exports = function (C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; /***/ }), /* 54 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var ITERATOR = __w_pdfjs_require__(2)('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; Array.from(riter, function () { throw 2; }); } catch (e) {} module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) {} return safe; }; /***/ }), /* 55 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var ctx = __w_pdfjs_require__(10); var IObject = __w_pdfjs_require__(26); var toObject = __w_pdfjs_require__(33); var toLength = __w_pdfjs_require__(28); var asc = __w_pdfjs_require__(97); module.exports = function (TYPE, $create) { var IS_MAP = TYPE == 1; var IS_FILTER = TYPE == 2; var IS_SOME = TYPE == 3; var IS_EVERY = TYPE == 4; var IS_FIND_INDEX = TYPE == 6; var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; var create = $create || asc; return function ($this, callbackfn, that) { var O = toObject($this); var self = IObject(O); var f = ctx(callbackfn, that, 3); var length = toLength(self.length); var index = 0; var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; var val, res; for (; length > index; index++) { if (NO_HOLES || index in self) { val = self[index]; res = f(val, index, O); if (TYPE) { if (IS_MAP) result[index] = res;else if (res) switch (TYPE) { case 3: return true; case 5: return val; case 6: return index; case 2: result.push(val); } else if (IS_EVERY) return false; } } }return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; /***/ }), /* 56 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); module.exports = function (it, TYPE) { if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); return it; }; /***/ }), /* 57 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.build = exports.version = exports.setPDFNetworkStreamClass = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFWorker = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.getDocument = undefined; 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 _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 _util = __w_pdfjs_require__(0); var _dom_utils = __w_pdfjs_require__(8); var _font_loader = __w_pdfjs_require__(114); var _canvas = __w_pdfjs_require__(115); var _global_scope = __w_pdfjs_require__(14); var _global_scope2 = _interopRequireDefault(_global_scope); var _metadata = __w_pdfjs_require__(59); var _transport_stream = __w_pdfjs_require__(117); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DEFAULT_RANGE_CHUNK_SIZE = 65536; var isWorkerDisabled = false; var workerSrc; var isPostMessageTransfersDisabled = false; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var fakeWorkerFilesLoader = null; var useRequireEnsure = false; { if (typeof window === 'undefined') { isWorkerDisabled = true; if (typeof require.ensure === 'undefined') { require.ensure = require('node-ensure'); } useRequireEnsure = true; } else if (typeof require !== 'undefined' && typeof require.ensure === 'function') { useRequireEnsure = true; } if (typeof requirejs !== 'undefined' && requirejs.toUrl) { workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js'); } var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load; fakeWorkerFilesLoader = useRequireEnsure ? function (callback) { require.ensure([], function () { var worker; worker = require('./pdf.worker.js'); callback(worker.WorkerMessageHandler); }); } : dynamicLoaderSupported ? function (callback) { requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) { callback(worker.WorkerMessageHandler); }); } : null; } var PDFNetworkStream; function setPDFNetworkStreamClass(cls) { PDFNetworkStream = cls; } function getDocument(src) { var task = new PDFDocumentLoadingTask(); var source; if (typeof src === 'string') { source = { url: src }; } else if ((0, _util.isArrayBuffer)(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if ((typeof src === 'undefined' ? 'undefined' : _typeof(src)) !== 'object') { throw new Error('Invalid parameter in getDocument, ' + 'need either Uint8Array, string or a parameter object'); } if (!src.url && !src.data && !src.range) { throw new Error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; var CMapReaderFactory = _dom_utils.DOMCMapReaderFactory; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { params[key] = new URL(source[key], window.location).href; continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = (0, _util.stringToBytes)(pdfBytes); } else if ((typeof pdfBytes === 'undefined' ? 'undefined' : _typeof(pdfBytes)) === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if ((0, _util.isArrayBuffer)(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { throw new Error('Invalid PDF binary data: either typed array, ' + 'string or array-like object is expected in the ' + 'data property.'); } continue; } else if (key === 'CMapReaderFactory') { CMapReaderFactory = source[key]; continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; params.ignoreErrors = params.stopAtErrors !== true; var nativeImageDecoderValues = Object.values(_util.NativeImageDecoding); if (params.nativeImageDecoderSupport === undefined || !nativeImageDecoderValues.includes(params.nativeImageDecoderSupport)) { params.nativeImageDecoderSupport = _util.NativeImageDecoding.DECODE; } if (!worker) { var workerPort = (0, _dom_utils.getDefaultSetting)('workerPort'); worker = workerPort ? PDFWorker.fromPort(workerPort) : new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var networkStream = void 0; if (rangeTransport) { networkStream = new _transport_stream.PDFDataTransportStream(params, rangeTransport); } else if (!params.data) { networkStream = new PDFNetworkStream({ source: params, disableRange: (0, _dom_utils.getDefaultSetting)('disableRange') }); } var messageHandler = new _util.MessageHandler(docId, workerId, worker.port); messageHandler.postMessageTransfers = worker.postMessageTransfers; var transport = new WorkerTransport(messageHandler, task, networkStream, CMapReaderFactory); task._transport = transport; messageHandler.send('Ready', null); }); }).catch(task._capability.reject); return task; } function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } var apiVersion = '2.0.112'; source.disableAutoFetch = (0, _dom_utils.getDefaultSetting)('disableAutoFetch'); source.disableStream = (0, _dom_utils.getDefaultSetting)('disableStream'); source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, apiVersion: apiVersion, source: { data: source.data, url: source.url, password: source.password, disableAutoFetch: source.disableAutoFetch, rangeChunkSize: source.rangeChunkSize, length: source.length }, maxImageSize: (0, _dom_utils.getDefaultSetting)('maxImageSize'), disableFontFace: (0, _dom_utils.getDefaultSetting)('disableFontFace'), disableCreateObjectURL: (0, _dom_utils.getDefaultSetting)('disableCreateObjectURL'), postMessageTransfers: (0, _dom_utils.getDefaultSetting)('postMessageTransfers') && !isPostMessageTransfersDisabled, docBaseUrl: source.docBaseUrl, nativeImageDecoderSupport: source.nativeImageDecoderSupport, ignoreErrors: source.ignoreErrors, isEvalSupported: (0, _dom_utils.getDefaultSetting)('isEvalSupported') }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; function PDFDocumentLoadingTask() { this._capability = (0, _util.createPromiseCapability)(); this._transport = null; this._worker = null; this.docId = 'd' + nextDocumentId++; this.destroyed = false; this.onPassword = null; this.onProgress = null; this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = { get promise() { return this._capability.promise; }, destroy: function destroy() { var _this = this; this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { _this._transport = null; if (_this._worker) { _this._worker.destroy(); _this._worker = null; } }); }, then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; }(); var PDFDataRangeTransport = function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = (0, _util.createPromiseCapability)(); } PDFDataRangeTransport.prototype = { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { var _this2 = this; this._readyCapability.promise.then(function () { var listeners = _this2._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { var _this3 = this; this._readyCapability.promise.then(function () { var listeners = _this3._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() {} }; return PDFDataRangeTransport; }(); var PDFDocumentProxy = function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = { get numPages() { return this.pdfInfo.numPages; }, get fingerprint() { return this.pdfInfo.fingerprint; }, getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, getPageLabels: function PDFDocumentProxy_getPageLabels() { return this.transport.getPageLabels(); }, getPageMode: function getPageMode() { return this.transport.getPageMode(); }, getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, getJavaScript: function getJavaScript() { return this.transport.getJavaScript(); }, getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; }(); var PDFPageProxy = function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new _util.StatTimer(); this.stats.enabled = (0, _dom_utils.getDefaultSetting)('enableStats'); this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = Object.create(null); this.destroyed = false; } PDFPageProxy.prototype = { get pageNumber() { return this.pageIndex + 1; }, get rotate() { return this.pageInfo.rotate; }, get ref() { return this.pageInfo.ref; }, get userUnit() { return this.pageInfo.userUnit; }, get view() { return this.pageInfo.view; }, getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new _util.PageViewport(this.view, scale, rotate, 0, 0); }, getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = params && params.intent || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, render: function PDFPageProxy_render(params) { var _this4 = this; var stats = this.stats; stats.time('Overall'); this.pendingCleanup = false; var renderingIntent = params.intent === 'print' ? 'print' : 'display'; var canvasFactory = params.canvasFactory || new _dom_utils.DOMCanvasFactory(); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = Object.create(null); } var intentState = this.intentStates[renderingIntent]; if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = (0, _util.createPromiseCapability)(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent, renderInteractiveForms: params.renderInteractiveForms === true }); } var complete = function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (_this4.cleanupAfterRender) { _this4.pendingCleanup = true; } _this4._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); }; var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber, canvasFactory); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; intentState.displayReadyCapability.promise.then(function (transparency) { if (_this4.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initializeGraphics(transparency); internalRenderTask.operatorListChanged(); }).catch(complete); return renderTask; }, getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); var i = intentState.renderTasks.indexOf(opListTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = Object.create(null); } var intentState = this.intentStates[renderingIntent]; var opListTask; if (!intentState.opListReadCapability) { opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = (0, _util.createPromiseCapability)(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, streamTextContent: function streamTextContent() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var TEXT_CONTENT_CHUNK_SIZE = 100; return this.transport.messageHandler.sendWithStream('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: params.normalizeWhitespace === true, combineTextItems: params.disableCombineTextItems !== true }, { highWaterMark: TEXT_CONTENT_CHUNK_SIZE, size: function size(textContent) { return textContent.items.length; } }); }, getTextContent: function PDFPageProxy_getTextContent(params) { params = params || {}; var readableStream = this.streamTextContent(params); return new Promise(function (resolve, reject) { function pump() { reader.read().then(function (_ref) { var value = _ref.value, done = _ref.done; if (done) { resolve(textContent); return; } _util.Util.extendObj(textContent.styles, value.styles); _util.Util.appendToArray(textContent.items, value.items); pump(); }, reject); } var reader = readableStream.getReader(); var textContent = { items: [], styles: Object.create(null) }; pump(); }); }, _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function (intent) { if (intent === 'oplist') { return; } var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function (renderTask) { var renderCompleted = renderTask.capability.promise.catch(function () {}); waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) { var intentState = this.intentStates[intent]; return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList; }, this)) { return; } Object.keys(this.intentStates).forEach(function (intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; }(); var LoopbackPort = function () { function LoopbackPort(defer) { _classCallCheck(this, LoopbackPort); this._listeners = []; this._defer = defer; this._deferred = Promise.resolve(undefined); } _createClass(LoopbackPort, [{ key: 'postMessage', value: function postMessage(obj, transfers) { var _this5 = this; function cloneValue(value) { if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object' || value === null) { return value; } if (cloned.has(value)) { return cloned.get(value); } var result; var buffer; if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) { var transferable = transfers && transfers.indexOf(buffer) >= 0; if (value === buffer) { result = value; } else if (transferable) { result = new value.constructor(buffer, value.byteOffset, value.byteLength); } else { result = new value.constructor(value); } cloned.set(value, result); return result; } result = Array.isArray(value) ? [] : {}; cloned.set(value, result); for (var i in value) { var desc, p = value; while (!(desc = Object.getOwnPropertyDescriptor(p, i))) { p = Object.getPrototypeOf(p); } if (typeof desc.value === 'undefined' || typeof desc.value === 'function') { continue; } result[i] = cloneValue(desc.value); } return result; } if (!this._defer) { this._listeners.forEach(function (listener) { listener.call(this, { data: obj }); }, this); return; } var cloned = new WeakMap(); var e = { data: cloneValue(obj) }; this._deferred.then(function () { _this5._listeners.forEach(function (listener) { listener.call(this, e); }, _this5); }); } }, { key: 'addEventListener', value: function addEventListener(name, listener) { this._listeners.push(listener); } }, { key: 'removeEventListener', value: function removeEventListener(name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); } }, { key: 'terminate', value: function terminate() { this._listeners = []; } }]); return LoopbackPort; }(); var PDFWorker = function PDFWorkerClosure() { var nextFakeWorkerId = 0; function getWorkerSrc() { if (typeof workerSrc !== 'undefined') { return workerSrc; } if ((0, _dom_utils.getDefaultSetting)('workerSrc')) { return (0, _dom_utils.getDefaultSetting)('workerSrc'); } if (pdfjsFilePath) { return pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, '.worker$1$2'); } throw new Error('No PDFJS.workerSrc specified'); } var fakeWorkerFilesLoadedCapability = void 0; function setupFakeWorkerGlobal() { var WorkerMessageHandler; if (fakeWorkerFilesLoadedCapability) { return fakeWorkerFilesLoadedCapability.promise; } fakeWorkerFilesLoadedCapability = (0, _util.createPromiseCapability)(); var loader = fakeWorkerFilesLoader || function (callback) { _util.Util.loadScript(getWorkerSrc(), function () { callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler); }); }; loader(fakeWorkerFilesLoadedCapability.resolve); return fakeWorkerFilesLoadedCapability.promise; } function createCDNWrapper(url) { var wrapper = 'importScripts(\'' + url + '\');'; return URL.createObjectURL(new Blob([wrapper])); } var pdfWorkerPorts = new WeakMap(); function PDFWorker(name, port) { if (port && pdfWorkerPorts.has(port)) { throw new Error('Cannot use more than one PDFWorker per port'); } this.name = name; this.destroyed = false; this.postMessageTransfers = true; this._readyCapability = (0, _util.createPromiseCapability)(); this._port = null; this._webWorker = null; this._messageHandler = null; if (port) { pdfWorkerPorts.set(port, this); this._initializeFromPort(port); return; } this._initialize(); } PDFWorker.prototype = { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initializeFromPort: function PDFWorker_initializeFromPort(port) { this._port = port; this._messageHandler = new _util.MessageHandler('main', 'worker', port); this._messageHandler.on('ready', function () {}); this._readyCapability.resolve(); }, _initialize: function PDFWorker_initialize() { var _this6 = this; if (!isWorkerDisabled && !(0, _dom_utils.getDefaultSetting)('disableWorker') && typeof Worker !== 'undefined') { var workerSrc = getWorkerSrc(); try { if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) { workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href); } var worker = new Worker(workerSrc); var messageHandler = new _util.MessageHandler('main', 'worker', worker); var terminateEarly = function terminateEarly() { worker.removeEventListener('error', onWorkerError); messageHandler.destroy(); worker.terminate(); if (_this6.destroyed) { _this6._readyCapability.reject(new Error('Worker was destroyed')); } else { _this6._setupFakeWorker(); } }; var onWorkerError = function onWorkerError() { if (!_this6._webWorker) { terminateEarly(); } }; worker.addEventListener('error', onWorkerError); messageHandler.on('test', function (data) { worker.removeEventListener('error', onWorkerError); if (_this6.destroyed) { terminateEarly(); return; } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { _this6._messageHandler = messageHandler; _this6._port = worker; _this6._webWorker = worker; if (!data.supportTransfers) { _this6.postMessageTransfers = false; isPostMessageTransfersDisabled = true; } _this6._readyCapability.resolve(); messageHandler.send('configure', { verbosity: (0, _util.getVerbosityLevel)() }); } else { _this6._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); messageHandler.on('ready', function (data) { worker.removeEventListener('error', onWorkerError); if (_this6.destroyed) { terminateEarly(); return; } try { sendTest(); } catch (e) { _this6._setupFakeWorker(); } }); var sendTest = function sendTest() { var postMessageTransfers = (0, _dom_utils.getDefaultSetting)('postMessageTransfers') && !isPostMessageTransfersDisabled; var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]); try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { (0, _util.info)('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } }; sendTest(); return; } catch (e) { (0, _util.info)('The worker has been disabled.'); } } this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { var _this7 = this; if (!isWorkerDisabled && !(0, _dom_utils.getDefaultSetting)('disableWorker')) { (0, _util.warn)('Setting up fake worker.'); isWorkerDisabled = true; } setupFakeWorkerGlobal().then(function (WorkerMessageHandler) { if (_this7.destroyed) { _this7._readyCapability.reject(new Error('Worker was destroyed')); return; } var isTypedArraysPresent = Uint8Array !== Float32Array; var port = new LoopbackPort(isTypedArraysPresent); _this7._port = port; var id = 'fake' + nextFakeWorkerId++; var workerHandler = new _util.MessageHandler(id + '_worker', id, port); WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new _util.MessageHandler(id, id + '_worker', port); _this7._messageHandler = messageHandler; _this7._readyCapability.resolve(); }); }, destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { this._webWorker.terminate(); this._webWorker = null; } pdfWorkerPorts.delete(this._port); this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; PDFWorker.fromPort = function (port) { if (pdfWorkerPorts.has(port)) { return pdfWorkerPorts.get(port); } return new PDFWorker(null, port); }; return PDFWorker; }(); var WorkerTransport = function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, networkStream, CMapReaderFactory) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.commonObjs = new PDFObjects(); this.fontLoader = new _font_loader.FontLoader(loadingTask.docId); this.CMapReaderFactory = new CMapReaderFactory({ baseUrl: (0, _dom_utils.getDefaultSetting)('cMapUrl'), isCompressed: (0, _dom_utils.getDefaultSetting)('cMapPacked') }); this.destroyed = false; this.destroyCapability = null; this._passwordCapability = null; this._networkStream = networkStream; this._fullReader = null; this._lastProgress = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = (0, _util.createPromiseCapability)(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { var _this8 = this; if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = (0, _util.createPromiseCapability)(); if (this._passwordCapability) { this._passwordCapability.reject(new Error('Worker was destroyed during onPassword callback')); } var waitOn = []; this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { _this8.fontLoader.clear(); if (_this8._networkStream) { _this8._networkStream.cancelAllRequests(); } if (_this8.messageHandler) { _this8.messageHandler.destroy(); _this8.messageHandler = null; } _this8.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; var loadingTask = this.loadingTask; messageHandler.on('GetReader', function (data, sink) { var _this9 = this; (0, _util.assert)(this._networkStream); this._fullReader = this._networkStream.getFullReader(); this._fullReader.onProgress = function (evt) { _this9._lastProgress = { loaded: evt.loaded, total: evt.total }; }; sink.onPull = function () { _this9._fullReader.read().then(function (_ref2) { var value = _ref2.value, done = _ref2.done; if (done) { sink.close(); return; } (0, _util.assert)((0, _util.isArrayBuffer)(value)); sink.enqueue(new Uint8Array(value), 1, [value]); }).catch(function (reason) { sink.error(reason); }); }; sink.onCancel = function (reason) { _this9._fullReader.cancel(reason); }; }, this); messageHandler.on('ReaderHeadersReady', function (data) { var _this10 = this; var headersCapability = (0, _util.createPromiseCapability)(); var fullReader = this._fullReader; fullReader.headersReady.then(function () { if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) { if (_this10._lastProgress) { var _loadingTask = _this10.loadingTask; if (_loadingTask.onProgress) { _loadingTask.onProgress(_this10._lastProgress); } } fullReader.onProgress = function (evt) { var loadingTask = _this10.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: evt.loaded, total: evt.total }); } }; } headersCapability.resolve({ isStreamingSupported: fullReader.isStreamingSupported, isRangeSupported: fullReader.isRangeSupported, contentLength: fullReader.contentLength }); }, headersCapability.reject); return headersCapability.promise; }, this); messageHandler.on('GetRangeReader', function (data, sink) { (0, _util.assert)(this._networkStream); var _rangeReader = this._networkStream.getRangeReader(data.begin, data.end); sink.onPull = function () { _rangeReader.read().then(function (_ref3) { var value = _ref3.value, done = _ref3.done; if (done) { sink.close(); return; } (0, _util.assert)((0, _util.isArrayBuffer)(value)); sink.enqueue(new Uint8Array(value), 1, [value]); }).catch(function (reason) { sink.error(reason); }); }; sink.onCancel = function (reason) { _rangeReader.cancel(reason); }; }, this); messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('PasswordRequest', function transportPasswordRequest(exception) { var _this11 = this; this._passwordCapability = (0, _util.createPromiseCapability)(); if (loadingTask.onPassword) { var updatePassword = function updatePassword(password) { _this11._passwordCapability.resolve({ password: password }); }; loadingTask.onPassword(updatePassword, exception.code); } else { this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code)); } return this._passwordCapability.promise; }, this); messageHandler.on('PasswordException', function transportPasswordException(exception) { loadingTask._capability.reject(new _util.PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject(new _util.InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject(new _util.MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject(new _util.UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject(new _util.UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) {}, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { var _this12 = this; if (this.destroyed) { return; } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; if ('error' in exportedData) { var exportedError = exportedData.error; (0, _util.warn)('Error during font loading: ' + exportedError); this.commonObjs.resolve(id, exportedError); break; } var fontRegistry = null; if ((0, _dom_utils.getDefaultSetting)('pdfBug') && _global_scope2.default.FontInspector && _global_scope2.default['FontInspector'].enabled) { fontRegistry = { registerFont: function registerFont(font, url) { _global_scope2.default['FontInspector'].fontAdded(font, url); } }; } var font = new _font_loader.FontFaceObject(exportedData, { isEvalSupported: (0, _dom_utils.getDefaultSetting)('isEvalSupported'), disableFontFace: (0, _dom_utils.getDefaultSetting)('disableFontFace'), fontRegistry: fontRegistry }); var fontReady = function fontReady(fontObjs) { _this12.commonObjs.resolve(id, font); }; this.fontLoader.bind([font], fontReady); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: throw new Error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; (0, _util.loadJpegStream)(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: throw new Error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { throw new Error(data.error); } if (intentState.operatorList) { intentState.operatorList.lastChunk = true; for (var i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } } }, this); messageHandler.on('UnsupportedFeature', function (data) { if (this.destroyed) { return; } var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(data.featureId); } }, this); messageHandler.on('JpegDecode', function (data) { if (this.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } if (typeof document === 'undefined') { return Promise.reject(new Error('"document" is not defined.')); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject(new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = width; tmpCanvas.height = height; var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height }); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); messageHandler.on('FetchBuiltInCMap', function (data) { if (this.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } return this.CMapReaderFactory.fetch({ name: data.name }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { var _this13 = this; if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (_this13.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, _this13); _this13.pageCache[pageIndex] = page; return page; }); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) { return Promise.reject(new Error(reason)); }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getPageLabels: function WorkerTransport_getPageLabels() { return this.messageHandler.sendWithPromise('GetPageLabels', null); }, getPageMode: function getPageMode() { return this.messageHandler.sendWithPromise('GetPageMode', null); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) { return { info: results[0], metadata: results[1] ? new _metadata.Metadata(results[1]) : null }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { var _this14 = this; this.messageHandler.sendWithPromise('Cleanup', null).then(function () { for (var i = 0, ii = _this14.pageCache.length; i < ii; i++) { var page = _this14.pageCache[i]; if (page) { page.cleanup(); } } _this14.commonObjs.clear(); _this14.fontLoader.clear(); }); } }; return WorkerTransport; }(); var PDFObjects = function PDFObjectsClosure() { function PDFObjects() { this.objs = Object.create(null); } PDFObjects.prototype = { ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: (0, _util.createPromiseCapability)(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, get: function PDFObjects_get(objId, callback) { if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } var obj = this.objs[objId]; if (!obj || !obj.resolved) { throw new Error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } return objs[objId].resolved; }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } return objs[objId].data; }, clear: function PDFObjects_clear() { this.objs = Object.create(null); } }; return PDFObjects; }(); var RenderTask = function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; this.onContinue = null; } RenderTask.prototype = { get promise() { return this._internalRenderTask.capability.promise; }, cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; }(); var InternalRenderTask = function InternalRenderTaskClosure() { var canvasInRendering = new WeakMap(); function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber, canvasFactory) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.canvasFactory = canvasFactory; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = (0, _util.createPromiseCapability)(); this.task = new RenderTask(this); this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); this._canvas = params.canvasContext.canvas; } InternalRenderTask.prototype = { initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) { if (this._canvas) { if (canvasInRendering.has(this._canvas)) { throw new Error('Cannot use the same canvas during multiple render() operations. ' + 'Use different canvas or ensure previous operations were ' + 'cancelled or completed.'); } canvasInRendering.set(this._canvas, this); } if (this.cancelled) { return; } if ((0, _dom_utils.getDefaultSetting)('pdfBug') && _global_scope2.default.StepperManager && _global_scope2.default.StepperManager.enabled) { this.stepper = _global_scope2.default.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new _canvas.CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, this.canvasFactory, params.imageLayer); this.gfx.beginDrawing({ transform: params.transform, viewport: params.viewport, transparency: transparency, background: params.background }); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; if (this._canvas) { canvasInRendering.delete(this._canvas); } this.callback(new _dom_utils.RenderingCancelledException('Rendering cancelled, page ' + this.pageNumber, 'canvas')); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue(this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame && typeof window !== 'undefined') { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); if (this._canvas) { canvasInRendering.delete(this._canvas); } this.callback(); } } } }; return InternalRenderTask; }(); var version, build; { exports.version = version = '2.0.112'; exports.build = build = '9686f665'; } exports.getDocument = getDocument; exports.LoopbackPort = LoopbackPort; exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFWorker = PDFWorker; exports.PDFDocumentProxy = PDFDocumentProxy; exports.PDFPageProxy = PDFPageProxy; exports.setPDFNetworkStreamClass = setPDFNetworkStreamClass; exports.version = version; exports.build = build; /***/ }), /* 58 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebGLUtils = undefined; var _dom_utils = __w_pdfjs_require__(8); var _util = __w_pdfjs_require__(0); var WebGLUtils = function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = figures[i].coords.length / figures[i].verticesPerRow | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = ps.length / cols | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if ((0, _dom_utils.getDefaultSetting)('disableWebGL')) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) {} return (0, _util.shadow)(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; }(); exports.WebGLUtils = WebGLUtils; /***/ }), /* 59 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Metadata = undefined; 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 _util = __w_pdfjs_require__(0); var _dom_utils = __w_pdfjs_require__(8); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Metadata = function () { function Metadata(data) { _classCallCheck(this, Metadata); (0, _util.assert)(typeof data === 'string', 'Metadata: input is not a string'); data = this._repair(data); var parser = new _dom_utils.SimpleXMLParser(); data = parser.parseFromString(data); this._metadata = Object.create(null); this._parse(data); } _createClass(Metadata, [{ key: '_repair', value: function _repair(data) { return data.replace(/>\\376\\377([^<]+)/g, function (all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0, ii = bytes.length; i < ii; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); if (code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38) { chars += String.fromCharCode(code); } else { chars += '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } } return '>' + chars; }); } }, { key: '_parse', value: function _parse(domDocument) { var rdf = domDocument.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = rdf ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes; for (var i = 0, ii = children.length; i < ii; i++) { var desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (var j = 0, jj = desc.childNodes.length; j < jj; j++) { if (desc.childNodes[j].nodeName.toLowerCase() !== '#text') { var entry = desc.childNodes[j]; var name = entry.nodeName.toLowerCase(); this._metadata[name] = entry.textContent.trim(); } } } } }, { key: 'get', value: function get(name) { return this._metadata[name] || null; } }, { key: 'getAll', value: function getAll() { return this._metadata; } }, { key: 'has', value: function has(name) { return typeof this._metadata[name] !== 'undefined'; } }]); return Metadata; }(); exports.Metadata = Metadata; /***/ }), /* 60 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnnotationLayer = undefined; 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 _dom_utils = __w_pdfjs_require__(8); var _util = __w_pdfjs_require__(0); 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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var AnnotationElementFactory = function () { function AnnotationElementFactory() { _classCallCheck(this, AnnotationElementFactory); } _createClass(AnnotationElementFactory, null, [{ key: 'create', value: function create(parameters) { var subtype = parameters.data.annotationType; switch (subtype) { case _util.AnnotationType.LINK: return new LinkAnnotationElement(parameters); case _util.AnnotationType.TEXT: return new TextAnnotationElement(parameters); case _util.AnnotationType.WIDGET: var fieldType = parameters.data.fieldType; switch (fieldType) { case 'Tx': return new TextWidgetAnnotationElement(parameters); case 'Btn': if (parameters.data.radioButton) { return new RadioButtonWidgetAnnotationElement(parameters); } else if (parameters.data.checkBox) { return new CheckboxWidgetAnnotationElement(parameters); } (0, _util.warn)('Unimplemented button widget annotation: pushbutton'); break; case 'Ch': return new ChoiceWidgetAnnotationElement(parameters); } return new WidgetAnnotationElement(parameters); case _util.AnnotationType.POPUP: return new PopupAnnotationElement(parameters); case _util.AnnotationType.LINE: return new LineAnnotationElement(parameters); case _util.AnnotationType.SQUARE: return new SquareAnnotationElement(parameters); case _util.AnnotationType.CIRCLE: return new CircleAnnotationElement(parameters); case _util.AnnotationType.POLYLINE: return new PolylineAnnotationElement(parameters); case _util.AnnotationType.POLYGON: return new PolygonAnnotationElement(parameters); case _util.AnnotationType.HIGHLIGHT: return new HighlightAnnotationElement(parameters); case _util.AnnotationType.UNDERLINE: return new UnderlineAnnotationElement(parameters); case _util.AnnotationType.SQUIGGLY: return new SquigglyAnnotationElement(parameters); case _util.AnnotationType.STRIKEOUT: return new StrikeOutAnnotationElement(parameters); case _util.AnnotationType.STAMP: return new StampAnnotationElement(parameters); case _util.AnnotationType.FILEATTACHMENT: return new FileAttachmentAnnotationElement(parameters); default: return new AnnotationElement(parameters); } } }]); return AnnotationElementFactory; }(); var AnnotationElement = function () { function AnnotationElement(parameters) { var isRenderable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var ignoreBorder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; _classCallCheck(this, AnnotationElement); this.isRenderable = isRenderable; this.data = parameters.data; this.layer = parameters.layer; this.page = parameters.page; this.viewport = parameters.viewport; this.linkService = parameters.linkService; this.downloadManager = parameters.downloadManager; this.imageResourcesPath = parameters.imageResourcesPath; this.renderInteractiveForms = parameters.renderInteractiveForms; this.svgFactory = parameters.svgFactory; if (isRenderable) { this.container = this._createContainer(ignoreBorder); } } _createClass(AnnotationElement, [{ key: '_createContainer', value: function _createContainer() { var ignoreBorder = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var data = this.data, page = this.page, viewport = this.viewport; var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); var rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]); _dom_utils.CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); _dom_utils.CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px'); if (!ignoreBorder && data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) { width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; _dom_utils.CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case _util.AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case _util.AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case _util.AnnotationBorderStyleType.BEVELED: (0, _util.warn)('Unimplemented border style: beveled'); break; case _util.AnnotationBorderStyleType.INSET: (0, _util.warn)('Unimplemented border style: inset'); break; case _util.AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = _util.Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { container.style.borderWidth = 0; } } container.style.left = rect[0] + 'px'; container.style.top = rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; } }, { key: '_createPopup', value: function _createPopup(container, trigger, data) { if (!trigger) { trigger = document.createElement('div'); trigger.style.height = container.style.height; trigger.style.width = container.style.width; container.appendChild(trigger); } var popupElement = new PopupElement({ container: container, trigger: trigger, color: data.color, title: data.title, contents: data.contents, hideWrapper: true }); var popup = popupElement.render(); popup.style.left = container.style.width; container.appendChild(popup); } }, { key: 'render', value: function render() { throw new Error('Abstract method `AnnotationElement.render` called'); } }]); return AnnotationElement; }(); var LinkAnnotationElement = function (_AnnotationElement) { _inherits(LinkAnnotationElement, _AnnotationElement); function LinkAnnotationElement(parameters) { _classCallCheck(this, LinkAnnotationElement); var isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action); return _possibleConstructorReturn(this, (LinkAnnotationElement.__proto__ || Object.getPrototypeOf(LinkAnnotationElement)).call(this, parameters, isRenderable)); } _createClass(LinkAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'linkAnnotation'; var link = document.createElement('a'); (0, _dom_utils.addLinkAttributes)(link, { url: this.data.url, target: this.data.newWindow ? _dom_utils.LinkTarget.BLANK : undefined }); if (!this.data.url) { if (this.data.action) { this._bindNamedAction(link, this.data.action); } else { this._bindLink(link, this.data.dest); } } this.container.appendChild(link); return this.container; } }, { key: '_bindLink', value: function _bindLink(link, destination) { var _this2 = this; link.href = this.linkService.getDestinationHash(destination); link.onclick = function () { if (destination) { _this2.linkService.navigateTo(destination); } return false; }; if (destination) { link.className = 'internalLink'; } } }, { key: '_bindNamedAction', value: function _bindNamedAction(link, action) { var _this3 = this; link.href = this.linkService.getAnchorUrl(''); link.onclick = function () { _this3.linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } }]); return LinkAnnotationElement; }(AnnotationElement); var TextAnnotationElement = function (_AnnotationElement2) { _inherits(TextAnnotationElement, _AnnotationElement2); function TextAnnotationElement(parameters) { _classCallCheck(this, TextAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (TextAnnotationElement.__proto__ || Object.getPrototypeOf(TextAnnotationElement)).call(this, parameters, isRenderable)); } _createClass(TextAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'textAnnotation'; var image = document.createElement('img'); image.style.height = this.container.style.height; image.style.width = this.container.style.width; image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({ type: this.data.name }); if (!this.data.hasPopup) { this._createPopup(this.container, image, this.data); } this.container.appendChild(image); return this.container; } }]); return TextAnnotationElement; }(AnnotationElement); var WidgetAnnotationElement = function (_AnnotationElement3) { _inherits(WidgetAnnotationElement, _AnnotationElement3); function WidgetAnnotationElement() { _classCallCheck(this, WidgetAnnotationElement); return _possibleConstructorReturn(this, (WidgetAnnotationElement.__proto__ || Object.getPrototypeOf(WidgetAnnotationElement)).apply(this, arguments)); } _createClass(WidgetAnnotationElement, [{ key: 'render', value: function render() { return this.container; } }]); return WidgetAnnotationElement; }(AnnotationElement); var TextWidgetAnnotationElement = function (_WidgetAnnotationElem) { _inherits(TextWidgetAnnotationElement, _WidgetAnnotationElem); function TextWidgetAnnotationElement(parameters) { _classCallCheck(this, TextWidgetAnnotationElement); var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue; return _possibleConstructorReturn(this, (TextWidgetAnnotationElement.__proto__ || Object.getPrototypeOf(TextWidgetAnnotationElement)).call(this, parameters, isRenderable)); } _createClass(TextWidgetAnnotationElement, [{ key: 'render', value: function render() { var TEXT_ALIGNMENT = ['left', 'center', 'right']; this.container.className = 'textWidgetAnnotation'; var element = null; if (this.renderInteractiveForms) { if (this.data.multiLine) { element = document.createElement('textarea'); element.textContent = this.data.fieldValue; } else { element = document.createElement('input'); element.type = 'text'; element.setAttribute('value', this.data.fieldValue); } element.disabled = this.data.readOnly; if (this.data.maxLen !== null) { element.maxLength = this.data.maxLen; } if (this.data.comb) { var fieldWidth = this.data.rect[2] - this.data.rect[0]; var combWidth = fieldWidth / this.data.maxLen; element.classList.add('comb'); element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)'; } } else { element = document.createElement('div'); element.textContent = this.data.fieldValue; element.style.verticalAlign = 'middle'; element.style.display = 'table-cell'; var font = null; if (this.data.fontRefName) { font = this.page.commonObjs.getData(this.data.fontRefName); } this._setTextStyle(element, font); } if (this.data.textAlignment !== null) { element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; } this.container.appendChild(element); return this.container; } }, { key: '_setTextStyle', value: function _setTextStyle(element, font) { var style = element.style; style.fontSize = this.data.fontSize + 'px'; style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr'; if (!font) { return; } style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal'; style.fontStyle = font.italic ? 'italic' : 'normal'; var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : ''; var fallbackName = font.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } }]); return TextWidgetAnnotationElement; }(WidgetAnnotationElement); var CheckboxWidgetAnnotationElement = function (_WidgetAnnotationElem2) { _inherits(CheckboxWidgetAnnotationElement, _WidgetAnnotationElem2); function CheckboxWidgetAnnotationElement(parameters) { _classCallCheck(this, CheckboxWidgetAnnotationElement); return _possibleConstructorReturn(this, (CheckboxWidgetAnnotationElement.__proto__ || Object.getPrototypeOf(CheckboxWidgetAnnotationElement)).call(this, parameters, parameters.renderInteractiveForms)); } _createClass(CheckboxWidgetAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'buttonWidgetAnnotation checkBox'; var element = document.createElement('input'); element.disabled = this.data.readOnly; element.type = 'checkbox'; if (this.data.fieldValue && this.data.fieldValue !== 'Off') { element.setAttribute('checked', true); } this.container.appendChild(element); return this.container; } }]); return CheckboxWidgetAnnotationElement; }(WidgetAnnotationElement); var RadioButtonWidgetAnnotationElement = function (_WidgetAnnotationElem3) { _inherits(RadioButtonWidgetAnnotationElement, _WidgetAnnotationElem3); function RadioButtonWidgetAnnotationElement(parameters) { _classCallCheck(this, RadioButtonWidgetAnnotationElement); return _possibleConstructorReturn(this, (RadioButtonWidgetAnnotationElement.__proto__ || Object.getPrototypeOf(RadioButtonWidgetAnnotationElement)).call(this, parameters, parameters.renderInteractiveForms)); } _createClass(RadioButtonWidgetAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'buttonWidgetAnnotation radioButton'; var element = document.createElement('input'); element.disabled = this.data.readOnly; element.type = 'radio'; element.name = this.data.fieldName; if (this.data.fieldValue === this.data.buttonValue) { element.setAttribute('checked', true); } this.container.appendChild(element); return this.container; } }]); return RadioButtonWidgetAnnotationElement; }(WidgetAnnotationElement); var ChoiceWidgetAnnotationElement = function (_WidgetAnnotationElem4) { _inherits(ChoiceWidgetAnnotationElement, _WidgetAnnotationElem4); function ChoiceWidgetAnnotationElement(parameters) { _classCallCheck(this, ChoiceWidgetAnnotationElement); return _possibleConstructorReturn(this, (ChoiceWidgetAnnotationElement.__proto__ || Object.getPrototypeOf(ChoiceWidgetAnnotationElement)).call(this, parameters, parameters.renderInteractiveForms)); } _createClass(ChoiceWidgetAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'choiceWidgetAnnotation'; var selectElement = document.createElement('select'); selectElement.disabled = this.data.readOnly; if (!this.data.combo) { selectElement.size = this.data.options.length; if (this.data.multiSelect) { selectElement.multiple = true; } } for (var i = 0, ii = this.data.options.length; i < ii; i++) { var option = this.data.options[i]; var optionElement = document.createElement('option'); optionElement.textContent = option.displayValue; optionElement.value = option.exportValue; if (this.data.fieldValue.indexOf(option.displayValue) >= 0) { optionElement.setAttribute('selected', true); } selectElement.appendChild(optionElement); } this.container.appendChild(selectElement); return this.container; } }]); return ChoiceWidgetAnnotationElement; }(WidgetAnnotationElement); var PopupAnnotationElement = function (_AnnotationElement4) { _inherits(PopupAnnotationElement, _AnnotationElement4); function PopupAnnotationElement(parameters) { _classCallCheck(this, PopupAnnotationElement); var isRenderable = !!(parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (PopupAnnotationElement.__proto__ || Object.getPrototypeOf(PopupAnnotationElement)).call(this, parameters, isRenderable)); } _createClass(PopupAnnotationElement, [{ key: 'render', value: function render() { var IGNORE_TYPES = ['Line', 'Square', 'Circle', 'PolyLine', 'Polygon']; this.container.className = 'popupAnnotation'; if (IGNORE_TYPES.indexOf(this.data.parentType) >= 0) { return this.container; } var selector = '[data-annotation-id="' + this.data.parentId + '"]'; var parentElement = this.layer.querySelector(selector); if (!parentElement) { return this.container; } var popup = new PopupElement({ container: this.container, trigger: parentElement, color: this.data.color, title: this.data.title, contents: this.data.contents }); var parentLeft = parseFloat(parentElement.style.left); var parentWidth = parseFloat(parentElement.style.width); _dom_utils.CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top); this.container.style.left = parentLeft + parentWidth + 'px'; this.container.appendChild(popup.render()); return this.container; } }]); return PopupAnnotationElement; }(AnnotationElement); var PopupElement = function () { function PopupElement(parameters) { _classCallCheck(this, PopupElement); this.container = parameters.container; this.trigger = parameters.trigger; this.color = parameters.color; this.title = parameters.title; this.contents = parameters.contents; this.hideWrapper = parameters.hideWrapper || false; this.pinned = false; } _createClass(PopupElement, [{ key: 'render', value: function render() { var BACKGROUND_ENLIGHT = 0.7; var wrapper = document.createElement('div'); wrapper.className = 'popupWrapper'; this.hideElement = this.hideWrapper ? wrapper : this.container; this.hideElement.setAttribute('hidden', true); var popup = document.createElement('div'); popup.className = 'popup'; var color = this.color; if (color) { var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; popup.style.backgroundColor = _util.Util.makeCssRgb(r | 0, g | 0, b | 0); } var contents = this._formatContents(this.contents); var title = document.createElement('h1'); title.textContent = this.title; this.trigger.addEventListener('click', this._toggle.bind(this)); this.trigger.addEventListener('mouseover', this._show.bind(this, false)); this.trigger.addEventListener('mouseout', this._hide.bind(this, false)); popup.addEventListener('click', this._hide.bind(this, true)); popup.appendChild(title); popup.appendChild(contents); wrapper.appendChild(popup); return wrapper; } }, { key: '_formatContents', value: function _formatContents(contents) { var p = document.createElement('p'); var lines = contents.split(/(?:\r\n?|\n)/); for (var i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; p.appendChild(document.createTextNode(line)); if (i < ii - 1) { p.appendChild(document.createElement('br')); } } return p; } }, { key: '_toggle', value: function _toggle() { if (this.pinned) { this._hide(true); } else { this._show(true); } } }, { key: '_show', value: function _show() { var pin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (pin) { this.pinned = true; } if (this.hideElement.hasAttribute('hidden')) { this.hideElement.removeAttribute('hidden'); this.container.style.zIndex += 1; } } }, { key: '_hide', value: function _hide() { var unpin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; if (unpin) { this.pinned = false; } if (!this.hideElement.hasAttribute('hidden') && !this.pinned) { this.hideElement.setAttribute('hidden', true); this.container.style.zIndex -= 1; } } }]); return PopupElement; }(); var LineAnnotationElement = function (_AnnotationElement5) { _inherits(LineAnnotationElement, _AnnotationElement5); function LineAnnotationElement(parameters) { _classCallCheck(this, LineAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (LineAnnotationElement.__proto__ || Object.getPrototypeOf(LineAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(LineAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'lineAnnotation'; var data = this.data; var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; var svg = this.svgFactory.create(width, height); var line = this.svgFactory.createElement('svg:line'); line.setAttribute('x1', data.rect[2] - data.lineCoordinates[0]); line.setAttribute('y1', data.rect[3] - data.lineCoordinates[1]); line.setAttribute('x2', data.rect[2] - data.lineCoordinates[2]); line.setAttribute('y2', data.rect[3] - data.lineCoordinates[3]); line.setAttribute('stroke-width', data.borderStyle.width); line.setAttribute('stroke', 'transparent'); svg.appendChild(line); this.container.append(svg); this._createPopup(this.container, line, data); return this.container; } }]); return LineAnnotationElement; }(AnnotationElement); var SquareAnnotationElement = function (_AnnotationElement6) { _inherits(SquareAnnotationElement, _AnnotationElement6); function SquareAnnotationElement(parameters) { _classCallCheck(this, SquareAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (SquareAnnotationElement.__proto__ || Object.getPrototypeOf(SquareAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(SquareAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'squareAnnotation'; var data = this.data; var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; var svg = this.svgFactory.create(width, height); var borderWidth = data.borderStyle.width; var square = this.svgFactory.createElement('svg:rect'); square.setAttribute('x', borderWidth / 2); square.setAttribute('y', borderWidth / 2); square.setAttribute('width', width - borderWidth); square.setAttribute('height', height - borderWidth); square.setAttribute('stroke-width', borderWidth); square.setAttribute('stroke', 'transparent'); square.setAttribute('fill', 'none'); svg.appendChild(square); this.container.append(svg); this._createPopup(this.container, square, data); return this.container; } }]); return SquareAnnotationElement; }(AnnotationElement); var CircleAnnotationElement = function (_AnnotationElement7) { _inherits(CircleAnnotationElement, _AnnotationElement7); function CircleAnnotationElement(parameters) { _classCallCheck(this, CircleAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (CircleAnnotationElement.__proto__ || Object.getPrototypeOf(CircleAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(CircleAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'circleAnnotation'; var data = this.data; var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; var svg = this.svgFactory.create(width, height); var borderWidth = data.borderStyle.width; var circle = this.svgFactory.createElement('svg:ellipse'); circle.setAttribute('cx', width / 2); circle.setAttribute('cy', height / 2); circle.setAttribute('rx', width / 2 - borderWidth / 2); circle.setAttribute('ry', height / 2 - borderWidth / 2); circle.setAttribute('stroke-width', borderWidth); circle.setAttribute('stroke', 'transparent'); circle.setAttribute('fill', 'none'); svg.appendChild(circle); this.container.append(svg); this._createPopup(this.container, circle, data); return this.container; } }]); return CircleAnnotationElement; }(AnnotationElement); var PolylineAnnotationElement = function (_AnnotationElement8) { _inherits(PolylineAnnotationElement, _AnnotationElement8); function PolylineAnnotationElement(parameters) { _classCallCheck(this, PolylineAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); var _this14 = _possibleConstructorReturn(this, (PolylineAnnotationElement.__proto__ || Object.getPrototypeOf(PolylineAnnotationElement)).call(this, parameters, isRenderable, true)); _this14.containerClassName = 'polylineAnnotation'; _this14.svgElementName = 'svg:polyline'; return _this14; } _createClass(PolylineAnnotationElement, [{ key: 'render', value: function render() { this.container.className = this.containerClassName; var data = this.data; var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; var svg = this.svgFactory.create(width, height); var vertices = data.vertices; var points = []; for (var i = 0, ii = vertices.length; i < ii; i++) { var x = vertices[i].x - data.rect[0]; var y = data.rect[3] - vertices[i].y; points.push(x + ',' + y); } points = points.join(' '); var borderWidth = data.borderStyle.width; var polyline = this.svgFactory.createElement(this.svgElementName); polyline.setAttribute('points', points); polyline.setAttribute('stroke-width', borderWidth); polyline.setAttribute('stroke', 'transparent'); polyline.setAttribute('fill', 'none'); svg.appendChild(polyline); this.container.append(svg); this._createPopup(this.container, polyline, data); return this.container; } }]); return PolylineAnnotationElement; }(AnnotationElement); var PolygonAnnotationElement = function (_PolylineAnnotationEl) { _inherits(PolygonAnnotationElement, _PolylineAnnotationEl); function PolygonAnnotationElement(parameters) { _classCallCheck(this, PolygonAnnotationElement); var _this15 = _possibleConstructorReturn(this, (PolygonAnnotationElement.__proto__ || Object.getPrototypeOf(PolygonAnnotationElement)).call(this, parameters)); _this15.containerClassName = 'polygonAnnotation'; _this15.svgElementName = 'svg:polygon'; return _this15; } return PolygonAnnotationElement; }(PolylineAnnotationElement); var HighlightAnnotationElement = function (_AnnotationElement9) { _inherits(HighlightAnnotationElement, _AnnotationElement9); function HighlightAnnotationElement(parameters) { _classCallCheck(this, HighlightAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (HighlightAnnotationElement.__proto__ || Object.getPrototypeOf(HighlightAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(HighlightAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'highlightAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }]); return HighlightAnnotationElement; }(AnnotationElement); var UnderlineAnnotationElement = function (_AnnotationElement10) { _inherits(UnderlineAnnotationElement, _AnnotationElement10); function UnderlineAnnotationElement(parameters) { _classCallCheck(this, UnderlineAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (UnderlineAnnotationElement.__proto__ || Object.getPrototypeOf(UnderlineAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(UnderlineAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'underlineAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }]); return UnderlineAnnotationElement; }(AnnotationElement); var SquigglyAnnotationElement = function (_AnnotationElement11) { _inherits(SquigglyAnnotationElement, _AnnotationElement11); function SquigglyAnnotationElement(parameters) { _classCallCheck(this, SquigglyAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (SquigglyAnnotationElement.__proto__ || Object.getPrototypeOf(SquigglyAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(SquigglyAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'squigglyAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }]); return SquigglyAnnotationElement; }(AnnotationElement); var StrikeOutAnnotationElement = function (_AnnotationElement12) { _inherits(StrikeOutAnnotationElement, _AnnotationElement12); function StrikeOutAnnotationElement(parameters) { _classCallCheck(this, StrikeOutAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (StrikeOutAnnotationElement.__proto__ || Object.getPrototypeOf(StrikeOutAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(StrikeOutAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'strikeoutAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }]); return StrikeOutAnnotationElement; }(AnnotationElement); var StampAnnotationElement = function (_AnnotationElement13) { _inherits(StampAnnotationElement, _AnnotationElement13); function StampAnnotationElement(parameters) { _classCallCheck(this, StampAnnotationElement); var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); return _possibleConstructorReturn(this, (StampAnnotationElement.__proto__ || Object.getPrototypeOf(StampAnnotationElement)).call(this, parameters, isRenderable, true)); } _createClass(StampAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'stampAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }]); return StampAnnotationElement; }(AnnotationElement); var FileAttachmentAnnotationElement = function (_AnnotationElement14) { _inherits(FileAttachmentAnnotationElement, _AnnotationElement14); function FileAttachmentAnnotationElement(parameters) { _classCallCheck(this, FileAttachmentAnnotationElement); var _this21 = _possibleConstructorReturn(this, (FileAttachmentAnnotationElement.__proto__ || Object.getPrototypeOf(FileAttachmentAnnotationElement)).call(this, parameters, true)); var file = _this21.data.file; _this21.filename = (0, _dom_utils.getFilenameFromUrl)(file.filename); _this21.content = file.content; _this21.linkService.onFileAttachmentAnnotation({ id: (0, _util.stringToPDFString)(file.filename), filename: file.filename, content: file.content }); return _this21; } _createClass(FileAttachmentAnnotationElement, [{ key: 'render', value: function render() { this.container.className = 'fileAttachmentAnnotation'; var trigger = document.createElement('div'); trigger.style.height = this.container.style.height; trigger.style.width = this.container.style.width; trigger.addEventListener('dblclick', this._download.bind(this)); if (!this.data.hasPopup && (this.data.title || this.data.contents)) { this._createPopup(this.container, trigger, this.data); } this.container.appendChild(trigger); return this.container; } }, { key: '_download', value: function _download() { if (!this.downloadManager) { (0, _util.warn)('Download cannot be started due to unavailable download manager'); return; } this.downloadManager.downloadData(this.content, this.filename, ''); } }]); return FileAttachmentAnnotationElement; }(AnnotationElement); var AnnotationLayer = function () { function AnnotationLayer() { _classCallCheck(this, AnnotationLayer); } _createClass(AnnotationLayer, null, [{ key: 'render', value: function render(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; if (!data) { continue; } var element = AnnotationElementFactory.create({ data: data, layer: parameters.div, page: parameters.page, viewport: parameters.viewport, linkService: parameters.linkService, downloadManager: parameters.downloadManager, imageResourcesPath: parameters.imageResourcesPath || (0, _dom_utils.getDefaultSetting)('imageResourcesPath'), renderInteractiveForms: parameters.renderInteractiveForms || false, svgFactory: new _dom_utils.DOMSVGFactory() }); if (element.isRenderable) { parameters.div.appendChild(element.render()); } } } }, { key: 'update', value: function update(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]'); if (element) { _dom_utils.CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')'); } } parameters.div.removeAttribute('hidden'); } }]); return AnnotationLayer; }(); exports.AnnotationLayer = AnnotationLayer; /***/ }), /* 61 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.renderTextLayer = undefined; var _util = __w_pdfjs_require__(0); var _dom_utils = __w_pdfjs_require__(8); var renderTextLayer = function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0, 'px; font-family: ', '', ';']; function appendText(task, geom, styles) { var textDiv = document.createElement('div'); var textDivProperties = { style: null, angle: 0, canvasWidth: 0, isWhitespace: false, originalTransform: null, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, paddingTop: 0, scale: 1 }; task._textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDivProperties.isWhitespace = true; task._textDivProperties.set(textDiv, textDivProperties); return; } var tx = _util.Util.transform(task._viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); var style = styles[geom.fontName]; if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + fontAscent * Math.sin(angle); top = tx[5] - fontAscent * Math.cos(angle); } styleBuf[1] = left; styleBuf[3] = top; styleBuf[5] = fontHeight; styleBuf[7] = style.fontFamily; textDivProperties.style = styleBuf.join(''); textDiv.setAttribute('style', textDivProperties.style); textDiv.textContent = geom.str; if ((0, _dom_utils.getDefaultSetting)('pdfBug')) { textDiv.dataset.fontName = geom.fontName; } if (angle !== 0) { textDivProperties.angle = angle * (180 / Math.PI); } if (geom.str.length > 1) { if (style.vertical) { textDivProperties.canvasWidth = geom.height * task._viewport.scale; } else { textDivProperties.canvasWidth = geom.width * task._viewport.scale; } } task._textDivProperties.set(textDiv, textDivProperties); if (task._textContentStream) { task._layoutText(textDiv); } if (task._enhanceTextSelection) { var angleCos = 1, angleSin = 0; if (angle !== 0) { angleCos = Math.cos(angle); angleSin = Math.sin(angle); } var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale; var divHeight = fontHeight; var m, b; if (angle !== 0) { m = [angleCos, angleSin, -angleSin, angleCos, left, top]; b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m); } else { b = [left, top, left + divWidth, top + divHeight]; } task._bounds.push({ left: b[0], top: b[1], right: b[2], bottom: b[3], div: textDiv, size: [divWidth, divHeight], m: m }); } } function render(task) { if (task._canceled) { return; } var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { task._renderingDone = true; capability.resolve(); return; } if (!task._textContentStream) { for (var i = 0; i < textDivsLength; i++) { task._layoutText(textDivs[i]); } } task._renderingDone = true; capability.resolve(); } function expand(task) { var bounds = task._bounds; var viewport = task._viewport; var expanded = expandBounds(viewport.width, viewport.height, bounds); for (var i = 0; i < expanded.length; i++) { var div = bounds[i].div; var divProperties = task._textDivProperties.get(div); if (divProperties.angle === 0) { divProperties.paddingLeft = bounds[i].left - expanded[i].left; divProperties.paddingTop = bounds[i].top - expanded[i].top; divProperties.paddingRight = expanded[i].right - bounds[i].right; divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom; task._textDivProperties.set(div, divProperties); continue; } var e = expanded[i], b = bounds[i]; var m = b.m, c = m[0], s = m[1]; var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size]; var ts = new Float64Array(64); points.forEach(function (p, i) { var t = _util.Util.applyTransform(p, m); ts[i + 0] = c && (e.left - t[0]) / c; ts[i + 4] = s && (e.top - t[1]) / s; ts[i + 8] = c && (e.right - t[0]) / c; ts[i + 12] = s && (e.bottom - t[1]) / s; ts[i + 16] = s && (e.left - t[0]) / -s; ts[i + 20] = c && (e.top - t[1]) / c; ts[i + 24] = s && (e.right - t[0]) / -s; ts[i + 28] = c && (e.bottom - t[1]) / c; ts[i + 32] = c && (e.left - t[0]) / -c; ts[i + 36] = s && (e.top - t[1]) / -s; ts[i + 40] = c && (e.right - t[0]) / -c; ts[i + 44] = s && (e.bottom - t[1]) / -s; ts[i + 48] = s && (e.left - t[0]) / s; ts[i + 52] = c && (e.top - t[1]) / -c; ts[i + 56] = s && (e.right - t[0]) / s; ts[i + 60] = c && (e.bottom - t[1]) / -c; }); var findPositiveMin = function findPositiveMin(ts, offset, count) { var result = 0; for (var i = 0; i < count; i++) { var t = ts[offset++]; if (t > 0) { result = result ? Math.min(t, result) : t; } } return result; }; var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s)); divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale; divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale; divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale; divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale; task._textDivProperties.set(div, divProperties); } } function expandBounds(width, height, boxes) { var bounds = boxes.map(function (box, i) { return { x1: box.left, y1: box.top, x2: box.right, y2: box.bottom, index: i, x1New: undefined, x2New: undefined }; }); expandBoundsLTR(width, bounds); var expanded = new Array(boxes.length); bounds.forEach(function (b) { var i = b.index; expanded[i] = { left: b.x1New, top: 0, right: b.x2New, bottom: 0 }; }); boxes.map(function (box, i) { var e = expanded[i], b = bounds[i]; b.x1 = box.top; b.y1 = width - e.right; b.x2 = box.bottom; b.y2 = width - e.left; b.index = i; b.x1New = undefined; b.x2New = undefined; }); expandBoundsLTR(height, bounds); bounds.forEach(function (b) { var i = b.index; expanded[i].top = b.x1New; expanded[i].bottom = b.x2New; }); return expanded; } function expandBoundsLTR(width, bounds) { bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; }); var fakeBoundary = { x1: -Infinity, y1: -Infinity, x2: 0, y2: Infinity, index: -1, x1New: 0, x2New: 0 }; var horizon = [{ start: -Infinity, end: Infinity, boundary: fakeBoundary }]; bounds.forEach(function (boundary) { var i = 0; while (i < horizon.length && horizon[i].end <= boundary.y1) { i++; } var j = horizon.length - 1; while (j >= 0 && horizon[j].start >= boundary.y2) { j--; } var horizonPart, affectedBoundary; var q, k, maxXNew = -Infinity; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; var xNew; if (affectedBoundary.x2 > boundary.x1) { xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1; } else if (affectedBoundary.x2New === undefined) { xNew = (affectedBoundary.x2 + boundary.x1) / 2; } else { xNew = affectedBoundary.x2New; } if (xNew > maxXNew) { maxXNew = xNew; } } boundary.x1New = maxXNew; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { if (affectedBoundary.x2 > boundary.x1) { if (affectedBoundary.index > boundary.index) { affectedBoundary.x2New = affectedBoundary.x2; } } else { affectedBoundary.x2New = maxXNew; } } else if (affectedBoundary.x2New > maxXNew) { affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2); } } var changedHorizon = [], lastBoundary = null; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary; if (lastBoundary === useBoundary) { changedHorizon[changedHorizon.length - 1].end = horizonPart.end; } else { changedHorizon.push({ start: horizonPart.start, end: horizonPart.end, boundary: useBoundary }); lastBoundary = useBoundary; } } if (horizon[i].start < boundary.y1) { changedHorizon[0].start = boundary.y1; changedHorizon.unshift({ start: horizon[i].start, end: boundary.y1, boundary: horizon[i].boundary }); } if (boundary.y2 < horizon[j].end) { changedHorizon[changedHorizon.length - 1].end = boundary.y2; changedHorizon.push({ start: boundary.y2, end: horizon[j].end, boundary: horizon[j].boundary }); } for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New !== undefined) { continue; } var used = false; for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) { used = horizon[k].boundary === affectedBoundary; } for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) { used = horizon[k].boundary === affectedBoundary; } for (k = 0; !used && k < changedHorizon.length; k++) { used = changedHorizon[k].boundary === affectedBoundary; } if (!used) { affectedBoundary.x2New = maxXNew; } } Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon)); }); horizon.forEach(function (horizonPart) { var affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { affectedBoundary.x2New = Math.max(width, affectedBoundary.x2); } }); } function TextLayerRenderTask(_ref) { var textContent = _ref.textContent, textContentStream = _ref.textContentStream, container = _ref.container, viewport = _ref.viewport, textDivs = _ref.textDivs, textContentItemsStr = _ref.textContentItemsStr, enhanceTextSelection = _ref.enhanceTextSelection; this._textContent = textContent; this._textContentStream = textContentStream; this._container = container; this._viewport = viewport; this._textDivs = textDivs || []; this._textContentItemsStr = textContentItemsStr || []; this._enhanceTextSelection = !!enhanceTextSelection; this._reader = null; this._layoutTextLastFontSize = null; this._layoutTextLastFontFamily = null; this._layoutTextCtx = null; this._textDivProperties = new WeakMap(); this._renderingDone = false; this._canceled = false; this._capability = (0, _util.createPromiseCapability)(); this._renderTimer = null; this._bounds = []; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { if (this._reader) { this._reader.cancel(new _util.AbortException('text layer task cancelled')); this._reader = null; } this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _processItems: function _processItems(items, styleCache) { for (var i = 0, len = items.length; i < len; i++) { this._textContentItemsStr.push(items[i].str); appendText(this, items[i], styleCache); } }, _layoutText: function _layoutText(textDiv) { var textLayerFrag = this._container; var textDivProperties = this._textDivProperties.get(textDiv); if (textDivProperties.isWhitespace) { return; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) { this._layoutTextCtx.font = fontSize + ' ' + fontFamily; this._lastFontSize = fontSize; this._lastFontFamily = fontFamily; } var width = this._layoutTextCtx.measureText(textDiv.textContent).width; var transform = ''; if (textDivProperties.canvasWidth !== 0 && width > 0) { textDivProperties.scale = textDivProperties.canvasWidth / width; transform = 'scaleX(' + textDivProperties.scale + ')'; } if (textDivProperties.angle !== 0) { transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform; } if (transform !== '') { textDivProperties.originalTransform = transform; _dom_utils.CustomStyle.setProp('transform', textDiv, transform); } this._textDivProperties.set(textDiv, textDivProperties); textLayerFrag.appendChild(textDiv); }, _render: function TextLayer_render(timeout) { var _this = this; var capability = (0, _util.createPromiseCapability)(); var styleCache = Object.create(null); var canvas = document.createElement('canvas'); canvas.mozOpaque = true; this._layoutTextCtx = canvas.getContext('2d', { alpha: false }); if (this._textContent) { var textItems = this._textContent.items; var textStyles = this._textContent.styles; this._processItems(textItems, textStyles); capability.resolve(); } else if (this._textContentStream) { var pump = function pump() { _this._reader.read().then(function (_ref2) { var value = _ref2.value, done = _ref2.done; if (done) { capability.resolve(); return; } _util.Util.extendObj(styleCache, value.styles); _this._processItems(value.items, styleCache); pump(); }, capability.reject); }; this._reader = this._textContentStream.getReader(); pump(); } else { throw new Error('Neither "textContent" nor "textContentStream"' + ' parameters specified.'); } capability.promise.then(function () { styleCache = null; if (!timeout) { render(_this); } else { _this._renderTimer = setTimeout(function () { render(_this); _this._renderTimer = null; }, timeout); } }, this._capability.reject); }, expandTextDivs: function TextLayer_expandTextDivs(expandDivs) { if (!this._enhanceTextSelection || !this._renderingDone) { return; } if (this._bounds !== null) { expand(this); this._bounds = null; } for (var i = 0, ii = this._textDivs.length; i < ii; i++) { var div = this._textDivs[i]; var divProperties = this._textDivProperties.get(div); if (divProperties.isWhitespace) { continue; } if (expandDivs) { var transform = '', padding = ''; if (divProperties.scale !== 1) { transform = 'scaleX(' + divProperties.scale + ')'; } if (divProperties.angle !== 0) { transform = 'rotate(' + divProperties.angle + 'deg) ' + transform; } if (divProperties.paddingLeft !== 0) { padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;'; transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)'; } if (divProperties.paddingTop !== 0) { padding += ' padding-top: ' + divProperties.paddingTop + 'px;'; transform += ' translateY(' + -divProperties.paddingTop + 'px)'; } if (divProperties.paddingRight !== 0) { padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;'; } if (divProperties.paddingBottom !== 0) { padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;'; } if (padding !== '') { div.setAttribute('style', divProperties.style + padding); } if (transform !== '') { _dom_utils.CustomStyle.setProp('transform', div, transform); } } else { div.style.padding = 0; _dom_utils.CustomStyle.setProp('transform', div, divProperties.originalTransform || ''); } } } }; function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask({ textContent: renderParameters.textContent, textContentStream: renderParameters.textContentStream, container: renderParameters.container, viewport: renderParameters.viewport, textDivs: renderParameters.textDivs, textContentItemsStr: renderParameters.textContentItemsStr, enhanceTextSelection: renderParameters.enhanceTextSelection }); task._render(renderParameters.timeout); return task; } return renderTextLayer; }(); exports.renderTextLayer = renderTextLayer; /***/ }), /* 62 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SVGGraphics = undefined; var _util = __w_pdfjs_require__(0); var _dom_utils = __w_pdfjs_require__(8); var SVGGraphics = function SVGGraphics() { throw new Error('Not implemented: SVGGraphics'); }; { var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ c >> 1 & 0x7fffffff; } else { c = c >> 1 & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = crc >>> 8 ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return b << 16 | a; } function deflateSync(literals) { if (!(0, _util.isNodeJS)()) { return deflateSyncUncompressed(literals); } try { var input; if (parseInt(process.versions.node) >= 8) { input = literals; } else { input = new Buffer(literals); } var output = require('zlib').deflateSync(input, { level: 9 }); return output instanceof Uint8Array ? output : new Uint8Array(output); } catch (e) { (0, _util.warn)('Not compressing PNG because zlib.deflateSync is unavailable: ' + e); } return deflateSyncUncompressed(literals); } function deflateSyncUncompressed(literals) { var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; idat[pi++] = 0x9c; var pos = 0; while (len > maxBlockLength) { idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = ~len & 0xffff & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; return idat; } function encode(imgData, kind, forceDataSchema) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case _util.ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = width + 7 >> 3; break; case _util.ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case _util.ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === _util.ImageKind.GRAYSCALE_1BPP) { offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]); var idat = deflateSync(literals); var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return (0, _util.createObjectURL)(data, 'image/png', forceDataSchema); } return function convertImgDataToPng(imgData, forceDataSchema) { var kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind; return encode(imgData, kind, forceDataSchema); }; }(); var SVGExtraState = function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = _util.IDENTITY_MATRIX; this.fontMatrix = _util.FONT_IDENTITY_MATRIX; this.leading = 0; this.x = 0; this.y = 0; this.lineX = 0; this.lineY = 0; this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; this.activeClipUrl = null; this.clipGroup = null; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; }(); exports.SVGGraphics = SVGGraphics = function SVGGraphicsClosure() { function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({ 'fnId': 92, 'fn': 'group', 'items': [] }); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if (opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } function pf(value) { if (Number.isInteger(value)) { return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs, forceDataSchema) { this.svgFactory = new _dom_utils.DOMSVGFactory(); this.current = new SVGExtraState(); this.transformMatrix = _util.IDENTITY_MATRIX; this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingClip = null; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = Object.create(null); this.cssStyle = null; this.forceDataSchema = !!forceDataSchema; } var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.pendingClip = null; this.tgrp = null; }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var _this = this; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; for (var i = 0; i < fnArrayLen; i++) { if (_util.OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function (resolve) { _this.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function (resolve) { _this.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = null; }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { var _this2 = this; this.viewport = viewport; var svgElement = this._initialize(viewport); return this.loadDependencies(operatorList).then(function () { _this2.transformMatrix = _util.IDENTITY_MATRIX; var opTree = _this2.convertOpList(operatorList); _this2.executeOpTree(opTree); return svgElement; }); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in _util.OPS) { REVOPS[_util.OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({ 'fnId': fnId, 'fn': REVOPS[fnId], 'args': argsArray[x] }); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for (var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case _util.OPS.beginText: this.beginText(); break; case _util.OPS.setLeading: this.setLeading(args); break; case _util.OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case _util.OPS.setFont: this.setFont(args); break; case _util.OPS.showText: this.showText(args[0]); break; case _util.OPS.showSpacedText: this.showText(args[0]); break; case _util.OPS.endText: this.endText(); break; case _util.OPS.moveText: this.moveText(args[0], args[1]); break; case _util.OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case _util.OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case _util.OPS.setHScale: this.setHScale(args[0]); break; case _util.OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case _util.OPS.setTextRise: this.setTextRise(args[0]); break; case _util.OPS.setLineWidth: this.setLineWidth(args[0]); break; case _util.OPS.setLineJoin: this.setLineJoin(args[0]); break; case _util.OPS.setLineCap: this.setLineCap(args[0]); break; case _util.OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case _util.OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case _util.OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case _util.OPS.setDash: this.setDash(args[0], args[1]); break; case _util.OPS.setGState: this.setGState(args[0]); break; case _util.OPS.fill: this.fill(); break; case _util.OPS.eoFill: this.eoFill(); break; case _util.OPS.stroke: this.stroke(); break; case _util.OPS.fillStroke: this.fillStroke(); break; case _util.OPS.eoFillStroke: this.eoFillStroke(); break; case _util.OPS.clip: this.clip('nonzero'); break; case _util.OPS.eoClip: this.clip('evenodd'); break; case _util.OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case _util.OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case _util.OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case _util.OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case _util.OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case _util.OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case _util.OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case _util.OPS.closePath: this.closePath(); break; case _util.OPS.closeStroke: this.closeStroke(); break; case _util.OPS.closeFillStroke: this.closeFillStroke(); break; case _util.OPS.nextLine: this.nextLine(); break; case _util.OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case _util.OPS.constructPath: this.constructPath(args[0], args[1]); break; case _util.OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: (0, _util.warn)('Unimplemented operator ' + fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = this.svgFactory.createElement('svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = this.svgFactory.createElement('svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = _util.IDENTITY_MATRIX; this.current.lineMatrix = _util.IDENTITY_MATRIX; this.current.tspan = this.svgFactory.createElement('svg:tspan'); this.current.txtElement = this.svgFactory.createElement('svg:text'); this.current.txtgrp = this.svgFactory.createElement('svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = this.svgFactory.createElement('svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { x += fontDirection * wordSpacing; continue; } else if ((0, _util.isNum)(glyph)) { x += -glyph * fontSize * 0.001; continue; } var width = glyph.width; var character = glyph.fontChar; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var charWidth = width * widthAdvanceScale + spacing * fontDirection; if (!glyph.isInFont && !font.missingFile) { x += charWidth; continue; } current.xcoords.push(current.x + x * textHScale); current.tspan.textContent += character; x += charWidth; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } var textMatrix = current.textMatrix; if (current.textRise !== 0) { textMatrix = textMatrix.slice(); textMatrix[5] += current.textRise; } current.txtElement.setAttributeNS(null, 'transform', pm(textMatrix) + ' scale(1, -1)'); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this._ensureTransformGroup().appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = this.svgFactory.createElement('svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : _util.FONT_IDENTITY_MATRIX; var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal'; var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = this.svgFactory.createElement('svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() {}, setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeAlpha: function SVGGraphics_setStrokeAlpha(strokeAlpha) { this.current.strokeAlpha = strokeAlpha; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = _util.Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillAlpha: function SVGGraphics_setFillAlpha(fillAlpha) { this.current.fillAlpha = fillAlpha; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = _util.Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = this.svgFactory.createElement('svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = this.svgFactory.createElement('svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case _util.OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case _util.OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case _util.OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x), pf(y)); break; case _util.OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case _util.OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case _util.OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case _util.OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'fill', 'none'); this._ensureTransformGroup().appendChild(current.path); current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { if (!this.pendingClip) { return; } var current = this.current; var clipId = 'clippath' + clipCount; clipCount++; var clipPath = this.svgFactory.createElement('svg:clipPath'); clipPath.setAttributeNS(null, 'id', clipId); clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); var clipElement = current.element.cloneNode(); if (this.pendingClip === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.pendingClip = null; clipPath.appendChild(clipElement); this.defs.appendChild(clipPath); if (current.activeClipUrl) { current.clipGroup = null; this.extraStack.forEach(function (prev) { prev.clipGroup = null; }); } current.activeClipUrl = 'url(#' + clipId + ')'; this.tgrp = null; }, clip: function SVGGraphics_clip(type) { this.pendingClip = type; }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'Font': this.setFont(value); break; case 'CA': this.setStrokeAlpha(value); break; case 'ca': this.setFillAlpha(value); break; default: (0, _util.warn)('Unimplemented graphic state ' + key); break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-opacity', current.fillAlpha); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'stroke-opacity', current.strokeAlpha); current.element.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.element.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.element.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.element.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.element.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.element.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fill(); }, fillStroke: function SVGGraphics_fillStroke() { this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = this.svgFactory.createElement('svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this._ensureTransformGroup().appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var imgObj = this.objs.get(objId); var imgEl = this.svgFactory.createElement('svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', pf(w)); imgEl.setAttributeNS(null, 'height', pf(h)); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this._ensureTransformGroup().appendChild(imgEl); }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { (0, _util.warn)('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema); var cliprect = this.svgFactory.createElement('svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); var imgEl = this.svgFactory.createElement('svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this._ensureTransformGroup().appendChild(imgEl); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = this.svgFactory.createElement('svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = this.svgFactory.createElement('svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')'); this.defs.appendChild(mask); this._ensureTransformGroup().appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { if (Array.isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (Array.isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = this.svgFactory.createElement('svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {}, _initialize: function _initialize(viewport) { var svg = this.svgFactory.create(viewport.width, viewport.height); var definitions = this.svgFactory.createElement('svg:defs'); svg.appendChild(definitions); this.defs = definitions; var rootGroup = this.svgFactory.createElement('svg:g'); rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform)); svg.appendChild(rootGroup); this.svg = rootGroup; return svg; }, _ensureClipGroup: function SVGGraphics_ensureClipGroup() { if (!this.current.clipGroup) { var clipGroup = this.svgFactory.createElement('svg:g'); clipGroup.setAttributeNS(null, 'clip-path', this.current.activeClipUrl); this.svg.appendChild(clipGroup); this.current.clipGroup = clipGroup; } return this.current.clipGroup; }, _ensureTransformGroup: function SVGGraphics_ensureTransformGroup() { if (!this.tgrp) { this.tgrp = this.svgFactory.createElement('svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); if (this.current.activeClipUrl) { this._ensureClipGroup().appendChild(this.tgrp); } else { this.svg.appendChild(this.tgrp); } } return this.tgrp; } }; return SVGGraphics; }(); } exports.SVGGraphics = SVGGraphics; /***/ }), /* 63 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var pdfjsVersion = '2.0.112'; var pdfjsBuild = '9686f665'; var pdfjsSharedUtil = __w_pdfjs_require__(0); var pdfjsDisplayGlobal = __w_pdfjs_require__(113); var pdfjsDisplayAPI = __w_pdfjs_require__(57); var pdfjsDisplayTextLayer = __w_pdfjs_require__(61); var pdfjsDisplayAnnotationLayer = __w_pdfjs_require__(60); var pdfjsDisplayDOMUtils = __w_pdfjs_require__(8); var pdfjsDisplaySVG = __w_pdfjs_require__(62); { if (pdfjsSharedUtil.isNodeJS()) { var PDFNodeStream = __w_pdfjs_require__(118).PDFNodeStream; pdfjsDisplayAPI.setPDFNetworkStreamClass(PDFNodeStream); } else if (typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream !== 'undefined') { var PDFFetchStream = __w_pdfjs_require__(119).PDFFetchStream; pdfjsDisplayAPI.setPDFNetworkStreamClass(PDFFetchStream); } else { var PDFNetworkStream = __w_pdfjs_require__(120).PDFNetworkStream; pdfjsDisplayAPI.setPDFNetworkStreamClass(PDFNetworkStream); } } exports.PDFJS = pdfjsDisplayGlobal.PDFJS; exports.build = pdfjsDisplayAPI.build; exports.version = pdfjsDisplayAPI.version; exports.getDocument = pdfjsDisplayAPI.getDocument; exports.LoopbackPort = pdfjsDisplayAPI.LoopbackPort; exports.PDFDataRangeTransport = pdfjsDisplayAPI.PDFDataRangeTransport; exports.PDFWorker = pdfjsDisplayAPI.PDFWorker; exports.renderTextLayer = pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsDisplayDOMUtils.CustomStyle; exports.createPromiseCapability = pdfjsSharedUtil.createPromiseCapability; exports.PasswordResponses = pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsSharedUtil.MissingPDFException; exports.SVGGraphics = pdfjsDisplaySVG.SVGGraphics; exports.NativeImageDecoding = pdfjsSharedUtil.NativeImageDecoding; exports.UnexpectedResponseException = pdfjsSharedUtil.UnexpectedResponseException; exports.OPS = pdfjsSharedUtil.OPS; exports.UNSUPPORTED_FEATURES = pdfjsSharedUtil.UNSUPPORTED_FEATURES; exports.createValidAbsoluteUrl = pdfjsSharedUtil.createValidAbsoluteUrl; exports.createObjectURL = pdfjsSharedUtil.createObjectURL; exports.removeNullCharacters = pdfjsSharedUtil.removeNullCharacters; exports.shadow = pdfjsSharedUtil.shadow; exports.createBlob = pdfjsSharedUtil.createBlob; exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException; exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl; exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes; exports.StatTimer = pdfjsSharedUtil.StatTimer; /***/ }), /* 64 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; 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; }; if (typeof PDFJS === 'undefined' || !PDFJS.compatibilityChecked) { var globalScope = __w_pdfjs_require__(14); var userAgent = typeof navigator !== 'undefined' && navigator.userAgent || ''; var isAndroid = /Android/.test(userAgent); var isAndroidPre3 = /Android\s[0-2][^\d]/.test(userAgent); var isAndroidPre5 = /Android\s[0-4][^\d]/.test(userAgent); var isChrome = userAgent.indexOf('Chrom') >= 0; var isChromeWithRangeBug = /Chrome\/(39|40)\./.test(userAgent); var isIOSChrome = userAgent.indexOf('CriOS') >= 0; var isIE = userAgent.indexOf('Trident') >= 0; var isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent); var isOpera = userAgent.indexOf('Opera') >= 0; var isSafari = /Safari\//.test(userAgent) && !/(Chrome\/|Android\s)/.test(userAgent); var hasDOM = (typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object'; if (typeof PDFJS === 'undefined') { globalScope.PDFJS = {}; } PDFJS.compatibilityChecked = true; (function normalizeURLObject() { if (!globalScope.URL) { globalScope.URL = globalScope.webkitURL; } })(); (function checkObjectDefinePropertyCompatibility() { if (typeof Object.defineProperty !== 'undefined') { var definePropertyPossible = true; try { if (hasDOM) { Object.defineProperty(new Image(), 'id', { value: 'test' }); } var Test = function Test() {}; Test.prototype = { get id() {} }; Object.defineProperty(new Test(), 'id', { value: '', configurable: true, enumerable: true, writable: false }); } catch (e) { definePropertyPossible = false; } if (definePropertyPossible) { return; } } Object.defineProperty = function objectDefineProperty(obj, name, def) { delete obj[name]; if ('get' in def) { obj.__defineGetter__(name, def['get']); } if ('set' in def) { obj.__defineSetter__(name, def['set']); } if ('value' in def) { obj.__defineSetter__(name, function objectDefinePropertySetter(value) { this.__defineGetter__(name, function objectDefinePropertyGetter() { return value; }); return value; }); obj[name] = def.value; } }; })(); (function checkXMLHttpRequestResponseCompatibility() { if (typeof XMLHttpRequest === 'undefined') { return; } var xhrPrototype = XMLHttpRequest.prototype; var xhr = new XMLHttpRequest(); if (!('overrideMimeType' in xhr)) { Object.defineProperty(xhrPrototype, 'overrideMimeType', { value: function xmlHttpRequestOverrideMimeType(mimeType) {} }); } if ('responseType' in xhr) { return; } Object.defineProperty(xhrPrototype, 'responseType', { get: function xmlHttpRequestGetResponseType() { return this._responseType || 'text'; }, set: function xmlHttpRequestSetResponseType(value) { if (value === 'text' || value === 'arraybuffer') { this._responseType = value; if (value === 'arraybuffer' && typeof this.overrideMimeType === 'function') { this.overrideMimeType('text/plain; charset=x-user-defined'); } } } }); if (typeof VBArray !== 'undefined') { Object.defineProperty(xhrPrototype, 'response', { get: function xmlHttpRequestResponseGet() { if (this.responseType === 'arraybuffer') { return new Uint8Array(new VBArray(this.responseBody).toArray()); } return this.responseText; } }); return; } Object.defineProperty(xhrPrototype, 'response', { get: function xmlHttpRequestResponseGet() { if (this.responseType !== 'arraybuffer') { return this.responseText; } var text = this.responseText; var i, n = text.length; var result = new Uint8Array(n); for (i = 0; i < n; ++i) { result[i] = text.charCodeAt(i) & 0xFF; } return result.buffer; } }); })(); (function checkWindowBtoaCompatibility() { if ('btoa' in globalScope) { return; } var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; globalScope.btoa = function (chars) { var buffer = ''; var i, n; for (i = 0, n = chars.length; i < n; i += 3) { var b1 = chars.charCodeAt(i) & 0xFF; var b2 = chars.charCodeAt(i + 1) & 0xFF; var b3 = chars.charCodeAt(i + 2) & 0xFF; var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4; var d3 = i + 1 < n ? (b2 & 0xF) << 2 | b3 >> 6 : 64; var d4 = i + 2 < n ? b3 & 0x3F : 64; buffer += digits.charAt(d1) + digits.charAt(d2) + digits.charAt(d3) + digits.charAt(d4); } return buffer; }; })(); (function checkWindowAtobCompatibility() { if ('atob' in globalScope) { return; } var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; globalScope.atob = function (input) { input = input.replace(/=+$/, ''); if (input.length % 4 === 1) { throw new Error('bad atob input'); } for (var bc = 0, bs, buffer, idx = 0, output = ''; buffer = input.charAt(idx++); ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) { buffer = digits.indexOf(buffer); } return output; }; })(); (function checkFunctionPrototypeBindCompatibility() { if (typeof Function.prototype.bind !== 'undefined') { return; } Function.prototype.bind = function functionPrototypeBind(obj) { var fn = this, headArgs = Array.prototype.slice.call(arguments, 1); var bound = function functionPrototypeBindBound() { var args = headArgs.concat(Array.prototype.slice.call(arguments)); return fn.apply(obj, args); }; return bound; }; })(); (function checkDatasetProperty() { if (!hasDOM) { return; } var div = document.createElement('div'); if ('dataset' in div) { return; } Object.defineProperty(HTMLElement.prototype, 'dataset', { get: function get() { if (this._dataset) { return this._dataset; } var dataset = {}; for (var j = 0, jj = this.attributes.length; j < jj; j++) { var attribute = this.attributes[j]; if (attribute.name.substring(0, 5) !== 'data-') { continue; } var key = attribute.name.substring(5).replace(/\-([a-z])/g, function (all, ch) { return ch.toUpperCase(); }); dataset[key] = attribute.value; } Object.defineProperty(this, '_dataset', { value: dataset, writable: false, enumerable: false }); return dataset; }, enumerable: true }); })(); (function checkClassListProperty() { function changeList(element, itemName, add, remove) { var s = element.className || ''; var list = s.split(/\s+/g); if (list[0] === '') { list.shift(); } var index = list.indexOf(itemName); if (index < 0 && add) { list.push(itemName); } if (index >= 0 && remove) { list.splice(index, 1); } element.className = list.join(' '); return index >= 0; } if (!hasDOM) { return; } var div = document.createElement('div'); if ('classList' in div) { return; } var classListPrototype = { add: function add(name) { changeList(this.element, name, true, false); }, contains: function contains(name) { return changeList(this.element, name, false, false); }, remove: function remove(name) { changeList(this.element, name, false, true); }, toggle: function toggle(name) { changeList(this.element, name, true, true); } }; Object.defineProperty(HTMLElement.prototype, 'classList', { get: function get() { if (this._classList) { return this._classList; } var classList = Object.create(classListPrototype, { element: { value: this, writable: false, enumerable: true } }); Object.defineProperty(this, '_classList', { value: classList, writable: false, enumerable: false }); return classList; }, enumerable: true }); })(); (function checkWorkerConsoleCompatibility() { if (typeof importScripts === 'undefined' || 'console' in globalScope) { return; } var consoleTimer = {}; var workerConsole = { log: function log() { var args = Array.prototype.slice.call(arguments); globalScope.postMessage({ targetName: 'main', action: 'console_log', data: args }); }, error: function error() { var args = Array.prototype.slice.call(arguments); globalScope.postMessage({ targetName: 'main', action: 'console_error', data: args }); }, time: function time(name) { consoleTimer[name] = Date.now(); }, timeEnd: function timeEnd(name) { var time = consoleTimer[name]; if (!time) { throw new Error('Unknown timer name ' + name); } this.log('Timer:', name, Date.now() - time); } }; globalScope.console = workerConsole; })(); (function checkConsoleCompatibility() { if (!hasDOM) { return; } if (!('console' in window)) { window.console = { log: function log() {}, error: function error() {}, warn: function warn() {} }; return; } if (!('bind' in console.log)) { console.log = function (fn) { return function (msg) { return fn(msg); }; }(console.log); console.error = function (fn) { return function (msg) { return fn(msg); }; }(console.error); console.warn = function (fn) { return function (msg) { return fn(msg); }; }(console.warn); return; } })(); (function checkOnClickCompatibility() { function ignoreIfTargetDisabled(event) { if (isDisabled(event.target)) { event.stopPropagation(); } } function isDisabled(node) { return node.disabled || node.parentNode && isDisabled(node.parentNode); } if (isOpera) { document.addEventListener('click', ignoreIfTargetDisabled, true); } })(); (function checkOnBlobSupport() { if (isIE || isIOSChrome) { PDFJS.disableCreateObjectURL = true; } })(); (function checkNavigatorLanguage() { if (typeof navigator === 'undefined') { return; } if ('language' in navigator) { return; } PDFJS.locale = navigator.userLanguage || 'en-US'; })(); (function checkRangeRequests() { if (isSafari || isAndroidPre3 || isChromeWithRangeBug || isIOS) { PDFJS.disableRange = true; PDFJS.disableStream = true; } })(); (function checkHistoryManipulation() { if (!hasDOM) { return; } if (!history.pushState || isAndroidPre3) { PDFJS.disableHistory = true; } })(); (function checkSetPresenceInImageData() { if (!hasDOM) { return; } if (window.CanvasPixelArray) { if (typeof window.CanvasPixelArray.prototype.set !== 'function') { window.CanvasPixelArray.prototype.set = function (arr) { for (var i = 0, ii = this.length; i < ii; i++) { this[i] = arr[i]; } }; } } else { var polyfill = false, versionMatch; if (isChrome) { versionMatch = userAgent.match(/Chrom(e|ium)\/([0-9]+)\./); polyfill = versionMatch && parseInt(versionMatch[2]) < 21; } else if (isAndroid) { polyfill = isAndroidPre5; } else if (isSafari) { versionMatch = userAgent.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//); polyfill = versionMatch && parseInt(versionMatch[1]) < 6; } if (polyfill) { var contextPrototype = window.CanvasRenderingContext2D.prototype; var createImageData = contextPrototype.createImageData; contextPrototype.createImageData = function (w, h) { var imageData = createImageData.call(this, w, h); imageData.data.set = function (arr) { for (var i = 0, ii = this.length; i < ii; i++) { this[i] = arr[i]; } }; return imageData; }; contextPrototype = null; } } })(); (function checkRequestAnimationFrame() { function installFakeAnimationFrameFunctions() { window.requestAnimationFrame = function (callback) { return window.setTimeout(callback, 20); }; window.cancelAnimationFrame = function (timeoutID) { window.clearTimeout(timeoutID); }; } if (!hasDOM) { return; } if (isIOS) { installFakeAnimationFrameFunctions(); return; } if ('requestAnimationFrame' in window) { return; } window.requestAnimationFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame; if (window.requestAnimationFrame) { return; } installFakeAnimationFrameFunctions(); })(); (function checkCanvasSizeLimitation() { if (isIOS || isAndroid) { PDFJS.maxCanvasPixels = 5242880; } })(); (function checkFullscreenSupport() { if (!hasDOM) { return; } if (isIE && window.parent !== window) { PDFJS.disableFullscreen = true; } })(); (function checkCurrentScript() { if (!hasDOM) { return; } if ('currentScript' in document) { return; } Object.defineProperty(document, 'currentScript', { get: function get() { var scripts = document.getElementsByTagName('script'); return scripts[scripts.length - 1]; }, enumerable: true, configurable: true }); })(); (function checkInputTypeNumberAssign() { if (!hasDOM) { return; } var el = document.createElement('input'); try { el.type = 'number'; } catch (ex) { var inputProto = el.constructor.prototype; var typeProperty = Object.getOwnPropertyDescriptor(inputProto, 'type'); Object.defineProperty(inputProto, 'type', { get: function get() { return typeProperty.get.call(this); }, set: function set(value) { typeProperty.set.call(this, value === 'number' ? 'text' : value); }, enumerable: true, configurable: true }); } })(); (function checkDocumentReadyState() { if (!hasDOM) { return; } if (!document.attachEvent) { return; } var documentProto = document.constructor.prototype; var readyStateProto = Object.getOwnPropertyDescriptor(documentProto, 'readyState'); Object.defineProperty(documentProto, 'readyState', { get: function get() { var value = readyStateProto.get.call(this); return value === 'interactive' ? 'loading' : value; }, set: function set(value) { readyStateProto.set.call(this, value); }, enumerable: true, configurable: true }); })(); (function checkChildNodeRemove() { if (!hasDOM) { return; } if (typeof Element.prototype.remove !== 'undefined') { return; } Element.prototype.remove = function () { if (this.parentNode) { this.parentNode.removeChild(this); } }; })(); (function checkObjectValues() { if (Object.values) { return; } Object.values = __w_pdfjs_require__(65); })(); (function checkArrayIncludes() { if (Array.prototype.includes) { return; } Array.prototype.includes = __w_pdfjs_require__(70); })(); (function checkNumberIsNaN() { if (Number.isNaN) { return; } Number.isNaN = __w_pdfjs_require__(72); })(); (function checkNumberIsInteger() { if (Number.isInteger) { return; } Number.isInteger = __w_pdfjs_require__(74); })(); (function checkPromise() { if (globalScope.Promise) { return; } globalScope.Promise = __w_pdfjs_require__(77); })(); (function checkWeakMap() { if (globalScope.WeakMap) { return; } globalScope.WeakMap = __w_pdfjs_require__(95); })(); (function checkURLConstructor() { var hasWorkingUrl = false; try { if (typeof URL === 'function' && _typeof(URL.prototype) === 'object' && 'origin' in URL.prototype) { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } } catch (e) {} if (hasWorkingUrl) { return; } var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if (h === '') { invalid.call(this); } return h.toLowerCase(); } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1) { return c; } return encodeURIComponent(c); } var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message); } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); } else if (c === ':') { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if (this._scheme === 'file') { state = 'relative'; } else if (this._isRelative && base && base._scheme === this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (c === EOF) { break loop; } else { err('Code point not allowed in scheme: ' + c); break loop; } break; case 'scheme data': if (c === '?') { this._query = '?'; state = 'query'; } else if (c === '#') { this._fragment = '#'; state = 'fragment'; } else { if (c !== EOF && c !== '\t' && c !== '\n' && c !== '\r') { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !isRelativeScheme(base._scheme)) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if (c === '/' && input[cursor + 1] === '/') { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue; } break; case 'relative': this._isRelative = true; if (this._scheme !== 'file') { this._scheme = base._scheme; } if (c === EOF) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._username = base._username; this._password = base._password; break loop; } else if (c === '/' || c === '\\') { if (c === '\\') { err('\\ is an invalid code point.'); } state = 'relative slash'; } else if (c === '?') { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; this._username = base._username; this._password = base._password; state = 'query'; } else if (c === '#') { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; this._username = base._username; this._password = base._password; state = 'fragment'; } else { var nextC = input[cursor + 1]; var nextNextC = input[cursor + 2]; if (this._scheme !== 'file' || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || nextNextC !== EOF && nextNextC !== '/' && nextNextC !== '\\' && nextNextC !== '?' && nextNextC !== '#') { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if (c === '/' || c === '\\') { if (c === '\\') { err('\\ is an invalid code point.'); } if (this._scheme === 'file') { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if (this._scheme !== 'file') { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; } state = 'relative path'; continue; } break; case 'authority first slash': if (c === '/') { state = 'authority second slash'; } else { err('Expected \'/\', got: ' + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if (c !== '/') { err('Expected \'/\', got: ' + c); continue; } break; case 'authority ignore slashes': if (c !== '/' && c !== '\\') { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if (c === '@') { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if (cp === '\t' || cp === '\n' || cp === '\r') { err('Invalid whitespace in authority.'); continue; } if (cp === ':' && this._password === null) { this._password = ''; continue; } var tempC = percentEscape(cp); if (this._password !== null) { this._password += tempC; } else { this._username += tempC; } } buffer = ''; } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') { if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) { state = 'relative path'; } else if (buffer.length === 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if (c === '\t' || c === '\n' || c === '\r') { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (c === ':' && !seenBracket) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if (stateOverride === 'hostname') { break loop; } } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if (c !== '\t' && c !== '\n' && c !== '\r') { if (c === '[') { seenBracket = true; } else if (c === ']') { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#' || stateOverride) { if (buffer !== '') { var temp = parseInt(buffer, 10); if (temp !== relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if (c === '\t' || c === '\n' || c === '\r') { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if (c === '\\') { err('\'\\\' not allowed in path.'); } state = 'relative path'; if (c !== '/' && c !== '\\') { continue; } break; case 'relative path': if (c === EOF || c === '/' || c === '\\' || !stateOverride && (c === '?' || c === '#')) { if (c === '\\') { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if (buffer === '..') { this._path.pop(); if (c !== '/' && c !== '\\') { this._path.push(''); } } else if (buffer === '.' && c !== '/' && c !== '\\') { this._path.push(''); } else if (buffer !== '.') { if (this._scheme === 'file' && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if (c === '?') { this._query = '?'; state = 'query'; } else if (c === '#') { this._fragment = '#'; state = 'fragment'; } } else if (c !== '\t' && c !== '\n' && c !== '\r') { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && c === '#') { this._fragment = '#'; state = 'fragment'; } else if (c !== EOF && c !== '\t' && c !== '\n' && c !== '\r') { this._query += percentEscapeQuery(c); } break; case 'fragment': if (c !== EOF && c !== '\t' && c !== '\n' && c !== '\r') { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } function JURL(url, base) { if (base !== undefined && !(base instanceof JURL)) { base = new JURL(String(base)); } this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); parse.call(this, input, null, base); } JURL.prototype = { toString: function toString() { return this.href; }, get href() { if (this._isInvalid) { return this._url; } var authority = ''; if (this._username !== '' || this._password !== null) { authority = this._username + (this._password !== null ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(value) { clear.call(this); parse.call(this, value); }, get protocol() { return this._scheme + ':'; }, set protocol(value) { if (this._isInvalid) { return; } parse.call(this, value + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(value) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, value, 'host'); }, get hostname() { return this._host; }, set hostname(value) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, value, 'hostname'); }, get port() { return this._port; }, set port(value) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, value, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(value) { if (this._isInvalid || !this._isRelative) { return; } this._path = []; parse.call(this, value, 'relative path start'); }, get search() { return this._isInvalid || !this._query || this._query === '?' ? '' : this._query; }, set search(value) { if (this._isInvalid || !this._isRelative) { return; } this._query = '?'; if (value[0] === '?') { value = value.slice(1); } parse.call(this, value, 'query'); }, get hash() { return this._isInvalid || !this._fragment || this._fragment === '#' ? '' : this._fragment; }, set hash(value) { if (this._isInvalid) { return; } this._fragment = '#'; if (value[0] === '#') { value = value.slice(1); } parse.call(this, value, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; case 'blob': try { return new JURL(this._schemeData).origin || 'null'; } catch (_) {} return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; var OriginalURL = globalScope.URL; if (OriginalURL) { JURL.createObjectURL = function (blob) { return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; JURL.revokeObjectURL = function (url) { OriginalURL.revokeObjectURL(url); }; } globalScope.URL = JURL; })(); } /***/ }), /* 65 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(66); module.exports = __w_pdfjs_require__(5).Object.values; /***/ }), /* 66 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); var $values = __w_pdfjs_require__(67)(false); $export($export.S, 'Object', { values: function values(it) { return $values(it); } }); /***/ }), /* 67 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var getKeys = __w_pdfjs_require__(21); var toIObject = __w_pdfjs_require__(17); var isEnum = __w_pdfjs_require__(31).f; module.exports = function (isEntries) { return function (it) { var O = toIObject(it); var keys = getKeys(O); var length = keys.length; var i = 0; var result = []; var key; while (length > i) { if (isEnum.call(O, key = keys[i++])) { result.push(isEntries ? [key, O[key]] : O[key]); } }return result; }; }; /***/ }), /* 68 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var has = __w_pdfjs_require__(7); var toIObject = __w_pdfjs_require__(17); var arrayIndexOf = __w_pdfjs_require__(41)(false); var IE_PROTO = __w_pdfjs_require__(30)('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) { if (key != IE_PROTO) has(O, key) && result.push(key); }while (names.length > i) { if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } }return result; }; /***/ }), /* 69 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var toInteger = __w_pdfjs_require__(29); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /* 70 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(71); module.exports = __w_pdfjs_require__(5).Array.includes; /***/ }), /* 71 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); var $includes = __w_pdfjs_require__(41)(true); $export($export.P, 'Array', { includes: function includes(el) { return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); __w_pdfjs_require__(44)('includes'); /***/ }), /* 72 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(73); module.exports = __w_pdfjs_require__(5).Number.isNaN; /***/ }), /* 73 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); $export($export.S, 'Number', { isNaN: function isNaN(number) { return number != number; } }); /***/ }), /* 74 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(75); module.exports = __w_pdfjs_require__(5).Number.isInteger; /***/ }), /* 75 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); $export($export.S, 'Number', { isInteger: __w_pdfjs_require__(76) }); /***/ }), /* 76 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); var floor = Math.floor; module.exports = function isInteger(it) { return !isObject(it) && isFinite(it) && floor(it) === it; }; /***/ }), /* 77 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(45); __w_pdfjs_require__(78); __w_pdfjs_require__(49); __w_pdfjs_require__(86); __w_pdfjs_require__(93); __w_pdfjs_require__(94); module.exports = __w_pdfjs_require__(5).Promise; /***/ }), /* 78 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $at = __w_pdfjs_require__(79)(true); __w_pdfjs_require__(46)(String, 'String', function (iterated) { this._t = String(iterated); this._i = 0; }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /* 79 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var toInteger = __w_pdfjs_require__(29); var defined = __w_pdfjs_require__(27); module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /* 80 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var create = __w_pdfjs_require__(81); var descriptor = __w_pdfjs_require__(25); var setToStringTag = __w_pdfjs_require__(22); var IteratorPrototype = {}; __w_pdfjs_require__(11)(IteratorPrototype, __w_pdfjs_require__(2)('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /* 81 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var anObject = __w_pdfjs_require__(6); var dPs = __w_pdfjs_require__(82); var enumBugKeys = __w_pdfjs_require__(43); var IE_PROTO = __w_pdfjs_require__(30)('IE_PROTO'); var Empty = function Empty() {}; var PROTOTYPE = 'prototype'; var _createDict = function createDict() { var iframe = __w_pdfjs_require__(24)('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __w_pdfjs_require__(48).appendChild(iframe); iframe.src = 'javascript:'; iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); _createDict = iframeDocument.F; while (i--) { delete _createDict[PROTOTYPE][enumBugKeys[i]]; }return _createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; result[IE_PROTO] = O; } else result = _createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /* 82 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var dP = __w_pdfjs_require__(15); var anObject = __w_pdfjs_require__(6); var getKeys = __w_pdfjs_require__(21); module.exports = __w_pdfjs_require__(12) ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) { dP.f(O, P = keys[i++], Properties[P]); }return O; }; /***/ }), /* 83 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var has = __w_pdfjs_require__(7); var toObject = __w_pdfjs_require__(33); var IE_PROTO = __w_pdfjs_require__(30)('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /* 84 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var addToUnscopables = __w_pdfjs_require__(44); var step = __w_pdfjs_require__(85); var Iterators = __w_pdfjs_require__(19); var toIObject = __w_pdfjs_require__(17); module.exports = __w_pdfjs_require__(46)(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); this._i = 0; this._k = kind; }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /* 85 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /* 86 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var LIBRARY = __w_pdfjs_require__(47); var global = __w_pdfjs_require__(3); var ctx = __w_pdfjs_require__(10); var classof = __w_pdfjs_require__(32); var $export = __w_pdfjs_require__(4); var isObject = __w_pdfjs_require__(1); var aFunction = __w_pdfjs_require__(16); var anInstance = __w_pdfjs_require__(34); var forOf = __w_pdfjs_require__(23); var speciesConstructor = __w_pdfjs_require__(50); var task = __w_pdfjs_require__(51).set; var microtask = __w_pdfjs_require__(91)(); var newPromiseCapabilityModule = __w_pdfjs_require__(35); var perform = __w_pdfjs_require__(52); var promiseResolve = __w_pdfjs_require__(53); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function empty() {}; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[__w_pdfjs_require__(2)('species')] = function (exec) { exec(empty, empty); }; return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch (e) {} }(); var isThenable = function isThenable(it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function notify(promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function run(reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value;else { if (domain) domain.enter(); result = handler(value); if (domain) domain.exit(); } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { reject(e); } }; while (chain.length > i) { run(chain[i++]); }promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function onUnhandled(promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function isUnhandled(promise) { if (promise._h == 1) return false; var chain = promise._a || promise._c; var i = 0; var reaction; while (chain.length > i) { reaction = chain[i++]; if (reaction.fail || !isUnhandled(reaction.promise)) return false; } return true; }; var onHandleUnhandled = function onHandleUnhandled(promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function $reject(value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function $resolve(value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); } }; if (!USE_NATIVE) { $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; Internal = function Promise(executor) { this._c = []; this._a = undefined; this._s = 0; this._d = false; this._v = undefined; this._h = 0; this._n = false; }; Internal.prototype = __w_pdfjs_require__(36)($Promise.prototype, { then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, 'catch': function _catch(onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function OwnPromiseCapability() { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function newPromiseCapability(C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); __w_pdfjs_require__(22)($Promise, PROMISE); __w_pdfjs_require__(92)(PROMISE); Wrapper = __w_pdfjs_require__(5)[PROMISE]; $export($export.S + $export.F * !USE_NATIVE, PROMISE, { reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && __w_pdfjs_require__(54)(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } }); /***/ }), /* 87 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var anObject = __w_pdfjs_require__(6); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /* 88 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var Iterators = __w_pdfjs_require__(19); var ITERATOR = __w_pdfjs_require__(2)('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /* 89 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var classof = __w_pdfjs_require__(32); var ITERATOR = __w_pdfjs_require__(2)('iterator'); var Iterators = __w_pdfjs_require__(19); module.exports = __w_pdfjs_require__(5).getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /* 90 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; module.exports = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }), /* 91 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = __w_pdfjs_require__(3); var macrotask = __w_pdfjs_require__(51).set; var Observer = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; var isNode = __w_pdfjs_require__(18)(process) == 'process'; module.exports = function () { var head, last, notify; var flush = function flush() { var parent, fn; if (isNode && (parent = process.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (e) { if (head) notify();else last = undefined; throw e; } } last = undefined; if (parent) parent.enter(); }; if (isNode) { notify = function notify() { process.nextTick(flush); }; } else if (Observer) { var toggle = true; var node = document.createTextNode(''); new Observer(flush).observe(node, { characterData: true }); notify = function notify() { node.data = toggle = !toggle; }; } else if (Promise && Promise.resolve) { var promise = Promise.resolve(); notify = function notify() { promise.then(flush); }; } else { notify = function notify() { macrotask.call(global, flush); }; } return function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; }; /***/ }), /* 92 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = __w_pdfjs_require__(3); var dP = __w_pdfjs_require__(15); var DESCRIPTORS = __w_pdfjs_require__(12); var SPECIES = __w_pdfjs_require__(2)('species'); module.exports = function (KEY) { var C = global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function get() { return this; } }); }; /***/ }), /* 93 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); var core = __w_pdfjs_require__(5); var global = __w_pdfjs_require__(3); var speciesConstructor = __w_pdfjs_require__(50); var promiseResolve = __w_pdfjs_require__(53); $export($export.P + $export.R, 'Promise', { 'finally': function _finally(onFinally) { var C = speciesConstructor(this, core.Promise || global.Promise); var isFunction = typeof onFinally == 'function'; return this.then(isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally); } }); /***/ }), /* 94 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); var newPromiseCapability = __w_pdfjs_require__(35); var perform = __w_pdfjs_require__(52); $export($export.S, 'Promise', { 'try': function _try(callbackfn) { var promiseCapability = newPromiseCapability.f(this); var result = perform(callbackfn); (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); return promiseCapability.promise; } }); /***/ }), /* 95 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(45); __w_pdfjs_require__(49); __w_pdfjs_require__(96); __w_pdfjs_require__(107); __w_pdfjs_require__(109); module.exports = __w_pdfjs_require__(5).WeakMap; /***/ }), /* 96 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var each = __w_pdfjs_require__(55)(0); var redefine = __w_pdfjs_require__(9); var meta = __w_pdfjs_require__(37); var assign = __w_pdfjs_require__(100); var weak = __w_pdfjs_require__(102); var isObject = __w_pdfjs_require__(1); var fails = __w_pdfjs_require__(13); var validate = __w_pdfjs_require__(56); var WEAK_MAP = 'WeakMap'; var getWeak = meta.getWeak; var isExtensible = Object.isExtensible; var uncaughtFrozenStore = weak.ufstore; var tmp = {}; var InternalMap; var wrapper = function wrapper(get) { return function WeakMap() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { get: function get(key) { if (isObject(key)) { var data = getWeak(key); if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); return data ? data[this._i] : undefined; } }, set: function set(key, value) { return weak.def(validate(this, WEAK_MAP), key, value); } }; var $WeakMap = module.exports = __w_pdfjs_require__(103)(WEAK_MAP, wrapper, methods, weak, true, true); if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { InternalMap = weak.getConstructor(wrapper, WEAK_MAP); assign(InternalMap.prototype, methods); meta.NEED = true; each(['delete', 'has', 'get', 'set'], function (key) { var proto = $WeakMap.prototype; var method = proto[key]; redefine(proto, key, function (a, b) { if (isObject(a) && !isExtensible(a)) { if (!this._f) this._f = new InternalMap(); var result = this._f[key](a, b); return key == 'set' ? this : result; } return method.call(this, a, b); }); }); } /***/ }), /* 97 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var speciesConstructor = __w_pdfjs_require__(98); module.exports = function (original, length) { return new (speciesConstructor(original))(length); }; /***/ }), /* 98 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); var isArray = __w_pdfjs_require__(99); var SPECIES = __w_pdfjs_require__(2)('species'); module.exports = function (original) { var C; if (isArray(original)) { C = original.constructor; if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return C === undefined ? Array : C; }; /***/ }), /* 99 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var cof = __w_pdfjs_require__(18); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /* 100 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var getKeys = __w_pdfjs_require__(21); var gOPS = __w_pdfjs_require__(101); var pIE = __w_pdfjs_require__(31); var toObject = __w_pdfjs_require__(33); var IObject = __w_pdfjs_require__(26); var $assign = Object.assign; module.exports = !$assign || __w_pdfjs_require__(13)(function () { var A = {}; var B = {}; var S = Symbol(); var K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function (k) { B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source) { var T = toObject(target); var aLen = arguments.length; var index = 1; var getSymbols = gOPS.f; var isEnum = pIE.f; while (aLen > index) { var S = IObject(arguments[index++]); var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); var length = keys.length; var j = 0; var key; while (length > j) { if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; } } return T; } : $assign; /***/ }), /* 101 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; exports.f = Object.getOwnPropertySymbols; /***/ }), /* 102 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var redefineAll = __w_pdfjs_require__(36); var getWeak = __w_pdfjs_require__(37).getWeak; var anObject = __w_pdfjs_require__(6); var isObject = __w_pdfjs_require__(1); var anInstance = __w_pdfjs_require__(34); var forOf = __w_pdfjs_require__(23); var createArrayMethod = __w_pdfjs_require__(55); var $has = __w_pdfjs_require__(7); var validate = __w_pdfjs_require__(56); var arrayFind = createArrayMethod(5); var arrayFindIndex = createArrayMethod(6); var id = 0; var uncaughtFrozenStore = function uncaughtFrozenStore(that) { return that._l || (that._l = new UncaughtFrozenStore()); }; var UncaughtFrozenStore = function UncaughtFrozenStore() { this.a = []; }; var findUncaughtFrozen = function findUncaughtFrozen(store, key) { return arrayFind(store.a, function (it) { return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function get(key) { var entry = findUncaughtFrozen(this, key); if (entry) return entry[1]; }, has: function has(key) { return !!findUncaughtFrozen(this, key); }, set: function set(key, value) { var entry = findUncaughtFrozen(this, key); if (entry) entry[1] = value;else this.a.push([key, value]); }, 'delete': function _delete(key) { var index = arrayFindIndex(this.a, function (it) { return it[0] === key; }); if (~index) this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function getConstructor(wrapper, NAME, IS_MAP, ADDER) { var C = wrapper(function (that, iterable) { anInstance(that, C, NAME, '_i'); that._t = NAME; that._i = id++; that._l = undefined; if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { 'delete': function _delete(key) { if (!isObject(key)) return false; var data = getWeak(key); if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, has: function has(key) { if (!isObject(key)) return false; var data = getWeak(key); if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); return data && $has(data, this._i); } }); return C; }, def: function def(that, key, value) { var data = getWeak(anObject(key), true); if (data === true) uncaughtFrozenStore(that).set(key, value);else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; /***/ }), /* 103 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var global = __w_pdfjs_require__(3); var $export = __w_pdfjs_require__(4); var redefine = __w_pdfjs_require__(9); var redefineAll = __w_pdfjs_require__(36); var meta = __w_pdfjs_require__(37); var forOf = __w_pdfjs_require__(23); var anInstance = __w_pdfjs_require__(34); var isObject = __w_pdfjs_require__(1); var fails = __w_pdfjs_require__(13); var $iterDetect = __w_pdfjs_require__(54); var setToStringTag = __w_pdfjs_require__(22); var inheritIfRequired = __w_pdfjs_require__(104); module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { var Base = global[NAME]; var C = Base; var ADDER = IS_MAP ? 'set' : 'add'; var proto = C && C.prototype; var O = {}; var fixMethod = function fixMethod(KEY) { var fn = proto[KEY]; redefine(proto, KEY, KEY == 'delete' ? function (a) { return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'has' ? function has(a) { return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'get' ? function get(a) { return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; }); }; if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { new C().entries().next(); }))) { C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { var instance = new C(); var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); var BUGGY_ZERO = !IS_WEAK && fails(function () { var $instance = new C(); var index = 5; while (index--) { $instance[ADDER](index, index); }return !$instance.has(-0); }); if (!ACCEPT_ITERABLES) { C = wrapper(function (target, iterable) { anInstance(target, C, NAME); var that = inheritIfRequired(new Base(), target, C); if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); return that; }); C.prototype = proto; proto.constructor = C; } if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); if (IS_WEAK && proto.clear) delete proto.clear; } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F * (C != Base), O); if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); return C; }; /***/ }), /* 104 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); var setPrototypeOf = __w_pdfjs_require__(105).set; module.exports = function (that, target, C) { var S = target.constructor; var P; if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { setPrototypeOf(that, P); } return that; }; /***/ }), /* 105 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isObject = __w_pdfjs_require__(1); var anObject = __w_pdfjs_require__(6); var check = function check(O, proto) { anObject(O); if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? function (test, buggy, set) { try { set = __w_pdfjs_require__(10)(Function.call, __w_pdfjs_require__(106).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch (e) { buggy = true; } return function setPrototypeOf(O, proto) { check(O, proto); if (buggy) O.__proto__ = proto;else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }), /* 106 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var pIE = __w_pdfjs_require__(31); var createDesc = __w_pdfjs_require__(25); var toIObject = __w_pdfjs_require__(17); var toPrimitive = __w_pdfjs_require__(40); var has = __w_pdfjs_require__(7); var IE8_DOM_DEFINE = __w_pdfjs_require__(39); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __w_pdfjs_require__(12) ? gOPD : function getOwnPropertyDescriptor(O, P) { O = toIObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return gOPD(O, P); } catch (e) {} if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /* 107 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(108)('WeakMap'); /***/ }), /* 108 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); module.exports = function (COLLECTION) { $export($export.S, COLLECTION, { of: function of() { var length = arguments.length; var A = Array(length); while (length--) { A[length] = arguments[length]; }return new this(A); } }); }; /***/ }), /* 109 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; __w_pdfjs_require__(110)('WeakMap'); /***/ }), /* 110 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var $export = __w_pdfjs_require__(4); var aFunction = __w_pdfjs_require__(16); var ctx = __w_pdfjs_require__(10); var forOf = __w_pdfjs_require__(23); module.exports = function (COLLECTION) { $export($export.S, COLLECTION, { from: function from(source) { var mapFn = arguments[1]; var mapping, A, n, cb; aFunction(this); mapping = mapFn !== undefined; if (mapping) aFunction(mapFn); if (source == undefined) return new this(); A = []; if (mapping) { n = 0; cb = ctx(mapFn, arguments[2], 2); forOf(source, false, function (nextItem) { A.push(cb(nextItem, n++)); }); } else { forOf(source, false, A.push, A); } return new this(A); } }); }; /***/ }), /* 111 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var isReadableStreamSupported = false; if (typeof ReadableStream !== 'undefined') { try { new ReadableStream({ start: function start(controller) { controller.close(); } }); isReadableStreamSupported = true; } catch (e) {} } if (isReadableStreamSupported) { exports.ReadableStream = ReadableStream; } else { exports.ReadableStream = __w_pdfjs_require__(112).ReadableStream; } /***/ }), /* 112 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; var _typeof2 = 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; }; (function (e, a) { for (var i in a) { e[i] = a[i]; } })(exports, function (modules) { var installedModules = {}; function __w_pdfjs_require__(moduleId) { if (installedModules[moduleId]) return installedModules[moduleId].exports; var module = installedModules[moduleId] = { i: moduleId, l: false, exports: {} }; modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__); module.l = true; return module.exports; } __w_pdfjs_require__.m = modules; __w_pdfjs_require__.c = installedModules; __w_pdfjs_require__.i = function (value) { return value; }; __w_pdfjs_require__.d = function (exports, name, getter) { if (!__w_pdfjs_require__.o(exports, name)) { Object.defineProperty(exports, name, { configurable: false, enumerable: true, get: getter }); } }; __w_pdfjs_require__.n = function (module) { var getter = module && module.__esModule ? function getDefault() { return module['default']; } : function getModuleExports() { return module; }; __w_pdfjs_require__.d(getter, 'a', getter); return getter; }; __w_pdfjs_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; __w_pdfjs_require__.p = ""; return __w_pdfjs_require__(__w_pdfjs_require__.s = 7); }([function (module, exports, __w_pdfjs_require__) { "use strict"; var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) { return typeof obj === 'undefined' ? 'undefined' : _typeof2(obj); } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === 'undefined' ? 'undefined' : _typeof2(obj); }; var _require = __w_pdfjs_require__(1), assert = _require.assert; function IsPropertyKey(argument) { return typeof argument === 'string' || (typeof argument === 'undefined' ? 'undefined' : _typeof(argument)) === 'symbol'; } exports.typeIsObject = function (x) { return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x !== null || typeof x === 'function'; }; exports.createDataProperty = function (o, p, v) { assert(exports.typeIsObject(o)); Object.defineProperty(o, p, { value: v, writable: true, enumerable: true, configurable: true }); }; exports.createArrayFromList = function (elements) { return elements.slice(); }; exports.ArrayBufferCopy = function (dest, destOffset, src, srcOffset, n) { new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); }; exports.CreateIterResultObject = function (value, done) { assert(typeof done === 'boolean'); var obj = {}; Object.defineProperty(obj, 'value', { value: value, enumerable: true, writable: true, configurable: true }); Object.defineProperty(obj, 'done', { value: done, enumerable: true, writable: true, configurable: true }); return obj; }; exports.IsFiniteNonNegativeNumber = function (v) { if (Number.isNaN(v)) { return false; } if (v === Infinity) { return false; } if (v < 0) { return false; } return true; }; function Call(F, V, args) { if (typeof F !== 'function') { throw new TypeError('Argument is not a function'); } return Function.prototype.apply.call(F, V, args); } exports.InvokeOrNoop = function (O, P, args) { assert(O !== undefined); assert(IsPropertyKey(P)); assert(Array.isArray(args)); var method = O[P]; if (method === undefined) { return undefined; } return Call(method, O, args); }; exports.PromiseInvokeOrNoop = function (O, P, args) { assert(O !== undefined); assert(IsPropertyKey(P)); assert(Array.isArray(args)); try { return Promise.resolve(exports.InvokeOrNoop(O, P, args)); } catch (returnValueE) { return Promise.reject(returnValueE); } }; exports.PromiseInvokeOrPerformFallback = function (O, P, args, F, argsF) { assert(O !== undefined); assert(IsPropertyKey(P)); assert(Array.isArray(args)); assert(Array.isArray(argsF)); var method = void 0; try { method = O[P]; } catch (methodE) { return Promise.reject(methodE); } if (method === undefined) { return F.apply(null, argsF); } try { return Promise.resolve(Call(method, O, args)); } catch (e) { return Promise.reject(e); } }; exports.TransferArrayBuffer = function (O) { return O.slice(); }; exports.ValidateAndNormalizeHighWaterMark = function (highWaterMark) { highWaterMark = Number(highWaterMark); if (Number.isNaN(highWaterMark) || highWaterMark < 0) { throw new RangeError('highWaterMark property of a queuing strategy must be non-negative and non-NaN'); } return highWaterMark; }; exports.ValidateAndNormalizeQueuingStrategy = function (size, highWaterMark) { if (size !== undefined && typeof size !== 'function') { throw new TypeError('size property of a queuing strategy must be a function'); } highWaterMark = exports.ValidateAndNormalizeHighWaterMark(highWaterMark); return { size: size, highWaterMark: highWaterMark }; }; }, function (module, exports, __w_pdfjs_require__) { "use strict"; function rethrowAssertionErrorRejection(e) { if (e && e.constructor === AssertionError) { setTimeout(function () { throw e; }, 0); } } function AssertionError(message) { this.name = 'AssertionError'; this.message = message || ''; this.stack = new Error().stack; } AssertionError.prototype = Object.create(Error.prototype); AssertionError.prototype.constructor = AssertionError; function assert(value, message) { if (!value) { throw new AssertionError(message); } } module.exports = { rethrowAssertionErrorRejection: rethrowAssertionErrorRejection, AssertionError: AssertionError, assert: assert }; }, function (module, exports, __w_pdfjs_require__) { "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; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __w_pdfjs_require__(0), InvokeOrNoop = _require.InvokeOrNoop, PromiseInvokeOrNoop = _require.PromiseInvokeOrNoop, ValidateAndNormalizeQueuingStrategy = _require.ValidateAndNormalizeQueuingStrategy, typeIsObject = _require.typeIsObject; var _require2 = __w_pdfjs_require__(1), assert = _require2.assert, rethrowAssertionErrorRejection = _require2.rethrowAssertionErrorRejection; var _require3 = __w_pdfjs_require__(3), DequeueValue = _require3.DequeueValue, EnqueueValueWithSize = _require3.EnqueueValueWithSize, PeekQueueValue = _require3.PeekQueueValue, ResetQueue = _require3.ResetQueue; var WritableStream = function () { function WritableStream() { var underlyingSink = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, size = _ref.size, _ref$highWaterMark = _ref.highWaterMark, highWaterMark = _ref$highWaterMark === undefined ? 1 : _ref$highWaterMark; _classCallCheck(this, WritableStream); this._state = 'writable'; this._storedError = undefined; this._writer = undefined; this._writableStreamController = undefined; this._writeRequests = []; this._inFlightWriteRequest = undefined; this._closeRequest = undefined; this._inFlightCloseRequest = undefined; this._pendingAbortRequest = undefined; this._backpressure = false; var type = underlyingSink.type; if (type !== undefined) { throw new RangeError('Invalid type is specified'); } this._writableStreamController = new WritableStreamDefaultController(this, underlyingSink, size, highWaterMark); this._writableStreamController.__startSteps(); } _createClass(WritableStream, [{ key: 'abort', value: function abort(reason) { if (IsWritableStream(this) === false) { return Promise.reject(streamBrandCheckException('abort')); } if (IsWritableStreamLocked(this) === true) { return Promise.reject(new TypeError('Cannot abort a stream that already has a writer')); } return WritableStreamAbort(this, reason); } }, { key: 'getWriter', value: function getWriter() { if (IsWritableStream(this) === false) { throw streamBrandCheckException('getWriter'); } return AcquireWritableStreamDefaultWriter(this); } }, { key: 'locked', get: function get() { if (IsWritableStream(this) === false) { throw streamBrandCheckException('locked'); } return IsWritableStreamLocked(this); } }]); return WritableStream; }(); module.exports = { AcquireWritableStreamDefaultWriter: AcquireWritableStreamDefaultWriter, IsWritableStream: IsWritableStream, IsWritableStreamLocked: IsWritableStreamLocked, WritableStream: WritableStream, WritableStreamAbort: WritableStreamAbort, WritableStreamDefaultControllerError: WritableStreamDefaultControllerError, WritableStreamDefaultWriterCloseWithErrorPropagation: WritableStreamDefaultWriterCloseWithErrorPropagation, WritableStreamDefaultWriterRelease: WritableStreamDefaultWriterRelease, WritableStreamDefaultWriterWrite: WritableStreamDefaultWriterWrite, WritableStreamCloseQueuedOrInFlight: WritableStreamCloseQueuedOrInFlight }; function AcquireWritableStreamDefaultWriter(stream) { return new WritableStreamDefaultWriter(stream); } function IsWritableStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { return false; } return true; } function IsWritableStreamLocked(stream) { assert(IsWritableStream(stream) === true, 'IsWritableStreamLocked should only be used on known writable streams'); if (stream._writer === undefined) { return false; } return true; } function WritableStreamAbort(stream, reason) { var state = stream._state; if (state === 'closed') { return Promise.resolve(undefined); } if (state === 'errored') { return Promise.reject(stream._storedError); } var error = new TypeError('Requested to abort'); if (stream._pendingAbortRequest !== undefined) { return Promise.reject(error); } assert(state === 'writable' || state === 'erroring', 'state must be writable or erroring'); var wasAlreadyErroring = false; if (state === 'erroring') { wasAlreadyErroring = true; reason = undefined; } var promise = new Promise(function (resolve, reject) { stream._pendingAbortRequest = { _resolve: resolve, _reject: reject, _reason: reason, _wasAlreadyErroring: wasAlreadyErroring }; }); if (wasAlreadyErroring === false) { WritableStreamStartErroring(stream, error); } return promise; } function WritableStreamAddWriteRequest(stream) { assert(IsWritableStreamLocked(stream) === true); assert(stream._state === 'writable'); var promise = new Promise(function (resolve, reject) { var writeRequest = { _resolve: resolve, _reject: reject }; stream._writeRequests.push(writeRequest); }); return promise; } function WritableStreamDealWithRejection(stream, error) { var state = stream._state; if (state === 'writable') { WritableStreamStartErroring(stream, error); return; } assert(state === 'erroring'); WritableStreamFinishErroring(stream); } function WritableStreamStartErroring(stream, reason) { assert(stream._storedError === undefined, 'stream._storedError === undefined'); assert(stream._state === 'writable', 'state must be writable'); var controller = stream._writableStreamController; assert(controller !== undefined, 'controller must not be undefined'); stream._state = 'erroring'; stream._storedError = reason; var writer = stream._writer; if (writer !== undefined) { WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); } if (WritableStreamHasOperationMarkedInFlight(stream) === false && controller._started === true) { WritableStreamFinishErroring(stream); } } function WritableStreamFinishErroring(stream) { assert(stream._state === 'erroring', 'stream._state === erroring'); assert(WritableStreamHasOperationMarkedInFlight(stream) === false, 'WritableStreamHasOperationMarkedInFlight(stream) === false'); stream._state = 'errored'; stream._writableStreamController.__errorSteps(); var storedError = stream._storedError; for (var i = 0; i < stream._writeRequests.length; i++) { var writeRequest = stream._writeRequests[i]; writeRequest._reject(storedError); } stream._writeRequests = []; if (stream._pendingAbortRequest === undefined) { WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } var abortRequest = stream._pendingAbortRequest; stream._pendingAbortRequest = undefined; if (abortRequest._wasAlreadyErroring === true) { abortRequest._reject(storedError); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); return; } var promise = stream._writableStreamController.__abortSteps(abortRequest._reason); promise.then(function () { abortRequest._resolve(); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); }, function (reason) { abortRequest._reject(reason); WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); }); } function WritableStreamFinishInFlightWrite(stream) { assert(stream._inFlightWriteRequest !== undefined); stream._inFlightWriteRequest._resolve(undefined); stream._inFlightWriteRequest = undefined; } function WritableStreamFinishInFlightWriteWithError(stream, error) { assert(stream._inFlightWriteRequest !== undefined); stream._inFlightWriteRequest._reject(error); stream._inFlightWriteRequest = undefined; assert(stream._state === 'writable' || stream._state === 'erroring'); WritableStreamDealWithRejection(stream, error); } function WritableStreamFinishInFlightClose(stream) { assert(stream._inFlightCloseRequest !== undefined); stream._inFlightCloseRequest._resolve(undefined); stream._inFlightCloseRequest = undefined; var state = stream._state; assert(state === 'writable' || state === 'erroring'); if (state === 'erroring') { stream._storedError = undefined; if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._resolve(); stream._pendingAbortRequest = undefined; } } stream._state = 'closed'; var writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseResolve(writer); } assert(stream._pendingAbortRequest === undefined, 'stream._pendingAbortRequest === undefined'); assert(stream._storedError === undefined, 'stream._storedError === undefined'); } function WritableStreamFinishInFlightCloseWithError(stream, error) { assert(stream._inFlightCloseRequest !== undefined); stream._inFlightCloseRequest._reject(error); stream._inFlightCloseRequest = undefined; assert(stream._state === 'writable' || stream._state === 'erroring'); if (stream._pendingAbortRequest !== undefined) { stream._pendingAbortRequest._reject(error); stream._pendingAbortRequest = undefined; } WritableStreamDealWithRejection(stream, error); } function WritableStreamCloseQueuedOrInFlight(stream) { if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamHasOperationMarkedInFlight(stream) { if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { return false; } return true; } function WritableStreamMarkCloseRequestInFlight(stream) { assert(stream._inFlightCloseRequest === undefined); assert(stream._closeRequest !== undefined); stream._inFlightCloseRequest = stream._closeRequest; stream._closeRequest = undefined; } function WritableStreamMarkFirstWriteRequestInFlight(stream) { assert(stream._inFlightWriteRequest === undefined, 'there must be no pending write request'); assert(stream._writeRequests.length !== 0, 'writeRequests must not be empty'); stream._inFlightWriteRequest = stream._writeRequests.shift(); } function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { assert(stream._state === 'errored', '_stream_.[[state]] is `"errored"`'); if (stream._closeRequest !== undefined) { assert(stream._inFlightCloseRequest === undefined); stream._closeRequest._reject(stream._storedError); stream._closeRequest = undefined; } var writer = stream._writer; if (writer !== undefined) { defaultWriterClosedPromiseReject(writer, stream._storedError); writer._closedPromise.catch(function () {}); } } function WritableStreamUpdateBackpressure(stream, backpressure) { assert(stream._state === 'writable'); assert(WritableStreamCloseQueuedOrInFlight(stream) === false); var writer = stream._writer; if (writer !== undefined && backpressure !== stream._backpressure) { if (backpressure === true) { defaultWriterReadyPromiseReset(writer); } else { assert(backpressure === false); defaultWriterReadyPromiseResolve(writer); } } stream._backpressure = backpressure; } var WritableStreamDefaultWriter = function () { function WritableStreamDefaultWriter(stream) { _classCallCheck(this, WritableStreamDefaultWriter); if (IsWritableStream(stream) === false) { throw new TypeError('WritableStreamDefaultWriter can only be constructed with a WritableStream instance'); } if (IsWritableStreamLocked(stream) === true) { throw new TypeError('This stream has already been locked for exclusive writing by another writer'); } this._ownerWritableStream = stream; stream._writer = this; var state = stream._state; if (state === 'writable') { if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._backpressure === true) { defaultWriterReadyPromiseInitialize(this); } else { defaultWriterReadyPromiseInitializeAsResolved(this); } defaultWriterClosedPromiseInitialize(this); } else if (state === 'erroring') { defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); this._readyPromise.catch(function () {}); defaultWriterClosedPromiseInitialize(this); } else if (state === 'closed') { defaultWriterReadyPromiseInitializeAsResolved(this); defaultWriterClosedPromiseInitializeAsResolved(this); } else { assert(state === 'errored', 'state must be errored'); var storedError = stream._storedError; defaultWriterReadyPromiseInitializeAsRejected(this, storedError); this._readyPromise.catch(function () {}); defaultWriterClosedPromiseInitializeAsRejected(this, storedError); this._closedPromise.catch(function () {}); } } _createClass(WritableStreamDefaultWriter, [{ key: 'abort', value: function abort(reason) { if (IsWritableStreamDefaultWriter(this) === false) { return Promise.reject(defaultWriterBrandCheckException('abort')); } if (this._ownerWritableStream === undefined) { return Promise.reject(defaultWriterLockException('abort')); } return WritableStreamDefaultWriterAbort(this, reason); } }, { key: 'close', value: function close() { if (IsWritableStreamDefaultWriter(this) === false) { return Promise.reject(defaultWriterBrandCheckException('close')); } var stream = this._ownerWritableStream; if (stream === undefined) { return Promise.reject(defaultWriterLockException('close')); } if (WritableStreamCloseQueuedOrInFlight(stream) === true) { return Promise.reject(new TypeError('cannot close an already-closing stream')); } return WritableStreamDefaultWriterClose(this); } }, { key: 'releaseLock', value: function releaseLock() { if (IsWritableStreamDefaultWriter(this) === false) { throw defaultWriterBrandCheckException('releaseLock'); } var stream = this._ownerWritableStream; if (stream === undefined) { return; } assert(stream._writer !== undefined); WritableStreamDefaultWriterRelease(this); } }, { key: 'write', value: function write(chunk) { if (IsWritableStreamDefaultWriter(this) === false) { return Promise.reject(defaultWriterBrandCheckException('write')); } if (this._ownerWritableStream === undefined) { return Promise.reject(defaultWriterLockException('write to')); } return WritableStreamDefaultWriterWrite(this, chunk); } }, { key: 'closed', get: function get() { if (IsWritableStreamDefaultWriter(this) === false) { return Promise.reject(defaultWriterBrandCheckException('closed')); } return this._closedPromise; } }, { key: 'desiredSize', get: function get() { if (IsWritableStreamDefaultWriter(this) === false) { throw defaultWriterBrandCheckException('desiredSize'); } if (this._ownerWritableStream === undefined) { throw defaultWriterLockException('desiredSize'); } return WritableStreamDefaultWriterGetDesiredSize(this); } }, { key: 'ready', get: function get() { if (IsWritableStreamDefaultWriter(this) === false) { return Promise.reject(defaultWriterBrandCheckException('ready')); } return this._readyPromise; } }]); return WritableStreamDefaultWriter; }(); function IsWritableStreamDefaultWriter(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { return false; } return true; } function WritableStreamDefaultWriterAbort(writer, reason) { var stream = writer._ownerWritableStream; assert(stream !== undefined); return WritableStreamAbort(stream, reason); } function WritableStreamDefaultWriterClose(writer) { var stream = writer._ownerWritableStream; assert(stream !== undefined); var state = stream._state; if (state === 'closed' || state === 'errored') { return Promise.reject(new TypeError('The stream (in ' + state + ' state) is not in the writable state and cannot be closed')); } assert(state === 'writable' || state === 'erroring'); assert(WritableStreamCloseQueuedOrInFlight(stream) === false); var promise = new Promise(function (resolve, reject) { var closeRequest = { _resolve: resolve, _reject: reject }; stream._closeRequest = closeRequest; }); if (stream._backpressure === true && state === 'writable') { defaultWriterReadyPromiseResolve(writer); } WritableStreamDefaultControllerClose(stream._writableStreamController); return promise; } function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { var stream = writer._ownerWritableStream; assert(stream !== undefined); var state = stream._state; if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') { return Promise.resolve(); } if (state === 'errored') { return Promise.reject(stream._storedError); } assert(state === 'writable' || state === 'erroring'); return WritableStreamDefaultWriterClose(writer); } function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { if (writer._closedPromiseState === 'pending') { defaultWriterClosedPromiseReject(writer, error); } else { defaultWriterClosedPromiseResetToRejected(writer, error); } writer._closedPromise.catch(function () {}); } function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { if (writer._readyPromiseState === 'pending') { defaultWriterReadyPromiseReject(writer, error); } else { defaultWriterReadyPromiseResetToRejected(writer, error); } writer._readyPromise.catch(function () {}); } function WritableStreamDefaultWriterGetDesiredSize(writer) { var stream = writer._ownerWritableStream; var state = stream._state; if (state === 'errored' || state === 'erroring') { return null; } if (state === 'closed') { return 0; } return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); } function WritableStreamDefaultWriterRelease(writer) { var stream = writer._ownerWritableStream; assert(stream !== undefined); assert(stream._writer === writer); var releasedError = new TypeError('Writer was released and can no longer be used to monitor the stream\'s closedness'); WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); stream._writer = undefined; writer._ownerWritableStream = undefined; } function WritableStreamDefaultWriterWrite(writer, chunk) { var stream = writer._ownerWritableStream; assert(stream !== undefined); var controller = stream._writableStreamController; var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); if (stream !== writer._ownerWritableStream) { return Promise.reject(defaultWriterLockException('write to')); } var state = stream._state; if (state === 'errored') { return Promise.reject(stream._storedError); } if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') { return Promise.reject(new TypeError('The stream is closing or closed and cannot be written to')); } if (state === 'erroring') { return Promise.reject(stream._storedError); } assert(state === 'writable'); var promise = WritableStreamAddWriteRequest(stream); WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); return promise; } var WritableStreamDefaultController = function () { function WritableStreamDefaultController(stream, underlyingSink, size, highWaterMark) { _classCallCheck(this, WritableStreamDefaultController); if (IsWritableStream(stream) === false) { throw new TypeError('WritableStreamDefaultController can only be constructed with a WritableStream instance'); } if (stream._writableStreamController !== undefined) { throw new TypeError('WritableStreamDefaultController instances can only be created by the WritableStream constructor'); } this._controlledWritableStream = stream; this._underlyingSink = underlyingSink; this._queue = undefined; this._queueTotalSize = undefined; ResetQueue(this); this._started = false; var normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark); this._strategySize = normalizedStrategy.size; this._strategyHWM = normalizedStrategy.highWaterMark; var backpressure = WritableStreamDefaultControllerGetBackpressure(this); WritableStreamUpdateBackpressure(stream, backpressure); } _createClass(WritableStreamDefaultController, [{ key: 'error', value: function error(e) { if (IsWritableStreamDefaultController(this) === false) { throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController'); } var state = this._controlledWritableStream._state; if (state !== 'writable') { return; } WritableStreamDefaultControllerError(this, e); } }, { key: '__abortSteps', value: function __abortSteps(reason) { return PromiseInvokeOrNoop(this._underlyingSink, 'abort', [reason]); } }, { key: '__errorSteps', value: function __errorSteps() { ResetQueue(this); } }, { key: '__startSteps', value: function __startSteps() { var _this = this; var startResult = InvokeOrNoop(this._underlyingSink, 'start', [this]); var stream = this._controlledWritableStream; Promise.resolve(startResult).then(function () { assert(stream._state === 'writable' || stream._state === 'erroring'); _this._started = true; WritableStreamDefaultControllerAdvanceQueueIfNeeded(_this); }, function (r) { assert(stream._state === 'writable' || stream._state === 'erroring'); _this._started = true; WritableStreamDealWithRejection(stream, r); }).catch(rethrowAssertionErrorRejection); } }]); return WritableStreamDefaultController; }(); function WritableStreamDefaultControllerClose(controller) { EnqueueValueWithSize(controller, 'close', 0); WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { var strategySize = controller._strategySize; if (strategySize === undefined) { return 1; } try { return strategySize(chunk); } catch (chunkSizeE) { WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); return 1; } } function WritableStreamDefaultControllerGetDesiredSize(controller) { return controller._strategyHWM - controller._queueTotalSize; } function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { var writeRecord = { chunk: chunk }; try { EnqueueValueWithSize(controller, writeRecord, chunkSize); } catch (enqueueE) { WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); return; } var stream = controller._controlledWritableStream; if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._state === 'writable') { var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); } function IsWritableStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSink')) { return false; } return true; } function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { var stream = controller._controlledWritableStream; if (controller._started === false) { return; } if (stream._inFlightWriteRequest !== undefined) { return; } var state = stream._state; if (state === 'closed' || state === 'errored') { return; } if (state === 'erroring') { WritableStreamFinishErroring(stream); return; } if (controller._queue.length === 0) { return; } var writeRecord = PeekQueueValue(controller); if (writeRecord === 'close') { WritableStreamDefaultControllerProcessClose(controller); } else { WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk); } } function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { if (controller._controlledWritableStream._state === 'writable') { WritableStreamDefaultControllerError(controller, error); } } function WritableStreamDefaultControllerProcessClose(controller) { var stream = controller._controlledWritableStream; WritableStreamMarkCloseRequestInFlight(stream); DequeueValue(controller); assert(controller._queue.length === 0, 'queue must be empty once the final write record is dequeued'); var sinkClosePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'close', []); sinkClosePromise.then(function () { WritableStreamFinishInFlightClose(stream); }, function (reason) { WritableStreamFinishInFlightCloseWithError(stream, reason); }).catch(rethrowAssertionErrorRejection); } function WritableStreamDefaultControllerProcessWrite(controller, chunk) { var stream = controller._controlledWritableStream; WritableStreamMarkFirstWriteRequestInFlight(stream); var sinkWritePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'write', [chunk, controller]); sinkWritePromise.then(function () { WritableStreamFinishInFlightWrite(stream); var state = stream._state; assert(state === 'writable' || state === 'erroring'); DequeueValue(controller); if (WritableStreamCloseQueuedOrInFlight(stream) === false && state === 'writable') { var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); WritableStreamUpdateBackpressure(stream, backpressure); } WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); }, function (reason) { WritableStreamFinishInFlightWriteWithError(stream, reason); }).catch(rethrowAssertionErrorRejection); } function WritableStreamDefaultControllerGetBackpressure(controller) { var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); return desiredSize <= 0; } function WritableStreamDefaultControllerError(controller, error) { var stream = controller._controlledWritableStream; assert(stream._state === 'writable'); WritableStreamStartErroring(stream, error); } function streamBrandCheckException(name) { return new TypeError('WritableStream.prototype.' + name + ' can only be used on a WritableStream'); } function defaultWriterBrandCheckException(name) { return new TypeError('WritableStreamDefaultWriter.prototype.' + name + ' can only be used on a WritableStreamDefaultWriter'); } function defaultWriterLockException(name) { return new TypeError('Cannot ' + name + ' a stream using a released writer'); } function defaultWriterClosedPromiseInitialize(writer) { writer._closedPromise = new Promise(function (resolve, reject) { writer._closedPromise_resolve = resolve; writer._closedPromise_reject = reject; writer._closedPromiseState = 'pending'; }); } function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { writer._closedPromise = Promise.reject(reason); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'rejected'; } function defaultWriterClosedPromiseInitializeAsResolved(writer) { writer._closedPromise = Promise.resolve(undefined); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'resolved'; } function defaultWriterClosedPromiseReject(writer, reason) { assert(writer._closedPromise_resolve !== undefined, 'writer._closedPromise_resolve !== undefined'); assert(writer._closedPromise_reject !== undefined, 'writer._closedPromise_reject !== undefined'); assert(writer._closedPromiseState === 'pending', 'writer._closedPromiseState is pending'); writer._closedPromise_reject(reason); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'rejected'; } function defaultWriterClosedPromiseResetToRejected(writer, reason) { assert(writer._closedPromise_resolve === undefined, 'writer._closedPromise_resolve === undefined'); assert(writer._closedPromise_reject === undefined, 'writer._closedPromise_reject === undefined'); assert(writer._closedPromiseState !== 'pending', 'writer._closedPromiseState is not pending'); writer._closedPromise = Promise.reject(reason); writer._closedPromiseState = 'rejected'; } function defaultWriterClosedPromiseResolve(writer) { assert(writer._closedPromise_resolve !== undefined, 'writer._closedPromise_resolve !== undefined'); assert(writer._closedPromise_reject !== undefined, 'writer._closedPromise_reject !== undefined'); assert(writer._closedPromiseState === 'pending', 'writer._closedPromiseState is pending'); writer._closedPromise_resolve(undefined); writer._closedPromise_resolve = undefined; writer._closedPromise_reject = undefined; writer._closedPromiseState = 'resolved'; } function defaultWriterReadyPromiseInitialize(writer) { writer._readyPromise = new Promise(function (resolve, reject) { writer._readyPromise_resolve = resolve; writer._readyPromise_reject = reject; }); writer._readyPromiseState = 'pending'; } function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { writer._readyPromise = Promise.reject(reason); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'rejected'; } function defaultWriterReadyPromiseInitializeAsResolved(writer) { writer._readyPromise = Promise.resolve(undefined); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'fulfilled'; } function defaultWriterReadyPromiseReject(writer, reason) { assert(writer._readyPromise_resolve !== undefined, 'writer._readyPromise_resolve !== undefined'); assert(writer._readyPromise_reject !== undefined, 'writer._readyPromise_reject !== undefined'); writer._readyPromise_reject(reason); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'rejected'; } function defaultWriterReadyPromiseReset(writer) { assert(writer._readyPromise_resolve === undefined, 'writer._readyPromise_resolve === undefined'); assert(writer._readyPromise_reject === undefined, 'writer._readyPromise_reject === undefined'); writer._readyPromise = new Promise(function (resolve, reject) { writer._readyPromise_resolve = resolve; writer._readyPromise_reject = reject; }); writer._readyPromiseState = 'pending'; } function defaultWriterReadyPromiseResetToRejected(writer, reason) { assert(writer._readyPromise_resolve === undefined, 'writer._readyPromise_resolve === undefined'); assert(writer._readyPromise_reject === undefined, 'writer._readyPromise_reject === undefined'); writer._readyPromise = Promise.reject(reason); writer._readyPromiseState = 'rejected'; } function defaultWriterReadyPromiseResolve(writer) { assert(writer._readyPromise_resolve !== undefined, 'writer._readyPromise_resolve !== undefined'); assert(writer._readyPromise_reject !== undefined, 'writer._readyPromise_reject !== undefined'); writer._readyPromise_resolve(undefined); writer._readyPromise_resolve = undefined; writer._readyPromise_reject = undefined; writer._readyPromiseState = 'fulfilled'; } }, function (module, exports, __w_pdfjs_require__) { "use strict"; var _require = __w_pdfjs_require__(0), IsFiniteNonNegativeNumber = _require.IsFiniteNonNegativeNumber; var _require2 = __w_pdfjs_require__(1), assert = _require2.assert; exports.DequeueValue = function (container) { assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: DequeueValue should only be used on containers with [[queue]] and [[queueTotalSize]].'); assert(container._queue.length > 0, 'Spec-level failure: should never dequeue from an empty queue.'); var pair = container._queue.shift(); container._queueTotalSize -= pair.size; if (container._queueTotalSize < 0) { container._queueTotalSize = 0; } return pair.value; }; exports.EnqueueValueWithSize = function (container, value, size) { assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: EnqueueValueWithSize should only be used on containers with [[queue]] and ' + '[[queueTotalSize]].'); size = Number(size); if (!IsFiniteNonNegativeNumber(size)) { throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); } container._queue.push({ value: value, size: size }); container._queueTotalSize += size; }; exports.PeekQueueValue = function (container) { assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: PeekQueueValue should only be used on containers with [[queue]] and [[queueTotalSize]].'); assert(container._queue.length > 0, 'Spec-level failure: should never peek at an empty queue.'); var pair = container._queue[0]; return pair.value; }; exports.ResetQueue = function (container) { assert('_queue' in container && '_queueTotalSize' in container, 'Spec-level failure: ResetQueue should only be used on containers with [[queue]] and [[queueTotalSize]].'); container._queue = []; container._queueTotalSize = 0; }; }, function (module, exports, __w_pdfjs_require__) { "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; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __w_pdfjs_require__(0), ArrayBufferCopy = _require.ArrayBufferCopy, CreateIterResultObject = _require.CreateIterResultObject, IsFiniteNonNegativeNumber = _require.IsFiniteNonNegativeNumber, InvokeOrNoop = _require.InvokeOrNoop, PromiseInvokeOrNoop = _require.PromiseInvokeOrNoop, TransferArrayBuffer = _require.TransferArrayBuffer, ValidateAndNormalizeQueuingStrategy = _require.ValidateAndNormalizeQueuingStrategy, ValidateAndNormalizeHighWaterMark = _require.ValidateAndNormalizeHighWaterMark; var _require2 = __w_pdfjs_require__(0), createArrayFromList = _require2.createArrayFromList, createDataProperty = _require2.createDataProperty, typeIsObject = _require2.typeIsObject; var _require3 = __w_pdfjs_require__(1), assert = _require3.assert, rethrowAssertionErrorRejection = _require3.rethrowAssertionErrorRejection; var _require4 = __w_pdfjs_require__(3), DequeueValue = _require4.DequeueValue, EnqueueValueWithSize = _require4.EnqueueValueWithSize, ResetQueue = _require4.ResetQueue; var _require5 = __w_pdfjs_require__(2), AcquireWritableStreamDefaultWriter = _require5.AcquireWritableStreamDefaultWriter, IsWritableStream = _require5.IsWritableStream, IsWritableStreamLocked = _require5.IsWritableStreamLocked, WritableStreamAbort = _require5.WritableStreamAbort, WritableStreamDefaultWriterCloseWithErrorPropagation = _require5.WritableStreamDefaultWriterCloseWithErrorPropagation, WritableStreamDefaultWriterRelease = _require5.WritableStreamDefaultWriterRelease, WritableStreamDefaultWriterWrite = _require5.WritableStreamDefaultWriterWrite, WritableStreamCloseQueuedOrInFlight = _require5.WritableStreamCloseQueuedOrInFlight; var ReadableStream = function () { function ReadableStream() { var underlyingSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, size = _ref.size, highWaterMark = _ref.highWaterMark; _classCallCheck(this, ReadableStream); this._state = 'readable'; this._reader = undefined; this._storedError = undefined; this._disturbed = false; this._readableStreamController = undefined; var type = underlyingSource.type; var typeString = String(type); if (typeString === 'bytes') { if (highWaterMark === undefined) { highWaterMark = 0; } this._readableStreamController = new ReadableByteStreamController(this, underlyingSource, highWaterMark); } else if (type === undefined) { if (highWaterMark === undefined) { highWaterMark = 1; } this._readableStreamController = new ReadableStreamDefaultController(this, underlyingSource, size, highWaterMark); } else { throw new RangeError('Invalid type is specified'); } } _createClass(ReadableStream, [{ key: 'cancel', value: function cancel(reason) { if (IsReadableStream(this) === false) { return Promise.reject(streamBrandCheckException('cancel')); } if (IsReadableStreamLocked(this) === true) { return Promise.reject(new TypeError('Cannot cancel a stream that already has a reader')); } return ReadableStreamCancel(this, reason); } }, { key: 'getReader', value: function getReader() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, mode = _ref2.mode; if (IsReadableStream(this) === false) { throw streamBrandCheckException('getReader'); } if (mode === undefined) { return AcquireReadableStreamDefaultReader(this); } mode = String(mode); if (mode === 'byob') { return AcquireReadableStreamBYOBReader(this); } throw new RangeError('Invalid mode is specified'); } }, { key: 'pipeThrough', value: function pipeThrough(_ref3, options) { var writable = _ref3.writable, readable = _ref3.readable; var promise = this.pipeTo(writable, options); ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise); return readable; } }, { key: 'pipeTo', value: function pipeTo(dest) { var _this = this; var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, preventClose = _ref4.preventClose, preventAbort = _ref4.preventAbort, preventCancel = _ref4.preventCancel; if (IsReadableStream(this) === false) { return Promise.reject(streamBrandCheckException('pipeTo')); } if (IsWritableStream(dest) === false) { return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo\'s first argument must be a WritableStream')); } preventClose = Boolean(preventClose); preventAbort = Boolean(preventAbort); preventCancel = Boolean(preventCancel); if (IsReadableStreamLocked(this) === true) { return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); } if (IsWritableStreamLocked(dest) === true) { return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); } var reader = AcquireReadableStreamDefaultReader(this); var writer = AcquireWritableStreamDefaultWriter(dest); var shuttingDown = false; var currentWrite = Promise.resolve(); return new Promise(function (resolve, reject) { function pipeLoop() { currentWrite = Promise.resolve(); if (shuttingDown === true) { return Promise.resolve(); } return writer._readyPromise.then(function () { return ReadableStreamDefaultReaderRead(reader).then(function (_ref5) { var value = _ref5.value, done = _ref5.done; if (done === true) { return; } currentWrite = WritableStreamDefaultWriterWrite(writer, value).catch(function () {}); }); }).then(pipeLoop); } isOrBecomesErrored(_this, reader._closedPromise, function (storedError) { if (preventAbort === false) { shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); } else { shutdown(true, storedError); } }); isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { if (preventCancel === false) { shutdownWithAction(function () { return ReadableStreamCancel(_this, storedError); }, true, storedError); } else { shutdown(true, storedError); } }); isOrBecomesClosed(_this, reader._closedPromise, function () { if (preventClose === false) { shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); } else { shutdown(); } }); if (WritableStreamCloseQueuedOrInFlight(dest) === true || dest._state === 'closed') { var destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); if (preventCancel === false) { shutdownWithAction(function () { return ReadableStreamCancel(_this, destClosed); }, true, destClosed); } else { shutdown(true, destClosed); } } pipeLoop().catch(function (err) { currentWrite = Promise.resolve(); rethrowAssertionErrorRejection(err); }); function waitForWritesToFinish() { var oldCurrentWrite = currentWrite; return currentWrite.then(function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); } function isOrBecomesErrored(stream, promise, action) { if (stream._state === 'errored') { action(stream._storedError); } else { promise.catch(action).catch(rethrowAssertionErrorRejection); } } function isOrBecomesClosed(stream, promise, action) { if (stream._state === 'closed') { action(); } else { promise.then(action).catch(rethrowAssertionErrorRejection); } } function shutdownWithAction(action, originalIsError, originalError) { if (shuttingDown === true) { return; } shuttingDown = true; if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) { waitForWritesToFinish().then(doTheRest); } else { doTheRest(); } function doTheRest() { action().then(function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }).catch(rethrowAssertionErrorRejection); } } function shutdown(isError, error) { if (shuttingDown === true) { return; } shuttingDown = true; if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) { waitForWritesToFinish().then(function () { return finalize(isError, error); }).catch(rethrowAssertionErrorRejection); } else { finalize(isError, error); } } function finalize(isError, error) { WritableStreamDefaultWriterRelease(writer); ReadableStreamReaderGenericRelease(reader); if (isError) { reject(error); } else { resolve(undefined); } } }); } }, { key: 'tee', value: function tee() { if (IsReadableStream(this) === false) { throw streamBrandCheckException('tee'); } var branches = ReadableStreamTee(this, false); return createArrayFromList(branches); } }, { key: 'locked', get: function get() { if (IsReadableStream(this) === false) { throw streamBrandCheckException('locked'); } return IsReadableStreamLocked(this); } }]); return ReadableStream; }(); module.exports = { ReadableStream: ReadableStream, IsReadableStreamDisturbed: IsReadableStreamDisturbed, ReadableStreamDefaultControllerClose: ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue: ReadableStreamDefaultControllerEnqueue, ReadableStreamDefaultControllerError: ReadableStreamDefaultControllerError, ReadableStreamDefaultControllerGetDesiredSize: ReadableStreamDefaultControllerGetDesiredSize }; function AcquireReadableStreamBYOBReader(stream) { return new ReadableStreamBYOBReader(stream); } function AcquireReadableStreamDefaultReader(stream) { return new ReadableStreamDefaultReader(stream); } function IsReadableStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { return false; } return true; } function IsReadableStreamDisturbed(stream) { assert(IsReadableStream(stream) === true, 'IsReadableStreamDisturbed should only be used on known readable streams'); return stream._disturbed; } function IsReadableStreamLocked(stream) { assert(IsReadableStream(stream) === true, 'IsReadableStreamLocked should only be used on known readable streams'); if (stream._reader === undefined) { return false; } return true; } function ReadableStreamTee(stream, cloneForBranch2) { assert(IsReadableStream(stream) === true); assert(typeof cloneForBranch2 === 'boolean'); var reader = AcquireReadableStreamDefaultReader(stream); var teeState = { closedOrErrored: false, canceled1: false, canceled2: false, reason1: undefined, reason2: undefined }; teeState.promise = new Promise(function (resolve) { teeState._resolve = resolve; }); var pull = create_ReadableStreamTeePullFunction(); pull._reader = reader; pull._teeState = teeState; pull._cloneForBranch2 = cloneForBranch2; var cancel1 = create_ReadableStreamTeeBranch1CancelFunction(); cancel1._stream = stream; cancel1._teeState = teeState; var cancel2 = create_ReadableStreamTeeBranch2CancelFunction(); cancel2._stream = stream; cancel2._teeState = teeState; var underlyingSource1 = Object.create(Object.prototype); createDataProperty(underlyingSource1, 'pull', pull); createDataProperty(underlyingSource1, 'cancel', cancel1); var branch1Stream = new ReadableStream(underlyingSource1); var underlyingSource2 = Object.create(Object.prototype); createDataProperty(underlyingSource2, 'pull', pull); createDataProperty(underlyingSource2, 'cancel', cancel2); var branch2Stream = new ReadableStream(underlyingSource2); pull._branch1 = branch1Stream._readableStreamController; pull._branch2 = branch2Stream._readableStreamController; reader._closedPromise.catch(function (r) { if (teeState.closedOrErrored === true) { return; } ReadableStreamDefaultControllerError(pull._branch1, r); ReadableStreamDefaultControllerError(pull._branch2, r); teeState.closedOrErrored = true; }); return [branch1Stream, branch2Stream]; } function create_ReadableStreamTeePullFunction() { function f() { var reader = f._reader, branch1 = f._branch1, branch2 = f._branch2, teeState = f._teeState; return ReadableStreamDefaultReaderRead(reader).then(function (result) { assert(typeIsObject(result)); var value = result.value; var done = result.done; assert(typeof done === 'boolean'); if (done === true && teeState.closedOrErrored === false) { if (teeState.canceled1 === false) { ReadableStreamDefaultControllerClose(branch1); } if (teeState.canceled2 === false) { ReadableStreamDefaultControllerClose(branch2); } teeState.closedOrErrored = true; } if (teeState.closedOrErrored === true) { return; } var value1 = value; var value2 = value; if (teeState.canceled1 === false) { ReadableStreamDefaultControllerEnqueue(branch1, value1); } if (teeState.canceled2 === false) { ReadableStreamDefaultControllerEnqueue(branch2, value2); } }); } return f; } function create_ReadableStreamTeeBranch1CancelFunction() { function f(reason) { var stream = f._stream, teeState = f._teeState; teeState.canceled1 = true; teeState.reason1 = reason; if (teeState.canceled2 === true) { var compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]); var cancelResult = ReadableStreamCancel(stream, compositeReason); teeState._resolve(cancelResult); } return teeState.promise; } return f; } function create_ReadableStreamTeeBranch2CancelFunction() { function f(reason) { var stream = f._stream, teeState = f._teeState; teeState.canceled2 = true; teeState.reason2 = reason; if (teeState.canceled1 === true) { var compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]); var cancelResult = ReadableStreamCancel(stream, compositeReason); teeState._resolve(cancelResult); } return teeState.promise; } return f; } function ReadableStreamAddReadIntoRequest(stream) { assert(IsReadableStreamBYOBReader(stream._reader) === true); assert(stream._state === 'readable' || stream._state === 'closed'); var promise = new Promise(function (resolve, reject) { var readIntoRequest = { _resolve: resolve, _reject: reject }; stream._reader._readIntoRequests.push(readIntoRequest); }); return promise; } function ReadableStreamAddReadRequest(stream) { assert(IsReadableStreamDefaultReader(stream._reader) === true); assert(stream._state === 'readable'); var promise = new Promise(function (resolve, reject) { var readRequest = { _resolve: resolve, _reject: reject }; stream._reader._readRequests.push(readRequest); }); return promise; } function ReadableStreamCancel(stream, reason) { stream._disturbed = true; if (stream._state === 'closed') { return Promise.resolve(undefined); } if (stream._state === 'errored') { return Promise.reject(stream._storedError); } ReadableStreamClose(stream); var sourceCancelPromise = stream._readableStreamController.__cancelSteps(reason); return sourceCancelPromise.then(function () { return undefined; }); } function ReadableStreamClose(stream) { assert(stream._state === 'readable'); stream._state = 'closed'; var reader = stream._reader; if (reader === undefined) { return undefined; } if (IsReadableStreamDefaultReader(reader) === true) { for (var i = 0; i < reader._readRequests.length; i++) { var _resolve = reader._readRequests[i]._resolve; _resolve(CreateIterResultObject(undefined, true)); } reader._readRequests = []; } defaultReaderClosedPromiseResolve(reader); return undefined; } function ReadableStreamError(stream, e) { assert(IsReadableStream(stream) === true, 'stream must be ReadableStream'); assert(stream._state === 'readable', 'state must be readable'); stream._state = 'errored'; stream._storedError = e; var reader = stream._reader; if (reader === undefined) { return undefined; } if (IsReadableStreamDefaultReader(reader) === true) { for (var i = 0; i < reader._readRequests.length; i++) { var readRequest = reader._readRequests[i]; readRequest._reject(e); } reader._readRequests = []; } else { assert(IsReadableStreamBYOBReader(reader), 'reader must be ReadableStreamBYOBReader'); for (var _i = 0; _i < reader._readIntoRequests.length; _i++) { var readIntoRequest = reader._readIntoRequests[_i]; readIntoRequest._reject(e); } reader._readIntoRequests = []; } defaultReaderClosedPromiseReject(reader, e); reader._closedPromise.catch(function () {}); } function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { var reader = stream._reader; assert(reader._readIntoRequests.length > 0); var readIntoRequest = reader._readIntoRequests.shift(); readIntoRequest._resolve(CreateIterResultObject(chunk, done)); } function ReadableStreamFulfillReadRequest(stream, chunk, done) { var reader = stream._reader; assert(reader._readRequests.length > 0); var readRequest = reader._readRequests.shift(); readRequest._resolve(CreateIterResultObject(chunk, done)); } function ReadableStreamGetNumReadIntoRequests(stream) { return stream._reader._readIntoRequests.length; } function ReadableStreamGetNumReadRequests(stream) { return stream._reader._readRequests.length; } function ReadableStreamHasBYOBReader(stream) { var reader = stream._reader; if (reader === undefined) { return false; } if (IsReadableStreamBYOBReader(reader) === false) { return false; } return true; } function ReadableStreamHasDefaultReader(stream) { var reader = stream._reader; if (reader === undefined) { return false; } if (IsReadableStreamDefaultReader(reader) === false) { return false; } return true; } var ReadableStreamDefaultReader = function () { function ReadableStreamDefaultReader(stream) { _classCallCheck(this, ReadableStreamDefaultReader); if (IsReadableStream(stream) === false) { throw new TypeError('ReadableStreamDefaultReader can only be constructed with a ReadableStream instance'); } if (IsReadableStreamLocked(stream) === true) { throw new TypeError('This stream has already been locked for exclusive reading by another reader'); } ReadableStreamReaderGenericInitialize(this, stream); this._readRequests = []; } _createClass(ReadableStreamDefaultReader, [{ key: 'cancel', value: function cancel(reason) { if (IsReadableStreamDefaultReader(this) === false) { return Promise.reject(defaultReaderBrandCheckException('cancel')); } if (this._ownerReadableStream === undefined) { return Promise.reject(readerLockException('cancel')); } return ReadableStreamReaderGenericCancel(this, reason); } }, { key: 'read', value: function read() { if (IsReadableStreamDefaultReader(this) === false) { return Promise.reject(defaultReaderBrandCheckException('read')); } if (this._ownerReadableStream === undefined) { return Promise.reject(readerLockException('read from')); } return ReadableStreamDefaultReaderRead(this); } }, { key: 'releaseLock', value: function releaseLock() { if (IsReadableStreamDefaultReader(this) === false) { throw defaultReaderBrandCheckException('releaseLock'); } if (this._ownerReadableStream === undefined) { return; } if (this._readRequests.length > 0) { throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); } ReadableStreamReaderGenericRelease(this); } }, { key: 'closed', get: function get() { if (IsReadableStreamDefaultReader(this) === false) { return Promise.reject(defaultReaderBrandCheckException('closed')); } return this._closedPromise; } }]); return ReadableStreamDefaultReader; }(); var ReadableStreamBYOBReader = function () { function ReadableStreamBYOBReader(stream) { _classCallCheck(this, ReadableStreamBYOBReader); if (!IsReadableStream(stream)) { throw new TypeError('ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a ' + 'byte source'); } if (IsReadableByteStreamController(stream._readableStreamController) === false) { throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + 'source'); } if (IsReadableStreamLocked(stream)) { throw new TypeError('This stream has already been locked for exclusive reading by another reader'); } ReadableStreamReaderGenericInitialize(this, stream); this._readIntoRequests = []; } _createClass(ReadableStreamBYOBReader, [{ key: 'cancel', value: function cancel(reason) { if (!IsReadableStreamBYOBReader(this)) { return Promise.reject(byobReaderBrandCheckException('cancel')); } if (this._ownerReadableStream === undefined) { return Promise.reject(readerLockException('cancel')); } return ReadableStreamReaderGenericCancel(this, reason); } }, { key: 'read', value: function read(view) { if (!IsReadableStreamBYOBReader(this)) { return Promise.reject(byobReaderBrandCheckException('read')); } if (this._ownerReadableStream === undefined) { return Promise.reject(readerLockException('read from')); } if (!ArrayBuffer.isView(view)) { return Promise.reject(new TypeError('view must be an array buffer view')); } if (view.byteLength === 0) { return Promise.reject(new TypeError('view must have non-zero byteLength')); } return ReadableStreamBYOBReaderRead(this, view); } }, { key: 'releaseLock', value: function releaseLock() { if (!IsReadableStreamBYOBReader(this)) { throw byobReaderBrandCheckException('releaseLock'); } if (this._ownerReadableStream === undefined) { return; } if (this._readIntoRequests.length > 0) { throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled'); } ReadableStreamReaderGenericRelease(this); } }, { key: 'closed', get: function get() { if (!IsReadableStreamBYOBReader(this)) { return Promise.reject(byobReaderBrandCheckException('closed')); } return this._closedPromise; } }]); return ReadableStreamBYOBReader; }(); function IsReadableStreamBYOBReader(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { return false; } return true; } function IsReadableStreamDefaultReader(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { return false; } return true; } function ReadableStreamReaderGenericInitialize(reader, stream) { reader._ownerReadableStream = stream; stream._reader = reader; if (stream._state === 'readable') { defaultReaderClosedPromiseInitialize(reader); } else if (stream._state === 'closed') { defaultReaderClosedPromiseInitializeAsResolved(reader); } else { assert(stream._state === 'errored', 'state must be errored'); defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); reader._closedPromise.catch(function () {}); } } function ReadableStreamReaderGenericCancel(reader, reason) { var stream = reader._ownerReadableStream; assert(stream !== undefined); return ReadableStreamCancel(stream, reason); } function ReadableStreamReaderGenericRelease(reader) { assert(reader._ownerReadableStream !== undefined); assert(reader._ownerReadableStream._reader === reader); if (reader._ownerReadableStream._state === 'readable') { defaultReaderClosedPromiseReject(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness')); } else { defaultReaderClosedPromiseResetToRejected(reader, new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness')); } reader._closedPromise.catch(function () {}); reader._ownerReadableStream._reader = undefined; reader._ownerReadableStream = undefined; } function ReadableStreamBYOBReaderRead(reader, view) { var stream = reader._ownerReadableStream; assert(stream !== undefined); stream._disturbed = true; if (stream._state === 'errored') { return Promise.reject(stream._storedError); } return ReadableByteStreamControllerPullInto(stream._readableStreamController, view); } function ReadableStreamDefaultReaderRead(reader) { var stream = reader._ownerReadableStream; assert(stream !== undefined); stream._disturbed = true; if (stream._state === 'closed') { return Promise.resolve(CreateIterResultObject(undefined, true)); } if (stream._state === 'errored') { return Promise.reject(stream._storedError); } assert(stream._state === 'readable'); return stream._readableStreamController.__pullSteps(); } var ReadableStreamDefaultController = function () { function ReadableStreamDefaultController(stream, underlyingSource, size, highWaterMark) { _classCallCheck(this, ReadableStreamDefaultController); if (IsReadableStream(stream) === false) { throw new TypeError('ReadableStreamDefaultController can only be constructed with a ReadableStream instance'); } if (stream._readableStreamController !== undefined) { throw new TypeError('ReadableStreamDefaultController instances can only be created by the ReadableStream constructor'); } this._controlledReadableStream = stream; this._underlyingSource = underlyingSource; this._queue = undefined; this._queueTotalSize = undefined; ResetQueue(this); this._started = false; this._closeRequested = false; this._pullAgain = false; this._pulling = false; var normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark); this._strategySize = normalizedStrategy.size; this._strategyHWM = normalizedStrategy.highWaterMark; var controller = this; var startResult = InvokeOrNoop(underlyingSource, 'start', [this]); Promise.resolve(startResult).then(function () { controller._started = true; assert(controller._pulling === false); assert(controller._pullAgain === false); ReadableStreamDefaultControllerCallPullIfNeeded(controller); }, function (r) { ReadableStreamDefaultControllerErrorIfNeeded(controller, r); }).catch(rethrowAssertionErrorRejection); } _createClass(ReadableStreamDefaultController, [{ key: 'close', value: function close() { if (IsReadableStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('close'); } if (this._closeRequested === true) { throw new TypeError('The stream has already been closed; do not close it again!'); } var state = this._controlledReadableStream._state; if (state !== 'readable') { throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be closed'); } ReadableStreamDefaultControllerClose(this); } }, { key: 'enqueue', value: function enqueue(chunk) { if (IsReadableStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('enqueue'); } if (this._closeRequested === true) { throw new TypeError('stream is closed or draining'); } var state = this._controlledReadableStream._state; if (state !== 'readable') { throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be enqueued to'); } return ReadableStreamDefaultControllerEnqueue(this, chunk); } }, { key: 'error', value: function error(e) { if (IsReadableStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('error'); } var stream = this._controlledReadableStream; if (stream._state !== 'readable') { throw new TypeError('The stream is ' + stream._state + ' and so cannot be errored'); } ReadableStreamDefaultControllerError(this, e); } }, { key: '__cancelSteps', value: function __cancelSteps(reason) { ResetQueue(this); return PromiseInvokeOrNoop(this._underlyingSource, 'cancel', [reason]); } }, { key: '__pullSteps', value: function __pullSteps() { var stream = this._controlledReadableStream; if (this._queue.length > 0) { var chunk = DequeueValue(this); if (this._closeRequested === true && this._queue.length === 0) { ReadableStreamClose(stream); } else { ReadableStreamDefaultControllerCallPullIfNeeded(this); } return Promise.resolve(CreateIterResultObject(chunk, false)); } var pendingPromise = ReadableStreamAddReadRequest(stream); ReadableStreamDefaultControllerCallPullIfNeeded(this); return pendingPromise; } }, { key: 'desiredSize', get: function get() { if (IsReadableStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('desiredSize'); } return ReadableStreamDefaultControllerGetDesiredSize(this); } }]); return ReadableStreamDefaultController; }(); function IsReadableStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSource')) { return false; } return true; } function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); if (shouldPull === false) { return undefined; } if (controller._pulling === true) { controller._pullAgain = true; return undefined; } assert(controller._pullAgain === false); controller._pulling = true; var pullPromise = PromiseInvokeOrNoop(controller._underlyingSource, 'pull', [controller]); pullPromise.then(function () { controller._pulling = false; if (controller._pullAgain === true) { controller._pullAgain = false; return ReadableStreamDefaultControllerCallPullIfNeeded(controller); } return undefined; }, function (e) { ReadableStreamDefaultControllerErrorIfNeeded(controller, e); }).catch(rethrowAssertionErrorRejection); return undefined; } function ReadableStreamDefaultControllerShouldCallPull(controller) { var stream = controller._controlledReadableStream; if (stream._state === 'closed' || stream._state === 'errored') { return false; } if (controller._closeRequested === true) { return false; } if (controller._started === false) { return false; } if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); if (desiredSize > 0) { return true; } return false; } function ReadableStreamDefaultControllerClose(controller) { var stream = controller._controlledReadableStream; assert(controller._closeRequested === false); assert(stream._state === 'readable'); controller._closeRequested = true; if (controller._queue.length === 0) { ReadableStreamClose(stream); } } function ReadableStreamDefaultControllerEnqueue(controller, chunk) { var stream = controller._controlledReadableStream; assert(controller._closeRequested === false); assert(stream._state === 'readable'); if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) { ReadableStreamFulfillReadRequest(stream, chunk, false); } else { var chunkSize = 1; if (controller._strategySize !== undefined) { var strategySize = controller._strategySize; try { chunkSize = strategySize(chunk); } catch (chunkSizeE) { ReadableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); throw chunkSizeE; } } try { EnqueueValueWithSize(controller, chunk, chunkSize); } catch (enqueueE) { ReadableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); throw enqueueE; } } ReadableStreamDefaultControllerCallPullIfNeeded(controller); return undefined; } function ReadableStreamDefaultControllerError(controller, e) { var stream = controller._controlledReadableStream; assert(stream._state === 'readable'); ResetQueue(controller); ReadableStreamError(stream, e); } function ReadableStreamDefaultControllerErrorIfNeeded(controller, e) { if (controller._controlledReadableStream._state === 'readable') { ReadableStreamDefaultControllerError(controller, e); } } function ReadableStreamDefaultControllerGetDesiredSize(controller) { var stream = controller._controlledReadableStream; var state = stream._state; if (state === 'errored') { return null; } if (state === 'closed') { return 0; } return controller._strategyHWM - controller._queueTotalSize; } var ReadableStreamBYOBRequest = function () { function ReadableStreamBYOBRequest(controller, view) { _classCallCheck(this, ReadableStreamBYOBRequest); this._associatedReadableByteStreamController = controller; this._view = view; } _createClass(ReadableStreamBYOBRequest, [{ key: 'respond', value: function respond(bytesWritten) { if (IsReadableStreamBYOBRequest(this) === false) { throw byobRequestBrandCheckException('respond'); } if (this._associatedReadableByteStreamController === undefined) { throw new TypeError('This BYOB request has been invalidated'); } ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); } }, { key: 'respondWithNewView', value: function respondWithNewView(view) { if (IsReadableStreamBYOBRequest(this) === false) { throw byobRequestBrandCheckException('respond'); } if (this._associatedReadableByteStreamController === undefined) { throw new TypeError('This BYOB request has been invalidated'); } if (!ArrayBuffer.isView(view)) { throw new TypeError('You can only respond with array buffer views'); } ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); } }, { key: 'view', get: function get() { return this._view; } }]); return ReadableStreamBYOBRequest; }(); var ReadableByteStreamController = function () { function ReadableByteStreamController(stream, underlyingByteSource, highWaterMark) { _classCallCheck(this, ReadableByteStreamController); if (IsReadableStream(stream) === false) { throw new TypeError('ReadableByteStreamController can only be constructed with a ReadableStream instance given ' + 'a byte source'); } if (stream._readableStreamController !== undefined) { throw new TypeError('ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte ' + 'source'); } this._controlledReadableStream = stream; this._underlyingByteSource = underlyingByteSource; this._pullAgain = false; this._pulling = false; ReadableByteStreamControllerClearPendingPullIntos(this); this._queue = this._queueTotalSize = undefined; ResetQueue(this); this._closeRequested = false; this._started = false; this._strategyHWM = ValidateAndNormalizeHighWaterMark(highWaterMark); var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; if (autoAllocateChunkSize !== undefined) { if (Number.isInteger(autoAllocateChunkSize) === false || autoAllocateChunkSize <= 0) { throw new RangeError('autoAllocateChunkSize must be a positive integer'); } } this._autoAllocateChunkSize = autoAllocateChunkSize; this._pendingPullIntos = []; var controller = this; var startResult = InvokeOrNoop(underlyingByteSource, 'start', [this]); Promise.resolve(startResult).then(function () { controller._started = true; assert(controller._pulling === false); assert(controller._pullAgain === false); ReadableByteStreamControllerCallPullIfNeeded(controller); }, function (r) { if (stream._state === 'readable') { ReadableByteStreamControllerError(controller, r); } }).catch(rethrowAssertionErrorRejection); } _createClass(ReadableByteStreamController, [{ key: 'close', value: function close() { if (IsReadableByteStreamController(this) === false) { throw byteStreamControllerBrandCheckException('close'); } if (this._closeRequested === true) { throw new TypeError('The stream has already been closed; do not close it again!'); } var state = this._controlledReadableStream._state; if (state !== 'readable') { throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be closed'); } ReadableByteStreamControllerClose(this); } }, { key: 'enqueue', value: function enqueue(chunk) { if (IsReadableByteStreamController(this) === false) { throw byteStreamControllerBrandCheckException('enqueue'); } if (this._closeRequested === true) { throw new TypeError('stream is closed or draining'); } var state = this._controlledReadableStream._state; if (state !== 'readable') { throw new TypeError('The stream (in ' + state + ' state) is not in the readable state and cannot be enqueued to'); } if (!ArrayBuffer.isView(chunk)) { throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController'); } ReadableByteStreamControllerEnqueue(this, chunk); } }, { key: 'error', value: function error(e) { if (IsReadableByteStreamController(this) === false) { throw byteStreamControllerBrandCheckException('error'); } var stream = this._controlledReadableStream; if (stream._state !== 'readable') { throw new TypeError('The stream is ' + stream._state + ' and so cannot be errored'); } ReadableByteStreamControllerError(this, e); } }, { key: '__cancelSteps', value: function __cancelSteps(reason) { if (this._pendingPullIntos.length > 0) { var firstDescriptor = this._pendingPullIntos[0]; firstDescriptor.bytesFilled = 0; } ResetQueue(this); return PromiseInvokeOrNoop(this._underlyingByteSource, 'cancel', [reason]); } }, { key: '__pullSteps', value: function __pullSteps() { var stream = this._controlledReadableStream; assert(ReadableStreamHasDefaultReader(stream) === true); if (this._queueTotalSize > 0) { assert(ReadableStreamGetNumReadRequests(stream) === 0); var entry = this._queue.shift(); this._queueTotalSize -= entry.byteLength; ReadableByteStreamControllerHandleQueueDrain(this); var view = void 0; try { view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); } catch (viewE) { return Promise.reject(viewE); } return Promise.resolve(CreateIterResultObject(view, false)); } var autoAllocateChunkSize = this._autoAllocateChunkSize; if (autoAllocateChunkSize !== undefined) { var buffer = void 0; try { buffer = new ArrayBuffer(autoAllocateChunkSize); } catch (bufferE) { return Promise.reject(bufferE); } var pullIntoDescriptor = { buffer: buffer, byteOffset: 0, byteLength: autoAllocateChunkSize, bytesFilled: 0, elementSize: 1, ctor: Uint8Array, readerType: 'default' }; this._pendingPullIntos.push(pullIntoDescriptor); } var promise = ReadableStreamAddReadRequest(stream); ReadableByteStreamControllerCallPullIfNeeded(this); return promise; } }, { key: 'byobRequest', get: function get() { if (IsReadableByteStreamController(this) === false) { throw byteStreamControllerBrandCheckException('byobRequest'); } if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) { var firstDescriptor = this._pendingPullIntos[0]; var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); this._byobRequest = new ReadableStreamBYOBRequest(this, view); } return this._byobRequest; } }, { key: 'desiredSize', get: function get() { if (IsReadableByteStreamController(this) === false) { throw byteStreamControllerBrandCheckException('desiredSize'); } return ReadableByteStreamControllerGetDesiredSize(this); } }]); return ReadableByteStreamController; }(); function IsReadableByteStreamController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_underlyingByteSource')) { return false; } return true; } function IsReadableStreamBYOBRequest(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { return false; } return true; } function ReadableByteStreamControllerCallPullIfNeeded(controller) { var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); if (shouldPull === false) { return undefined; } if (controller._pulling === true) { controller._pullAgain = true; return undefined; } assert(controller._pullAgain === false); controller._pulling = true; var pullPromise = PromiseInvokeOrNoop(controller._underlyingByteSource, 'pull', [controller]); pullPromise.then(function () { controller._pulling = false; if (controller._pullAgain === true) { controller._pullAgain = false; ReadableByteStreamControllerCallPullIfNeeded(controller); } }, function (e) { if (controller._controlledReadableStream._state === 'readable') { ReadableByteStreamControllerError(controller, e); } }).catch(rethrowAssertionErrorRejection); return undefined; } function ReadableByteStreamControllerClearPendingPullIntos(controller) { ReadableByteStreamControllerInvalidateBYOBRequest(controller); controller._pendingPullIntos = []; } function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { assert(stream._state !== 'errored', 'state must not be errored'); var done = false; if (stream._state === 'closed') { assert(pullIntoDescriptor.bytesFilled === 0); done = true; } var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); if (pullIntoDescriptor.readerType === 'default') { ReadableStreamFulfillReadRequest(stream, filledView, done); } else { assert(pullIntoDescriptor.readerType === 'byob'); ReadableStreamFulfillReadIntoRequest(stream, filledView, done); } } function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { var bytesFilled = pullIntoDescriptor.bytesFilled; var elementSize = pullIntoDescriptor.elementSize; assert(bytesFilled <= pullIntoDescriptor.byteLength); assert(bytesFilled % elementSize === 0); return new pullIntoDescriptor.ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); } function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); controller._queueTotalSize += byteLength; } function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { var elementSize = pullIntoDescriptor.elementSize; var currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; var maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; var totalBytesToCopyRemaining = maxBytesToCopy; var ready = false; if (maxAlignedBytes > currentAlignedBytes) { totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; ready = true; } var queue = controller._queue; while (totalBytesToCopyRemaining > 0) { var headOfQueue = queue[0]; var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); if (headOfQueue.byteLength === bytesToCopy) { queue.shift(); } else { headOfQueue.byteOffset += bytesToCopy; headOfQueue.byteLength -= bytesToCopy; } controller._queueTotalSize -= bytesToCopy; ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); totalBytesToCopyRemaining -= bytesToCopy; } if (ready === false) { assert(controller._queueTotalSize === 0, 'queue must be empty'); assert(pullIntoDescriptor.bytesFilled > 0); assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize); } return ready; } function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos[0] === pullIntoDescriptor); ReadableByteStreamControllerInvalidateBYOBRequest(controller); pullIntoDescriptor.bytesFilled += size; } function ReadableByteStreamControllerHandleQueueDrain(controller) { assert(controller._controlledReadableStream._state === 'readable'); if (controller._queueTotalSize === 0 && controller._closeRequested === true) { ReadableStreamClose(controller._controlledReadableStream); } else { ReadableByteStreamControllerCallPullIfNeeded(controller); } } function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { if (controller._byobRequest === undefined) { return; } controller._byobRequest._associatedReadableByteStreamController = undefined; controller._byobRequest._view = undefined; controller._byobRequest = undefined; } function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { assert(controller._closeRequested === false); while (controller._pendingPullIntos.length > 0) { if (controller._queueTotalSize === 0) { return; } var pullIntoDescriptor = controller._pendingPullIntos[0]; if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) { ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor); } } } function ReadableByteStreamControllerPullInto(controller, view) { var stream = controller._controlledReadableStream; var elementSize = 1; if (view.constructor !== DataView) { elementSize = view.constructor.BYTES_PER_ELEMENT; } var ctor = view.constructor; var pullIntoDescriptor = { buffer: view.buffer, byteOffset: view.byteOffset, byteLength: view.byteLength, bytesFilled: 0, elementSize: elementSize, ctor: ctor, readerType: 'byob' }; if (controller._pendingPullIntos.length > 0) { pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); controller._pendingPullIntos.push(pullIntoDescriptor); return ReadableStreamAddReadIntoRequest(stream); } if (stream._state === 'closed') { var emptyView = new view.constructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); return Promise.resolve(CreateIterResultObject(emptyView, true)); } if (controller._queueTotalSize > 0) { if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) { var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); ReadableByteStreamControllerHandleQueueDrain(controller); return Promise.resolve(CreateIterResultObject(filledView, false)); } if (controller._closeRequested === true) { var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); ReadableByteStreamControllerError(controller, e); return Promise.reject(e); } } pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); controller._pendingPullIntos.push(pullIntoDescriptor); var promise = ReadableStreamAddReadIntoRequest(stream); ReadableByteStreamControllerCallPullIfNeeded(controller); return promise; } function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); assert(firstDescriptor.bytesFilled === 0, 'bytesFilled must be 0'); var stream = controller._controlledReadableStream; if (ReadableStreamHasBYOBReader(stream) === true) { while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); } } } function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) { throw new RangeError('bytesWritten out of range'); } ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { return; } ReadableByteStreamControllerShiftPendingPullInto(controller); var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; if (remainderSize > 0) { var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; var remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end); ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); } pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer); pullIntoDescriptor.bytesFilled -= remainderSize; ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { var firstDescriptor = controller._pendingPullIntos[0]; var stream = controller._controlledReadableStream; if (stream._state === 'closed') { if (bytesWritten !== 0) { throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); } ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); } else { assert(stream._state === 'readable'); ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); } } function ReadableByteStreamControllerShiftPendingPullInto(controller) { var descriptor = controller._pendingPullIntos.shift(); ReadableByteStreamControllerInvalidateBYOBRequest(controller); return descriptor; } function ReadableByteStreamControllerShouldCallPull(controller) { var stream = controller._controlledReadableStream; if (stream._state !== 'readable') { return false; } if (controller._closeRequested === true) { return false; } if (controller._started === false) { return false; } if (ReadableStreamHasDefaultReader(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) { return true; } if (ReadableStreamHasBYOBReader(stream) === true && ReadableStreamGetNumReadIntoRequests(stream) > 0) { return true; } if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) { return true; } return false; } function ReadableByteStreamControllerClose(controller) { var stream = controller._controlledReadableStream; assert(controller._closeRequested === false); assert(stream._state === 'readable'); if (controller._queueTotalSize > 0) { controller._closeRequested = true; return; } if (controller._pendingPullIntos.length > 0) { var firstPendingPullInto = controller._pendingPullIntos[0]; if (firstPendingPullInto.bytesFilled > 0) { var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); ReadableByteStreamControllerError(controller, e); throw e; } } ReadableStreamClose(stream); } function ReadableByteStreamControllerEnqueue(controller, chunk) { var stream = controller._controlledReadableStream; assert(controller._closeRequested === false); assert(stream._state === 'readable'); var buffer = chunk.buffer; var byteOffset = chunk.byteOffset; var byteLength = chunk.byteLength; var transferredBuffer = TransferArrayBuffer(buffer); if (ReadableStreamHasDefaultReader(stream) === true) { if (ReadableStreamGetNumReadRequests(stream) === 0) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } else { assert(controller._queue.length === 0); var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); ReadableStreamFulfillReadRequest(stream, transferredView, false); } } else if (ReadableStreamHasBYOBReader(stream) === true) { ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); } else { assert(IsReadableStreamLocked(stream) === false, 'stream must not be locked'); ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); } } function ReadableByteStreamControllerError(controller, e) { var stream = controller._controlledReadableStream; assert(stream._state === 'readable'); ReadableByteStreamControllerClearPendingPullIntos(controller); ResetQueue(controller); ReadableStreamError(stream, e); } function ReadableByteStreamControllerGetDesiredSize(controller) { var stream = controller._controlledReadableStream; var state = stream._state; if (state === 'errored') { return null; } if (state === 'closed') { return 0; } return controller._strategyHWM - controller._queueTotalSize; } function ReadableByteStreamControllerRespond(controller, bytesWritten) { bytesWritten = Number(bytesWritten); if (IsFiniteNonNegativeNumber(bytesWritten) === false) { throw new RangeError('bytesWritten must be a finite'); } assert(controller._pendingPullIntos.length > 0); ReadableByteStreamControllerRespondInternal(controller, bytesWritten); } function ReadableByteStreamControllerRespondWithNewView(controller, view) { assert(controller._pendingPullIntos.length > 0); var firstDescriptor = controller._pendingPullIntos[0]; if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { throw new RangeError('The region specified by view does not match byobRequest'); } if (firstDescriptor.byteLength !== view.byteLength) { throw new RangeError('The buffer of view has different capacity than byobRequest'); } firstDescriptor.buffer = view.buffer; ReadableByteStreamControllerRespondInternal(controller, view.byteLength); } function streamBrandCheckException(name) { return new TypeError('ReadableStream.prototype.' + name + ' can only be used on a ReadableStream'); } function readerLockException(name) { return new TypeError('Cannot ' + name + ' a stream using a released reader'); } function defaultReaderBrandCheckException(name) { return new TypeError('ReadableStreamDefaultReader.prototype.' + name + ' can only be used on a ReadableStreamDefaultReader'); } function defaultReaderClosedPromiseInitialize(reader) { reader._closedPromise = new Promise(function (resolve, reject) { reader._closedPromise_resolve = resolve; reader._closedPromise_reject = reject; }); } function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { reader._closedPromise = Promise.reject(reason); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } function defaultReaderClosedPromiseInitializeAsResolved(reader) { reader._closedPromise = Promise.resolve(undefined); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } function defaultReaderClosedPromiseReject(reader, reason) { assert(reader._closedPromise_resolve !== undefined); assert(reader._closedPromise_reject !== undefined); reader._closedPromise_reject(reason); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } function defaultReaderClosedPromiseResetToRejected(reader, reason) { assert(reader._closedPromise_resolve === undefined); assert(reader._closedPromise_reject === undefined); reader._closedPromise = Promise.reject(reason); } function defaultReaderClosedPromiseResolve(reader) { assert(reader._closedPromise_resolve !== undefined); assert(reader._closedPromise_reject !== undefined); reader._closedPromise_resolve(undefined); reader._closedPromise_resolve = undefined; reader._closedPromise_reject = undefined; } function byobReaderBrandCheckException(name) { return new TypeError('ReadableStreamBYOBReader.prototype.' + name + ' can only be used on a ReadableStreamBYOBReader'); } function defaultControllerBrandCheckException(name) { return new TypeError('ReadableStreamDefaultController.prototype.' + name + ' can only be used on a ReadableStreamDefaultController'); } function byobRequestBrandCheckException(name) { return new TypeError('ReadableStreamBYOBRequest.prototype.' + name + ' can only be used on a ReadableStreamBYOBRequest'); } function byteStreamControllerBrandCheckException(name) { return new TypeError('ReadableByteStreamController.prototype.' + name + ' can only be used on a ReadableByteStreamController'); } function ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise) { try { Promise.prototype.then.call(promise, undefined, function () {}); } catch (e) {} } }, function (module, exports, __w_pdfjs_require__) { "use strict"; var transformStream = __w_pdfjs_require__(6); var readableStream = __w_pdfjs_require__(4); var writableStream = __w_pdfjs_require__(2); exports.TransformStream = transformStream.TransformStream; exports.ReadableStream = readableStream.ReadableStream; exports.IsReadableStreamDisturbed = readableStream.IsReadableStreamDisturbed; exports.ReadableStreamDefaultControllerClose = readableStream.ReadableStreamDefaultControllerClose; exports.ReadableStreamDefaultControllerEnqueue = readableStream.ReadableStreamDefaultControllerEnqueue; exports.ReadableStreamDefaultControllerError = readableStream.ReadableStreamDefaultControllerError; exports.ReadableStreamDefaultControllerGetDesiredSize = readableStream.ReadableStreamDefaultControllerGetDesiredSize; exports.AcquireWritableStreamDefaultWriter = writableStream.AcquireWritableStreamDefaultWriter; exports.IsWritableStream = writableStream.IsWritableStream; exports.IsWritableStreamLocked = writableStream.IsWritableStreamLocked; exports.WritableStream = writableStream.WritableStream; exports.WritableStreamAbort = writableStream.WritableStreamAbort; exports.WritableStreamDefaultControllerError = writableStream.WritableStreamDefaultControllerError; exports.WritableStreamDefaultWriterCloseWithErrorPropagation = writableStream.WritableStreamDefaultWriterCloseWithErrorPropagation; exports.WritableStreamDefaultWriterRelease = writableStream.WritableStreamDefaultWriterRelease; exports.WritableStreamDefaultWriterWrite = writableStream.WritableStreamDefaultWriterWrite; }, function (module, exports, __w_pdfjs_require__) { "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; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _require = __w_pdfjs_require__(1), assert = _require.assert; var _require2 = __w_pdfjs_require__(0), InvokeOrNoop = _require2.InvokeOrNoop, PromiseInvokeOrPerformFallback = _require2.PromiseInvokeOrPerformFallback, PromiseInvokeOrNoop = _require2.PromiseInvokeOrNoop, typeIsObject = _require2.typeIsObject; var _require3 = __w_pdfjs_require__(4), ReadableStream = _require3.ReadableStream, ReadableStreamDefaultControllerClose = _require3.ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue = _require3.ReadableStreamDefaultControllerEnqueue, ReadableStreamDefaultControllerError = _require3.ReadableStreamDefaultControllerError, ReadableStreamDefaultControllerGetDesiredSize = _require3.ReadableStreamDefaultControllerGetDesiredSize; var _require4 = __w_pdfjs_require__(2), WritableStream = _require4.WritableStream, WritableStreamDefaultControllerError = _require4.WritableStreamDefaultControllerError; function TransformStreamCloseReadable(transformStream) { if (transformStream._errored === true) { throw new TypeError('TransformStream is already errored'); } if (transformStream._readableClosed === true) { throw new TypeError('Readable side is already closed'); } TransformStreamCloseReadableInternal(transformStream); } function TransformStreamEnqueueToReadable(transformStream, chunk) { if (transformStream._errored === true) { throw new TypeError('TransformStream is already errored'); } if (transformStream._readableClosed === true) { throw new TypeError('Readable side is already closed'); } var controller = transformStream._readableController; try { ReadableStreamDefaultControllerEnqueue(controller, chunk); } catch (e) { transformStream._readableClosed = true; TransformStreamErrorIfNeeded(transformStream, e); throw transformStream._storedError; } var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); var maybeBackpressure = desiredSize <= 0; if (maybeBackpressure === true && transformStream._backpressure === false) { TransformStreamSetBackpressure(transformStream, true); } } function TransformStreamError(transformStream, e) { if (transformStream._errored === true) { throw new TypeError('TransformStream is already errored'); } TransformStreamErrorInternal(transformStream, e); } function TransformStreamCloseReadableInternal(transformStream) { assert(transformStream._errored === false); assert(transformStream._readableClosed === false); try { ReadableStreamDefaultControllerClose(transformStream._readableController); } catch (e) { assert(false); } transformStream._readableClosed = true; } function TransformStreamErrorIfNeeded(transformStream, e) { if (transformStream._errored === false) { TransformStreamErrorInternal(transformStream, e); } } function TransformStreamErrorInternal(transformStream, e) { assert(transformStream._errored === false); transformStream._errored = true; transformStream._storedError = e; if (transformStream._writableDone === false) { WritableStreamDefaultControllerError(transformStream._writableController, e); } if (transformStream._readableClosed === false) { ReadableStreamDefaultControllerError(transformStream._readableController, e); } } function TransformStreamReadableReadyPromise(transformStream) { assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized'); if (transformStream._backpressure === false) { return Promise.resolve(); } assert(transformStream._backpressure === true, '_backpressure should have been initialized'); return transformStream._backpressureChangePromise; } function TransformStreamSetBackpressure(transformStream, backpressure) { assert(transformStream._backpressure !== backpressure, 'TransformStreamSetBackpressure() should be called only when backpressure is changed'); if (transformStream._backpressureChangePromise !== undefined) { transformStream._backpressureChangePromise_resolve(backpressure); } transformStream._backpressureChangePromise = new Promise(function (resolve) { transformStream._backpressureChangePromise_resolve = resolve; }); transformStream._backpressureChangePromise.then(function (resolution) { assert(resolution !== backpressure, '_backpressureChangePromise should be fulfilled only when backpressure is changed'); }); transformStream._backpressure = backpressure; } function TransformStreamDefaultTransform(chunk, transformStreamController) { var transformStream = transformStreamController._controlledTransformStream; TransformStreamEnqueueToReadable(transformStream, chunk); return Promise.resolve(); } function TransformStreamTransform(transformStream, chunk) { assert(transformStream._errored === false); assert(transformStream._transforming === false); assert(transformStream._backpressure === false); transformStream._transforming = true; var transformer = transformStream._transformer; var controller = transformStream._transformStreamController; var transformPromise = PromiseInvokeOrPerformFallback(transformer, 'transform', [chunk, controller], TransformStreamDefaultTransform, [chunk, controller]); return transformPromise.then(function () { transformStream._transforming = false; return TransformStreamReadableReadyPromise(transformStream); }, function (e) { TransformStreamErrorIfNeeded(transformStream, e); return Promise.reject(e); }); } function IsTransformStreamDefaultController(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { return false; } return true; } function IsTransformStream(x) { if (!typeIsObject(x)) { return false; } if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { return false; } return true; } var TransformStreamSink = function () { function TransformStreamSink(transformStream, startPromise) { _classCallCheck(this, TransformStreamSink); this._transformStream = transformStream; this._startPromise = startPromise; } _createClass(TransformStreamSink, [{ key: 'start', value: function start(c) { var transformStream = this._transformStream; transformStream._writableController = c; return this._startPromise.then(function () { return TransformStreamReadableReadyPromise(transformStream); }); } }, { key: 'write', value: function write(chunk) { var transformStream = this._transformStream; return TransformStreamTransform(transformStream, chunk); } }, { key: 'abort', value: function abort() { var transformStream = this._transformStream; transformStream._writableDone = true; TransformStreamErrorInternal(transformStream, new TypeError('Writable side aborted')); } }, { key: 'close', value: function close() { var transformStream = this._transformStream; assert(transformStream._transforming === false); transformStream._writableDone = true; var flushPromise = PromiseInvokeOrNoop(transformStream._transformer, 'flush', [transformStream._transformStreamController]); return flushPromise.then(function () { if (transformStream._errored === true) { return Promise.reject(transformStream._storedError); } if (transformStream._readableClosed === false) { TransformStreamCloseReadableInternal(transformStream); } return Promise.resolve(); }).catch(function (r) { TransformStreamErrorIfNeeded(transformStream, r); return Promise.reject(transformStream._storedError); }); } }]); return TransformStreamSink; }(); var TransformStreamSource = function () { function TransformStreamSource(transformStream, startPromise) { _classCallCheck(this, TransformStreamSource); this._transformStream = transformStream; this._startPromise = startPromise; } _createClass(TransformStreamSource, [{ key: 'start', value: function start(c) { var transformStream = this._transformStream; transformStream._readableController = c; return this._startPromise.then(function () { assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized'); if (transformStream._backpressure === true) { return Promise.resolve(); } assert(transformStream._backpressure === false, '_backpressure should have been initialized'); return transformStream._backpressureChangePromise; }); } }, { key: 'pull', value: function pull() { var transformStream = this._transformStream; assert(transformStream._backpressure === true, 'pull() should be never called while _backpressure is false'); assert(transformStream._backpressureChangePromise !== undefined, '_backpressureChangePromise should have been initialized'); TransformStreamSetBackpressure(transformStream, false); return transformStream._backpressureChangePromise; } }, { key: 'cancel', value: function cancel() { var transformStream = this._transformStream; transformStream._readableClosed = true; TransformStreamErrorInternal(transformStream, new TypeError('Readable side canceled')); } }]); return TransformStreamSource; }(); var TransformStreamDefaultController = function () { function TransformStreamDefaultController(transformStream) { _classCallCheck(this, TransformStreamDefaultController); if (IsTransformStream(transformStream) === false) { throw new TypeError('TransformStreamDefaultController can only be ' + 'constructed with a TransformStream instance'); } if (transformStream._transformStreamController !== undefined) { throw new TypeError('TransformStreamDefaultController instances can ' + 'only be created by the TransformStream constructor'); } this._controlledTransformStream = transformStream; } _createClass(TransformStreamDefaultController, [{ key: 'enqueue', value: function enqueue(chunk) { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('enqueue'); } TransformStreamEnqueueToReadable(this._controlledTransformStream, chunk); } }, { key: 'close', value: function close() { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('close'); } TransformStreamCloseReadable(this._controlledTransformStream); } }, { key: 'error', value: function error(reason) { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('error'); } TransformStreamError(this._controlledTransformStream, reason); } }, { key: 'desiredSize', get: function get() { if (IsTransformStreamDefaultController(this) === false) { throw defaultControllerBrandCheckException('desiredSize'); } var transformStream = this._controlledTransformStream; var readableController = transformStream._readableController; return ReadableStreamDefaultControllerGetDesiredSize(readableController); } }]); return TransformStreamDefaultController; }(); var TransformStream = function () { function TransformStream() { var transformer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, TransformStream); this._transformer = transformer; var readableStrategy = transformer.readableStrategy, writableStrategy = transformer.writableStrategy; this._transforming = false; this._errored = false; this._storedError = undefined; this._writableController = undefined; this._readableController = undefined; this._transformStreamController = undefined; this._writableDone = false; this._readableClosed = false; this._backpressure = undefined; this._backpressureChangePromise = undefined; this._backpressureChangePromise_resolve = undefined; this._transformStreamController = new TransformStreamDefaultController(this); var startPromise_resolve = void 0; var startPromise = new Promise(function (resolve) { startPromise_resolve = resolve; }); var source = new TransformStreamSource(this, startPromise); this._readable = new ReadableStream(source, readableStrategy); var sink = new TransformStreamSink(this, startPromise); this._writable = new WritableStream(sink, writableStrategy); assert(this._writableController !== undefined); assert(this._readableController !== undefined); var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(this._readableController); TransformStreamSetBackpressure(this, desiredSize <= 0); var transformStream = this; var startResult = InvokeOrNoop(transformer, 'start', [transformStream._transformStreamController]); startPromise_resolve(startResult); startPromise.catch(function (e) { if (transformStream._errored === false) { transformStream._errored = true; transformStream._storedError = e; } }); } _createClass(TransformStream, [{ key: 'readable', get: function get() { if (IsTransformStream(this) === false) { throw streamBrandCheckException('readable'); } return this._readable; } }, { key: 'writable', get: function get() { if (IsTransformStream(this) === false) { throw streamBrandCheckException('writable'); } return this._writable; } }]); return TransformStream; }(); module.exports = { TransformStream: TransformStream }; function defaultControllerBrandCheckException(name) { return new TypeError('TransformStreamDefaultController.prototype.' + name + ' can only be used on a TransformStreamDefaultController'); } function streamBrandCheckException(name) { return new TypeError('TransformStream.prototype.' + name + ' can only be used on a TransformStream'); } }, function (module, exports, __w_pdfjs_require__) { module.exports = __w_pdfjs_require__(5); }])); /***/ }), /* 113 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PDFJS = exports.globalScope = undefined; var _dom_utils = __w_pdfjs_require__(8); var _util = __w_pdfjs_require__(0); var _api = __w_pdfjs_require__(57); var _annotation_layer = __w_pdfjs_require__(60); var _global_scope = __w_pdfjs_require__(14); var _global_scope2 = _interopRequireDefault(_global_scope); var _metadata = __w_pdfjs_require__(59); var _text_layer = __w_pdfjs_require__(61); var _svg = __w_pdfjs_require__(62); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } if (!_global_scope2.default.PDFJS) { _global_scope2.default.PDFJS = {}; } var PDFJS = _global_scope2.default.PDFJS; { PDFJS.version = '2.0.112'; PDFJS.build = '9686f665'; } PDFJS.pdfBug = false; if (PDFJS.verbosity !== undefined) { (0, _util.setVerbosityLevel)(PDFJS.verbosity); } delete PDFJS.verbosity; Object.defineProperty(PDFJS, 'verbosity', { get: function get() { return (0, _util.getVerbosityLevel)(); }, set: function set(level) { (0, _util.setVerbosityLevel)(level); }, enumerable: true, configurable: true }); PDFJS.VERBOSITY_LEVELS = _util.VERBOSITY_LEVELS; PDFJS.OPS = _util.OPS; PDFJS.UNSUPPORTED_FEATURES = _util.UNSUPPORTED_FEATURES; PDFJS.isValidUrl = _dom_utils.isValidUrl; PDFJS.shadow = _util.shadow; PDFJS.createBlob = _util.createBlob; PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) { return (0, _util.createObjectURL)(data, contentType, PDFJS.disableCreateObjectURL); }; Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return (0, _util.shadow)(PDFJS, 'isLittleEndian', (0, _util.isLittleEndian)()); } }); PDFJS.removeNullCharacters = _util.removeNullCharacters; PDFJS.PasswordResponses = _util.PasswordResponses; PDFJS.PasswordException = _util.PasswordException; PDFJS.UnknownErrorException = _util.UnknownErrorException; PDFJS.InvalidPDFException = _util.InvalidPDFException; PDFJS.MissingPDFException = _util.MissingPDFException; PDFJS.UnexpectedResponseException = _util.UnexpectedResponseException; PDFJS.Util = _util.Util; PDFJS.PageViewport = _util.PageViewport; PDFJS.createPromiseCapability = _util.createPromiseCapability; PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize; PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl; PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace; PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath; PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker; PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc; PDFJS.workerPort = PDFJS.workerPort === undefined ? null : PDFJS.workerPort; PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange; PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream; PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch; PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug; PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers; PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL; PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL; PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? _dom_utils.LinkTarget.NONE : PDFJS.externalLinkTarget; PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? _dom_utils.DEFAULT_LINK_REL : PDFJS.externalLinkRel; PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported; PDFJS.getDocument = _api.getDocument; PDFJS.LoopbackPort = _api.LoopbackPort; PDFJS.PDFDataRangeTransport = _api.PDFDataRangeTransport; PDFJS.PDFWorker = _api.PDFWorker; PDFJS.CustomStyle = _dom_utils.CustomStyle; PDFJS.LinkTarget = _dom_utils.LinkTarget; PDFJS.addLinkAttributes = _dom_utils.addLinkAttributes; PDFJS.getFilenameFromUrl = _dom_utils.getFilenameFromUrl; PDFJS.isExternalLinkTargetSet = _dom_utils.isExternalLinkTargetSet; PDFJS.AnnotationLayer = _annotation_layer.AnnotationLayer; PDFJS.renderTextLayer = _text_layer.renderTextLayer; PDFJS.Metadata = _metadata.Metadata; PDFJS.SVGGraphics = _svg.SVGGraphics; exports.globalScope = _global_scope2.default; exports.PDFJS = PDFJS; /***/ }), /* 114 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FontLoader = exports.FontFaceObject = undefined; var _util = __w_pdfjs_require__(0); function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { if (this.styleElement) { this.styleElement.remove(); this.styleElement = null; } this.nativeFontFaces.forEach(function (nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; } }; { var getLoadTestFont = function getLoadTestFont() { return atob('T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA=='); }; Object.defineProperty(FontLoader.prototype, 'loadTestFont', { get: function get() { return (0, _util.shadow)(this, 'loadTestFont', getLoadTestFont()); }, configurable: true }); FontLoader.prototype.addNativeFontFace = function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }; FontLoader.prototype.bind = function fontLoaderBind(fonts, callback) { var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function getNativeFontPromise(nativeFontFace) { return nativeFontFace.loaded.catch(function (e) { (0, _util.warn)('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported && !FontLoader.isSyncFontLoadingSupported; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; if (font.attached || font.loading === false) { continue; } font.attached = true; if (isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function () { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }; FontLoader.prototype.queueLoadingCallback = function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { (0, _util.assert)(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + context.nextRequestId++; var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }; FontLoader.prototype.prepareFontLoadEvent = function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { function int32(data, offset) { return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff; } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; if (called > 30) { (0, _util.warn)('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; var data = this.loadTestFont; var COMMENT_OFFSET = 976; data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0; } if (i < loadTestFontId.length) { checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function () { document.body.removeChild(div); request.complete(); }); }; } { FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts; } { var isSyncFontLoadingSupported = function isSyncFontLoadingSupported() { if (typeof navigator === 'undefined') { return true; } var supported = false; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent); if (m && m[1] >= 14) { supported = true; } return supported; }; Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function get() { return (0, _util.shadow)(FontLoader, 'isSyncFontLoadingSupported', isSyncFontLoadingSupported()); }, enumerable: true, configurable: true }); } var IsEvalSupportedCached = { get value() { return (0, _util.shadow)(this, 'value', (0, _util.isEvalSupported)()); } }; var FontFaceObject = function FontFaceObjectClosure() { function FontFaceObject(translatedData, options) { this.compiledGlyphs = Object.create(null); for (var i in translatedData) { this[i] = translatedData[i]; } this.options = options; } FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (this.options.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (this.options.fontRegistry) { this.options.fontRegistry.registerFont(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (this.options.disableFontFace) { this.disableFontFace = true; return null; } var data = (0, _util.bytesToString)(new Uint8Array(this.data)); var fontName = this.loadedName; var url = 'url(data:' + this.mimetype + ';base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (this.options.fontRegistry) { this.options.fontRegistry.registerFont(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; if (this.options.isEvalSupported && IsEvalSupportedCached.value) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } this.compiledGlyphs[character] = new Function('c', 'size', js); } else { this.compiledGlyphs[character] = function (c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; }(); exports.FontFaceObject = FontFaceObject; exports.FontLoader = FontLoader; /***/ }), /* 115 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CanvasGraphics = undefined; var _util = __w_pdfjs_require__(0); var _pattern_helper = __w_pdfjs_require__(116); var _webgl = __w_pdfjs_require__(58); var MIN_FONT_SIZE = 16; var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; var IsLittleEndianCached = { get value() { return (0, _util.shadow)(IsLittleEndianCached, 'value', (0, _util.isLittleEndian)()); } }; function addContextCurrentTransform(ctx) { if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]]; this._originalRotate(angle); }; } } var CachedCanvases = function CachedCanvasesClosure() { function CachedCanvases(canvasFactory) { this.canvasFactory = canvasFactory; this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; this.canvasFactory.reset(canvasEntry, width, height); canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { canvasEntry = this.canvasFactory.create(width, height); this.cache[id] = canvasEntry; } if (trackTransform) { addContextCurrentTransform(canvasEntry.context); } return canvasEntry; }, clear: function clear() { for (var id in this.cache) { var canvasEntry = this.cache[id]; this.canvasFactory.destroy(canvasEntry); delete this.cache[id]; } } }; return CachedCanvases; }(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); var lineSize = width + 7 & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = elem & mask ? 0 : 255; mask >>= 1; } } var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { type = pp; points[p] = 0; } else { type = pp & 0x33 * type >> 4; points[p] &= type >> 2 | type << 2; } coords.push(p % width1); coords.push(p / width1 | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function drawOutline(c) { c.save(); c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j + 1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = function CanvasExtraStateClosure() { function CanvasExtraState() { this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = _util.IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = _util.FONT_IDENTITY_MATRIX; this.leading = 0; this.x = 0; this.y = 0; this.lineX = 0; this.lineY = 0; this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = _util.TextRenderingMode.FILL; this.textRise = 0; this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; this.resumeSMaskCtx = null; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; }(); var CanvasGraphics = function CanvasGraphicsClosure() { var EXECUTION_TIME = 15; var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, canvasFactory, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.canvasFactory = canvasFactory; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(this.canvasFactory); if (canvasCtx) { addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) { var srcLength = src.byteLength; var dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); var dest32DataLength = dest32.length; var fullSrcDiff = width + 7 >> 3; var white = 0xFFFFFFFF; var black = IsLittleEndianCached.value ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = srcByte & 128 ? white : black; dest32[destPos++] = srcByte & 64 ? white : black; dest32[destPos++] = srcByte & 32 ? white : black; dest32[destPos++] = srcByte & 16 ? white : black; dest32[destPos++] = srcByte & 8 ? white : black; dest32[destPos++] = srcByte & 4 ? white : black; dest32[destPos++] = srcByte & 2 ? white : black; dest32[destPos++] = srcByte & 1 ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = srcByte & mask ? white : black; mask >>= 1; } } while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) { j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === _util.ImageKind.RGB_24BPP) { thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { throw new Error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; var destPos = 3; for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = elem & mask ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } } function resetCtxToDefault(ctx) { ctx.strokeStyle = '#000000'; ctx.fillStyle = '#000000'; ctx.fillRule = 'nonzero'; ctx.globalAlpha = 1; ctx.lineWidth = 1; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 10; ctx.globalCompositeOperation = 'source-over'; ctx.font = '10px sans-serif'; if (ctx.setLineDash !== undefined) { ctx.setLineDash([]); ctx.lineDashOffset = 0; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8; bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8; bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = layerData[i] * alpha * scale | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28; layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && _webgl.WebGLUtils.isEnabled) { var composed = _webgl.WebGLUtils.composeSMask(layerCtx.canvas, mask, { subtype: smask.subtype, backdrop: backdrop }); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function beginDrawing(_ref) { var transform = _ref.transform, viewport = _ref.viewport, transparency = _ref.transparency, _ref$background = _ref.background, background = _ref$background === undefined ? null : _ref$background; var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = background || 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); resetCtxToDefault(this.ctx); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; if (argsArrayLen === i) { return i; } var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'; var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== _util.OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; if (i === argsArrayLen) { return i; } if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } } }, endDrawing: function CanvasGraphics_endDrawing() { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.save(); this.ctx.setTransform(1, 0, 0, 1, 0, 0); this.ctx.drawImage(this.transparentCanvas, 0, 0); this.ctx.restore(); this.transparentCanvas = null; } this.cachedCanvases.clear(); _webgl.WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {}, setFlatness: function CanvasGraphics_setFlatness(flatness) {}, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': this.ctx.globalCompositeOperation = value; break; case 'SMask': if (this.current.activeSMask) { if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) { this.suspendSMaskGroup(); } else { this.endSMaskGroup(); } } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse; copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([['BM', 'source-over'], ['ca', 1], ['CA', 1]]); this.groupStack.push(currentCtx); this.groupLevel++; }, suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); this.ctx.save(); copyCtxState(groupCtx, this.ctx); this.current.resumeSMaskCtx = groupCtx; var deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); this.ctx.transform.apply(this.ctx, deltaTransform); groupCtx.save(); groupCtx.setTransform(1, 0, 0, 1, 0, 0); groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height); groupCtx.restore(); }, resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.current.resumeSMaskCtx; var currentCtx = this.ctx; this.ctx = groupCtx; this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); var deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); this.ctx.transform.apply(this.ctx, deltaTransform); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.resumeSMaskCtx = null; }, restore: function CanvasGraphics_restore() { if (this.current.resumeSMaskCtx) { this.resumeSMaskGroup(); } if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) { this.endSMaskGroup(); } if (this.stateStack.length !== 0) { this.current = this.stateStack.pop(); this.ctx.restore(); this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case _util.OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case _util.OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case _util.OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case _util.OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case _util.OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case _util.OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case _util.OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { ctx.fill('evenodd'); this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, beginText: function CanvasGraphics_beginText() { this.current.textMatrix = _util.IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { throw new Error('Can\'t find font for ' + fontRefName); } current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : _util.FONT_IDENTITY_MATRIX; if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { (0, _util.warn)('Invalid font matrix for font ' + fontRefName); } if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? '900' : fontObj.bold ? 'bold' : 'normal'; var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { var ctx = this.canvasFactory.create(10, 10).context; ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return (0, _util.shadow)(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.patternFill) { ctx.fillStyle = current.fillColor.getPattern(ctx, this); } if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if ((0, _util.isNum)(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } if (glyph.isInFont || font.missingFile) { if (simpleFillText && !accent) { ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if ((0, _util.isNum)(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { (0, _util.warn)('Type3 character "' + glyph.operatorListId + '" is not available.'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {}, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var _this = this; var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); var canvasGraphicsFactory = { createCanvasGraphics: function createCanvasGraphics(ctx) { return new CanvasGraphics(ctx, _this.commonObjs, _this.objs, _this.canvasFactory); } }; pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); } else { pattern = (0, _pattern_helper.getShadingPatternFromIR)(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN() { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN() { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = _util.Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = _util.Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = (0, _pattern_helper.getShadingPatternFromIR)(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = _util.Util.applyTransform([0, 0], inv); var br = _util.Util.applyTransform([0, height], inv); var ul = _util.Util.applyTransform([width, 0], inv); var ur = _util.Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, beginInlineImage: function CanvasGraphics_beginInlineImage() { throw new Error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { throw new Error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (Array.isArray(matrix) && matrix.length === 6) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (Array.isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; if (!group.isolated) { (0, _util.info)('TODO: Support non-isolated groups.'); } if (group.knockout) { (0, _util.warn)('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } if (!group.bbox) { throw new Error('Bounding box is required.'); } var bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform); var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { cacheId += '_smask_' + this.smaskCounter++ % 2; } var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null, startTransformInverse: null }); } else { currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([['BM', 'source-over'], ['ca', 1], ['CA', 1]]); this.groupStack.push(currentCtx); this.groupLevel++; this.current.activeSMask = null; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); if (this.baseTransform) { this.ctx.setTransform.apply(this.ctx, this.baseTransform); } }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); resetCtxToDefault(this.ctx); this.current = new CanvasExtraState(); if (Array.isArray(rect) && rect.length === 4) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { (0, _util.warn)('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({ data: img.data, width: width, height: height }); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { (0, _util.warn)('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { (0, _util.warn)('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({ transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height }); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { (0, _util.warn)('Unsupported \'paintXObject\' command.'); }, markPoint: function CanvasGraphics_markPoint(tag) {}, markPointProps: function CanvasGraphics_markPointProps(tag, properties) {}, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {}, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {}, endMarkedContent: function CanvasGraphics_endMarkedContent() {}, beginCompat: function CanvasGraphics_beginCompat() {}, endCompat: function CanvasGraphics_endCompat() {}, consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { ctx.clip('evenodd'); } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { this.ctx.save(); var inverse = this.ctx.mozCurrentTransformInverse; this.ctx.restore(); this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3])); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]]; } }; for (var op in _util.OPS) { CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; }(); exports.CanvasGraphics = CanvasGraphics; /***/ }), /* 116 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TilingPattern = exports.getShadingPatternFromIR = undefined; var _util = __w_pdfjs_require__(0); var _webgl = __w_pdfjs_require__(58); var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = car - (car - cbr) * k | 0; bytes[j++] = cag - (cag - cbg) * k | 0; bytes[j++] = cab - (cab - cbb) * k | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: throw new Error('illegal figure'); } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { var EXPECTED_SCALE = 1.1; var MAX_PATTERN_SIZE = 3000; var BORDER_SIZE = 2; var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var paddedWidth = width + BORDER_SIZE * 2; var paddedHeight = height + BORDER_SIZE * 2; var canvas, tmpCanvas, i, ii; if (_webgl.WebGLUtils.isEnabled) { canvas = _webgl.WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false); tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); canvas = tmpCanvas.canvas; } return { canvas: canvas, offsetX: offsetX - BORDER_SIZE * scaleX, offsetY: offsetY - BORDER_SIZE * scaleY, scaleX: scaleX, scaleY: scaleY }; } return createMeshCanvas; }(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = _util.Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { throw new Error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.canvasGraphicsFactory = canvasGraphicsFactory; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var canvasGraphicsFactory = this.canvasGraphicsFactory; (0, _util.info)('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; var matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(graphics, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (Array.isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(graphics, paintType, color) { var context = graphics.ctx, current = graphics.current; switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; current.fillColor = ctx.fillStyle; current.strokeColor = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = _util.Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; current.fillColor = cssColor; current.strokeColor = cssColor; break; default: throw new _util.FormatError('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; }(); exports.getShadingPatternFromIR = getShadingPatternFromIR; exports.TilingPattern = TilingPattern; /***/ }), /* 117 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PDFDataTransportStream = undefined; var _util = __w_pdfjs_require__(0); var PDFDataTransportStream = function PDFDataTransportStreamClosure() { function PDFDataTransportStream(params, pdfDataRangeTransport) { var _this = this; (0, _util.assert)(pdfDataRangeTransport); this._queuedChunks = []; var initialData = params.initialData; if (initialData && initialData.length > 0) { var buffer = new Uint8Array(initialData).buffer; this._queuedChunks.push(buffer); } this._pdfDataRangeTransport = pdfDataRangeTransport; this._isRangeSupported = !params.disableRange; this._isStreamingSupported = !params.disableStream; this._contentLength = params.length; this._fullRequestReader = null; this._rangeReaders = []; this._pdfDataRangeTransport.addRangeListener(function (begin, chunk) { _this._onReceiveData({ begin: begin, chunk: chunk }); }); this._pdfDataRangeTransport.addProgressListener(function (loaded) { _this._onProgress({ loaded: loaded }); }); this._pdfDataRangeTransport.addProgressiveReadListener(function (chunk) { _this._onReceiveData({ chunk: chunk }); }); this._pdfDataRangeTransport.transportReady(); } PDFDataTransportStream.prototype = { _onReceiveData: function PDFDataTransportStream_onReceiveData(args) { var buffer = new Uint8Array(args.chunk).buffer; if (args.begin === undefined) { if (this._fullRequestReader) { this._fullRequestReader._enqueue(buffer); } else { this._queuedChunks.push(buffer); } } else { var found = this._rangeReaders.some(function (rangeReader) { if (rangeReader._begin !== args.begin) { return false; } rangeReader._enqueue(buffer); return true; }); (0, _util.assert)(found); } }, _onProgress: function PDFDataTransportStream_onDataProgress(evt) { if (this._rangeReaders.length > 0) { var firstReader = this._rangeReaders[0]; if (firstReader.onProgress) { firstReader.onProgress({ loaded: evt.loaded }); } } }, _removeRangeReader: function PDFDataTransportStream_removeRangeReader(reader) { var i = this._rangeReaders.indexOf(reader); if (i >= 0) { this._rangeReaders.splice(i, 1); } }, getFullReader: function PDFDataTransportStream_getFullReader() { (0, _util.assert)(!this._fullRequestReader); var queuedChunks = this._queuedChunks; this._queuedChunks = null; return new PDFDataTransportStreamReader(this, queuedChunks); }, getRangeReader: function PDFDataTransportStream_getRangeReader(begin, end) { var reader = new PDFDataTransportStreamRangeReader(this, begin, end); this._pdfDataRangeTransport.requestDataRange(begin, end); this._rangeReaders.push(reader); return reader; }, cancelAllRequests: function PDFDataTransportStream_cancelAllRequests(reason) { if (this._fullRequestReader) { this._fullRequestReader.cancel(reason); } var readers = this._rangeReaders.slice(0); readers.forEach(function (rangeReader) { rangeReader.cancel(reason); }); this._pdfDataRangeTransport.abort(); } }; function PDFDataTransportStreamReader(stream, queuedChunks) { this._stream = stream; this._done = false; this._queuedChunks = queuedChunks || []; this._requests = []; this._headersReady = Promise.resolve(); stream._fullRequestReader = this; this.onProgress = null; } PDFDataTransportStreamReader.prototype = { _enqueue: function PDFDataTransportStreamReader_enqueue(chunk) { if (this._done) { return; } if (this._requests.length > 0) { var requestCapability = this._requests.shift(); requestCapability.resolve({ value: chunk, done: false }); return; } this._queuedChunks.push(chunk); }, get headersReady() { return this._headersReady; }, get isRangeSupported() { return this._stream._isRangeSupported; }, get isStreamingSupported() { return this._stream._isStreamingSupported; }, get contentLength() { return this._stream._contentLength; }, read: function PDFDataTransportStreamReader_read() { if (this._queuedChunks.length > 0) { var chunk = this._queuedChunks.shift(); return Promise.resolve({ value: chunk, done: false }); } if (this._done) { return Promise.resolve({ value: undefined, done: true }); } var requestCapability = (0, _util.createPromiseCapability)(); this._requests.push(requestCapability); return requestCapability.promise; }, cancel: function PDFDataTransportStreamReader_cancel(reason) { this._done = true; this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; } }; function PDFDataTransportStreamRangeReader(stream, begin, end) { this._stream = stream; this._begin = begin; this._end = end; this._queuedChunk = null; this._requests = []; this._done = false; this.onProgress = null; } PDFDataTransportStreamRangeReader.prototype = { _enqueue: function PDFDataTransportStreamRangeReader_enqueue(chunk) { if (this._done) { return; } if (this._requests.length === 0) { this._queuedChunk = chunk; } else { var requestsCapability = this._requests.shift(); requestsCapability.resolve({ value: chunk, done: false }); this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; } this._done = true; this._stream._removeRangeReader(this); }, get isStreamingSupported() { return false; }, read: function PDFDataTransportStreamRangeReader_read() { if (this._queuedChunk) { var chunk = this._queuedChunk; this._queuedChunk = null; return Promise.resolve({ value: chunk, done: false }); } if (this._done) { return Promise.resolve({ value: undefined, done: true }); } var requestCapability = (0, _util.createPromiseCapability)(); this._requests.push(requestCapability); return requestCapability.promise; }, cancel: function PDFDataTransportStreamRangeReader_cancel(reason) { this._done = true; this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; this._stream._removeRangeReader(this); } }; return PDFDataTransportStream; }(); exports.PDFDataTransportStream = PDFDataTransportStream; /***/ }), /* 118 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PDFNodeStream = undefined; 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 _util = __w_pdfjs_require__(0); var _network_utils = __w_pdfjs_require__(38); 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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var fs = require('fs'); var http = require('http'); var https = require('https'); var url = require('url'); var PDFNodeStream = function () { function PDFNodeStream(options) { _classCallCheck(this, PDFNodeStream); this.options = options; this.source = options.source; this.url = url.parse(this.source.url); this.isHttp = this.url.protocol === 'http:' || this.url.protocol === 'https:'; this.isFsUrl = this.url.protocol === 'file:' || !this.url.host; this.httpHeaders = this.isHttp && this.source.httpHeaders || {}; this._fullRequest = null; this._rangeRequestReaders = []; } _createClass(PDFNodeStream, [{ key: 'getFullReader', value: function getFullReader() { (0, _util.assert)(!this._fullRequest); this._fullRequest = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this); return this._fullRequest; } }, { key: 'getRangeReader', value: function getRangeReader(start, end) { var rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end); this._rangeRequestReaders.push(rangeReader); return rangeReader; } }, { key: 'cancelAllRequests', value: function cancelAllRequests(reason) { if (this._fullRequest) { this._fullRequest.cancel(reason); } var readers = this._rangeRequestReaders.slice(0); readers.forEach(function (reader) { reader.cancel(reason); }); } }]); return PDFNodeStream; }(); var BaseFullReader = function () { function BaseFullReader(stream) { _classCallCheck(this, BaseFullReader); this._url = stream.url; this._done = false; this._errored = false; this._reason = null; this.onProgress = null; this._contentLength = stream.source.length; this._loaded = 0; this._disableRange = stream.options.disableRange || false; this._rangeChunkSize = stream.source.rangeChunkSize; if (!this._rangeChunkSize && !this._disableRange) { this._disableRange = true; } this._isStreamingSupported = !stream.source.disableStream; this._isRangeSupported = !stream.options.disableRange; this._readableStream = null; this._readCapability = (0, _util.createPromiseCapability)(); this._headersCapability = (0, _util.createPromiseCapability)(); } _createClass(BaseFullReader, [{ key: 'read', value: function read() { var _this = this; return this._readCapability.promise.then(function () { if (_this._done) { return Promise.resolve({ value: undefined, done: true }); } if (_this._errored) { return Promise.reject(_this._reason); } var chunk = _this._readableStream.read(); if (chunk === null) { _this._readCapability = (0, _util.createPromiseCapability)(); return _this.read(); } _this._loaded += chunk.length; if (_this.onProgress) { _this.onProgress({ loaded: _this._loaded, total: _this._contentLength }); } var buffer = new Uint8Array(chunk).buffer; return Promise.resolve({ value: buffer, done: false }); }); } }, { key: 'cancel', value: function cancel(reason) { if (!this._readableStream) { this._error(reason); return; } this._readableStream.destroy(reason); } }, { key: '_error', value: function _error(reason) { this._errored = true; this._reason = reason; this._readCapability.resolve(); } }, { key: '_setReadableStream', value: function _setReadableStream(readableStream) { var _this2 = this; this._readableStream = readableStream; readableStream.on('readable', function () { _this2._readCapability.resolve(); }); readableStream.on('end', function () { readableStream.destroy(); _this2._done = true; _this2._readCapability.resolve(); }); readableStream.on('error', function (reason) { _this2._error(reason); }); if (!this._isStreamingSupported && this._isRangeSupported) { this._error(new _util.AbortException('streaming is disabled')); } if (this._errored) { this._readableStream.destroy(this._reason); } } }, { key: 'headersReady', get: function get() { return this._headersCapability.promise; } }, { key: 'contentLength', get: function get() { return this._contentLength; } }, { key: 'isRangeSupported', get: function get() { return this._isRangeSupported; } }, { key: 'isStreamingSupported', get: function get() { return this._isStreamingSupported; } }]); return BaseFullReader; }(); var BaseRangeReader = function () { function BaseRangeReader(stream) { _classCallCheck(this, BaseRangeReader); this._url = stream.url; this._done = false; this._errored = false; this._reason = null; this.onProgress = null; this._loaded = 0; this._readableStream = null; this._readCapability = (0, _util.createPromiseCapability)(); this._isStreamingSupported = !stream.source.disableStream; } _createClass(BaseRangeReader, [{ key: 'read', value: function read() { var _this3 = this; return this._readCapability.promise.then(function () { if (_this3._done) { return Promise.resolve({ value: undefined, done: true }); } if (_this3._errored) { return Promise.reject(_this3._reason); } var chunk = _this3._readableStream.read(); if (chunk === null) { _this3._readCapability = (0, _util.createPromiseCapability)(); return _this3.read(); } _this3._loaded += chunk.length; if (_this3.onProgress) { _this3.onProgress({ loaded: _this3._loaded }); } var buffer = new Uint8Array(chunk).buffer; return Promise.resolve({ value: buffer, done: false }); }); } }, { key: 'cancel', value: function cancel(reason) { if (!this._readableStream) { this._error(reason); return; } this._readableStream.destroy(reason); } }, { key: '_error', value: function _error(reason) { this._errored = true; this._reason = reason; this._readCapability.resolve(); } }, { key: '_setReadableStream', value: function _setReadableStream(readableStream) { var _this4 = this; this._readableStream = readableStream; readableStream.on('readable', function () { _this4._readCapability.resolve(); }); readableStream.on('end', function () { readableStream.destroy(); _this4._done = true; _this4._readCapability.resolve(); }); readableStream.on('error', function (reason) { _this4._error(reason); }); if (this._errored) { this._readableStream.destroy(this._reason); } } }, { key: 'isStreamingSupported', get: function get() { return this._isStreamingSupported; } }]); return BaseRangeReader; }(); function createRequestOptions(url, headers) { return { protocol: url.protocol, auth: url.auth, host: url.hostname, port: url.port, path: url.path, method: 'GET', headers: headers }; } var PDFNodeStreamFullReader = function (_BaseFullReader) { _inherits(PDFNodeStreamFullReader, _BaseFullReader); function PDFNodeStreamFullReader(stream) { _classCallCheck(this, PDFNodeStreamFullReader); var _this5 = _possibleConstructorReturn(this, (PDFNodeStreamFullReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFullReader)).call(this, stream)); var handleResponse = function handleResponse(response) { _this5._headersCapability.resolve(); _this5._setReadableStream(response); var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({ getResponseHeader: function getResponseHeader(name) { return _this5._readableStream.headers[name.toLowerCase()]; }, isHttp: stream.isHttp, rangeChunkSize: _this5._rangeChunkSize, disableRange: _this5._disableRange }), allowRangeRequests = _validateRangeRequest.allowRangeRequests, suggestedLength = _validateRangeRequest.suggestedLength; if (allowRangeRequests) { _this5._isRangeSupported = true; } _this5._contentLength = suggestedLength; }; _this5._request = null; if (_this5._url.protocol === 'http:') { _this5._request = http.request(createRequestOptions(_this5._url, stream.httpHeaders), handleResponse); } else { _this5._request = https.request(createRequestOptions(_this5._url, stream.httpHeaders), handleResponse); } _this5._request.on('error', function (reason) { _this5._errored = true; _this5._reason = reason; _this5._headersCapability.reject(reason); }); _this5._request.end(); return _this5; } return PDFNodeStreamFullReader; }(BaseFullReader); var PDFNodeStreamRangeReader = function (_BaseRangeReader) { _inherits(PDFNodeStreamRangeReader, _BaseRangeReader); function PDFNodeStreamRangeReader(stream, start, end) { _classCallCheck(this, PDFNodeStreamRangeReader); var _this6 = _possibleConstructorReturn(this, (PDFNodeStreamRangeReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamRangeReader)).call(this, stream)); _this6._httpHeaders = {}; for (var property in stream.httpHeaders) { var value = stream.httpHeaders[property]; if (typeof value === 'undefined') { continue; } _this6._httpHeaders[property] = value; } _this6._httpHeaders['Range'] = 'bytes=' + start + '-' + (end - 1); _this6._request = null; if (_this6._url.protocol === 'http:') { _this6._request = http.request(createRequestOptions(_this6._url, _this6._httpHeaders), function (response) { _this6._setReadableStream(response); }); } else { _this6._request = https.request(createRequestOptions(_this6._url, _this6._httpHeaders), function (response) { _this6._setReadableStream(response); }); } _this6._request.on('error', function (reason) { _this6._errored = true; _this6._reason = reason; }); _this6._request.end(); return _this6; } return PDFNodeStreamRangeReader; }(BaseRangeReader); var PDFNodeStreamFsFullReader = function (_BaseFullReader2) { _inherits(PDFNodeStreamFsFullReader, _BaseFullReader2); function PDFNodeStreamFsFullReader(stream) { _classCallCheck(this, PDFNodeStreamFsFullReader); var _this7 = _possibleConstructorReturn(this, (PDFNodeStreamFsFullReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsFullReader)).call(this, stream)); var path = decodeURI(_this7._url.path); fs.lstat(path, function (error, stat) { if (error) { _this7._errored = true; _this7._reason = error; _this7._headersCapability.reject(error); return; } _this7._contentLength = stat.size; _this7._setReadableStream(fs.createReadStream(path)); _this7._headersCapability.resolve(); }); return _this7; } return PDFNodeStreamFsFullReader; }(BaseFullReader); var PDFNodeStreamFsRangeReader = function (_BaseRangeReader2) { _inherits(PDFNodeStreamFsRangeReader, _BaseRangeReader2); function PDFNodeStreamFsRangeReader(stream, start, end) { _classCallCheck(this, PDFNodeStreamFsRangeReader); var _this8 = _possibleConstructorReturn(this, (PDFNodeStreamFsRangeReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFsRangeReader)).call(this, stream)); _this8._setReadableStream(fs.createReadStream(decodeURI(_this8._url.path), { start: start, end: end - 1 })); return _this8; } return PDFNodeStreamFsRangeReader; }(BaseRangeReader); exports.PDFNodeStream = PDFNodeStream; /***/ }), /* 119 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PDFFetchStream = undefined; 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 _util = __w_pdfjs_require__(0); var _network_utils = __w_pdfjs_require__(38); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function createFetchOptions(headers, withCredentials) { return { method: 'GET', headers: headers, mode: 'cors', credentials: withCredentials ? 'include' : 'same-origin', redirect: 'follow' }; } var PDFFetchStream = function () { function PDFFetchStream(options) { _classCallCheck(this, PDFFetchStream); this.options = options; this.source = options.source; this.isHttp = /^https?:/i.test(this.source.url); this.httpHeaders = this.isHttp && this.source.httpHeaders || {}; this._fullRequestReader = null; this._rangeRequestReaders = []; } _createClass(PDFFetchStream, [{ key: 'getFullReader', value: function getFullReader() { (0, _util.assert)(!this._fullRequestReader); this._fullRequestReader = new PDFFetchStreamReader(this); return this._fullRequestReader; } }, { key: 'getRangeReader', value: function getRangeReader(begin, end) { var reader = new PDFFetchStreamRangeReader(this, begin, end); this._rangeRequestReaders.push(reader); return reader; } }, { key: 'cancelAllRequests', value: function cancelAllRequests(reason) { if (this._fullRequestReader) { this._fullRequestReader.cancel(reason); } var readers = this._rangeRequestReaders.slice(0); readers.forEach(function (reader) { reader.cancel(reason); }); } }]); return PDFFetchStream; }(); var PDFFetchStreamReader = function () { function PDFFetchStreamReader(stream) { var _this = this; _classCallCheck(this, PDFFetchStreamReader); this._stream = stream; this._reader = null; this._loaded = 0; this._withCredentials = stream.source.withCredentials; this._contentLength = this._stream.source.length; this._headersCapability = (0, _util.createPromiseCapability)(); this._disableRange = this._stream.options.disableRange; this._rangeChunkSize = this._stream.source.rangeChunkSize; if (!this._rangeChunkSize && !this._disableRange) { this._disableRange = true; } this._isRangeSupported = !this._stream.options.disableRange; this._isStreamingSupported = !this._stream.source.disableStream; this._headers = new Headers(); for (var property in this._stream.httpHeaders) { var value = this._stream.httpHeaders[property]; if (typeof value === 'undefined') { continue; } this._headers.append(property, value); } var url = this._stream.source.url; fetch(url, createFetchOptions(this._headers, this._withCredentials)).then(function (response) { if (!(0, _network_utils.validateResponseStatus)(response.status)) { throw (0, _network_utils.createResponseStatusError)(response.status, url); } _this._reader = response.body.getReader(); _this._headersCapability.resolve(); var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({ getResponseHeader: function getResponseHeader(name) { return response.headers.get(name); }, isHttp: _this._stream.isHttp, rangeChunkSize: _this._rangeChunkSize, disableRange: _this._disableRange }), allowRangeRequests = _validateRangeRequest.allowRangeRequests, suggestedLength = _validateRangeRequest.suggestedLength; _this._contentLength = suggestedLength; _this._isRangeSupported = allowRangeRequests; if (!_this._isStreamingSupported && _this._isRangeSupported) { _this.cancel(new _util.AbortException('streaming is disabled')); } }).catch(this._headersCapability.reject); this.onProgress = null; } _createClass(PDFFetchStreamReader, [{ key: 'read', value: function read() { var _this2 = this; return this._headersCapability.promise.then(function () { return _this2._reader.read().then(function (_ref) { var value = _ref.value, done = _ref.done; if (done) { return Promise.resolve({ value: value, done: done }); } _this2._loaded += value.byteLength; if (_this2.onProgress) { _this2.onProgress({ loaded: _this2._loaded, total: _this2._contentLength }); } var buffer = new Uint8Array(value).buffer; return Promise.resolve({ value: buffer, done: false }); }); }); } }, { key: 'cancel', value: function cancel(reason) { if (this._reader) { this._reader.cancel(reason); } } }, { key: 'headersReady', get: function get() { return this._headersCapability.promise; } }, { key: 'contentLength', get: function get() { return this._contentLength; } }, { key: 'isRangeSupported', get: function get() { return this._isRangeSupported; } }, { key: 'isStreamingSupported', get: function get() { return this._isStreamingSupported; } }]); return PDFFetchStreamReader; }(); var PDFFetchStreamRangeReader = function () { function PDFFetchStreamRangeReader(stream, begin, end) { var _this3 = this; _classCallCheck(this, PDFFetchStreamRangeReader); this._stream = stream; this._reader = null; this._loaded = 0; this._withCredentials = stream.source.withCredentials; this._readCapability = (0, _util.createPromiseCapability)(); this._isStreamingSupported = !stream.source.disableStream; this._headers = new Headers(); for (var property in this._stream.httpHeaders) { var value = this._stream.httpHeaders[property]; if (typeof value === 'undefined') { continue; } this._headers.append(property, value); } var rangeStr = begin + '-' + (end - 1); this._headers.append('Range', 'bytes=' + rangeStr); var url = this._stream.source.url; fetch(url, createFetchOptions(this._headers, this._withCredentials)).then(function (response) { if (!(0, _network_utils.validateResponseStatus)(response.status)) { throw (0, _network_utils.createResponseStatusError)(response.status, url); } _this3._readCapability.resolve(); _this3._reader = response.body.getReader(); }); this.onProgress = null; } _createClass(PDFFetchStreamRangeReader, [{ key: 'read', value: function read() { var _this4 = this; return this._readCapability.promise.then(function () { return _this4._reader.read().then(function (_ref2) { var value = _ref2.value, done = _ref2.done; if (done) { return Promise.resolve({ value: value, done: done }); } _this4._loaded += value.byteLength; if (_this4.onProgress) { _this4.onProgress({ loaded: _this4._loaded }); } var buffer = new Uint8Array(value).buffer; return Promise.resolve({ value: buffer, done: false }); }); }); } }, { key: 'cancel', value: function cancel(reason) { if (this._reader) { this._reader.cancel(reason); } } }, { key: 'isStreamingSupported', get: function get() { return this._isStreamingSupported; } }]); return PDFFetchStreamRangeReader; }(); exports.PDFFetchStream = PDFFetchStream; /***/ }), /* 120 */ /***/ (function(module, exports, __w_pdfjs_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NetworkManager = exports.PDFNetworkStream = undefined; var _util = __w_pdfjs_require__(0); var _network_utils = __w_pdfjs_require__(38); var _global_scope = __w_pdfjs_require__(14); var _global_scope2 = _interopRequireDefault(_global_scope); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } ; var OK_RESPONSE = 200; var PARTIAL_CONTENT_RESPONSE = 206; function NetworkManager(url, args) { this.url = url; args = args || {}; this.isHttp = /^https?:/i.test(url); this.httpHeaders = this.isHttp && args.httpHeaders || {}; this.withCredentials = args.withCredentials || false; this.getXhr = args.getXhr || function NetworkManager_getXhr() { return new XMLHttpRequest(); }; this.currXhrId = 0; this.pendingRequests = Object.create(null); this.loadedRequests = Object.create(null); } function getArrayBuffer(xhr) { var data = xhr.response; if (typeof data !== 'string') { return data; } var array = (0, _util.stringToBytes)(data); return array.buffer; } var supportsMozChunked = function supportsMozChunkedClosure() { try { var x = new XMLHttpRequest(); x.open('GET', _global_scope2.default.location.href); x.responseType = 'moz-chunked-arraybuffer'; return x.responseType === 'moz-chunked-arraybuffer'; } catch (e) { return false; } }(); NetworkManager.prototype = { requestRange: function NetworkManager_requestRange(begin, end, listeners) { var args = { begin: begin, end: end }; for (var prop in listeners) { args[prop] = listeners[prop]; } return this.request(args); }, requestFull: function NetworkManager_requestFull(listeners) { return this.request(listeners); }, request: function NetworkManager_request(args) { var xhr = this.getXhr(); var xhrId = this.currXhrId++; var pendingRequest = this.pendingRequests[xhrId] = { xhr: xhr }; xhr.open('GET', this.url); xhr.withCredentials = this.withCredentials; for (var property in this.httpHeaders) { var value = this.httpHeaders[property]; if (typeof value === 'undefined') { continue; } xhr.setRequestHeader(property, value); } if (this.isHttp && 'begin' in args && 'end' in args) { var rangeStr = args.begin + '-' + (args.end - 1); xhr.setRequestHeader('Range', 'bytes=' + rangeStr); pendingRequest.expectedStatus = 206; } else { pendingRequest.expectedStatus = 200; } var useMozChunkedLoading = supportsMozChunked && !!args.onProgressiveData; if (useMozChunkedLoading) { xhr.responseType = 'moz-chunked-arraybuffer'; pendingRequest.onProgressiveData = args.onProgressiveData; pendingRequest.mozChunked = true; } else { xhr.responseType = 'arraybuffer'; } if (args.onError) { xhr.onerror = function (evt) { args.onError(xhr.status); }; } xhr.onreadystatechange = this.onStateChange.bind(this, xhrId); xhr.onprogress = this.onProgress.bind(this, xhrId); pendingRequest.onHeadersReceived = args.onHeadersReceived; pendingRequest.onDone = args.onDone; pendingRequest.onError = args.onError; pendingRequest.onProgress = args.onProgress; xhr.send(null); return xhrId; }, onProgress: function NetworkManager_onProgress(xhrId, evt) { var pendingRequest = this.pendingRequests[xhrId]; if (!pendingRequest) { return; } if (pendingRequest.mozChunked) { var chunk = getArrayBuffer(pendingRequest.xhr); pendingRequest.onProgressiveData(chunk); } var onProgress = pendingRequest.onProgress; if (onProgress) { onProgress(evt); } }, onStateChange: function NetworkManager_onStateChange(xhrId, evt) { var pendingRequest = this.pendingRequests[xhrId]; if (!pendingRequest) { return; } var xhr = pendingRequest.xhr; if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { pendingRequest.onHeadersReceived(); delete pendingRequest.onHeadersReceived; } if (xhr.readyState !== 4) { return; } if (!(xhrId in this.pendingRequests)) { return; } delete this.pendingRequests[xhrId]; if (xhr.status === 0 && this.isHttp) { if (pendingRequest.onError) { pendingRequest.onError(xhr.status); } return; } var xhrStatus = xhr.status || OK_RESPONSE; var ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE; if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) { if (pendingRequest.onError) { pendingRequest.onError(xhr.status); } return; } this.loadedRequests[xhrId] = true; var chunk = getArrayBuffer(xhr); if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { var rangeHeader = xhr.getResponseHeader('Content-Range'); var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader); var begin = parseInt(matches[1], 10); pendingRequest.onDone({ begin: begin, chunk: chunk }); } else if (pendingRequest.onProgressiveData) { pendingRequest.onDone(null); } else if (chunk) { pendingRequest.onDone({ begin: 0, chunk: chunk }); } else if (pendingRequest.onError) { pendingRequest.onError(xhr.status); } }, hasPendingRequests: function NetworkManager_hasPendingRequests() { for (var xhrId in this.pendingRequests) { return true; } return false; }, getRequestXhr: function NetworkManager_getXhr(xhrId) { return this.pendingRequests[xhrId].xhr; }, isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) { return !!this.pendingRequests[xhrId].onProgressiveData; }, isPendingRequest: function NetworkManager_isPendingRequest(xhrId) { return xhrId in this.pendingRequests; }, isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) { return xhrId in this.loadedRequests; }, abortAllRequests: function NetworkManager_abortAllRequests() { for (var xhrId in this.pendingRequests) { this.abortRequest(xhrId | 0); } }, abortRequest: function NetworkManager_abortRequest(xhrId) { var xhr = this.pendingRequests[xhrId].xhr; delete this.pendingRequests[xhrId]; xhr.abort(); } }; function PDFNetworkStream(options) { this._options = options; var source = options.source; this._manager = new NetworkManager(source.url, { httpHeaders: source.httpHeaders, withCredentials: source.withCredentials }); this._rangeChunkSize = source.rangeChunkSize; this._fullRequestReader = null; this._rangeRequestReaders = []; } PDFNetworkStream.prototype = { _onRangeRequestReaderClosed: function PDFNetworkStream_onRangeRequestReaderClosed(reader) { var i = this._rangeRequestReaders.indexOf(reader); if (i >= 0) { this._rangeRequestReaders.splice(i, 1); } }, getFullReader: function PDFNetworkStream_getFullReader() { (0, _util.assert)(!this._fullRequestReader); this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._options); return this._fullRequestReader; }, getRangeReader: function PDFNetworkStream_getRangeReader(begin, end) { var reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end); reader.onClosed = this._onRangeRequestReaderClosed.bind(this); this._rangeRequestReaders.push(reader); return reader; }, cancelAllRequests: function PDFNetworkStream_cancelAllRequests(reason) { if (this._fullRequestReader) { this._fullRequestReader.cancel(reason); } var readers = this._rangeRequestReaders.slice(0); readers.forEach(function (reader) { reader.cancel(reason); }); } }; function PDFNetworkStreamFullRequestReader(manager, options) { this._manager = manager; var source = options.source; var args = { onHeadersReceived: this._onHeadersReceived.bind(this), onProgressiveData: source.disableStream ? null : this._onProgressiveData.bind(this), onDone: this._onDone.bind(this), onError: this._onError.bind(this), onProgress: this._onProgress.bind(this) }; this._url = source.url; this._fullRequestId = manager.requestFull(args); this._headersReceivedCapability = (0, _util.createPromiseCapability)(); this._disableRange = options.disableRange || false; this._contentLength = source.length; this._rangeChunkSize = source.rangeChunkSize; if (!this._rangeChunkSize && !this._disableRange) { this._disableRange = true; } this._isStreamingSupported = false; this._isRangeSupported = false; this._cachedChunks = []; this._requests = []; this._done = false; this._storedError = undefined; this.onProgress = null; } PDFNetworkStreamFullRequestReader.prototype = { _onHeadersReceived: function PDFNetworkStreamFullRequestReader_onHeadersReceived() { var fullRequestXhrId = this._fullRequestId; var fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({ getResponseHeader: function getResponseHeader(name) { return fullRequestXhr.getResponseHeader(name); }, isHttp: this._manager.isHttp, rangeChunkSize: this._rangeChunkSize, disableRange: this._disableRange }), allowRangeRequests = _validateRangeRequest.allowRangeRequests, suggestedLength = _validateRangeRequest.suggestedLength; this._contentLength = suggestedLength || this._contentLength; if (allowRangeRequests) { this._isRangeSupported = true; } var networkManager = this._manager; if (networkManager.isStreamingRequest(fullRequestXhrId)) { this._isStreamingSupported = true; } else if (this._isRangeSupported) { networkManager.abortRequest(fullRequestXhrId); } this._headersReceivedCapability.resolve(); }, _onProgressiveData: function PDFNetworkStreamFullRequestReader_onProgressiveData(chunk) { if (this._requests.length > 0) { var requestCapability = this._requests.shift(); requestCapability.resolve({ value: chunk, done: false }); } else { this._cachedChunks.push(chunk); } }, _onDone: function PDFNetworkStreamFullRequestReader_onDone(args) { if (args) { this._onProgressiveData(args.chunk); } this._done = true; if (this._cachedChunks.length > 0) { return; } this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; }, _onError: function PDFNetworkStreamFullRequestReader_onError(status) { var url = this._url; var exception = (0, _network_utils.createResponseStatusError)(status, url); this._storedError = exception; this._headersReceivedCapability.reject(exception); this._requests.forEach(function (requestCapability) { requestCapability.reject(exception); }); this._requests = []; this._cachedChunks = []; }, _onProgress: function PDFNetworkStreamFullRequestReader_onProgress(data) { if (this.onProgress) { this.onProgress({ loaded: data.loaded, total: data.lengthComputable ? data.total : this._contentLength }); } }, get isRangeSupported() { return this._isRangeSupported; }, get isStreamingSupported() { return this._isStreamingSupported; }, get contentLength() { return this._contentLength; }, get headersReady() { return this._headersReceivedCapability.promise; }, read: function PDFNetworkStreamFullRequestReader_read() { if (this._storedError) { return Promise.reject(this._storedError); } if (this._cachedChunks.length > 0) { var chunk = this._cachedChunks.shift(); return Promise.resolve({ value: chunk, done: false }); } if (this._done) { return Promise.resolve({ value: undefined, done: true }); } var requestCapability = (0, _util.createPromiseCapability)(); this._requests.push(requestCapability); return requestCapability.promise; }, cancel: function PDFNetworkStreamFullRequestReader_cancel(reason) { this._done = true; this._headersReceivedCapability.reject(reason); this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; if (this._manager.isPendingRequest(this._fullRequestId)) { this._manager.abortRequest(this._fullRequestId); } this._fullRequestReader = null; } }; function PDFNetworkStreamRangeRequestReader(manager, begin, end) { this._manager = manager; var args = { onDone: this._onDone.bind(this), onProgress: this._onProgress.bind(this) }; this._requestId = manager.requestRange(begin, end, args); this._requests = []; this._queuedChunk = null; this._done = false; this.onProgress = null; this.onClosed = null; } PDFNetworkStreamRangeRequestReader.prototype = { _close: function PDFNetworkStreamRangeRequestReader_close() { if (this.onClosed) { this.onClosed(this); } }, _onDone: function PDFNetworkStreamRangeRequestReader_onDone(data) { var chunk = data.chunk; if (this._requests.length > 0) { var requestCapability = this._requests.shift(); requestCapability.resolve({ value: chunk, done: false }); } else { this._queuedChunk = chunk; } this._done = true; this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; this._close(); }, _onProgress: function PDFNetworkStreamRangeRequestReader_onProgress(evt) { if (!this.isStreamingSupported && this.onProgress) { this.onProgress({ loaded: evt.loaded }); } }, get isStreamingSupported() { return false; }, read: function PDFNetworkStreamRangeRequestReader_read() { if (this._queuedChunk !== null) { var chunk = this._queuedChunk; this._queuedChunk = null; return Promise.resolve({ value: chunk, done: false }); } if (this._done) { return Promise.resolve({ value: undefined, done: true }); } var requestCapability = (0, _util.createPromiseCapability)(); this._requests.push(requestCapability); return requestCapability.promise; }, cancel: function PDFNetworkStreamRangeRequestReader_cancel(reason) { this._done = true; this._requests.forEach(function (requestCapability) { requestCapability.resolve({ value: undefined, done: true }); }); this._requests = []; if (this._manager.isPendingRequest(this._requestId)) { this._manager.abortRequest(this._requestId); } this._close(); } }; exports.PDFNetworkStream = PDFNetworkStream; exports.NetworkManager = NetworkManager; /***/ }) /******/ ]); }); //# sourceMappingURL=pdf.js.map
src/svg-icons/action/fingerprint.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFingerprint = (props) => ( <SvgIcon {...props}> <path d="M17.81 4.47c-.08 0-.16-.02-.23-.06C15.66 3.42 14 3 12.01 3c-1.98 0-3.86.47-5.57 1.41-.24.13-.54.04-.68-.2-.13-.24-.04-.55.2-.68C7.82 2.52 9.86 2 12.01 2c2.13 0 3.99.47 6.03 1.52.25.13.34.43.21.67-.09.18-.26.28-.44.28zM3.5 9.72c-.1 0-.2-.03-.29-.09-.23-.16-.28-.47-.12-.7.99-1.4 2.25-2.5 3.75-3.27C9.98 4.04 14 4.03 17.15 5.65c1.5.77 2.76 1.86 3.75 3.25.16.22.11.54-.12.7-.23.16-.54.11-.7-.12-.9-1.26-2.04-2.25-3.39-2.94-2.87-1.47-6.54-1.47-9.4.01-1.36.7-2.5 1.7-3.4 2.96-.08.14-.23.21-.39.21zm6.25 12.07c-.13 0-.26-.05-.35-.15-.87-.87-1.34-1.43-2.01-2.64-.69-1.23-1.05-2.73-1.05-4.34 0-2.97 2.54-5.39 5.66-5.39s5.66 2.42 5.66 5.39c0 .28-.22.5-.5.5s-.5-.22-.5-.5c0-2.42-2.09-4.39-4.66-4.39-2.57 0-4.66 1.97-4.66 4.39 0 1.44.32 2.77.93 3.85.64 1.15 1.08 1.64 1.85 2.42.19.2.19.51 0 .71-.11.1-.24.15-.37.15zm7.17-1.85c-1.19 0-2.24-.3-3.1-.89-1.49-1.01-2.38-2.65-2.38-4.39 0-.28.22-.5.5-.5s.5.22.5.5c0 1.41.72 2.74 1.94 3.56.71.48 1.54.71 2.54.71.24 0 .64-.03 1.04-.1.27-.05.53.13.58.41.05.27-.13.53-.41.58-.57.11-1.07.12-1.21.12zM14.91 22c-.04 0-.09-.01-.13-.02-1.59-.44-2.63-1.03-3.72-2.1-1.4-1.39-2.17-3.24-2.17-5.22 0-1.62 1.38-2.94 3.08-2.94 1.7 0 3.08 1.32 3.08 2.94 0 1.07.93 1.94 2.08 1.94s2.08-.87 2.08-1.94c0-3.77-3.25-6.83-7.25-6.83-2.84 0-5.44 1.58-6.61 4.03-.39.81-.59 1.76-.59 2.8 0 .78.07 2.01.67 3.61.1.26-.03.55-.29.64-.26.1-.55-.04-.64-.29-.49-1.31-.73-2.61-.73-3.96 0-1.2.23-2.29.68-3.24 1.33-2.79 4.28-4.6 7.51-4.6 4.55 0 8.25 3.51 8.25 7.83 0 1.62-1.38 2.94-3.08 2.94s-3.08-1.32-3.08-2.94c0-1.07-.93-1.94-2.08-1.94s-2.08.87-2.08 1.94c0 1.71.66 3.31 1.87 4.51.95.94 1.86 1.46 3.27 1.85.27.07.42.35.35.61-.05.23-.26.38-.47.38z"/> </SvgIcon> ); ActionFingerprint = pure(ActionFingerprint); ActionFingerprint.displayName = 'ActionFingerprint'; ActionFingerprint.muiName = 'SvgIcon'; export default ActionFingerprint;
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Create/FormComponents/CheckboxOrRadioGroup.js
dewmini/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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. */ import React from 'react'; const CheckboxOrRadioGroup = (props) => ( <div> <label className="form-label">{props.title}</label> <div className="checkbox-group"> {props.options.map(option => { return ( <label key={option} className="form-label capitalize"> <input className="form-checkbox" name={props.setName} onChange={props.controlFunc} value={option} checked={props.selectedOptions.indexOf(option) > -1} type={props.type} /> {option} </label> ); })} </div> </div> ); CheckboxOrRadioGroup.propTypes = { title: React.PropTypes.string.isRequired, type: React.PropTypes.oneOf(['checkbox', 'radio']).isRequired, setName: React.PropTypes.string.isRequired, options: React.PropTypes.array.isRequired, selectedOptions: React.PropTypes.array, controlFunc: React.PropTypes.func.isRequired }; export default CheckboxOrRadioGroup;
docs/app/Examples/collections/Menu/Content/MenuExampleButtons.js
clemensw/stardust
import React from 'react' import { Button, Menu } from 'semantic-ui-react' const MenuExampleButtons = () => { return ( <Menu> <Menu.Item> <Button primary>Sign up</Button> </Menu.Item> <Menu.Item> <Button>Log-in</Button> </Menu.Item> </Menu> ) } export default MenuExampleButtons
frontend/test/app/components/Header-test.js
mozilla/testpilot
import React from 'react'; import { expect } from 'chai'; import sinon from 'sinon'; import { shallow } from 'enzyme'; import Header from '../../../src/app/components/Header'; describe('app/components/Header', () => { let preventDefault, stopPropagation, mockClickEvent, props, subject; beforeEach(() => { preventDefault = sinon.spy(); stopPropagation = sinon.spy(); mockClickEvent = { preventDefault, stopPropagation }; props = { uninstallAddon: sinon.spy(), sendToGA: sinon.spy(), openWindow: sinon.spy() } subject = shallow(<Header {...props} />); }); const expectMenuGA = label => { expect(props.sendToGA.lastCall.args).to.deep.equal(['event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: label }]); }; describe('with hasAddon default', () => { it('should render default expected content', () => { expect(subject.find('#main-header')).to.have.property('length', 1); }); it('should not show the settings button', () => { expect(subject.find('.settings-button')).to.have.property('length', 0); }); }); describe('with hasAddon=true', () => { beforeEach(() => { subject.setProps({ hasAddon: true }); }); it('should show the settings button', () => { expect(subject.find('.settings-button')).to.have.property('length', 1); }); it('should show the settings menu when the settings button is clicked', () => { subject.find('.settings-button').simulate('click', mockClickEvent); expect(subject.state('showSettings')).to.be.true; expect(subject.find('.settings-contain')).to.have.property('length', 1); expectMenuGA('Toggle Menu'); }); describe('and showSettings=true', () => { beforeEach(() => { subject.setState({ showSettings: true }); }); const clickItem = name => { subject .findWhere(el => name === el.props()['data-l10n-id']) .simulate('click', mockClickEvent); }; it('should ping GA and show retire dialog on retire item click', () => { clickItem('menuRetire'); expect(preventDefault.called).to.be.true; expect(subject.state('showRetireDialog')).to.be.true; expect(subject.find('RetireConfirmationDialog')).to.have.property('length', 1); expectMenuGA('Retire'); }); it('should ping GA and show discuss dialog on discuss item click', () => { clickItem('menuDiscuss'); expect(preventDefault.called).to.be.true; expect(subject.state('showDiscussDialog')).to.be.true; expect(subject.find('DiscussDialog')).to.have.property('length', 1); expectMenuGA('Discuss'); }); it('should ping GA and close menu on wiki clicks', () => { clickItem('menuWiki'); expectMenuGA('wiki'); }); it('should ping GA and close menu on file issue click', () => { clickItem('menuFileIssue'); expectMenuGA('file issue'); }); }); }); });
debugger/cerebral-debugger/src/components/Debugger/Components/StatePaths/index.js
FWeinb/cerebral
import './styles.css' import React from 'react' export default function StatePaths (props) { let uniqueComponents = [] return ( <div className='statePaths-wrapper'> <div className='statePaths-componentsWrapper'> <div key='header' className='statePaths-itemHeader' > <div className='statePaths-pathName'> {Object.keys(props.map).length} <small>active state paths</small> </div> <div className='statePaths-components'> {Object.keys(props.map).reduce((count, key) => { const components = props.map[key].filter(component => uniqueComponents.indexOf(component) === -1) uniqueComponents = uniqueComponents.concat(components) return count + components.length }, 0)} {' '} <small>registered components</small> </div> </div> {Object.keys(props.map).map(key => { return ( <div key={key} className='statePaths-item' onClick={() => this.componentMapPathClick({ mapPath: key })} > <div className='statePaths-pathName'>{key}</div> <div className='statePaths-components'> {props.map[key].map((component) => { return component.name }).join(', ')} </div> </div> ) })} </div> </div> ) }
src/Parser/Warlock/Demonology/Modules/Features/AlwaysBeCasting.js
enragednuke/WoWAnalyzer
import React from 'react'; import CoreAlwaysBeCasting from 'Parser/Core/Modules/AlwaysBeCasting'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'Main/StatisticBox'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; class AlwaysBeCasting extends CoreAlwaysBeCasting { get suggestionThresholds() { return { actual: this.downtimePercentage, isGreaterThan: { minor: 0.2, average: 0.35, major: 0.4, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<Wrapper>Your downtime can be improved. Try to Always Be Casting (ABC), try to reduce the delay between casting spells. Even if you have to move, try casting something instant - maybe refresh your dots or replenish your mana with <SpellLink id={SPELLS.LIFE_TAP.id} />. Make good use of your <SpellLink id={SPELLS.DEMONIC_CIRCLE_TALENT_TELEPORT.id} /> when you can.</Wrapper>) .icon('spell_mage_altertime') .actual(`${formatPercentage(actual)}% downtime`) .recommended(`<${formatPercentage(recommended)}% is recommended`); }); } statisticOrder = STATISTIC_ORDER.CORE(1); } export default AlwaysBeCasting;
ajax/libs/forerunnerdb/1.3.517/fdb-legacy.min.js
nolsherry/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":39}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":33,"./Shared":39}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),l=a("./Crc"),e=d.modules.Db,m=a("./Overload"),n=a("./ReactorIO"),o=new h,p.prototype.crc=l,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c=this.find(a,b);return(new p).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I=this._metrics.create("find"),J=this.primaryKey(),K=this,L=!0,M={},N=[],O=[],P=[],Q={},R={},S=function(c){return K._match(c,a,b,"and",Q)};if(I.start(),a){if(I.time("analyseQuery"),c=this._analyseQuery(K.decouple(a),b,I),I.time("analyseQuery"),I.data("analysis",c),c.hasJoin&&c.queriesJoin){for(I.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],M[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];I.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(I.data("index.potential",c.indexMatch),I.data("index.used",c.indexMatch[0].index),I.time("indexLookup"),e=c.indexMatch[0].lookup||[],I.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(L=!1)):I.flag("usedIndex",!1),L&&(e&&e.length?(d=e.length,I.time("tableScan: "+d),e=e.filter(S)):(d=this._data.length,I.time("tableScan: "+d),e=this._data.filter(S)),I.time("tableScan: "+d)),b.$orderBy&&(I.time("sort"),e=this.sort(b.$orderBy,e),I.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(R.page=b.$page,R.pages=Math.ceil(e.length/b.$limit),R.records=e.length,b.$page&&b.$limit>0&&(I.data("cursor",R),e.splice(0,b.$page*b.$limit))),b.$skip&&(R.skip=b.$skip,e.splice(0,b.$skip),I.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(R.limit=b.$limit,e.length=b.$limit,I.data("limit",b.$limit)),b.$decouple&&(I.time("decouple"),e=this.decouple(e),I.time("decouple"),I.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=M[k]?M[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=K._resolveDynamicQuery(m[n].query,e[x])),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=K._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else N.push(e[x])}I.data("flag.join",!0)}if(N.length){for(I.time("removalQueue"),z=0;z<N.length;z++)y=e.indexOf(N[z]),y>-1&&e.splice(y,1);I.time("removalQueue")}if(b.$transform){for(I.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));I.time("transform"),I.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(I.time("transformOut"),e=this.transformOut(e),I.time("transformOut")),I.data("results",e.length)}else e=[];if(!b.$aggregate){I.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?O.push(z):0===b[z]&&P.push(z));if(I.time("scanFields"),O.length||P.length){for(I.data("flag.limitFields",!0),I.data("limitFields.on",O),I.data("limitFields.off",P),I.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(O.length&&A!==J&&-1===O.indexOf(A)&&delete G[A],P.length&&P.indexOf(A)>-1&&delete G[A])}I.time("limitFields")}if(b.$elemMatch){I.data("flag.elemMatch",!0),I.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(K._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}I.time("projection-elemMatch")}if(b.$elemsMatch){I.data("flag.elemsMatch",!0),I.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)K._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}I.time("projection-elemsMatch")}}return b.$aggregate&&(I.data("flag.aggregate",!0),I.time("aggregate"),H=new h(b.$aggregate),e=H.value(e),I.time("aggregate")),I.stop(),e.__fdbOp=I,e.$cursor=R,e},p.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn, dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},s=[],t=[];if(c.time("checkIndexes"),m=new h,n=m.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(o=typeof a[this._primaryKey],("string"===o||"number"===o||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),p=this._primaryIndex.lookup(a,b),r.indexMatch.push({lookup:p,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(q in this._indexById)if(this._indexById.hasOwnProperty(q)&&(j=this._indexById[q],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),r.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),r.indexMatch.length>1&&(c.time("findOptimalIndex"),r.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(r.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(s.push(e),"$as"in b.$join[d][e]?t.push(b.$join[d][e].$as):t.push(e));for(g=0;g<t.length;g++)f=this._queryReferencesCollection(a,t[g],""),f&&(r.joinQueries[s[g]]=f,r.queriesJoin=!0);r.joinsOn=s,r.queriesOn=r.queriesOn.concat(s)}return r},p.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":7,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":4,"./Shared":39}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document=this._document||{},this._document[a]=this._document[a]||new g(a).db(this),this._document[a]}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":4,"./Shared":39}],10:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],11:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked>&nbsp;All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{ switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":31,"./Shared":39}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./Geohash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./Geohash":10,"./Path":33,"./Shared":39}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":33,"./Shared":39}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":39}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":30,"./Shared":39}],18:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":31,"./Serialiser":38}],21:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":31}],23:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!this.db())throw"Cannot operate a "+a+" sub-query on an anonymous collection (one with no db set)!";if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d={ sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":31}],27:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],28:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":39}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],delete this._listeners,!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":33,"./Shared":39}],31:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],32:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){return a?a instanceof h?a:(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":4,"./Document":9,"./Shared":39}],33:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":39}],34:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({ "function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,async:41,localforage:77}],35:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":39,pako:78}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":39,"crypto-js":50}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":39}],38:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){return new RegExp(a.source,a.params)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],39:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.517",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},l.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},l.prototype.primaryKey=function(){return this.publicData().primaryKey()},l.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){var b=this;return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof l?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),b.emit("create",[b._view[a],"view",a]),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39}],41:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}); },{_process:76}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":44}],44:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":44}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":44}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":43,"./core":44}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":44}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":44}],52:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":44}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":43,"./core":44}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":43,"./core":44}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":43,"./core":44}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":43,"./core":44}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":43,"./core":44}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":43,"./core":44}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":43,"./core":44}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":43,"./core":44}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":43,"./core":44}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":43,"./core":44}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8, ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":44}],68:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":44}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":44,"./sha256":70}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":44}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":44,"./x64-core":75}],72:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":44,"./x64-core":75}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":44}],76:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],77:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){ function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0,function(){function a(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},b.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},b.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},b.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},b.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return w(d,b),d}function s(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return w(c,a),c}function t(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function u(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return w(d,b),d}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=n.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return a([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],78:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],82:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":81}],83:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],84:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],85:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],86:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha));); }while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],88:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],89:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":81}],91:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],92:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){ g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":81}],93:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]);
node_modules/react-router/es6/Router.js
dulik06/ReduxStarter
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import createHashHistory from 'history/lib/createHashHistory'; import useQueries from 'history/lib/useQueries'; import invariant from 'invariant'; import React from 'react'; import createTransitionManager from './createTransitionManager'; import { routes } from './InternalPropTypes'; import RouterContext from './RouterContext'; import { createRoutes } from './RouteUtils'; import { createRouterObject, createRoutingHistory } from './RouterUtils'; import warning from './routerWarning'; function isDeprecatedHistory(history) { return !history || !history.__v2_compatible__; } /* istanbul ignore next: sanity check */ function isUnsupportedHistory(history) { // v3 histories expose getCurrentLocation, but aren't currently supported. return history && history.getCurrentLocation; } var _React$PropTypes = React.PropTypes; var func = _React$PropTypes.func; var object = _React$PropTypes.object; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = React.createClass({ displayName: 'Router', propTypes: { history: object, children: routes, routes: routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // Deprecated: parseQueryString: func, stringifyQuery: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return React.createElement(RouterContext, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount: function componentWillMount() { var _this = this; var _props = this.props; var parseQueryString = _props.parseQueryString; var stringifyQuery = _props.stringifyQuery; process.env.NODE_ENV !== 'production' ? warning(!(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring') : void 0; var _createRouterObjects = this.createRouterObjects(); var history = _createRouterObjects.history; var transitionManager = _createRouterObjects.transitionManager; var router = _createRouterObjects.router; this._unlisten = transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { _this.setState(state, _this.props.onUpdate); } }); this.history = history; this.router = router; }, createRouterObjects: function createRouterObjects() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext; } var history = this.props.history; var _props2 = this.props; var routes = _props2.routes; var children = _props2.children; !!isUnsupportedHistory(history) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You have provided a history object created with history v3.x. ' + 'This version of React Router is not compatible with v3 history ' + 'objects. Please use history v2.x instead.') : invariant(false) : void 0; if (isDeprecatedHistory(history)) { history = this.wrapDeprecatedHistory(history); } var transitionManager = createTransitionManager(history, createRoutes(routes || children)); var router = createRouterObject(history, transitionManager); var routingHistory = createRoutingHistory(history, transitionManager); return { history: routingHistory, transitionManager: transitionManager, router: router }; }, wrapDeprecatedHistory: function wrapDeprecatedHistory(history) { var _props3 = this.props; var parseQueryString = _props3.parseQueryString; var stringifyQuery = _props3.stringifyQuery; var createHistory = void 0; if (history) { process.env.NODE_ENV !== 'production' ? warning(false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') : void 0; createHistory = function createHistory() { return history; }; } else { process.env.NODE_ENV !== 'production' ? warning(false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') : void 0; createHistory = createHashHistory; } return useQueries(createHistory)({ parseQueryString: parseQueryString, stringifyQuery: stringifyQuery }); }, /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0; process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state; var location = _state.location; var routes = _state.routes; var params = _state.params; var components = _state.components; var _props4 = this.props; var createElement = _props4.createElement; var render = _props4.render; var props = _objectWithoutProperties(_props4, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { history: this.history, router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); export default Router;
vendor/yiisoft/yii2/assets/yii.gridView.js
timjcook/achieve-it
/** * Yii GridView widget. * * This is the JavaScript widget used by the yii\grid\GridView widget. * * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ (function ($) { $.fn.yiiGridView = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.yiiGridView'); return false; } }; var defaults = { filterUrl: undefined, filterSelector: undefined }; var gridData = {}; var gridEvents = { /** * beforeFilter event is triggered before filtering the grid. * The signature of the event handler should be: * function (event) * where * - event: an Event object. * * If the handler returns a boolean false, it will stop filter form submission after this event. As * a result, afterFilter event will not be triggered. */ beforeFilter: 'beforeFilter', /** * afterFilter event is triggered after filtering the grid and filtered results are fetched. * The signature of the event handler should be: * function (event) * where * - event: an Event object. */ afterFilter: 'afterFilter' }; var methods = { init: function (options) { return this.each(function () { var $e = $(this); var settings = $.extend({}, defaults, options || {}); var id = $e.attr('id'); if (gridData[id] === undefined) { gridData[id] = {}; } gridData[id] = $.extend(gridData[id], {settings: settings}); var enterPressed = false; $(document).off('change.yiiGridView keydown.yiiGridView', settings.filterSelector) .on('change.yiiGridView keydown.yiiGridView', settings.filterSelector, function (event) { if (event.type === 'keydown') { if (event.keyCode !== 13) { return; // only react to enter key } else { enterPressed = true; } } else { // prevent processing for both keydown and change events if (enterPressed) { enterPressed = false; return; } } methods.applyFilter.apply($e); return false; }); }); }, applyFilter: function () { var $grid = $(this), event; var settings = gridData[$grid.attr('id')].settings; var data = {}; $.each($(settings.filterSelector).serializeArray(), function () { if (!(this.name in data)) { data[this.name] = []; } data[this.name].push(this.value); }); var namesInFilter = Object.keys(data); $.each(yii.getQueryParams(settings.filterUrl), function (name, value) { if (namesInFilter.indexOf(name) === -1 && namesInFilter.indexOf(name.replace(/\[\]$/, '')) === -1) { if (!$.isArray(value)) { value = [value]; } if (!(name in data)) { data[name] = value; } else { $.each(value, function (i, val) { if ($.inArray(val, data[name])) { data[name].push(val); } }); } } }); var pos = settings.filterUrl.indexOf('?'); var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos); $grid.find('form.gridview-filter-form').remove(); var $form = $('<form/>', { action: url, method: 'get', 'class': 'gridview-filter-form', style: 'display:none', 'data-pjax': '' }).appendTo($grid); $.each(data, function (name, values) { $.each(values, function (index, value) { $form.append($('<input/>').attr({type: 'hidden', name: name, value: value})); }); }); event = $.Event(gridEvents.beforeFilter); $grid.trigger(event); if (event.result === false) { return; } $form.submit(); $grid.trigger(gridEvents.afterFilter); }, setSelectionColumn: function (options) { var $grid = $(this); var id = $(this).attr('id'); if (gridData.id === undefined) { gridData[id] = {}; } gridData[id].selectionColumn = options.name; if (!options.multiple || !options.checkAll) { return; } var checkAll = "#" + id + " input[name='" + options.checkAll + "']"; var inputs = options.class ? "input." + options.class : "input[name='" + options.name + "']"; var inputsEnabled = "#" + id + " " + inputs + ":enabled"; $(document).off('click.yiiGridView', checkAll).on('click.yiiGridView', checkAll, function () { $grid.find(inputs + ":enabled").prop('checked', this.checked); }); $(document).off('click.yiiGridView', inputsEnabled).on('click.yiiGridView', inputsEnabled, function () { var all = $grid.find(inputs).length == $grid.find(inputs + ":checked").length; $grid.find("input[name='" + options.checkAll + "']").prop('checked', all); }); }, getSelectedRows: function () { var $grid = $(this); var data = gridData[$grid.attr('id')]; var keys = []; if (data.selectionColumn) { $grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () { keys.push($(this).parent().closest('tr').data('key')); }); } return keys; }, destroy: function () { return this.each(function () { $(window).unbind('.yiiGridView'); $(this).removeData('yiiGridView'); }); }, data: function () { var id = $(this).attr('id'); return gridData[id]; } }; })(window.jQuery);
src/components/docker/plain-wordmark/DockerPlainWordmark.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './DockerPlainWordmark.svg' /** DockerPlainWordmark */ function DockerPlainWordmark({ width, height, className }) { return ( <SVGDeviconInline className={'DockerPlainWordmark' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } DockerPlainWordmark.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default DockerPlainWordmark
components/page/footer/index.js
sgmap/inspire
import React from 'react' import Container from '../../container' import Social from './social' import Sitemap from './sitemap' const Footer = () => ( <footer> <Container> <div className='content'> <div> <img src='/static/images/etalab.png' alt='Etalab' /> <Social /> </div> <Sitemap /> </div> </Container> <style jsx>{` @import 'colors'; footer { background: $darkblue; color: $white; padding: 2em 0; line-height: 2em; } .content { display: flex; flex-direction: row; justify-content: space-between; align-items: center; @media (max-width: 551px) { flex-direction: column; align-items: flex-start; } } `}</style> </footer> ) export default Footer
src/Footer/Footer.js
Pearson-Higher-Ed/compounds
import React from 'react'; import PropTypes from 'prop-types'; import './Footer.scss'; const currentYear = new Date().getFullYear(); const Footer = ({ copyrightText, links, anchorTarget, light, singlePageStick }) => { const renderCopy = () => { return <p className="pe-label">{copyrightText}</p>; }; const renderLinks = () => { let items = []; for (let i = 0; i < links.length; i++) { let item = links[i]; items.push(<li key={i}> <a href={item.href} target={`_${anchorTarget}`}>{item.text}</a> <span aria-hidden={true}>|</span> </li>); } return items; }; const lightCheck = light ? 'pe-footer--light':''; const stickCheck = singlePageStick ? '--stick':''; return ( <footer className={`pe-footer${stickCheck} pe-label ${lightCheck}`}> <ul> {renderLinks()} </ul> {renderCopy()} </footer> ); } export default Footer; Footer.propTypes = { links: PropTypes.array.isRequired, light: PropTypes.bool, singlePageStick: PropTypes.bool, anchorTarget: PropTypes.oneOf(['blank', 'self']) } Footer.defaultProps = { light: false, singlePageStick: false, anchorTarget: 'self', copyrightText: ['Copyright', <span>&copy;</span>, `${currentYear} Pearson Education Inc. All Rights Reserved.`] }
src/components/Main.js
Aikk/gallery-by-react
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom'; let imageDatas = require('json!../data/images.json'); imageDatas = (function genImageURL(imageDatasArr) { for (let i = 0, n = imageDatasArr.length; i < n; i++) { let singleImageData = imageDatasArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imageDatasArr[i] = singleImageData; } return imageDatasArr; })(imageDatas); /** * 获取坐标区间内的一个随机值 * @param {[type]} low 最小值 * @param {[type]} high 最大值 * @return {[type]} 坐标随机值 */ let getRangeRandom = (low, high) => Math.floor(Math.random() * (high - low) + low); /** * 获取偏转角度随机值 -30° ~ 30° * @return {[type]} 角度随机值 */ let get30DegRandom = () => ((Math.random() < 0.5 ? '' : '-') + Math.ceil(Math.random() * 30)); /** * 划分为三个区域:左侧、右侧、上侧 * 左侧: * -图片宽度/2 < x < 舞台宽度一半 - 图片宽度/2*3 * -图片高度/2 < y < 舞台高度 - 图片高度/2 * 右侧: * 舞台宽度/2-图片宽度/2 < x < 舞台宽度-图片宽度/2 * -图片高度/2 < y < 舞台高度 - 图片高度/2 * 上侧: * 舞台宽度/2 - 图片宽度 < x < 舞台宽度/2 * -图片高度/2 < y < 舞台高度/2 - 图片高度/2*3 */ class ImgFigure extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } // 图片点击事件处理函数 handleClick(e) { if (this.props.arrange.center) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { let styleObj = {}; if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } if (this.props.arrange.rotate) { (['-moz-', '-ms-', 'webkit', '']).forEach((value) => { styleObj[value + 'transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }); } let imgFigureClassName = 'img-figure'; if (this.props.arrange.center) { imgFigureClassName += ' center'; if (this.props.arrange.inverse) { imgFigureClassName += ' inverse'; } } return ( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.fileName} /> <figcaption> <h2 className="img-title">{this.props.data.desc}</h2> <div className="img-back"> <p>{this.props.data.desc}</p> </div> </figcaption> </figure> ); } } class ControllerUnit extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e) { if (this.props.arrange.center) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { let ctrlUnitClassName = 'ctrl-unit'; if (this.props.arrange.center) { ctrlUnitClassName += ' center'; if (this.props.arrange.inverse) { ctrlUnitClassName += ' inverse'; } } return ( <span className={ctrlUnitClassName} onClick={this.handleClick}> </span> ); } } class AppComponent extends React.Component { constructor(props) { super(props); // 左侧、右侧、上侧、中心 各部分的坐标范围 this.Constant = { centerPos: { top: 0, right: 0 }, hPosRange: { leftX: [0, 0], rightX: [0, 0], y: [0, 0] }, vPosRange: { x: [0, 0], topY: [0, 0] } }, this.state = { imgsArrangeArr: [] } } /** * 重新布局所有图片 * @param centerIndex 指定居中的图片 */ arrange(centerIndex) { let imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftX = hPosRange.leftX, hPosRangeRightX = hPosRange.rightX, hPosRangeY = hPosRange.y, vPosRangeX = vPosRange.x, vPosRangeTopY = vPosRange.topY, // 上侧的图片信息 imgsArrangeTopArr = [], topNum = Math.floor(Math.random() * 2), topIndex = 0, // 居中的图片信息 imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1); imgsArrangeCenterArr[0] = { pos: centerPos, rotate: 0, center: true } topIndex = Math.floor(Math.random() * (imgsArrangeArr.length - topNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topIndex, topNum); imgsArrangeTopArr.forEach((value, index) => { imgsArrangeTopArr[index] = { pos: { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), center: false } }); // 布局左右两侧的图片 for (let i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { let hPosRangeLORX = (i < k) ? hPosRangeLeftX : hPosRangeRightX; imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), center: false } } if (imgsArrangeTopArr && imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); } /** * 翻转图片 * param index 图片下标 * return 图片状态信息 */ inverse(index) { return () => { var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].inverse = !imgsArrangeArr[index].inverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); } } /** * 图片居中 * param index 图片下标 * return 重新排列 */ center(index) { return () => { this.arrange(index); } } // 组件加载后,为每张图片计算其位置 componentDidMount() { var stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgFigureW = imgFigureDOM.scrollWidth, imgFigureH = imgFigureDOM.scrollHeight, halfImgFigureW = Math.ceil(imgFigureW / 2), halfImgFigureH = Math.ceil(imgFigureH / 2); this.Constant.centerPos = { top: halfStageH - halfImgFigureH, left: halfStageW - halfImgFigureW } this.Constant.hPosRange = { leftX: [-halfImgFigureW, halfStageW - halfImgFigureW * 3], rightX: [halfStageW + halfImgFigureW, stageW - halfImgFigureW], y: [-halfImgFigureH, stageH - halfImgFigureH] } this.Constant.vPosRange = { x: [halfStageW - imgFigureW, halfStageW], topY: [-halfImgFigureH, halfStageH - halfImgFigureH * 3] } this.arrange(0); } render() { let ctrlUnits = [], imgFigures = []; imageDatas.forEach(function(value, index) { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { top: 0, left: 0 }, rotate: 0, inverse: false, center: false } } imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); ctrlUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <section className="ctrl-sec"> {ctrlUnits} </section> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
ajax/libs/yui/3.16.0/datatable-core/datatable-core-coverage.js
kentcdodds/cdnjs
/* YUI 3.16.0 (build 76f0e08) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/datatable-core/datatable-core.js']) { __coverage__['build/datatable-core/datatable-core.js'] = {"path":"build/datatable-core/datatable-core.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0],"53":[0,0],"54":[0,0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0,0],"62":[0,0],"63":[0,0,0],"64":[0,0],"65":[0,0,0],"66":[0,0],"67":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":38,"loc":{"start":{"line":38,"column":40},"end":{"line":38,"column":52}}},"3":{"name":"(anonymous_3)","line":231,"loc":{"start":{"line":231,"column":15},"end":{"line":231,"column":31}}},"4":{"name":"(anonymous_4)","line":278,"loc":{"start":{"line":278,"column":15},"end":{"line":278,"column":31}}},"5":{"name":"(anonymous_5)","line":344,"loc":{"start":{"line":344,"column":25},"end":{"line":344,"column":38}}},"6":{"name":"(anonymous_6)","line":357,"loc":{"start":{"line":357,"column":22},"end":{"line":357,"column":35}}},"7":{"name":"(anonymous_7)","line":377,"loc":{"start":{"line":377,"column":28},"end":{"line":377,"column":41}}},"8":{"name":"(anonymous_8)","line":406,"loc":{"start":{"line":406,"column":24},"end":{"line":406,"column":41}}},"9":{"name":"(anonymous_9)","line":429,"loc":{"start":{"line":429,"column":16},"end":{"line":429,"column":28}}},"10":{"name":"(anonymous_10)","line":445,"loc":{"start":{"line":445,"column":17},"end":{"line":445,"column":42}}},"11":{"name":"(anonymous_11)","line":468,"loc":{"start":{"line":468,"column":19},"end":{"line":468,"column":38}}},"12":{"name":"(anonymous_12)","line":480,"loc":{"start":{"line":480,"column":20},"end":{"line":480,"column":35}}},"13":{"name":"(anonymous_13)","line":500,"loc":{"start":{"line":500,"column":18},"end":{"line":500,"column":30}}},"14":{"name":"(anonymous_14)","line":526,"loc":{"start":{"line":526,"column":21},"end":{"line":526,"column":33}}},"15":{"name":"(anonymous_15)","line":544,"loc":{"start":{"line":544,"column":15},"end":{"line":544,"column":27}}},"16":{"name":"(anonymous_16)","line":569,"loc":{"start":{"line":569,"column":23},"end":{"line":569,"column":39}}},"17":{"name":"(anonymous_17)","line":607,"loc":{"start":{"line":607,"column":17},"end":{"line":607,"column":35}}},"18":{"name":"(anonymous_18)","line":653,"loc":{"start":{"line":653,"column":19},"end":{"line":653,"column":38}}},"19":{"name":"process","line":656,"loc":{"start":{"line":656,"column":8},"end":{"line":656,"column":31}}},"20":{"name":"(anonymous_20)","line":703,"loc":{"start":{"line":703,"column":17},"end":{"line":703,"column":32}}},"21":{"name":"copyObj","line":709,"loc":{"start":{"line":709,"column":8},"end":{"line":709,"column":28}}},"22":{"name":"genId","line":735,"loc":{"start":{"line":735,"column":8},"end":{"line":735,"column":29}}},"23":{"name":"process","line":749,"loc":{"start":{"line":749,"column":8},"end":{"line":749,"column":39}}},"24":{"name":"(anonymous_24)","line":805,"loc":{"start":{"line":805,"column":19},"end":{"line":805,"column":34}}},"25":{"name":"(anonymous_25)","line":828,"loc":{"start":{"line":828,"column":14},"end":{"line":828,"column":29}}},"26":{"name":"(anonymous_26)","line":866,"loc":{"start":{"line":866,"column":19},"end":{"line":866,"column":34}}},"27":{"name":"(anonymous_27)","line":871,"loc":{"start":{"line":871,"column":21},"end":{"line":871,"column":39}}},"28":{"name":"(anonymous_28)","line":898,"loc":{"start":{"line":898,"column":20},"end":{"line":898,"column":35}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1319,"column":76}},"2":{"start":{"line":11,"column":0},"end":{"line":24,"column":10}},"3":{"start":{"line":38,"column":0},"end":{"line":38,"column":55}},"4":{"start":{"line":40,"column":0},"end":{"line":199,"column":2}},"5":{"start":{"line":201,"column":0},"end":{"line":911,"column":3}},"6":{"start":{"line":232,"column":8},"end":{"line":232,"column":39}},"7":{"start":{"line":234,"column":8},"end":{"line":242,"column":9}},"8":{"start":{"line":235,"column":12},"end":{"line":239,"column":13}},"9":{"start":{"line":236,"column":16},"end":{"line":236,"column":48}},"10":{"start":{"line":238,"column":16},"end":{"line":238,"column":27}},"11":{"start":{"line":241,"column":12},"end":{"line":241,"column":46}},"12":{"start":{"line":244,"column":8},"end":{"line":246,"column":9}},"13":{"start":{"line":245,"column":12},"end":{"line":245,"column":23}},"14":{"start":{"line":248,"column":8},"end":{"line":248,"column":38}},"15":{"start":{"line":250,"column":8},"end":{"line":259,"column":9}},"16":{"start":{"line":251,"column":12},"end":{"line":251,"column":33}},"17":{"start":{"line":252,"column":12},"end":{"line":252,"column":27}},"18":{"start":{"line":254,"column":12},"end":{"line":256,"column":13}},"19":{"start":{"line":255,"column":16},"end":{"line":255,"column":63}},"20":{"start":{"line":258,"column":12},"end":{"line":258,"column":51}},"21":{"start":{"line":261,"column":8},"end":{"line":261,"column":20}},"22":{"start":{"line":279,"column":8},"end":{"line":279,"column":78}},"23":{"start":{"line":281,"column":8},"end":{"line":290,"column":9}},"24":{"start":{"line":282,"column":12},"end":{"line":284,"column":13}},"25":{"start":{"line":283,"column":16},"end":{"line":283,"column":46}},"26":{"start":{"line":287,"column":12},"end":{"line":289,"column":13}},"27":{"start":{"line":288,"column":16},"end":{"line":288,"column":73}},"28":{"start":{"line":292,"column":8},"end":{"line":292,"column":30}},"29":{"start":{"line":345,"column":8},"end":{"line":345,"column":37}},"30":{"start":{"line":358,"column":8},"end":{"line":358,"column":33}},"31":{"start":{"line":360,"column":8},"end":{"line":360,"column":29}},"32":{"start":{"line":362,"column":8},"end":{"line":366,"column":9}},"33":{"start":{"line":365,"column":12},"end":{"line":365,"column":32}},"34":{"start":{"line":378,"column":8},"end":{"line":378,"column":38}},"35":{"start":{"line":380,"column":8},"end":{"line":380,"column":35}},"36":{"start":{"line":382,"column":8},"end":{"line":382,"column":30}},"37":{"start":{"line":384,"column":8},"end":{"line":390,"column":9}},"38":{"start":{"line":385,"column":12},"end":{"line":389,"column":13}},"39":{"start":{"line":386,"column":16},"end":{"line":386,"column":36}},"40":{"start":{"line":388,"column":16},"end":{"line":388,"column":58}},"41":{"start":{"line":407,"column":8},"end":{"line":407,"column":26}},"42":{"start":{"line":409,"column":8},"end":{"line":417,"column":9}},"43":{"start":{"line":410,"column":12},"end":{"line":410,"column":23}},"44":{"start":{"line":412,"column":12},"end":{"line":414,"column":13}},"45":{"start":{"line":413,"column":16},"end":{"line":413,"column":37}},"46":{"start":{"line":415,"column":15},"end":{"line":417,"column":9}},"47":{"start":{"line":416,"column":12},"end":{"line":416,"column":26}},"48":{"start":{"line":419,"column":8},"end":{"line":419,"column":76}},"49":{"start":{"line":430,"column":8},"end":{"line":430,"column":72}},"50":{"start":{"line":449,"column":8},"end":{"line":449,"column":59}},"51":{"start":{"line":469,"column":8},"end":{"line":469,"column":63}},"52":{"start":{"line":487,"column":8},"end":{"line":487,"column":53}},"53":{"start":{"line":501,"column":8},"end":{"line":502,"column":17}},"54":{"start":{"line":505,"column":8},"end":{"line":514,"column":9}},"55":{"start":{"line":507,"column":12},"end":{"line":507,"column":37}},"56":{"start":{"line":509,"column":12},"end":{"line":511,"column":13}},"57":{"start":{"line":510,"column":16},"end":{"line":510,"column":37}},"58":{"start":{"line":513,"column":12},"end":{"line":513,"column":44}},"59":{"start":{"line":516,"column":8},"end":{"line":516,"column":36}},"60":{"start":{"line":527,"column":8},"end":{"line":531,"column":11}},"61":{"start":{"line":545,"column":8},"end":{"line":547,"column":42}},"62":{"start":{"line":549,"column":8},"end":{"line":551,"column":9}},"63":{"start":{"line":550,"column":12},"end":{"line":550,"column":41}},"64":{"start":{"line":553,"column":8},"end":{"line":553,"column":25}},"65":{"start":{"line":570,"column":8},"end":{"line":570,"column":23}},"66":{"start":{"line":572,"column":8},"end":{"line":596,"column":9}},"67":{"start":{"line":573,"column":12},"end":{"line":573,"column":48}},"68":{"start":{"line":575,"column":12},"end":{"line":589,"column":13}},"69":{"start":{"line":576,"column":16},"end":{"line":576,"column":33}},"70":{"start":{"line":578,"column":16},"end":{"line":580,"column":17}},"71":{"start":{"line":579,"column":20},"end":{"line":579,"column":49}},"72":{"start":{"line":584,"column":16},"end":{"line":584,"column":46}},"73":{"start":{"line":586,"column":16},"end":{"line":588,"column":17}},"74":{"start":{"line":587,"column":20},"end":{"line":587,"column":49}},"75":{"start":{"line":595,"column":12},"end":{"line":595,"column":38}},"76":{"start":{"line":608,"column":8},"end":{"line":610,"column":23}},"77":{"start":{"line":614,"column":8},"end":{"line":614,"column":37}},"78":{"start":{"line":620,"column":8},"end":{"line":633,"column":9}},"79":{"start":{"line":621,"column":12},"end":{"line":622,"column":51}},"80":{"start":{"line":624,"column":12},"end":{"line":628,"column":13}},"81":{"start":{"line":625,"column":16},"end":{"line":625,"column":49}},"82":{"start":{"line":626,"column":19},"end":{"line":628,"column":13}},"83":{"start":{"line":627,"column":16},"end":{"line":627,"column":40}},"84":{"start":{"line":630,"column":12},"end":{"line":632,"column":13}},"85":{"start":{"line":631,"column":16},"end":{"line":631,"column":45}},"86":{"start":{"line":635,"column":8},"end":{"line":635,"column":28}},"87":{"start":{"line":637,"column":8},"end":{"line":637,"column":32}},"88":{"start":{"line":639,"column":8},"end":{"line":639,"column":31}},"89":{"start":{"line":654,"column":8},"end":{"line":654,"column":21}},"90":{"start":{"line":656,"column":8},"end":{"line":678,"column":9}},"91":{"start":{"line":657,"column":12},"end":{"line":657,"column":33}},"92":{"start":{"line":659,"column":12},"end":{"line":677,"column":13}},"93":{"start":{"line":660,"column":16},"end":{"line":660,"column":30}},"94":{"start":{"line":661,"column":16},"end":{"line":661,"column":30}},"95":{"start":{"line":668,"column":16},"end":{"line":670,"column":17}},"96":{"start":{"line":669,"column":20},"end":{"line":669,"column":35}},"97":{"start":{"line":672,"column":16},"end":{"line":672,"column":35}},"98":{"start":{"line":674,"column":16},"end":{"line":676,"column":17}},"99":{"start":{"line":675,"column":20},"end":{"line":675,"column":42}},"100":{"start":{"line":680,"column":8},"end":{"line":680,"column":25}},"101":{"start":{"line":682,"column":8},"end":{"line":682,"column":30}},"102":{"start":{"line":704,"column":8},"end":{"line":707,"column":41}},"103":{"start":{"line":709,"column":8},"end":{"line":733,"column":9}},"104":{"start":{"line":710,"column":12},"end":{"line":711,"column":28}},"105":{"start":{"line":713,"column":12},"end":{"line":713,"column":26}},"106":{"start":{"line":714,"column":12},"end":{"line":714,"column":35}},"107":{"start":{"line":716,"column":12},"end":{"line":730,"column":13}},"108":{"start":{"line":717,"column":16},"end":{"line":729,"column":17}},"109":{"start":{"line":718,"column":20},"end":{"line":718,"column":33}},"110":{"start":{"line":720,"column":20},"end":{"line":728,"column":21}},"111":{"start":{"line":721,"column":24},"end":{"line":721,"column":48}},"112":{"start":{"line":722,"column":27},"end":{"line":728,"column":21}},"113":{"start":{"line":723,"column":24},"end":{"line":723,"column":51}},"114":{"start":{"line":725,"column":24},"end":{"line":725,"column":77}},"115":{"start":{"line":727,"column":24},"end":{"line":727,"column":43}},"116":{"start":{"line":732,"column":12},"end":{"line":732,"column":24}},"117":{"start":{"line":735,"column":8},"end":{"line":747,"column":9}},"118":{"start":{"line":738,"column":12},"end":{"line":738,"column":44}},"119":{"start":{"line":740,"column":12},"end":{"line":744,"column":13}},"120":{"start":{"line":741,"column":16},"end":{"line":741,"column":39}},"121":{"start":{"line":743,"column":16},"end":{"line":743,"column":31}},"122":{"start":{"line":746,"column":12},"end":{"line":746,"column":24}},"123":{"start":{"line":749,"column":8},"end":{"line":788,"column":9}},"124":{"start":{"line":750,"column":12},"end":{"line":751,"column":34}},"125":{"start":{"line":753,"column":12},"end":{"line":785,"column":13}},"126":{"start":{"line":754,"column":16},"end":{"line":755,"column":78}},"127":{"start":{"line":757,"column":16},"end":{"line":757,"column":36}},"128":{"start":{"line":760,"column":16},"end":{"line":764,"column":17}},"129":{"start":{"line":763,"column":20},"end":{"line":763,"column":34}},"130":{"start":{"line":765,"column":16},"end":{"line":769,"column":17}},"131":{"start":{"line":768,"column":20},"end":{"line":768,"column":41}},"132":{"start":{"line":771,"column":16},"end":{"line":775,"column":17}},"133":{"start":{"line":772,"column":20},"end":{"line":772,"column":41}},"134":{"start":{"line":774,"column":20},"end":{"line":774,"column":39}},"135":{"start":{"line":780,"column":16},"end":{"line":780,"column":63}},"136":{"start":{"line":782,"column":16},"end":{"line":784,"column":17}},"137":{"start":{"line":783,"column":20},"end":{"line":783,"column":62}},"138":{"start":{"line":787,"column":12},"end":{"line":787,"column":27}},"139":{"start":{"line":790,"column":8},"end":{"line":790,"column":35}},"140":{"start":{"line":806,"column":8},"end":{"line":806,"column":33}},"141":{"start":{"line":808,"column":8},"end":{"line":808,"column":44}},"142":{"start":{"line":829,"column":8},"end":{"line":831,"column":9}},"143":{"start":{"line":830,"column":12},"end":{"line":830,"column":21}},"144":{"start":{"line":833,"column":8},"end":{"line":849,"column":9}},"145":{"start":{"line":834,"column":12},"end":{"line":834,"column":37}},"146":{"start":{"line":840,"column":12},"end":{"line":840,"column":51}},"147":{"start":{"line":845,"column":12},"end":{"line":845,"column":28}},"148":{"start":{"line":846,"column":15},"end":{"line":849,"column":9}},"149":{"start":{"line":848,"column":12},"end":{"line":848,"column":26}},"150":{"start":{"line":851,"column":8},"end":{"line":851,"column":19}},"151":{"start":{"line":867,"column":8},"end":{"line":867,"column":17}},"152":{"start":{"line":869,"column":8},"end":{"line":875,"column":9}},"153":{"start":{"line":870,"column":12},"end":{"line":870,"column":22}},"154":{"start":{"line":871,"column":12},"end":{"line":873,"column":15}},"155":{"start":{"line":872,"column":16},"end":{"line":872,"column":46}},"156":{"start":{"line":874,"column":12},"end":{"line":874,"column":23}},"157":{"start":{"line":877,"column":8},"end":{"line":877,"column":30}},"158":{"start":{"line":879,"column":8},"end":{"line":879,"column":19}},"159":{"start":{"line":899,"column":8},"end":{"line":899,"column":23}},"160":{"start":{"line":902,"column":8},"end":{"line":906,"column":9}},"161":{"start":{"line":903,"column":12},"end":{"line":903,"column":29}},"162":{"start":{"line":904,"column":15},"end":{"line":906,"column":9}},"163":{"start":{"line":905,"column":12},"end":{"line":905,"column":54}},"164":{"start":{"line":908,"column":8},"end":{"line":908,"column":37}}},"branchMap":{"1":{"line":234,"type":"if","locations":[{"start":{"line":234,"column":8},"end":{"line":234,"column":8}},{"start":{"line":234,"column":8},"end":{"line":234,"column":8}}]},"2":{"line":234,"type":"binary-expr","locations":[{"start":{"line":234,"column":12},"end":{"line":234,"column":26}},{"start":{"line":234,"column":30},"end":{"line":234,"column":44}}]},"3":{"line":235,"type":"if","locations":[{"start":{"line":235,"column":12},"end":{"line":235,"column":12}},{"start":{"line":235,"column":12},"end":{"line":235,"column":12}}]},"4":{"line":235,"type":"binary-expr","locations":[{"start":{"line":235,"column":16},"end":{"line":235,"column":20}},{"start":{"line":235,"column":24},"end":{"line":235,"column":34}}]},"5":{"line":244,"type":"if","locations":[{"start":{"line":244,"column":8},"end":{"line":244,"column":8}},{"start":{"line":244,"column":8},"end":{"line":244,"column":8}}]},"6":{"line":250,"type":"if","locations":[{"start":{"line":250,"column":8},"end":{"line":250,"column":8}},{"start":{"line":250,"column":8},"end":{"line":250,"column":8}}]},"7":{"line":250,"type":"binary-expr","locations":[{"start":{"line":250,"column":12},"end":{"line":250,"column":26}},{"start":{"line":250,"column":30},"end":{"line":250,"column":43}}]},"8":{"line":254,"type":"binary-expr","locations":[{"start":{"line":254,"column":47},"end":{"line":254,"column":51}},{"start":{"line":254,"column":55},"end":{"line":254,"column":62}}]},"9":{"line":255,"type":"binary-expr","locations":[{"start":{"line":255,"column":23},"end":{"line":255,"column":36}},{"start":{"line":255,"column":40},"end":{"line":255,"column":62}}]},"10":{"line":258,"type":"binary-expr","locations":[{"start":{"line":258,"column":20},"end":{"line":258,"column":24}},{"start":{"line":258,"column":28},"end":{"line":258,"column":41}},{"start":{"line":258,"column":46},"end":{"line":258,"column":50}}]},"11":{"line":279,"type":"binary-expr","locations":[{"start":{"line":279,"column":21},"end":{"line":279,"column":44}},{"start":{"line":279,"column":48},"end":{"line":279,"column":77}}]},"12":{"line":281,"type":"if","locations":[{"start":{"line":281,"column":8},"end":{"line":281,"column":8}},{"start":{"line":281,"column":8},"end":{"line":281,"column":8}}]},"13":{"line":282,"type":"if","locations":[{"start":{"line":282,"column":12},"end":{"line":282,"column":12}},{"start":{"line":282,"column":12},"end":{"line":282,"column":12}}]},"14":{"line":287,"type":"if","locations":[{"start":{"line":287,"column":12},"end":{"line":287,"column":12}},{"start":{"line":287,"column":12},"end":{"line":287,"column":12}}]},"15":{"line":287,"type":"binary-expr","locations":[{"start":{"line":287,"column":16},"end":{"line":287,"column":23}},{"start":{"line":287,"column":27},"end":{"line":287,"column":36}},{"start":{"line":287,"column":40},"end":{"line":287,"column":59}}]},"16":{"line":292,"type":"binary-expr","locations":[{"start":{"line":292,"column":15},"end":{"line":292,"column":21}},{"start":{"line":292,"column":25},"end":{"line":292,"column":29}}]},"17":{"line":362,"type":"if","locations":[{"start":{"line":362,"column":8},"end":{"line":362,"column":8}},{"start":{"line":362,"column":8},"end":{"line":362,"column":8}}]},"18":{"line":362,"type":"binary-expr","locations":[{"start":{"line":362,"column":12},"end":{"line":362,"column":32}},{"start":{"line":362,"column":36},"end":{"line":362,"column":52}}]},"19":{"line":384,"type":"if","locations":[{"start":{"line":384,"column":8},"end":{"line":384,"column":8}},{"start":{"line":384,"column":8},"end":{"line":384,"column":8}}]},"20":{"line":384,"type":"binary-expr","locations":[{"start":{"line":384,"column":12},"end":{"line":384,"column":32}},{"start":{"line":384,"column":36},"end":{"line":384,"column":40}}]},"21":{"line":385,"type":"if","locations":[{"start":{"line":385,"column":12},"end":{"line":385,"column":12}},{"start":{"line":385,"column":12},"end":{"line":385,"column":12}}]},"22":{"line":409,"type":"if","locations":[{"start":{"line":409,"column":8},"end":{"line":409,"column":8}},{"start":{"line":409,"column":8},"end":{"line":409,"column":8}}]},"23":{"line":415,"type":"if","locations":[{"start":{"line":415,"column":15},"end":{"line":415,"column":15}},{"start":{"line":415,"column":15},"end":{"line":415,"column":15}}]},"24":{"line":449,"type":"cond-expr","locations":[{"start":{"line":449,"column":33},"end":{"line":449,"column":48}},{"start":{"line":449,"column":51},"end":{"line":449,"column":58}}]},"25":{"line":487,"type":"binary-expr","locations":[{"start":{"line":487,"column":15},"end":{"line":487,"column":18}},{"start":{"line":487,"column":23},"end":{"line":487,"column":32}},{"start":{"line":487,"column":36},"end":{"line":487,"column":51}}]},"26":{"line":501,"type":"binary-expr","locations":[{"start":{"line":501,"column":22},"end":{"line":501,"column":41}},{"start":{"line":501,"column":45},"end":{"line":501,"column":47}}]},"27":{"line":505,"type":"if","locations":[{"start":{"line":505,"column":8},"end":{"line":505,"column":8}},{"start":{"line":505,"column":8},"end":{"line":505,"column":8}}]},"28":{"line":505,"type":"binary-expr","locations":[{"start":{"line":505,"column":12},"end":{"line":505,"column":27}},{"start":{"line":505,"column":31},"end":{"line":505,"column":47}}]},"29":{"line":509,"type":"if","locations":[{"start":{"line":509,"column":12},"end":{"line":509,"column":12}},{"start":{"line":509,"column":12},"end":{"line":509,"column":12}}]},"30":{"line":549,"type":"if","locations":[{"start":{"line":549,"column":8},"end":{"line":549,"column":8}},{"start":{"line":549,"column":8},"end":{"line":549,"column":8}}]},"31":{"line":572,"type":"if","locations":[{"start":{"line":572,"column":8},"end":{"line":572,"column":8}},{"start":{"line":572,"column":8},"end":{"line":572,"column":8}}]},"32":{"line":575,"type":"if","locations":[{"start":{"line":575,"column":12},"end":{"line":575,"column":12}},{"start":{"line":575,"column":12},"end":{"line":575,"column":12}}]},"33":{"line":575,"type":"binary-expr","locations":[{"start":{"line":575,"column":16},"end":{"line":575,"column":20}},{"start":{"line":575,"column":24},"end":{"line":575,"column":33}},{"start":{"line":575,"column":37},"end":{"line":575,"column":48}}]},"34":{"line":578,"type":"if","locations":[{"start":{"line":578,"column":16},"end":{"line":578,"column":16}},{"start":{"line":578,"column":16},"end":{"line":578,"column":16}}]},"35":{"line":586,"type":"if","locations":[{"start":{"line":586,"column":16},"end":{"line":586,"column":16}},{"start":{"line":586,"column":16},"end":{"line":586,"column":16}}]},"36":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"37":{"line":621,"type":"binary-expr","locations":[{"start":{"line":621,"column":26},"end":{"line":621,"column":43}},{"start":{"line":621,"column":47},"end":{"line":621,"column":72}},{"start":{"line":622,"column":28},"end":{"line":622,"column":50}}]},"38":{"line":624,"type":"if","locations":[{"start":{"line":624,"column":12},"end":{"line":624,"column":12}},{"start":{"line":624,"column":12},"end":{"line":624,"column":12}}]},"39":{"line":626,"type":"if","locations":[{"start":{"line":626,"column":19},"end":{"line":626,"column":19}},{"start":{"line":626,"column":19},"end":{"line":626,"column":19}}]},"40":{"line":626,"type":"binary-expr","locations":[{"start":{"line":626,"column":23},"end":{"line":626,"column":36}},{"start":{"line":626,"column":40},"end":{"line":626,"column":51}}]},"41":{"line":630,"type":"if","locations":[{"start":{"line":630,"column":12},"end":{"line":630,"column":12}},{"start":{"line":630,"column":12},"end":{"line":630,"column":12}}]},"42":{"line":668,"type":"if","locations":[{"start":{"line":668,"column":16},"end":{"line":668,"column":16}},{"start":{"line":668,"column":16},"end":{"line":668,"column":16}}]},"43":{"line":668,"type":"binary-expr","locations":[{"start":{"line":668,"column":20},"end":{"line":668,"column":23}},{"start":{"line":668,"column":27},"end":{"line":668,"column":36}}]},"44":{"line":674,"type":"if","locations":[{"start":{"line":674,"column":16},"end":{"line":674,"column":16}},{"start":{"line":674,"column":16},"end":{"line":674,"column":16}}]},"45":{"line":717,"type":"if","locations":[{"start":{"line":717,"column":16},"end":{"line":717,"column":16}},{"start":{"line":717,"column":16},"end":{"line":717,"column":16}}]},"46":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":20},"end":{"line":720,"column":20}},{"start":{"line":720,"column":20},"end":{"line":720,"column":20}}]},"47":{"line":722,"type":"if","locations":[{"start":{"line":722,"column":27},"end":{"line":722,"column":27}},{"start":{"line":722,"column":27},"end":{"line":722,"column":27}}]},"48":{"line":725,"type":"cond-expr","locations":[{"start":{"line":725,"column":47},"end":{"line":725,"column":59}},{"start":{"line":725,"column":62},"end":{"line":725,"column":76}}]},"49":{"line":740,"type":"if","locations":[{"start":{"line":740,"column":12},"end":{"line":740,"column":12}},{"start":{"line":740,"column":12},"end":{"line":740,"column":12}}]},"50":{"line":755,"type":"cond-expr","locations":[{"start":{"line":755,"column":42},"end":{"line":755,"column":58}},{"start":{"line":755,"column":61},"end":{"line":755,"column":77}}]},"51":{"line":760,"type":"if","locations":[{"start":{"line":760,"column":16},"end":{"line":760,"column":16}},{"start":{"line":760,"column":16},"end":{"line":760,"column":16}}]},"52":{"line":765,"type":"if","locations":[{"start":{"line":765,"column":16},"end":{"line":765,"column":16}},{"start":{"line":765,"column":16},"end":{"line":765,"column":16}}]},"53":{"line":771,"type":"if","locations":[{"start":{"line":771,"column":16},"end":{"line":771,"column":16}},{"start":{"line":771,"column":16},"end":{"line":771,"column":16}}]},"54":{"line":780,"type":"binary-expr","locations":[{"start":{"line":780,"column":32},"end":{"line":780,"column":40}},{"start":{"line":780,"column":44},"end":{"line":780,"column":51}},{"start":{"line":780,"column":55},"end":{"line":780,"column":61}}]},"55":{"line":782,"type":"if","locations":[{"start":{"line":782,"column":16},"end":{"line":782,"column":16}},{"start":{"line":782,"column":16},"end":{"line":782,"column":16}}]},"56":{"line":790,"type":"binary-expr","locations":[{"start":{"line":790,"column":15},"end":{"line":790,"column":18}},{"start":{"line":790,"column":22},"end":{"line":790,"column":34}}]},"57":{"line":808,"type":"cond-expr","locations":[{"start":{"line":808,"column":30},"end":{"line":808,"column":33}},{"start":{"line":808,"column":36},"end":{"line":808,"column":43}}]},"58":{"line":829,"type":"if","locations":[{"start":{"line":829,"column":8},"end":{"line":829,"column":8}},{"start":{"line":829,"column":8},"end":{"line":829,"column":8}}]},"59":{"line":833,"type":"if","locations":[{"start":{"line":833,"column":8},"end":{"line":833,"column":8}},{"start":{"line":833,"column":8},"end":{"line":833,"column":8}}]},"60":{"line":846,"type":"if","locations":[{"start":{"line":846,"column":15},"end":{"line":846,"column":15}},{"start":{"line":846,"column":15},"end":{"line":846,"column":15}}]},"61":{"line":846,"type":"binary-expr","locations":[{"start":{"line":846,"column":19},"end":{"line":846,"column":23}},{"start":{"line":846,"column":27},"end":{"line":846,"column":36}},{"start":{"line":846,"column":40},"end":{"line":846,"column":51}}]},"62":{"line":869,"type":"if","locations":[{"start":{"line":869,"column":8},"end":{"line":869,"column":8}},{"start":{"line":869,"column":8},"end":{"line":869,"column":8}}]},"63":{"line":869,"type":"binary-expr","locations":[{"start":{"line":869,"column":12},"end":{"line":869,"column":15}},{"start":{"line":869,"column":19},"end":{"line":869,"column":30}},{"start":{"line":869,"column":34},"end":{"line":869,"column":60}}]},"64":{"line":902,"type":"if","locations":[{"start":{"line":902,"column":8},"end":{"line":902,"column":8}},{"start":{"line":902,"column":8},"end":{"line":902,"column":8}}]},"65":{"line":902,"type":"binary-expr","locations":[{"start":{"line":902,"column":12},"end":{"line":902,"column":27}},{"start":{"line":902,"column":31},"end":{"line":902,"column":51}},{"start":{"line":902,"column":55},"end":{"line":902,"column":77}}]},"66":{"line":904,"type":"if","locations":[{"start":{"line":904,"column":15},"end":{"line":904,"column":15}},{"start":{"line":904,"column":15},"end":{"line":904,"column":15}}]},"67":{"line":908,"type":"binary-expr","locations":[{"start":{"line":908,"column":15},"end":{"line":908,"column":25}},{"start":{"line":908,"column":29},"end":{"line":908,"column":36}}]}},"code":["(function () { YUI.add('datatable-core', function (Y, NAME) {","","/**","The core implementation of the `DataTable` and `DataTable.Base` Widgets.","","@module datatable","@submodule datatable-core","@since 3.5.0","**/","","var INVALID = Y.Attribute.INVALID_VALUE,",""," Lang = Y.Lang,"," isFunction = Lang.isFunction,"," isObject = Lang.isObject,"," isArray = Lang.isArray,"," isString = Lang.isString,"," isNumber = Lang.isNumber,",""," toArray = Y.Array,",""," keys = Y.Object.keys,",""," Table;","","/**","_API docs for this extension are included in the DataTable class._","","Class extension providing the core API and structure for the DataTable Widget.","","Use this class extension with Widget or another Base-based superclass to create","the basic DataTable model API and composing class structure.","","@class DataTable.Core","@for DataTable","@since 3.5.0","**/","Table = Y.namespace('DataTable').Core = function () {};","","Table.ATTRS = {"," /**"," Columns to include in the rendered table.",""," If omitted, the attributes on the configured `recordType` or the first item"," in the `data` collection will be used as a source.",""," This attribute takes an array of strings or objects (mixing the two is"," fine). Each string or object is considered a column to be rendered."," Strings are converted to objects, so `columns: ['first', 'last']` becomes"," `columns: [{ key: 'first' }, { key: 'last' }]`.",""," DataTable.Core only concerns itself with a few properties of columns."," These properties are:",""," * `key` - Used to identify the record field/attribute containing content for"," this column. Also used to create a default Model if no `recordType` or"," `data` are provided during construction. If `name` is not specified, this"," is assigned to the `_id` property (with added incrementer if the key is"," used by multiple columns)."," * `children` - Traversed to initialize nested column objects"," * `name` - Used in place of, or in addition to, the `key`. Useful for"," columns that aren't bound to a field/attribute in the record data. This"," is assigned to the `_id` property."," * `id` - For backward compatibility. Implementers can specify the id of"," the header cell. This should be avoided, if possible, to avoid the"," potential for creating DOM elements with duplicate IDs."," * `field` - For backward compatibility. Implementers should use `name`."," * `_id` - Assigned unique-within-this-instance id for a column. By order"," of preference, assumes the value of `name`, `key`, `id`, or `_yuid`."," This is used by the rendering views as well as feature module"," as a means to identify a specific column without ambiguity (such as"," multiple columns using the same `key`."," * `_yuid` - Guid stamp assigned to the column object."," * `_parent` - Assigned to all child columns, referencing their parent"," column.",""," @attribute columns"," @type {Object[]|String[]}"," @default (from `recordType` ATTRS or first item in the `data`)"," @since 3.5.0"," **/"," columns: {"," // TODO: change to setter to clone input array/objects"," validator: isArray,"," setter: '_setColumns',"," getter: '_getColumns'"," },",""," /**"," Model subclass to use as the `model` for the ModelList stored in the `data`"," attribute.",""," If not provided, it will try really hard to figure out what to use. The"," following attempts will be made to set a default value:",""," 1. If the `data` attribute is set with a ModelList instance and its `model`"," property is set, that will be used."," 2. If the `data` attribute is set with a ModelList instance, and its"," `model` property is unset, but it is populated, the `ATTRS` of the"," `constructor of the first item will be used."," 3. If the `data` attribute is set with a non-empty array, a Model subclass"," will be generated using the keys of the first item as its `ATTRS` (see"," the `_createRecordClass` method)."," 4. If the `columns` attribute is set, a Model subclass will be generated"," using the columns defined with a `key`. This is least desirable because"," columns can be duplicated or nested in a way that's not parsable."," 5. If neither `data` nor `columns` is set or populated, a change event"," subscriber will listen for the first to be changed and try all over"," again.",""," @attribute recordType"," @type {Function}"," @default (see description)"," @since 3.5.0"," **/"," recordType: {"," getter: '_getRecordType',"," setter: '_setRecordType'"," },",""," /**"," The collection of data records to display. This attribute is a pass"," through to a `data` property, which is a ModelList instance.",""," If this attribute is passed a ModelList or subclass, it will be assigned to"," the property directly. If an array of objects is passed, a new ModelList"," will be created using the configured `recordType` as its `model` property"," and seeded with the array.",""," Retrieving this attribute will return the ModelList stored in the `data`"," property.",""," @attribute data"," @type {ModelList|Object[]}"," @default `new ModelList()`"," @since 3.5.0"," **/"," data: {"," valueFn: '_initData',"," setter : '_setData',"," lazyAdd: false"," },",""," /**"," Content for the `<table summary=\"ATTRIBUTE VALUE HERE\">`. Values assigned"," to this attribute will be HTML escaped for security.",""," @attribute summary"," @type {String}"," @default '' (empty string)"," @since 3.5.0"," **/"," //summary: {},",""," /**"," HTML content of an optional `<caption>` element to appear above the table."," Leave this config unset or set to a falsy value to remove the caption.",""," @attribute caption"," @type HTML"," @default '' (empty string)"," @since 3.5.0"," **/"," //caption: {},",""," /**"," Deprecated as of 3.5.0. Passes through to the `data` attribute.",""," WARNING: `get('recordset')` will NOT return a Recordset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute recordset"," @type {Object[]|Recordset}"," @deprecated Use the `data` attribute"," @since 3.5.0"," **/"," recordset: {"," setter: '_setRecordset',"," getter: '_getRecordset',"," lazyAdd: false"," },",""," /**"," Deprecated as of 3.5.0. Passes through to the `columns` attribute.",""," WARNING: `get('columnset')` will NOT return a Columnset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute columnset"," @type {Object[]}"," @deprecated Use the `columns` attribute"," @since 3.5.0"," **/"," columnset: {"," setter: '_setColumnset',"," getter: '_getColumnset',"," lazyAdd: false"," }","};","","Y.mix(Table.prototype, {"," // -- Instance properties -------------------------------------------------"," /**"," The ModelList that manages the table's data.",""," @property data"," @type {ModelList}"," @default undefined (initially unset)"," @since 3.5.0"," **/"," //data: null,",""," // -- Public methods ------------------------------------------------------",""," /**"," Gets the column configuration object for the given key, name, or index. For"," nested columns, `name` can be an array of indexes, each identifying the index"," of that column in the respective parent's \"children\" array.",""," If you pass a column object, it will be returned.",""," For columns with keys, you can also fetch the column with"," `instance.get('columns.foo')`.",""," @method getColumn"," @param {String|Number|Number[]} name Key, \"name\", index, or index array to"," identify the column"," @return {Object} the column configuration object"," @since 3.5.0"," **/"," getColumn: function (name) {"," var col, columns, i, len, cols;",""," if (isObject(name) && !isArray(name)) {"," if (name && name._node) {"," col = this.body.getColumn(name);"," } else {"," col = name;"," }"," } else {"," col = this.get('columns.' + name);"," }",""," if (col) {"," return col;"," }",""," columns = this.get('columns');",""," if (isNumber(name) || isArray(name)) {"," name = toArray(name);"," cols = columns;",""," for (i = 0, len = name.length - 1; cols && i < len; ++i) {"," cols = cols[name[i]] && cols[name[i]].children;"," }",""," return (cols && cols[name[i]]) || null;"," }",""," return null;"," },",""," /**"," Returns the Model associated to the record `id`, `clientId`, or index (not"," row index). If none of those yield a Model from the `data` ModelList, the"," arguments will be passed to the `view` instance's `getRecord` method"," if it has one.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or"," identifier for a row or child element"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var record = this.data.getById(seed) || this.data.getByClientId(seed);",""," if (!record) {"," if (isNumber(seed)) {"," record = this.data.item(seed);"," }",""," // TODO: this should be split out to base somehow"," if (!record && this.view && this.view.getRecord) {"," record = this.view.getRecord.apply(this.view, arguments);"," }"," }",""," return record || null;"," },",""," // -- Protected and private properties and methods ------------------------",""," /**"," This tells `Y.Base` that it should create ad-hoc attributes for config"," properties passed to DataTable's constructor. This is useful for setting"," configurations on the DataTable that are intended for the rendering View(s).",""," @property _allowAdHocAttrs"," @type Boolean"," @default true"," @protected"," @since 3.6.0"," **/"," _allowAdHocAttrs: true,",""," /**"," A map of column key to column configuration objects parsed from the"," `columns` attribute.",""," @property _columnMap"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_columnMap: null,",""," /**"," The Node instance of the table containing the data rows. This is set when"," the table is rendered. It may also be set by progressive enhancement,"," though this extension does not provide the logic to parse from source.",""," @property _tableNode"," @type {Node}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_tableNode: null,",""," /**"," Updates the `_columnMap` property in response to changes in the `columns`"," attribute.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," _afterColumnsChange: function (e) {"," this._setColumnMap(e.newVal);"," },",""," /**"," Updates the `modelList` attributes of the rendered views in response to the"," `data` attribute being assigned a new ModelList.",""," @method _afterDataChange"," @param {EventFacade} e the `dataChange` event"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," var modelList = e.newVal;",""," this.data = e.newVal;",""," if (!this.get('columns') && modelList.size()) {"," // TODO: this will cause a re-render twice because the Views are"," // subscribed to columnsChange"," this._initColumns();"," }"," },",""," /**"," Assigns to the new recordType as the model for the data ModelList",""," @method _afterRecordTypeChange"," @param {EventFacade} e recordTypeChange event"," @protected"," @since 3.6.0"," **/"," _afterRecordTypeChange: function (e) {"," var data = this.data.toJSON();",""," this.data.model = e.newVal;",""," this.data.reset(data);",""," if (!this.get('columns') && data) {"," if (data.length) {"," this._initColumns();"," } else {"," this.set('columns', keys(e.newVal.ATTRS));"," }"," }"," },",""," /**"," Creates a Model subclass from an array of attribute names or an object of"," attribute definitions. This is used to generate a class suitable to"," represent the data passed to the `data` attribute if no `recordType` is"," set.",""," @method _createRecordClass"," @param {String[]|Object} attrs Names assigned to the Model subclass's"," `ATTRS` or its entire `ATTRS` definition object"," @return {Model}"," @protected"," @since 3.5.0"," **/"," _createRecordClass: function (attrs) {"," var ATTRS, i, len;",""," if (isArray(attrs)) {"," ATTRS = {};",""," for (i = 0, len = attrs.length; i < len; ++i) {"," ATTRS[attrs[i]] = {};"," }"," } else if (isObject(attrs)) {"," ATTRS = attrs;"," }",""," return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });"," },",""," /**"," Tears down the instance.",""," @method destructor"," @protected"," @since 3.6.0"," **/"," destructor: function () {"," new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();"," },",""," /**"," The getter for the `columns` attribute. Returns the array of column"," configuration objects if `instance.get('columns')` is called, or the"," specific column object if `instance.get('columns.columnKey')` is called.",""," @method _getColumns"," @param {Object[]} columns The full array of column objects"," @param {String} name The attribute name requested"," (e.g. 'columns' or 'columns.foo');"," @protected"," @since 3.5.0"," **/"," _getColumns: function (columns, name) {"," // Workaround for an attribute oddity (ticket #2529254)"," // getter is expected to return an object if get('columns.foo') is called."," // Note 'columns.' is 8 characters"," return name.length > 8 ? this._columnMap : columns;"," },",""," /**"," Relays the `get()` request for the deprecated `columnset` attribute to the"," `columns` attribute.",""," THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will"," expect a Columnset instance returned from `get('columnset')`.",""," @method _getColumnset"," @param {Object} ignored The current value stored in the `columnset` state"," @param {String} name The attribute name requested"," (e.g. 'columnset' or 'columnset.foo');"," @deprecated This will be removed with the `columnset` attribute in a future"," version."," @protected"," @since 3.5.0"," **/"," _getColumnset: function (_, name) {"," return this.get(name.replace(/^columnset/, 'columns'));"," },",""," /**"," Returns the Model class of the instance's `data` attribute ModelList. If"," not set, returns the explicitly configured value.",""," @method _getRecordType"," @param {Model} val The currently configured value"," @return {Model}"," **/"," _getRecordType: function (val) {"," // Prefer the value stored in the attribute because the attribute"," // change event defaultFn sets e.newVal = this.get('recordType')"," // before notifying the after() subs. But if this getter returns"," // this.data.model, then after() subs would get e.newVal === previous"," // model before _afterRecordTypeChange can set"," // this.data.model = e.newVal"," return val || (this.data && this.data.model);"," },",""," /**"," Initializes the `_columnMap` property from the configured `columns`"," attribute. If `columns` is not set, but there are records in the `data`"," ModelList, use"," `ATTRS` of that class.",""," @method _initColumns"," @protected"," @since 3.5.0"," **/"," _initColumns: function () {"," var columns = this.get('columns') || [],"," item;",""," // Default column definition from the configured recordType"," if (!columns.length && this.data.size()) {"," // TODO: merge superclass attributes up to Model?"," item = this.data.item(0);",""," if (item.toJSON) {"," item = item.toJSON();"," }",""," this.set('columns', keys(item));"," }",""," this._setColumnMap(columns);"," },",""," /**"," Sets up the change event subscriptions to maintain internal state.",""," @method _initCoreEvents"," @protected"," @since 3.6.0"," **/"," _initCoreEvents: function () {"," this._eventHandles.coreAttrChanges = this.after({"," columnsChange : Y.bind('_afterColumnsChange', this),"," recordTypeChange: Y.bind('_afterRecordTypeChange', this),"," dataChange : Y.bind('_afterDataChange', this)"," });"," },",""," /**"," Defaults the `data` attribute to an empty ModelList if not set during"," construction. Uses the configured `recordType` for the ModelList's `model`"," proeprty if set.",""," @method _initData"," @protected"," @return {ModelList}"," @since 3.6.0"," **/"," _initData: function () {"," var recordType = this.get('recordType'),"," // TODO: LazyModelList if recordType doesn't have complex ATTRS"," modelList = new Y.ModelList();",""," if (recordType) {"," modelList.model = recordType;"," }",""," return modelList;"," },",""," /**"," Initializes the instance's `data` property from the value of the `data`"," attribute. If the attribute value is a ModelList, it is assigned directly"," to `this.data`. If it is an array, a ModelList is created, its `model`"," property is set to the configured `recordType` class, and it is seeded with"," the array data. This ModelList is then assigned to `this.data`.",""," @method _initDataProperty"," @param {Array|ModelList|ArrayList} data Collection of data to populate the"," DataTable"," @protected"," @since 3.6.0"," **/"," _initDataProperty: function (data) {"," var recordType;",""," if (!this.data) {"," recordType = this.get('recordType');",""," if (data && data.each && data.toJSON) {"," this.data = data;",""," if (recordType) {"," this.data.model = recordType;"," }"," } else {"," // TODO: customize the ModelList or read the ModelList class"," // from a configuration option?"," this.data = new Y.ModelList();",""," if (recordType) {"," this.data.model = recordType;"," }"," }",""," // TODO: Replace this with an event relay for specific events."," // Using bubbling causes subscription conflicts with the models'"," // aggregated change event and 'change' events from DOM elements"," // inside the table (via Widget UI event)."," this.data.addTarget(this);"," }"," },",""," /**"," Initializes the columns, `recordType` and data ModelList.",""," @method initializer"," @param {Object} config Configuration object passed to constructor"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," var data = config.data,"," columns = config.columns,"," recordType;",""," // Referencing config.data to allow _setData to be more stringent"," // about its behavior"," this._initDataProperty(data);",""," // Default columns from recordType ATTRS if recordType is supplied at"," // construction. If no recordType is supplied, but the data is"," // supplied as a non-empty array, use the keys of the first item"," // as the columns."," if (!columns) {"," recordType = (config.recordType || config.data === this.data) &&"," this.get('recordType');",""," if (recordType) {"," columns = keys(recordType.ATTRS);"," } else if (isArray(data) && data.length) {"," columns = keys(data[0]);"," }",""," if (columns) {"," this.set('columns', columns);"," }"," }",""," this._initColumns();",""," this._eventHandles = {};",""," this._initCoreEvents();"," },",""," /**"," Iterates the array of column configurations to capture all columns with a"," `key` property. An map is built with column keys as the property name and"," the corresponding column object as the associated value. This map is then"," assigned to the instance's `_columnMap` property.",""," @method _setColumnMap"," @param {Object[]|String[]} columns The array of column config objects"," @protected"," @since 3.6.0"," **/"," _setColumnMap: function (columns) {"," var map = {};",""," function process(cols) {"," var i, len, col, key;",""," for (i = 0, len = cols.length; i < len; ++i) {"," col = cols[i];"," key = col.key;",""," // First in wins for multiple columns with the same key"," // because the first call to genId (in _setColumns) will"," // return the same key, which will then be overwritten by the"," // subsequent same-keyed column. So table.getColumn(key) would"," // return the last same-keyed column."," if (key && !map[key]) {"," map[key] = col;"," }"," //TODO: named columns can conflict with keyed columns"," map[col._id] = col;",""," if (col.children) {"," process(col.children);"," }"," }"," }",""," process(columns);",""," this._columnMap = map;"," },",""," /**"," Translates string columns into objects with that string as the value of its"," `key` property.",""," All columns are assigned a `_yuid` stamp and `_id` property corresponding"," to the column's configured `name` or `key` property with any spaces"," replaced with dashes. If the same `name` or `key` appears in multiple"," columns, subsequent appearances will have their `_id` appended with an"," incrementing number (e.g. if column \"foo\" is included in the `columns`"," attribute twice, the first will get `_id` of \"foo\", and the second an `_id`"," of \"foo1\"). Columns that are children of other columns will have the"," `_parent` property added, assigned the column object to which they belong.",""," @method _setColumns"," @param {null|Object[]|String[]} val Array of config objects or strings"," @return {null|Object[]}"," @protected"," **/"," _setColumns: function (val) {"," var keys = {},"," known = [],"," knownCopies = [],"," arrayIndex = Y.Array.indexOf;",""," function copyObj(o) {"," var copy = {},"," key, val, i;",""," known.push(o);"," knownCopies.push(copy);",""," for (key in o) {"," if (o.hasOwnProperty(key)) {"," val = o[key];",""," if (isArray(val)) {"," copy[key] = val.slice();"," } else if (isObject(val, true)) {"," i = arrayIndex(known, val);",""," copy[key] = i === -1 ? copyObj(val) : knownCopies[i];"," } else {"," copy[key] = o[key];"," }"," }"," }",""," return copy;"," }",""," function genId(name) {"," // Sanitize the name for use in generated CSS classes."," // TODO: is there more to do for other uses of _id?"," name = name.replace(/\\s+/, '-');",""," if (keys[name]) {"," name += (keys[name]++);"," } else {"," keys[name] = 1;"," }",""," return name;"," }",""," function process(cols, parent) {"," var columns = [],"," i, len, col, yuid;",""," for (i = 0, len = cols.length; i < len; ++i) {"," columns[i] = // chained assignment"," col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);",""," yuid = Y.stamp(col);",""," // For backward compatibility"," if (!col.id) {"," // Implementers can shoot themselves in the foot by setting"," // this config property to a non-unique value"," col.id = yuid;"," }"," if (col.field) {"," // Field is now known as \"name\" to avoid confusion with data"," // fields or schema.resultFields"," col.name = col.field;"," }",""," if (parent) {"," col._parent = parent;"," } else {"," delete col._parent;"," }",""," // Unique id based on the column's configured name or key,"," // falling back to the yuid. Duplicates will have a counter"," // added to the end."," col._id = genId(col.name || col.key || col.id);",""," if (isArray(col.children)) {"," col.children = process(col.children, col);"," }"," }",""," return columns;"," }",""," return val && process(val);"," },",""," /**"," Relays attribute assignments of the deprecated `columnset` attribute to the"," `columns` attribute. If a Columnset is object is passed, its basic object"," structure is mined.",""," @method _setColumnset"," @param {Array|Columnset} val The columnset value to relay"," @deprecated This will be removed with the deprecated `columnset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setColumnset: function (val) {"," this.set('columns', val);",""," return isArray(val) ? val : INVALID;"," },",""," /**"," Accepts an object with `each` and `getAttrs` (preferably a ModelList or"," subclass) or an array of data objects. If an array is passes, it will"," create a ModelList to wrap the data. In doing so, it will set the created"," ModelList's `model` property to the class in the `recordType` attribute,"," which will be defaulted if not yet set.",""," If the `data` property is already set with a ModelList, passing an array as"," the value will call the ModelList's `reset()` method with that array rather"," than replacing the stored ModelList wholesale.",""," Any non-ModelList-ish and non-array value is invalid.",""," @method _setData"," @protected"," @since 3.5.0"," **/"," _setData: function (val) {"," if (val === null) {"," val = [];"," }",""," if (isArray(val)) {"," this._initDataProperty();",""," // silent to prevent subscribers to both reset and dataChange"," // from reacting to the change twice."," // TODO: would it be better to return INVALID to silence the"," // dataChange event, or even allow both events?"," this.data.reset(val, { silent: true });",""," // Return the instance ModelList to avoid storing unprocessed"," // data in the state and their vivified Model representations in"," // the instance's data property. Decreases memory consumption."," val = this.data;"," } else if (!val || !val.each || !val.toJSON) {"," // ModelList/ArrayList duck typing"," val = INVALID;"," }",""," return val;"," },",""," /**"," Relays the value assigned to the deprecated `recordset` attribute to the"," `data` attribute. If a Recordset instance is passed, the raw object data"," will be culled from it.",""," @method _setRecordset"," @param {Object[]|Recordset} val The recordset value to relay"," @deprecated This will be removed with the deprecated `recordset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setRecordset: function (val) {"," var data;",""," if (val && Y.Recordset && val instanceof Y.Recordset) {"," data = [];"," val.each(function (record) {"," data.push(record.get('data'));"," });"," val = data;"," }",""," this.set('data', val);",""," return val;"," },",""," /**"," Accepts a Base subclass (preferably a Model subclass). Alternately, it will"," generate a custom Model subclass from an array of attribute names or an"," object defining attributes and their respective configurations (it is"," assigned as the `ATTRS` of the new class).",""," Any other value is invalid.",""," @method _setRecordType"," @param {Function|String[]|Object} val The Model subclass, array of"," attribute names, or the `ATTRS` definition for a custom model"," subclass"," @return {Function} A Base/Model subclass"," @protected"," @since 3.5.0"," **/"," _setRecordType: function (val) {"," var modelClass;",""," // Duck type based on known/likely consumed APIs"," if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {"," modelClass = val;"," } else if (isObject(val)) {"," modelClass = this._createRecordClass(val);"," }",""," return modelClass || INVALID;"," }","","});","","","","/**","_This is a documentation entry only_","","Columns are described by object literals with a set of properties.","There is not an actual `DataTable.Column` class.","However, for the purpose of documenting it, this pseudo-class is declared here.","","DataTables accept an array of column definitions in their [columns](DataTable.html#attr_columns)","attribute. Each entry in this array is a column definition which may contain","any combination of the properties listed below.","","There are no mandatory properties though a column will usually have a","[key](#property_key) property to reference the data it is supposed to show.","The [columns](DataTable.html#attr_columns) attribute can accept a plain string","in lieu of an object literal, which is the equivalent of an object with the","[key](#property_key) property set to that string.","","@class DataTable.Column","*/","","/**","Binds the column values to the named property in the [data](DataTable.html#attr_data).","","Optional if [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),","or [cellTemplate](#property_cellTemplate) is used to populate the content.","","It should not be set if [children](#property_children) is set.","","The value is used for the [\\_id](#property__id) property unless the [name](#property_name)","property is also set.",""," { key: 'username' }","","The above column definition can be reduced to this:",""," 'username'","","@property key","@type String"," */","/**","An identifier that can be used to locate a column via","[getColumn](DataTable.html#method_getColumn)","or style columns with class `yui3-datatable-col-NAME` after dropping characters","that are not valid for CSS class names.","","It defaults to the [key](#property_key).","","The value is used for the [\\_id](#property__id) property.",""," { name: 'fullname', formatter: ... }","","@property name","@type String","*/","/**","An alias for [name](#property_name) for backward compatibility.",""," { field: 'fullname', formatter: ... }","","@property field","@type String","*/","/**","Overrides the default unique id assigned `<th id=\"HERE\">`.","","__Use this with caution__, since it can result in","duplicate ids in the DOM.",""," {"," name: 'checkAll',"," id: 'check-all',"," label: ..."," formatter: ..."," }","","@property id","@type String"," */","/**","HTML to populate the header `<th>` for the column.","It defaults to the value of the [key](#property_key) property or the text","`Column n` where _n_ is an ordinal number.",""," { key: 'MfgvaPrtNum', label: 'Part Number' }","","@property label","@type {String}"," */","/**","Used to create stacked headers.","","Child columns may also contain `children`. There is no limit","to the depth of nesting.","","Columns configured with `children` are for display only and","<strong>should not</strong> be configured with a [key](#property_key).","Configurations relating to the display of data, such as","[formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),","[emptyCellValue](#property_emptyCellValue), etc. are ignored.",""," { label: 'Name', children: ["," { key: 'firstName', label: 'First`},"," { key: 'lastName', label: 'Last`}"," ]}","","@property children","@type Array","*/","/**","Assigns the value `<th abbr=\"HERE\">`.",""," {"," key : 'forecast',"," label: '1yr Target Forecast',"," abbr : 'Forecast'"," }","","@property abbr","@type String"," */","/**","Assigns the value `<th title=\"HERE\">`.",""," {"," key : 'forecast',"," label: '1yr Target Forecast',"," title: 'Target Forecast for the Next 12 Months'"," }","","@property title","@type String"," */","/**","Overrides the default [CELL_TEMPLATE](DataTable.HeaderView.html#property_CELL_TEMPLATE)","used by `Y.DataTable.HeaderView` to render the header cell","for this column. This is necessary when more control is","needed over the markup for the header itself, rather than","its content.","","Use the [label](#property_label) configuration if you don't need to","customize the `<th>` iteself.","","Implementers are strongly encouraged to preserve at least","the `{id}` and `{_id}` placeholders in the custom value.",""," {"," headerTemplate:"," '<th id=\"{id}\" ' +"," 'title=\"Unread\" ' +"," 'class=\"{className}\" ' +"," '{_id}>&#9679;</th>'"," }","","@property headerTemplate","@type HTML"," */","/**","Overrides the default [CELL_TEMPLATE](DataTable.BodyView.html#property_CELL_TEMPLATE)","used by `Y.DataTable.BodyView` to render the data cells","for this column. This is necessary when more control is","needed over the markup for the `<td>` itself, rather than","its content.",""," {"," key: 'id',"," cellTemplate:"," '<td class=\"{className}\">' +"," '<input type=\"checkbox\" ' +"," 'id=\"{content}\">' +"," '</td>'"," }","","","@property cellTemplate","@type String"," */","/**","String or function used to translate the raw record data for each cell in a","given column into a format better suited to display.","","If it is a string, it will initially be assumed to be the name of one of the","formatting functions in","[Y.DataTable.BodyView.Formatters](DataTable.BodyView.Formatters.html).","If one such formatting function exists, it will be used.","","If no such named formatter is found, it will be assumed to be a template","string and will be expanded. The placeholders can contain the key to any","field in the record or the placeholder `{value}` which represents the value","of the current field.","","If the value is a function, it will be assumed to be a formatting function.","A formatting function receives a single argument, an object with the following properties:","","* __value__ The raw value from the record Model to populate this cell."," Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.","* __data__ The Model data for this row in simple object format.","* __record__ The Model for this row.","* __column__ The column configuration object.","* __className__ A string of class names to add `<td class=\"HERE\">` in addition to"," the column class and any classes in the column's className configuration.","* __rowIndex__ The index of the current Model in the ModelList."," Typically correlates to the row index as well.","* __rowClass__ A string of css classes to add `<tr class=\"HERE\"><td....`"," This is useful to avoid the need for nodeFormatters to add classes to the containing row.","","The formatter function may return a string value that will be used for the cell","contents or it may change the value of the `value`, `className` or `rowClass`","properties which well then be used to format the cell. If the value for the cell","is returned in the `value` property of the input argument, no value should be returned.",""," {"," key: 'name',"," formatter: 'link', // named formatter"," linkFrom: 'website' // extra column property for link formatter"," },"," {"," key: 'cost',"," formatter: '${value}' // formatter template string"," //formatter: '${cost}' // same result but less portable"," },"," {"," name: 'Name', // column does not have associated field value"," // thus, it uses name instead of key"," formatter: '{firstName} {lastName}' // template references other fields"," },"," {"," key: 'price',"," formatter: function (o) { // function both returns a string to show"," if (o.value > 3) { // and a className to apply to the cell"," o.className += 'expensive';"," }",""," return '$' + o.value.toFixed(2);"," }"," },","@property formatter","@type String || Function","","*/","/**","Used to customize the content of the data cells for this column.","","`nodeFormatter` is significantly slower than [formatter](#property_formatter)","and should be avoided if possible. Unlike [formatter](#property_formatter),","`nodeFormatter` has access to the `<td>` element and its ancestors.","","The function provided is expected to fill in the `<td>` element itself.","__Node formatters should return `false`__ except in certain conditions as described","in the users guide.","","The function receives a single object","argument with the following properties:","","* __td__\tThe `<td>` Node for this cell.","* __cell__\tIf the cell `<td> contains an element with class `yui3-datatable-liner,"," this will refer to that Node. Otherwise, it is equivalent to `td` (default behavior).","* __value__\tThe raw value from the record Model to populate this cell."," Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.","* __data__\tThe Model data for this row in simple object format.","* __record__\tThe Model for this row.","* __column__\tThe column configuration object.","* __rowIndex__\tThe index of the current Model in the ModelList."," _Typically_ correlates to the row index as well.","","@example"," nodeFormatter: function (o) {"," if (o.value < o.data.quota) {"," o.td.setAttribute('rowspan', 2);"," o.td.setAttribute('data-term-id', this.record.get('id'));",""," o.td.ancestor().insert("," '<tr><td colspan\"3\">' +"," '<button class=\"term\">terminate</button>' +"," '</td></tr>',"," 'after');"," }",""," o.cell.setHTML(o.value);"," return false;"," }","","@property nodeFormatter","@type Function","*/","/**","Provides the default value to populate the cell if the data","for that cell is `undefined`, `null`, or an empty string.",""," {"," key: 'price',"," emptyCellValue: '???'"," }","","@property emptyCellValue","@type {String} depending on the setting of allowHTML"," */","/**","Skips the security step of HTML escaping the value for cells","in this column.","","This is also necessary if [emptyCellValue](#property_emptyCellValue)","is set with an HTML string.","`nodeFormatter`s ignore this configuration. If using a","`nodeFormatter`, it is recommended to use","[Y.Escape.html()](Escape.html#method_html)","on any user supplied content that is to be displayed.",""," {"," key: 'preview',"," allowHTML: true"," }","","@property allowHTML","@type Boolean","*/","/**","A string of CSS classes that will be added to the `<td>`'s","`class` attribute.","","Note, all cells will automatically have a class in the","form of \"yui3-datatable-col-XXX\" added to the `<td>`, where","XXX is the column's configured `name`, `key`, or `id` (in","that order of preference) sanitized from invalid characters.",""," {"," key: 'symbol',"," className: 'no-hide'"," }","","@property className","@type String","*/","/**","(__read-only__) The unique identifier assigned","to each column. This is used for the `id` if not set, and","the `_id` if none of [name](#property_name),","[field](#property_field), [key](#property_key), or [id](#property_id) are","set.","","@property _yuid","@type String","@protected"," */","/**","(__read-only__) A unique-to-this-instance name","used extensively in the rendering process. It is also used","to create the column's classname, as the input name","`table.getColumn(HERE)`, and in the column header's","`<th data-yui3-col-id=\"HERE\">`.","","The value is populated by the first of [name](#property_name),","[field](#property_field), [key](#property_key), [id](#property_id),"," or [_yuid](#property__yuid) to have a value. If that value","has already been used (such as when multiple columns have","the same `key`), an incrementer is added to the end. For","example, two columns with `key: \"id\"` will have `_id`s of","\"id\" and \"id2\". `table.getColumn(\"id\")` will return the","first column, and `table.getColumn(\"id2\")` will return the","second.","","@property _id","@type String","@protected"," */","/**","(__read-only__) Used by","`Y.DataTable.HeaderView` when building stacked column","headers.","","@property _colspan","@type Integer","@protected"," */","/**","(__read-only__) Used by","`Y.DataTable.HeaderView` when building stacked column","headers.","","@property _rowspan","@type Integer","@protected"," */","/**","(__read-only__) Assigned to all columns in a","column's `children` collection. References the parent","column object.","","@property _parent","@type DataTable.Column","@protected"," */","/**","(__read-only__) Array of the `id`s of the","column and all parent columns. Used by","`Y.DataTable.BodyView` to populate `<td headers=\"THIS\">`","when a cell references more than one header.","","@property _headers","@type Array","@protected","*/","","","}, '3.16.0', {\"requires\": [\"escape\", \"model-list\", \"node-event-delegate\"]});","","}());"]}; } var __cov_adU3eEuYYFqBLZ6_IZplXQ = __coverage__['build/datatable-core/datatable-core.js']; __cov_adU3eEuYYFqBLZ6_IZplXQ.s['1']++;YUI.add('datatable-core',function(Y,NAME){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['1']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['2']++;var INVALID=Y.Attribute.INVALID_VALUE,Lang=Y.Lang,isFunction=Lang.isFunction,isObject=Lang.isObject,isArray=Lang.isArray,isString=Lang.isString,isNumber=Lang.isNumber,toArray=Y.Array,keys=Y.Object.keys,Table;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['3']++;Table=Y.namespace('DataTable').Core=function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['2']++;};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['4']++;Table.ATTRS={columns:{validator:isArray,setter:'_setColumns',getter:'_getColumns'},recordType:{getter:'_getRecordType',setter:'_setRecordType'},data:{valueFn:'_initData',setter:'_setData',lazyAdd:false},recordset:{setter:'_setRecordset',getter:'_getRecordset',lazyAdd:false},columnset:{setter:'_setColumnset',getter:'_getColumnset',lazyAdd:false}};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['5']++;Y.mix(Table.prototype,{getColumn:function(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['3']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['6']++;var col,columns,i,len,cols;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['7']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][0]++,isObject(name))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][1]++,!isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['8']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][0]++,name)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][1]++,name._node)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['9']++;col=this.body.getColumn(name);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['10']++;col=name;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['11']++;col=this.get('columns.'+name);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['12']++;if(col){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['13']++;return col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['14']++;columns=this.get('columns');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['15']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][0]++,isNumber(name))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][1]++,isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['16']++;name=toArray(name);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['17']++;cols=columns;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['18']++;for(i=0,len=name.length-1;(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][1]++,i<len);++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['19']++;cols=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][0]++,cols[name[i]])&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][1]++,cols[name[i]].children);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['20']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][1]++,cols[name[i]])||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][2]++,null);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['21']++;return null;},getRecord:function(seed){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['4']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['22']++;var record=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][0]++,this.data.getById(seed))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][1]++,this.data.getByClientId(seed));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['23']++;if(!record){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['24']++;if(isNumber(seed)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['25']++;record=this.data.item(seed);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['26']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][0]++,!record)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][1]++,this.view)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][2]++,this.view.getRecord)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['27']++;record=this.view.getRecord.apply(this.view,arguments);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['28']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][0]++,record)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][1]++,null);},_allowAdHocAttrs:true,_afterColumnsChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['5']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['29']++;this._setColumnMap(e.newVal);},_afterDataChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['6']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['30']++;var modelList=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['31']++;this.data=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['32']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][1]++,modelList.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['33']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][1]++;}},_afterRecordTypeChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['7']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['34']++;var data=this.data.toJSON();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['35']++;this.data.model=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['36']++;this.data.reset(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['37']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][1]++,data)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['38']++;if(data.length){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['39']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['40']++;this.set('columns',keys(e.newVal.ATTRS));}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][1]++;}},_createRecordClass:function(attrs){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['8']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['41']++;var ATTRS,i,len;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['42']++;if(isArray(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['43']++;ATTRS={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['44']++;for(i=0,len=attrs.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['45']++;ATTRS[attrs[i]]={};}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['46']++;if(isObject(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['47']++;ATTRS=attrs;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['48']++;return Y.Base.create('record',Y.Model,[],null,{ATTRS:ATTRS});},destructor:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['9']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['49']++;new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();},_getColumns:function(columns,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['10']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['50']++;return name.length>8?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][0]++,this._columnMap):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][1]++,columns);},_getColumnset:function(_,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['11']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['51']++;return this.get(name.replace(/^columnset/,'columns'));},_getRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['12']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['52']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][0]++,val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][1]++,this.data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][2]++,this.data.model);},_initColumns:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['13']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['53']++;var columns=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][0]++,this.get('columns'))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][1]++,[]),item;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['54']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][0]++,!columns.length)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][1]++,this.data.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['55']++;item=this.data.item(0);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['56']++;if(item.toJSON){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['57']++;item=item.toJSON();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['58']++;this.set('columns',keys(item));}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['59']++;this._setColumnMap(columns);},_initCoreEvents:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['14']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['60']++;this._eventHandles.coreAttrChanges=this.after({columnsChange:Y.bind('_afterColumnsChange',this),recordTypeChange:Y.bind('_afterRecordTypeChange',this),dataChange:Y.bind('_afterDataChange',this)});},_initData:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['15']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['61']++;var recordType=this.get('recordType'),modelList=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['62']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['63']++;modelList.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['64']++;return modelList;},_initDataProperty:function(data){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['16']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['65']++;var recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['66']++;if(!this.data){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['67']++;recordType=this.get('recordType');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['68']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][0]++,data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][1]++,data.each)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][2]++,data.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['69']++;this.data=data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['70']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['71']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['72']++;this.data=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['73']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['74']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['75']++;this.data.addTarget(this);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][1]++;}},initializer:function(config){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['17']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['76']++;var data=config.data,columns=config.columns,recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['77']++;this._initDataProperty(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['78']++;if(!columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['79']++;recordType=((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][0]++,config.recordType)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][1]++,config.data===this.data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][2]++,this.get('recordType'));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['80']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['81']++;columns=keys(recordType.ATTRS);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['82']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][0]++,isArray(data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][1]++,data.length)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['83']++;columns=keys(data[0]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['84']++;if(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['85']++;this.set('columns',columns);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['86']++;this._initColumns();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['87']++;this._eventHandles={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['88']++;this._initCoreEvents();},_setColumnMap:function(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['18']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['89']++;var map={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['90']++;function process(cols){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['19']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['91']++;var i,len,col,key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['92']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['93']++;col=cols[i];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['94']++;key=col.key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['95']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][0]++,key)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][1]++,!map[key])){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['96']++;map[key]=col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['97']++;map[col._id]=col;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['98']++;if(col.children){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['99']++;process(col.children);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][1]++;}}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['100']++;process(columns);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['101']++;this._columnMap=map;},_setColumns:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['20']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['102']++;var keys={},known=[],knownCopies=[],arrayIndex=Y.Array.indexOf;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['103']++;function copyObj(o){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['21']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['104']++;var copy={},key,val,i;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['105']++;known.push(o);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['106']++;knownCopies.push(copy);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['107']++;for(key in o){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['108']++;if(o.hasOwnProperty(key)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['109']++;val=o[key];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['110']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['111']++;copy[key]=val.slice();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['112']++;if(isObject(val,true)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['113']++;i=arrayIndex(known,val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['114']++;copy[key]=i===-1?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][0]++,copyObj(val)):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][1]++,knownCopies[i]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['115']++;copy[key]=o[key];}}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['116']++;return copy;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['117']++;function genId(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['22']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['118']++;name=name.replace(/\s+/,'-');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['119']++;if(keys[name]){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['120']++;name+=keys[name]++;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['121']++;keys[name]=1;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['122']++;return name;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['123']++;function process(cols,parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['23']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['124']++;var columns=[],i,len,col,yuid;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['125']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['126']++;columns[i]=col=isString(cols[i])?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][0]++,{key:cols[i]}):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][1]++,copyObj(cols[i]));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['127']++;yuid=Y.stamp(col);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['128']++;if(!col.id){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['129']++;col.id=yuid;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['130']++;if(col.field){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['131']++;col.name=col.field;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['132']++;if(parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['133']++;col._parent=parent;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['134']++;delete col._parent;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['135']++;col._id=genId((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][0]++,col.name)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][1]++,col.key)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][2]++,col.id));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['136']++;if(isArray(col.children)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['137']++;col.children=process(col.children,col);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['138']++;return columns;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['139']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][1]++,process(val));},_setColumnset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['24']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['140']++;this.set('columns',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['141']++;return isArray(val)?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][0]++,val):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][1]++,INVALID);},_setData:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['25']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['142']++;if(val===null){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['143']++;val=[];}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['144']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['145']++;this._initDataProperty();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['146']++;this.data.reset(val,{silent:true});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['147']++;val=this.data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['148']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][0]++,!val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][1]++,!val.each)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][2]++,!val.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['149']++;val=INVALID;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['150']++;return val;},_setRecordset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['26']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['151']++;var data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['152']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][1]++,Y.Recordset)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][2]++,val instanceof Y.Recordset)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['153']++;data=[];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['154']++;val.each(function(record){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['27']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['155']++;data.push(record.get('data'));});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['156']++;val=data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['157']++;this.set('data',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['158']++;return val;},_setRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['28']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['159']++;var modelClass;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['160']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][0]++,isFunction(val))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][1]++,val.prototype.toJSON)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][2]++,val.prototype.setAttrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['161']++;modelClass=val;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['162']++;if(isObject(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['66'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['163']++;modelClass=this._createRecordClass(val);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['66'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['164']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['67'][0]++,modelClass)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['67'][1]++,INVALID);}});},'3.16.0',{'requires':['escape','model-list','node-event-delegate']});
packages/material-ui-icons/src/BlurOnTwoTone.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><circle cx="14" cy="10" r="1.5" /><circle cx="14" cy="18" r="1" /><circle cx="14" cy="14" r="1.5" /><circle cx="14" cy="6" r="1" /><path d="M3 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM14.5 3c0-.28-.22-.5-.5-.5s-.5.22-.5.5.22.5.5.5.5-.22.5-.5zM21 14.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5z" /><circle cx="18" cy="18" r="1" /><path d="M13.5 21c0 .28.22.5.5.5s.5-.22.5-.5-.22-.5-.5-.5-.5.22-.5.5zM21 10.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5z" /><circle cx="18" cy="14" r="1" /><circle cx="18" cy="6" r="1" /><circle cx="6" cy="18" r="1" /><circle cx="6" cy="14" r="1" /><path d="M3.5 14c0-.28-.22-.5-.5-.5s-.5.22-.5.5.22.5.5.5.5-.22.5-.5z" /><circle cx="10" cy="6" r="1" /><circle cx="6" cy="10" r="1" /><circle cx="6" cy="6" r="1" /><path d="M9.5 21c0 .28.22.5.5.5s.5-.22.5-.5-.22-.5-.5-.5-.5.22-.5.5z" /><circle cx="10" cy="18" r="1" /><path d="M10.5 3c0-.28-.22-.5-.5-.5s-.5.22-.5.5.22.5.5.5.5-.22.5-.5z" /><circle cx="10" cy="14" r="1.5" /><circle cx="10" cy="10" r="1.5" /><circle cx="18" cy="10" r="1" /></React.Fragment> , 'BlurOnTwoTone');
client/components/BaseTable.js
rodrigok/GradeFaccat
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Table, } from 'antd'; export class BaseTableComponent extends Component { static propTypes = { data: PropTypes.object, } state = {} static getDerivedStateFromProps(props, state) { return { ...state, records: props.data.records, }; } render() { const { records } = this.state; const { data: { loading } } = this.props; return ( <Table bordered loading={loading} dataSource={records} columns={this.state.columns} rowKey='_id' pagination={false} /> ); } }
src/components/MainNav/AppList/components/ResizeContainer/ResizeContainer.js
folio-org/stripes-core
/** * AppList -> ResizeContainer */ import React from 'react'; import classnames from 'classnames'; import debounce from 'lodash/debounce'; import PropTypes from 'prop-types'; import css from './ResizeContainer.css'; class ResizeContainer extends React.Component { static propTypes = { children: PropTypes.func, currentAppId: PropTypes.string, className: PropTypes.string, hideAllWidth: PropTypes.number, items: PropTypes.arrayOf(PropTypes.object), offset: PropTypes.number, } static defaultProps = { offset: 200, } constructor(props) { super(props); this.wrapperRef = React.createRef(null); } state = { ready: false, cachedItemWidths: [], hiddenItems: [], } componentDidMount() { this.initialize(); window.addEventListener('resize', this.onResize, true); } componentDidUpdate(prevProps) { // Update hidden items when the current app ID changes // to make sure that no items are hidden behind the current app label if (this.props.currentAppId && this.props.currentAppId !== prevProps.currentAppId) { this.updateHiddenItems(); } } componentWillUnmount() { window.removeEventListener('resize', this.onResize, true); } initialize = () => { const { items } = this.props; if (!items.length) { return; } // Save widths of items since they will probably not change unless the local is changed this.setState({ cachedItemWidths: items.reduce((acc, { id }) => Object.assign(acc, { [id]: document.getElementById(`app-list-item-${id}`).parentNode.offsetWidth, }), {}) }, () => { // Determine which items should be visible and hidden this.updateHiddenItems(() => { // We are hiding the content until we are finished setting hidden items (if any) // Setting ready will make the contents visible for the user this.setState({ ready: true }); }); }); } /** * Determine hidden items on mount and resize */ updateHiddenItems = (callback) => { const { hideAllWidth, offset } = this.props; const { cachedItemWidths } = this.state; const shouldHideAll = window.innerWidth <= hideAllWidth; const wrapperEl = this.wrapperRef.current; if (wrapperEl) { const wrapperWidth = wrapperEl.clientWidth; const newHiddenItems = // Set all items as hidden shouldHideAll ? Object.keys(cachedItemWidths) : // Find items that should be hidden Object.keys(cachedItemWidths).reduce((acc, id) => { const itemWidth = cachedItemWidths[id]; const shouldBeHidden = (itemWidth + acc.accWidth + offset) > wrapperWidth; const hidden = shouldBeHidden ? acc.hidden.concat(id) : acc.hidden; return { hidden, accWidth: acc.accWidth + itemWidth, }; }, { hidden: [], accWidth: 0, }).hidden; this.setState({ hiddenItems: newHiddenItems }, callback); } } onResize = debounce(() => { this.updateHiddenItems(); }, 150) render() { const { ready, cachedItemWidths, hiddenItems } = this.state; const { className, children } = this.props; return ( <div ref={this.wrapperRef} className={classnames(css.resizeContainerWrapper, { [css.ready]: ready }, className)} data-test-resize-container > <div className={css.resizeContainerInner}> {children({ hiddenItems, itemWidths: cachedItemWidths, ready, })} </div> </div> ); } } export default ResizeContainer;
packages/material-ui-icons/src/MenuBookRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M17.5 4.5c-1.95 0-4.05.4-5.5 1.5-1.45-1.1-3.55-1.5-5.5-1.5-1.45 0-2.99.22-4.28.79C1.49 5.62 1 6.33 1 7.14v11.28c0 1.3 1.22 2.26 2.48 1.94.98-.25 2.02-.36 3.02-.36 1.56 0 3.22.26 4.56.92.6.3 1.28.3 1.87 0 1.34-.67 3-.92 4.56-.92 1 0 2.04.11 3.02.36 1.26.33 2.48-.63 2.48-1.94V7.14c0-.81-.49-1.52-1.22-1.85-1.28-.57-2.82-.79-4.27-.79zM21 17.23c0 .63-.58 1.09-1.2.98-.75-.14-1.53-.2-2.3-.2-1.7 0-4.15.65-5.5 1.5V8c1.35-.85 3.8-1.5 5.5-1.5.92 0 1.83.09 2.7.28.46.1.8.51.8.98v9.47z" /><path d="M13.98 11.01c-.32 0-.61-.2-.71-.52-.13-.39.09-.82.48-.94 1.54-.5 3.53-.66 5.36-.45.41.05.71.42.66.83-.05.41-.42.71-.83.66-1.62-.19-3.39-.04-4.73.39-.08.01-.16.03-.23.03zM13.98 13.67c-.32 0-.61-.2-.71-.52-.13-.39.09-.82.48-.94 1.53-.5 3.53-.66 5.36-.45.41.05.71.42.66.83-.05.41-.42.71-.83.66-1.62-.19-3.39-.04-4.73.39-.08.02-.16.03-.23.03zM13.98 16.33c-.32 0-.61-.2-.71-.52-.13-.39.09-.82.48-.94 1.53-.5 3.53-.66 5.36-.45.41.05.71.42.66.83-.05.41-.42.7-.83.66-1.62-.19-3.39-.04-4.73.39-.08.02-.16.03-.23.03z" /></React.Fragment> , 'MenuBookRounded');
packages/vx-demo/components/tiles/axis.js
Flaque/vx
import React from 'react'; import { Grid } from '@vx/grid'; import { Group } from '@vx/group'; import { curveBasis } from '@vx/curve'; import { GradientOrangeRed } from '@vx/gradient'; import { genDateValue } from '@vx/mock-data'; import { AxisLeft, AxisBottom } from '@vx/axis'; import { AreaClosed, LinePath } from '@vx/shape'; import { scaleTime, scaleLinear } from '@vx/scale'; import { extent, max } from 'd3-array'; const data = genDateValue(20); // accessors const x = d => d.date; const y = d => d.value; // responsive utils for axis ticks function numTicksForHeight(height) { if (height <= 300) return 3; if (300 < height && height <= 600) return 5; return 10; } function numTicksForWidth(width) { if (width <= 300) return 2; if (300 < width && width <= 400) return 5; return 10; } export default ({ width, height, margin }) => { if (width < 10) return null; // bounds const xMax = width - margin.left - margin.right; const yMax = height - margin.top - margin.bottom; // scales const xScale = scaleTime({ range: [0, xMax], domain: extent(data, x), }); const yScale = scaleLinear({ range: [yMax, 0], domain: [0, max(data, y)], nice: true, }); // scale tick formats const yFormat = yScale.tickFormat ? yScale.tickFormat() : identity; const xFormat = xScale.tickFormat ? xScale.tickFormat() : identity; return ( <svg width={width} height={height}> <GradientOrangeRed id="linear" vertical={false} fromOpacity={0.8} toOpacity={0.3} /> <rect x={0} y={0} width={width} height={height} fill="#f4419f" rx={14} /> <Grid top={margin.top} left={margin.left} xScale={xScale} yScale={yScale} stroke="rgba(142, 32, 95, 0.9)" width={xMax} height={yMax} numTicksRows={numTicksForHeight(height)} numTicksColumns={numTicksForWidth(width)} /> <Group top={margin.top} left={margin.left}> <AreaClosed data={data} xScale={xScale} yScale={yScale} x={x} y={y} strokeWidth={2} stroke={'transparent'} fill={'url(#linear)'} curve={curveBasis} /> <LinePath data={data} xScale={xScale} yScale={yScale} x={x} y={y} stroke={"url('#linear')"} strokeWidth={2} curve={curveBasis} /> </Group> <AxisLeft top={margin.top} left={margin.left} scale={yScale} hideZero numTicks={numTicksForHeight(height)} label={ <text fill="#8e205f" textAnchor="middle" fontSize={10} fontFamily="Arial" > value </text> } stroke="#1b1a1e" tickLabelComponent={ <text fill="#8e205f" textAnchor="end" fontSize={10} fontFamily="Arial" dx="-0.25em" dy="0.25em" /> } /> <AxisBottom top={height - margin.bottom} left={margin.left} scale={xScale} numTicks={numTicksForWidth(width)} label={ <text fill="#8e205f" textAnchor="middle" fontSize={10} fontFamily="Arial" > time </text> } stroke={'#1b1a1e'} tickStroke={'#1b1a1e'} tickLabelComponent={ <text fill="#8e205f" textAnchor="middle" fontSize={10} fontFamily="Arial" dy="0.25em" /> } /> </svg> ); };
node_modules/@angular/forms/bundles/forms.umd.js
JuanMenendezBuitrago/angular-tour-of-heroes
/** * @license Angular v2.4.3 * (c) 2010-2016 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs/operator/toPromise'), require('rxjs/Subject'), require('rxjs/Observable'), require('rxjs/observable/fromPromise')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/core', 'rxjs/operator/toPromise', 'rxjs/Subject', 'rxjs/Observable', 'rxjs/observable/fromPromise'], factory) : (factory((global.ng = global.ng || {}, global.ng.forms = global.ng.forms || {}),global.ng.core,global.Rx.Observable.prototype,global.Rx,global.Rx,global.Rx.Observable)); }(this, function (exports,_angular_core,rxjs_operator_toPromise,rxjs_Subject,rxjs_Observable,rxjs_observable_fromPromise) { 'use strict'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Base class for control directives. * * * Only used internally in the forms module. * * * @abstract */ var AbstractControlDirective = (function () { function AbstractControlDirective() { } Object.defineProperty(AbstractControlDirective.prototype, "control", { /** * @return {?} */ get: function () { throw new Error('unimplemented'); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "value", { /** * @return {?} */ get: function () { return this.control ? this.control.value : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "valid", { /** * @return {?} */ get: function () { return this.control ? this.control.valid : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "invalid", { /** * @return {?} */ get: function () { return this.control ? this.control.invalid : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "pending", { /** * @return {?} */ get: function () { return this.control ? this.control.pending : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "errors", { /** * @return {?} */ get: function () { return this.control ? this.control.errors : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "pristine", { /** * @return {?} */ get: function () { return this.control ? this.control.pristine : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "dirty", { /** * @return {?} */ get: function () { return this.control ? this.control.dirty : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "touched", { /** * @return {?} */ get: function () { return this.control ? this.control.touched : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "untouched", { /** * @return {?} */ get: function () { return this.control ? this.control.untouched : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "disabled", { /** * @return {?} */ get: function () { return this.control ? this.control.disabled : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "enabled", { /** * @return {?} */ get: function () { return this.control ? this.control.enabled : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "statusChanges", { /** * @return {?} */ get: function () { return this.control ? this.control.statusChanges : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "valueChanges", { /** * @return {?} */ get: function () { return this.control ? this.control.valueChanges : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlDirective.prototype, "path", { /** * @return {?} */ get: function () { return null; }, enumerable: true, configurable: true }); /** * @param {?=} value * @return {?} */ AbstractControlDirective.prototype.reset = function (value) { if (value === void 0) { value = undefined; } if (this.control) this.control.reset(value); }; /** * @param {?} errorCode * @param {?=} path * @return {?} */ AbstractControlDirective.prototype.hasError = function (errorCode, path) { if (path === void 0) { path = null; } return this.control ? this.control.hasError(errorCode, path) : false; }; /** * @param {?} errorCode * @param {?=} path * @return {?} */ AbstractControlDirective.prototype.getError = function (errorCode, path) { if (path === void 0) { path = null; } return this.control ? this.control.getError(errorCode, path) : null; }; return AbstractControlDirective; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$1 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /** * A directive that contains multiple {@link NgControl}s. * * * Only used by the forms module. * * */ var ControlContainer = (function (_super) { __extends$1(ControlContainer, _super); function ControlContainer() { _super.apply(this, arguments); } Object.defineProperty(ControlContainer.prototype, "formDirective", { /** * Get the form to which this container belongs. * @return {?} */ get: function () { return null; }, enumerable: true, configurable: true }); Object.defineProperty(ControlContainer.prototype, "path", { /** * Get the path to this container. * @return {?} */ get: function () { return null; }, enumerable: true, configurable: true }); return ControlContainer; }(AbstractControlDirective)); /** * @param {?} obj * @return {?} */ function isPresent(obj) { return obj != null; } /** * @param {?} obj * @return {?} */ function isBlank(obj) { return obj == null; } /** * @param {?} a * @param {?} b * @return {?} */ function looseIdentical(a, b) { return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b); } /** * @param {?} o * @return {?} */ function isJsObject(o) { return o !== null && (typeof o === 'function' || typeof o === 'object'); } /** * @param {?} obj * @return {?} */ function isPrimitive(obj) { return !isJsObject(obj); } /** * Wraps Javascript Objects */ var StringMapWrapper = (function () { function StringMapWrapper() { } /** * @param {?} m1 * @param {?} m2 * @return {?} */ StringMapWrapper.merge = function (m1, m2) { var /** @type {?} */ m = {}; for (var _i = 0, _a = Object.keys(m1); _i < _a.length; _i++) { var k = _a[_i]; m[k] = m1[k]; } for (var _b = 0, _c = Object.keys(m2); _b < _c.length; _b++) { var k = _c[_b]; m[k] = m2[k]; } return m; }; /** * @param {?} m1 * @param {?} m2 * @return {?} */ StringMapWrapper.equals = function (m1, m2) { var /** @type {?} */ k1 = Object.keys(m1); var /** @type {?} */ k2 = Object.keys(m2); if (k1.length != k2.length) { return false; } for (var /** @type {?} */ i = 0; i < k1.length; i++) { var /** @type {?} */ key = k1[i]; if (m1[key] !== m2[key]) { return false; } } return true; }; return StringMapWrapper; }()); var ListWrapper = (function () { function ListWrapper() { } /** * @param {?} arr * @param {?} condition * @return {?} */ ListWrapper.findLast = function (arr, condition) { for (var /** @type {?} */ i = arr.length - 1; i >= 0; i--) { if (condition(arr[i])) { return arr[i]; } } return null; }; /** * @param {?} list * @param {?} items * @return {?} */ ListWrapper.removeAll = function (list, items) { for (var /** @type {?} */ i = 0; i < items.length; ++i) { var /** @type {?} */ index = list.indexOf(items[i]); if (index > -1) { list.splice(index, 1); } } }; /** * @param {?} list * @param {?} el * @return {?} */ ListWrapper.remove = function (list, el) { var /** @type {?} */ index = list.indexOf(el); if (index > -1) { list.splice(index, 1); return true; } return false; }; /** * @param {?} a * @param {?} b * @return {?} */ ListWrapper.equals = function (a, b) { if (a.length != b.length) return false; for (var /** @type {?} */ i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; }; /** * @param {?} list * @return {?} */ ListWrapper.flatten = function (list) { return list.reduce(function (flat, item) { var /** @type {?} */ flatItem = Array.isArray(item) ? ListWrapper.flatten(item) : item; return ((flat)).concat(flatItem); }, []); }; return ListWrapper; }()); var /** @type {?} */ isPromise = _angular_core.__core_private__.isPromise; /** * @param {?} value * @return {?} */ function isEmptyInputValue(value) { // we don't check for string here so it also works with arrays return value == null || value.length === 0; } /** * Providers for validators to be used for {@link FormControl}s in a form. * * Provide this using `multi: true` to add validators. * * ### Example * * {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'} * @stable */ var /** @type {?} */ NG_VALIDATORS = new _angular_core.OpaqueToken('NgValidators'); /** * Providers for asynchronous validators to be used for {@link FormControl}s * in a form. * * Provide this using `multi: true` to add validators. * * See {@link NG_VALIDATORS} for more details. * * @stable */ var /** @type {?} */ NG_ASYNC_VALIDATORS = new _angular_core.OpaqueToken('NgAsyncValidators'); /** * Provides a set of validators used by form controls. * * * A validator is a function that processes a {@link FormControl} or collection of * controls and returns a map of errors. A null map means that validation has passed. * * * ### Example * * * ```typescript * var loginControl = new FormControl("", Validators.required) * ``` * * */ var Validators = (function () { function Validators() { } /** * Validator that requires controls to have a non-empty value. * @param {?} control * @return {?} */ Validators.required = function (control) { return isEmptyInputValue(control.value) ? { 'required': true } : null; }; /** * Validator that requires control value to be true. * @param {?} control * @return {?} */ Validators.requiredTrue = function (control) { return control.value === true ? null : { 'required': true }; }; /** * Validator that requires controls to have a value of a minimum length. * @param {?} minLength * @return {?} */ Validators.minLength = function (minLength) { return function (control) { if (isEmptyInputValue(control.value)) { return null; // don't validate empty values to allow optional controls } var /** @type {?} */ length = control.value ? control.value.length : 0; return length < minLength ? { 'minlength': { 'requiredLength': minLength, 'actualLength': length } } : null; }; }; /** * Validator that requires controls to have a value of a maximum length. * @param {?} maxLength * @return {?} */ Validators.maxLength = function (maxLength) { return function (control) { var /** @type {?} */ length = control.value ? control.value.length : 0; return length > maxLength ? { 'maxlength': { 'requiredLength': maxLength, 'actualLength': length } } : null; }; }; /** * Validator that requires a control to match a regex to its value. * @param {?} pattern * @return {?} */ Validators.pattern = function (pattern) { if (!pattern) return Validators.nullValidator; var /** @type {?} */ regex; var /** @type {?} */ regexStr; if (typeof pattern === 'string') { regexStr = "^" + pattern + "$"; regex = new RegExp(regexStr); } else { regexStr = pattern.toString(); regex = pattern; } return function (control) { if (isEmptyInputValue(control.value)) { return null; // don't validate empty values to allow optional controls } var /** @type {?} */ value = control.value; return regex.test(value) ? null : { 'pattern': { 'requiredPattern': regexStr, 'actualValue': value } }; }; }; /** * No-op validator. * @param {?} c * @return {?} */ Validators.nullValidator = function (c) { return null; }; /** * Compose multiple validators into a single function that returns the union * of the individual error maps. * @param {?} validators * @return {?} */ Validators.compose = function (validators) { if (!validators) return null; var /** @type {?} */ presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function (control) { return _mergeErrors(_executeValidators(control, presentValidators)); }; }; /** * @param {?} validators * @return {?} */ Validators.composeAsync = function (validators) { if (!validators) return null; var /** @type {?} */ presentValidators = validators.filter(isPresent); if (presentValidators.length == 0) return null; return function (control) { var /** @type {?} */ promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise); return Promise.all(promises).then(_mergeErrors); }; }; return Validators; }()); /** * @param {?} obj * @return {?} */ function _convertToPromise(obj) { return isPromise(obj) ? obj : rxjs_operator_toPromise.toPromise.call(obj); } /** * @param {?} control * @param {?} validators * @return {?} */ function _executeValidators(control, validators) { return validators.map(function (v) { return v(control); }); } /** * @param {?} control * @param {?} validators * @return {?} */ function _executeAsyncValidators(control, validators) { return validators.map(function (v) { return v(control); }); } /** * @param {?} arrayOfErrors * @return {?} */ function _mergeErrors(arrayOfErrors) { var /** @type {?} */ res = arrayOfErrors.reduce(function (res, errors) { return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res; }, {}); return Object.keys(res).length === 0 ? null : res; } /** * Used to provide a {@link ControlValueAccessor} for form controls. * * See {@link DefaultValueAccessor} for how to implement one. * @stable */ var /** @type {?} */ NG_VALUE_ACCESSOR = new _angular_core.OpaqueToken('NgValueAccessor'); var /** @type {?} */ CHECKBOX_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return CheckboxControlValueAccessor; }), multi: true, }; /** * The accessor for writing a value and listening to changes on a checkbox input element. * * * ### Example * ``` * <input type="checkbox" name="rememberLogin" ngModel> * ``` * * * @stable */ var CheckboxControlValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function CheckboxControlValueAccessor(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; this.onChange = function (_) { }; this.onTouched = function () { }; } /** * @param {?} value * @return {?} */ CheckboxControlValueAccessor.prototype.writeValue = function (value) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value); }; /** * @param {?} fn * @return {?} */ CheckboxControlValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; }; /** * @param {?} fn * @return {?} */ CheckboxControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ CheckboxControlValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; CheckboxControlValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]', host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' }, providers: [CHECKBOX_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ CheckboxControlValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; return CheckboxControlValueAccessor; }()); var /** @type {?} */ DEFAULT_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return DefaultValueAccessor; }), multi: true }; /** * The default accessor for writing a value and listening to changes that is used by the * {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives. * * * ### Example * ``` * <input type="text" name="searchQuery" ngModel> * ``` * * * @stable */ var DefaultValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function DefaultValueAccessor(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; this.onChange = function (_) { }; this.onTouched = function () { }; } /** * @param {?} value * @return {?} */ DefaultValueAccessor.prototype.writeValue = function (value) { var /** @type {?} */ normalizedValue = value == null ? '' : value; this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue); }; /** * @param {?} fn * @return {?} */ DefaultValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = fn; }; /** * @param {?} fn * @return {?} */ DefaultValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ DefaultValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; DefaultValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]', // TODO: vsavkin replace the above selector with the one below it once // https://github.com/angular/angular/issues/3011 is implemented // selector: '[ngControl],[ngModel],[ngFormControl]', host: { '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' }, providers: [DEFAULT_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ DefaultValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; return DefaultValueAccessor; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @param {?} validator * @return {?} */ function normalizeValidator(validator) { if (((validator)).validate) { return function (c) { return ((validator)).validate(c); }; } else { return (validator); } } /** * @param {?} validator * @return {?} */ function normalizeAsyncValidator(validator) { if (((validator)).validate) { return function (c) { return ((validator)).validate(c); }; } else { return (validator); } } var /** @type {?} */ NUMBER_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return NumberValueAccessor; }), multi: true }; /** * The accessor for writing a number value and listening to changes that is used by the * {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives. * * * ### Example * ``` * <input type="number" [(ngModel)]="age"> * ``` */ var NumberValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function NumberValueAccessor(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; this.onChange = function (_) { }; this.onTouched = function () { }; } /** * @param {?} value * @return {?} */ NumberValueAccessor.prototype.writeValue = function (value) { // The value needs to be normalized for IE9, otherwise it is set to 'null' when null var /** @type {?} */ normalizedValue = value == null ? '' : value; this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue); }; /** * @param {?} fn * @return {?} */ NumberValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); }; }; /** * @param {?} fn * @return {?} */ NumberValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ NumberValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; NumberValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'input[type=number][formControlName],input[type=number][formControl],input[type=number][ngModel]', host: { '(change)': 'onChange($event.target.value)', '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' }, providers: [NUMBER_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ NumberValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; return NumberValueAccessor; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$2 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /** * @return {?} */ function unimplemented() { throw new Error('unimplemented'); } /** * A base class that all control directive extend. * It binds a {@link FormControl} object to a DOM element. * * * Used internally by Angular forms. * * * @abstract */ var NgControl = (function (_super) { __extends$2(NgControl, _super); function NgControl() { _super.apply(this, arguments); /** @internal */ this._parent = null; this.name = null; this.valueAccessor = null; /** @internal */ this._rawValidators = []; /** @internal */ this._rawAsyncValidators = []; } Object.defineProperty(NgControl.prototype, "validator", { /** * @return {?} */ get: function () { return (unimplemented()); }, enumerable: true, configurable: true }); Object.defineProperty(NgControl.prototype, "asyncValidator", { /** * @return {?} */ get: function () { return (unimplemented()); }, enumerable: true, configurable: true }); /** * @abstract * @param {?} newValue * @return {?} */ NgControl.prototype.viewToModelUpdate = function (newValue) { }; return NgControl; }(AbstractControlDirective)); var /** @type {?} */ RADIO_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return RadioControlValueAccessor; }), multi: true }; /** * Internal class used by Angular to uncheck radio buttons with the matching name. */ var RadioControlRegistry = (function () { function RadioControlRegistry() { this._accessors = []; } /** * @param {?} control * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype.add = function (control, accessor) { this._accessors.push([control, accessor]); }; /** * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype.remove = function (accessor) { for (var /** @type {?} */ i = this._accessors.length - 1; i >= 0; --i) { if (this._accessors[i][1] === accessor) { this._accessors.splice(i, 1); return; } } }; /** * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype.select = function (accessor) { var _this = this; this._accessors.forEach(function (c) { if (_this._isSameGroup(c, accessor) && c[1] !== accessor) { c[1].fireUncheck(accessor.value); } }); }; /** * @param {?} controlPair * @param {?} accessor * @return {?} */ RadioControlRegistry.prototype._isSameGroup = function (controlPair, accessor) { if (!controlPair[0].control) return false; return controlPair[0]._parent === accessor._control._parent && controlPair[1].name === accessor.name; }; RadioControlRegistry.decorators = [ { type: _angular_core.Injectable }, ]; /** @nocollapse */ RadioControlRegistry.ctorParameters = function () { return []; }; return RadioControlRegistry; }()); /** * * * Used by {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} * to keep the view synced with the {@link FormControl} model. * * * * * If you have imported the {@link FormsModule} or the {@link ReactiveFormsModule}, this * value accessor will be active on any radio control that has a form directive. You do * **not** need to add a special selector to activate it. * * * ### How to use radio buttons with form directives * * * To use radio buttons in a template-driven form, you'll want to ensure that radio buttons * in the same group have the same `name` attribute. Radio buttons with different `name` * attributes do not affect each other. * * * {@example forms/ts/radioButtons/radio_button_example.ts region='TemplateDriven'} * * * When using radio buttons in a reactive form, radio buttons in the same group should have the * same `formControlName`. You can also add a `name` attribute, but it's optional. * * * {@example forms/ts/reactiveRadioButtons/reactive_radio_button_example.ts region='Reactive'} * * * * **npm package**: `@angular/forms` * * * @stable */ var RadioControlValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef * @param {?} _registry * @param {?} _injector */ function RadioControlValueAccessor(_renderer, _elementRef, _registry, _injector) { this._renderer = _renderer; this._elementRef = _elementRef; this._registry = _registry; this._injector = _injector; this.onChange = function () { }; this.onTouched = function () { }; } /** * @return {?} */ RadioControlValueAccessor.prototype.ngOnInit = function () { this._control = this._injector.get(NgControl); this._checkName(); this._registry.add(this._control, this); }; /** * @return {?} */ RadioControlValueAccessor.prototype.ngOnDestroy = function () { this._registry.remove(this); }; /** * @param {?} value * @return {?} */ RadioControlValueAccessor.prototype.writeValue = function (value) { this._state = value === this.value; this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', this._state); }; /** * @param {?} fn * @return {?} */ RadioControlValueAccessor.prototype.registerOnChange = function (fn) { var _this = this; this._fn = fn; this.onChange = function () { fn(_this.value); _this._registry.select(_this); }; }; /** * @param {?} value * @return {?} */ RadioControlValueAccessor.prototype.fireUncheck = function (value) { this.writeValue(value); }; /** * @param {?} fn * @return {?} */ RadioControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ RadioControlValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; /** * @return {?} */ RadioControlValueAccessor.prototype._checkName = function () { if (this.name && this.formControlName && this.name !== this.formControlName) { this._throwNameError(); } if (!this.name && this.formControlName) this.name = this.formControlName; }; /** * @return {?} */ RadioControlValueAccessor.prototype._throwNameError = function () { throw new Error("\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type=\"radio\" formControlName=\"food\" name=\"food\">\n "); }; RadioControlValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'input[type=radio][formControlName],input[type=radio][formControl],input[type=radio][ngModel]', host: { '(change)': 'onChange()', '(blur)': 'onTouched()' }, providers: [RADIO_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ RadioControlValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, { type: RadioControlRegistry, }, { type: _angular_core.Injector, }, ]; }; RadioControlValueAccessor.propDecorators = { 'name': [{ type: _angular_core.Input },], 'formControlName': [{ type: _angular_core.Input },], 'value': [{ type: _angular_core.Input },], }; return RadioControlValueAccessor; }()); var /** @type {?} */ RANGE_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return RangeValueAccessor; }), multi: true }; /** * The accessor for writing a range value and listening to changes that is used by the * {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives. * * * ### Example * ``` * <input type="range" [(ngModel)]="age" > * ``` */ var RangeValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function RangeValueAccessor(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; this.onChange = function (_) { }; this.onTouched = function () { }; } /** * @param {?} value * @return {?} */ RangeValueAccessor.prototype.writeValue = function (value) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', parseFloat(value)); }; /** * @param {?} fn * @return {?} */ RangeValueAccessor.prototype.registerOnChange = function (fn) { this.onChange = function (value) { fn(value == '' ? null : parseFloat(value)); }; }; /** * @param {?} fn * @return {?} */ RangeValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ RangeValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; RangeValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'input[type=range][formControlName],input[type=range][formControl],input[type=range][ngModel]', host: { '(change)': 'onChange($event.target.value)', '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' }, providers: [RANGE_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ RangeValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; return RangeValueAccessor; }()); var /** @type {?} */ SELECT_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return SelectControlValueAccessor; }), multi: true }; /** * @param {?} id * @param {?} value * @return {?} */ function _buildValueString(id, value) { if (id == null) return "" + value; if (!isPrimitive(value)) value = 'Object'; return (id + ": " + value).slice(0, 50); } /** * @param {?} valueString * @return {?} */ function _extractId(valueString) { return valueString.split(':')[0]; } /** * * * Used by {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} * to keep the view synced with the {@link FormControl} model. * * * * * If you have imported the {@link FormsModule} or the {@link ReactiveFormsModule}, this * value accessor will be active on any select control that has a form directive. You do * **not** need to add a special selector to activate it. * * * ### How to use select controls with form directives * * * To use a select in a template-driven form, simply add an `ngModel` and a `name` * attribute to the main `<select>` tag. * * * If your option values are simple strings, you can bind to the normal `value` property * on the option. If your option values happen to be objects (and you'd like to save the * selection in your form as an object), use `ngValue` instead: * * * {@example forms/ts/selectControl/select_control_example.ts region='Component'} * * * In reactive forms, you'll also want to add your form directive (`formControlName` or * `formControl`) on the main `<select>` tag. Like in the former example, you have the * choice of binding to the `value` or `ngValue` property on the select's options. * * * {@example forms/ts/reactiveSelectControl/reactive_select_control_example.ts region='Component'} * * * Note: We listen to the 'change' event because 'input' events aren't fired * for selects in Firefox and IE: * https://bugzilla.mozilla.org/show_bug.cgi?id=1024350 * https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/4660045/ * * * * **npm package**: `@angular/forms` * * */ var SelectControlValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function SelectControlValueAccessor(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; /** @internal */ this._optionMap = new Map(); /** @internal */ this._idCounter = 0; this.onChange = function (_) { }; this.onTouched = function () { }; } /** * @param {?} value * @return {?} */ SelectControlValueAccessor.prototype.writeValue = function (value) { this.value = value; var /** @type {?} */ valueString = _buildValueString(this._getOptionId(value), value); this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', valueString); }; /** * @param {?} fn * @return {?} */ SelectControlValueAccessor.prototype.registerOnChange = function (fn) { var _this = this; this.onChange = function (valueString) { _this.value = valueString; fn(_this._getOptionValue(valueString)); }; }; /** * @param {?} fn * @return {?} */ SelectControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ SelectControlValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; /** * @return {?} */ SelectControlValueAccessor.prototype._registerOption = function () { return (this._idCounter++).toString(); }; /** * @param {?} value * @return {?} */ SelectControlValueAccessor.prototype._getOptionId = function (value) { for (var _i = 0, _a = Array.from(this._optionMap.keys()); _i < _a.length; _i++) { var id = _a[_i]; if (looseIdentical(this._optionMap.get(id), value)) return id; } return null; }; /** * @param {?} valueString * @return {?} */ SelectControlValueAccessor.prototype._getOptionValue = function (valueString) { var /** @type {?} */ id = _extractId(valueString); return this._optionMap.has(id) ? this._optionMap.get(id) : valueString; }; SelectControlValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'select:not([multiple])[formControlName],select:not([multiple])[formControl],select:not([multiple])[ngModel]', host: { '(change)': 'onChange($event.target.value)', '(blur)': 'onTouched()' }, providers: [SELECT_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ SelectControlValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; return SelectControlValueAccessor; }()); /** * * * * * See docs for {@link SelectControlValueAccessor} for usage examples. * * */ var NgSelectOption = (function () { /** * @param {?} _element * @param {?} _renderer * @param {?} _select */ function NgSelectOption(_element, _renderer, _select) { this._element = _element; this._renderer = _renderer; this._select = _select; if (this._select) this.id = this._select._registerOption(); } Object.defineProperty(NgSelectOption.prototype, "ngValue", { /** * @param {?} value * @return {?} */ set: function (value) { if (this._select == null) return; this._select._optionMap.set(this.id, value); this._setElementValue(_buildValueString(this.id, value)); this._select.writeValue(this._select.value); }, enumerable: true, configurable: true }); Object.defineProperty(NgSelectOption.prototype, "value", { /** * @param {?} value * @return {?} */ set: function (value) { this._setElementValue(value); if (this._select) this._select.writeValue(this._select.value); }, enumerable: true, configurable: true }); /** * @param {?} value * @return {?} */ NgSelectOption.prototype._setElementValue = function (value) { this._renderer.setElementProperty(this._element.nativeElement, 'value', value); }; /** * @return {?} */ NgSelectOption.prototype.ngOnDestroy = function () { if (this._select) { this._select._optionMap.delete(this.id); this._select.writeValue(this._select.value); } }; NgSelectOption.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'option' },] }, ]; /** @nocollapse */ NgSelectOption.ctorParameters = function () { return [ { type: _angular_core.ElementRef, }, { type: _angular_core.Renderer, }, { type: SelectControlValueAccessor, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host },] }, ]; }; NgSelectOption.propDecorators = { 'ngValue': [{ type: _angular_core.Input, args: ['ngValue',] },], 'value': [{ type: _angular_core.Input, args: ['value',] },], }; return NgSelectOption; }()); var /** @type {?} */ SELECT_MULTIPLE_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: _angular_core.forwardRef(function () { return SelectMultipleControlValueAccessor; }), multi: true }; /** * @param {?} id * @param {?} value * @return {?} */ function _buildValueString$1(id, value) { if (id == null) return "" + value; if (typeof value === 'string') value = "'" + value + "'"; if (!isPrimitive(value)) value = 'Object'; return (id + ": " + value).slice(0, 50); } /** * @param {?} valueString * @return {?} */ function _extractId$1(valueString) { return valueString.split(':')[0]; } /** * The accessor for writing a value and listening to changes on a select element. * * */ var SelectMultipleControlValueAccessor = (function () { /** * @param {?} _renderer * @param {?} _elementRef */ function SelectMultipleControlValueAccessor(_renderer, _elementRef) { this._renderer = _renderer; this._elementRef = _elementRef; /** @internal */ this._optionMap = new Map(); /** @internal */ this._idCounter = 0; this.onChange = function (_) { }; this.onTouched = function () { }; } /** * @param {?} value * @return {?} */ SelectMultipleControlValueAccessor.prototype.writeValue = function (value) { var _this = this; this.value = value; var /** @type {?} */ optionSelectedStateSetter; if (Array.isArray(value)) { // convert values to ids var /** @type {?} */ ids_1 = value.map(function (v) { return _this._getOptionId(v); }); optionSelectedStateSetter = function (opt, o) { opt._setSelected(ids_1.indexOf(o.toString()) > -1); }; } else { optionSelectedStateSetter = function (opt, o) { opt._setSelected(false); }; } this._optionMap.forEach(optionSelectedStateSetter); }; /** * @param {?} fn * @return {?} */ SelectMultipleControlValueAccessor.prototype.registerOnChange = function (fn) { var _this = this; this.onChange = function (_) { var /** @type {?} */ selected = []; if (_.hasOwnProperty('selectedOptions')) { var /** @type {?} */ options = _.selectedOptions; for (var /** @type {?} */ i = 0; i < options.length; i++) { var /** @type {?} */ opt = options.item(i); var /** @type {?} */ val = _this._getOptionValue(opt.value); selected.push(val); } } else { var /** @type {?} */ options = (_.options); for (var /** @type {?} */ i = 0; i < options.length; i++) { var /** @type {?} */ opt = options.item(i); if (opt.selected) { var /** @type {?} */ val = _this._getOptionValue(opt.value); selected.push(val); } } } _this.value = selected; fn(selected); }; }; /** * @param {?} fn * @return {?} */ SelectMultipleControlValueAccessor.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; /** * @param {?} isDisabled * @return {?} */ SelectMultipleControlValueAccessor.prototype.setDisabledState = function (isDisabled) { this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled); }; /** * @param {?} value * @return {?} */ SelectMultipleControlValueAccessor.prototype._registerOption = function (value) { var /** @type {?} */ id = (this._idCounter++).toString(); this._optionMap.set(id, value); return id; }; /** * @param {?} value * @return {?} */ SelectMultipleControlValueAccessor.prototype._getOptionId = function (value) { for (var _i = 0, _a = Array.from(this._optionMap.keys()); _i < _a.length; _i++) { var id = _a[_i]; if (looseIdentical(this._optionMap.get(id)._value, value)) return id; } return null; }; /** * @param {?} valueString * @return {?} */ SelectMultipleControlValueAccessor.prototype._getOptionValue = function (valueString) { var /** @type {?} */ id = _extractId$1(valueString); return this._optionMap.has(id) ? this._optionMap.get(id)._value : valueString; }; SelectMultipleControlValueAccessor.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'select[multiple][formControlName],select[multiple][formControl],select[multiple][ngModel]', host: { '(change)': 'onChange($event.target)', '(blur)': 'onTouched()' }, providers: [SELECT_MULTIPLE_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ SelectMultipleControlValueAccessor.ctorParameters = function () { return [ { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; return SelectMultipleControlValueAccessor; }()); /** * Marks `<option>` as dynamic, so Angular can be notified when options change. * * * ### Example * * * ``` * <select multiple name="city" ngModel> * <option *ngFor="let c of cities" [value]="c"></option> * </select> * ``` */ var NgSelectMultipleOption = (function () { /** * @param {?} _element * @param {?} _renderer * @param {?} _select */ function NgSelectMultipleOption(_element, _renderer, _select) { this._element = _element; this._renderer = _renderer; this._select = _select; if (this._select) { this.id = this._select._registerOption(this); } } Object.defineProperty(NgSelectMultipleOption.prototype, "ngValue", { /** * @param {?} value * @return {?} */ set: function (value) { if (this._select == null) return; this._value = value; this._setElementValue(_buildValueString$1(this.id, value)); this._select.writeValue(this._select.value); }, enumerable: true, configurable: true }); Object.defineProperty(NgSelectMultipleOption.prototype, "value", { /** * @param {?} value * @return {?} */ set: function (value) { if (this._select) { this._value = value; this._setElementValue(_buildValueString$1(this.id, value)); this._select.writeValue(this._select.value); } else { this._setElementValue(value); } }, enumerable: true, configurable: true }); /** * @param {?} value * @return {?} */ NgSelectMultipleOption.prototype._setElementValue = function (value) { this._renderer.setElementProperty(this._element.nativeElement, 'value', value); }; /** * @param {?} selected * @return {?} */ NgSelectMultipleOption.prototype._setSelected = function (selected) { this._renderer.setElementProperty(this._element.nativeElement, 'selected', selected); }; /** * @return {?} */ NgSelectMultipleOption.prototype.ngOnDestroy = function () { if (this._select) { this._select._optionMap.delete(this.id); this._select.writeValue(this._select.value); } }; NgSelectMultipleOption.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'option' },] }, ]; /** @nocollapse */ NgSelectMultipleOption.ctorParameters = function () { return [ { type: _angular_core.ElementRef, }, { type: _angular_core.Renderer, }, { type: SelectMultipleControlValueAccessor, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host },] }, ]; }; NgSelectMultipleOption.propDecorators = { 'ngValue': [{ type: _angular_core.Input, args: ['ngValue',] },], 'value': [{ type: _angular_core.Input, args: ['value',] },], }; return NgSelectMultipleOption; }()); /** * @param {?} name * @param {?} parent * @return {?} */ function controlPath(name, parent) { return parent.path.concat([name]); } /** * @param {?} control * @param {?} dir * @return {?} */ function setUpControl(control, dir) { if (!control) _throwError(dir, 'Cannot find control with'); if (!dir.valueAccessor) _throwError(dir, 'No value accessor for form control with'); control.validator = Validators.compose([control.validator, dir.validator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); dir.valueAccessor.writeValue(control.value); // view -> model dir.valueAccessor.registerOnChange(function (newValue) { dir.viewToModelUpdate(newValue); control.markAsDirty(); control.setValue(newValue, { emitModelToViewChange: false }); }); // touched dir.valueAccessor.registerOnTouched(function () { return control.markAsTouched(); }); control.registerOnChange(function (newValue, emitModelEvent) { // control -> view dir.valueAccessor.writeValue(newValue); // control -> ngModel if (emitModelEvent) dir.viewToModelUpdate(newValue); }); if (dir.valueAccessor.setDisabledState) { control.registerOnDisabledChange(function (isDisabled) { dir.valueAccessor.setDisabledState(isDisabled); }); } // re-run validation when validator binding changes, e.g. minlength=3 -> minlength=4 dir._rawValidators.forEach(function (validator) { if (((validator)).registerOnValidatorChange) ((validator)).registerOnValidatorChange(function () { return control.updateValueAndValidity(); }); }); dir._rawAsyncValidators.forEach(function (validator) { if (((validator)).registerOnValidatorChange) ((validator)).registerOnValidatorChange(function () { return control.updateValueAndValidity(); }); }); } /** * @param {?} control * @param {?} dir * @return {?} */ function cleanUpControl(control, dir) { dir.valueAccessor.registerOnChange(function () { return _noControlError(dir); }); dir.valueAccessor.registerOnTouched(function () { return _noControlError(dir); }); dir._rawValidators.forEach(function (validator) { if (validator.registerOnValidatorChange) { validator.registerOnValidatorChange(null); } }); dir._rawAsyncValidators.forEach(function (validator) { if (validator.registerOnValidatorChange) { validator.registerOnValidatorChange(null); } }); if (control) control._clearChangeFns(); } /** * @param {?} control * @param {?} dir * @return {?} */ function setUpFormContainer(control, dir) { if (isBlank(control)) _throwError(dir, 'Cannot find control with'); control.validator = Validators.compose([control.validator, dir.validator]); control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]); } /** * @param {?} dir * @return {?} */ function _noControlError(dir) { return _throwError(dir, 'There is no FormControl instance attached to form control element with'); } /** * @param {?} dir * @param {?} message * @return {?} */ function _throwError(dir, message) { var /** @type {?} */ messageEnd; if (dir.path.length > 1) { messageEnd = "path: '" + dir.path.join(' -> ') + "'"; } else if (dir.path[0]) { messageEnd = "name: '" + dir.path + "'"; } else { messageEnd = 'unspecified name attribute'; } throw new Error(message + " " + messageEnd); } /** * @param {?} validators * @return {?} */ function composeValidators(validators) { return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null; } /** * @param {?} validators * @return {?} */ function composeAsyncValidators(validators) { return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) : null; } /** * @param {?} changes * @param {?} viewModel * @return {?} */ function isPropertyUpdated(changes, viewModel) { if (!changes.hasOwnProperty('model')) return false; var /** @type {?} */ change = changes['model']; if (change.isFirstChange()) return true; return !looseIdentical(viewModel, change.currentValue); } var /** @type {?} */ BUILTIN_ACCESSORS = [ CheckboxControlValueAccessor, RangeValueAccessor, NumberValueAccessor, SelectControlValueAccessor, SelectMultipleControlValueAccessor, RadioControlValueAccessor, ]; /** * @param {?} valueAccessor * @return {?} */ function isBuiltInAccessor(valueAccessor) { return BUILTIN_ACCESSORS.some(function (a) { return valueAccessor.constructor === a; }); } /** * @param {?} dir * @param {?} valueAccessors * @return {?} */ function selectValueAccessor(dir, valueAccessors) { if (!valueAccessors) return null; var /** @type {?} */ defaultAccessor; var /** @type {?} */ builtinAccessor; var /** @type {?} */ customAccessor; valueAccessors.forEach(function (v) { if (v.constructor === DefaultValueAccessor) { defaultAccessor = v; } else if (isBuiltInAccessor(v)) { if (builtinAccessor) _throwError(dir, 'More than one built-in value accessor matches form control with'); builtinAccessor = v; } else { if (customAccessor) _throwError(dir, 'More than one custom value accessor matches form control with'); customAccessor = v; } }); if (customAccessor) return customAccessor; if (builtinAccessor) return builtinAccessor; if (defaultAccessor) return defaultAccessor; _throwError(dir, 'No valid value accessor for form control with'); return null; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /** * This is a base class for code shared between {@link NgModelGroup} and {@link FormGroupName}. * * */ var AbstractFormGroupDirective = (function (_super) { __extends(AbstractFormGroupDirective, _super); function AbstractFormGroupDirective() { _super.apply(this, arguments); } /** * @return {?} */ AbstractFormGroupDirective.prototype.ngOnInit = function () { this._checkParentType(); this.formDirective.addFormGroup(this); }; /** * @return {?} */ AbstractFormGroupDirective.prototype.ngOnDestroy = function () { if (this.formDirective) { this.formDirective.removeFormGroup(this); } }; Object.defineProperty(AbstractFormGroupDirective.prototype, "control", { /** * Get the {@link FormGroup} backing this binding. * @return {?} */ get: function () { return this.formDirective.getFormGroup(this); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractFormGroupDirective.prototype, "path", { /** * Get the path to this control group. * @return {?} */ get: function () { return controlPath(this.name, this._parent); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractFormGroupDirective.prototype, "formDirective", { /** * Get the {@link Form} to which this group belongs. * @return {?} */ get: function () { return this._parent ? this._parent.formDirective : null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractFormGroupDirective.prototype, "validator", { /** * @return {?} */ get: function () { return composeValidators(this._validators); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractFormGroupDirective.prototype, "asyncValidator", { /** * @return {?} */ get: function () { return composeAsyncValidators(this._asyncValidators); }, enumerable: true, configurable: true }); /** * @return {?} */ AbstractFormGroupDirective.prototype._checkParentType = function () { }; return AbstractFormGroupDirective; }(ControlContainer)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$3 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var AbstractControlStatus = (function () { /** * @param {?} cd */ function AbstractControlStatus(cd) { this._cd = cd; } Object.defineProperty(AbstractControlStatus.prototype, "ngClassUntouched", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.untouched : false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlStatus.prototype, "ngClassTouched", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.touched : false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlStatus.prototype, "ngClassPristine", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.pristine : false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlStatus.prototype, "ngClassDirty", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.dirty : false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlStatus.prototype, "ngClassValid", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.valid : false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlStatus.prototype, "ngClassInvalid", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.invalid : false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControlStatus.prototype, "ngClassPending", { /** * @return {?} */ get: function () { return this._cd.control ? this._cd.control.pending : false; }, enumerable: true, configurable: true }); return AbstractControlStatus; }()); var /** @type {?} */ ngControlStatusHost = { '[class.ng-untouched]': 'ngClassUntouched', '[class.ng-touched]': 'ngClassTouched', '[class.ng-pristine]': 'ngClassPristine', '[class.ng-dirty]': 'ngClassDirty', '[class.ng-valid]': 'ngClassValid', '[class.ng-invalid]': 'ngClassInvalid', '[class.ng-pending]': 'ngClassPending', }; /** * Directive automatically applied to Angular form controls that sets CSS classes * based on control status (valid/invalid/dirty/etc). * * */ var NgControlStatus = (function (_super) { __extends$3(NgControlStatus, _super); /** * @param {?} cd */ function NgControlStatus(cd) { _super.call(this, cd); } NgControlStatus.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formControlName],[ngModel],[formControl]', host: ngControlStatusHost },] }, ]; /** @nocollapse */ NgControlStatus.ctorParameters = function () { return [ { type: NgControl, decorators: [{ type: _angular_core.Self },] }, ]; }; return NgControlStatus; }(AbstractControlStatus)); /** * Directive automatically applied to Angular form groups that sets CSS classes * based on control status (valid/invalid/dirty/etc). * * */ var NgControlStatusGroup = (function (_super) { __extends$3(NgControlStatusGroup, _super); /** * @param {?} cd */ function NgControlStatusGroup(cd) { _super.call(this, cd); } NgControlStatusGroup.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]', host: ngControlStatusHost },] }, ]; /** @nocollapse */ NgControlStatusGroup.ctorParameters = function () { return [ { type: ControlContainer, decorators: [{ type: _angular_core.Self },] }, ]; }; return NgControlStatusGroup; }(AbstractControlStatus)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$5 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /** * Use by directives and components to emit custom Events. * * * ### Examples * * * In the following example, `Zippy` alternatively emits `open` and `close` events when its * title gets clicked: * * * ``` * selector: 'zippy', * template: ` * <div class="zippy"> * <div (click)="toggle()">Toggle</div> * <div [hidden]="!visible"> * <ng-content></ng-content> * </div> * </div>`}) * export class Zippy { * visible: boolean = true; * @Output() open: EventEmitter<any> = new EventEmitter(); * @Output() close: EventEmitter<any> = new EventEmitter(); * * * toggle() { * this.visible = !this.visible; * if (this.visible) { * this.open.emit(null); * } else { * this.close.emit(null); * } * } * } * ``` * * * The events payload can be accessed by the parameter `$event` on the components output event * handler: * * * ``` * <zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy> * ``` * * * Uses Rx.Observable but provides an adapter to make it work as specified here: * https://github.com/jhusain/observable-spec * * * Once a reference implementation of the spec is available, switch to it. */ var EventEmitter = (function (_super) { __extends$5(EventEmitter, _super); /** * Creates an instance of [EventEmitter], which depending on [isAsync], * delivers events synchronously or asynchronously. * @param {?=} isAsync */ function EventEmitter(isAsync) { if (isAsync === void 0) { isAsync = false; } _super.call(this); this.__isAsync = isAsync; } /** * @param {?=} value * @return {?} */ EventEmitter.prototype.emit = function (value) { _super.prototype.next.call(this, value); }; /** * @param {?=} generatorOrNext * @param {?=} error * @param {?=} complete * @return {?} */ EventEmitter.prototype.subscribe = function (generatorOrNext, error, complete) { var /** @type {?} */ schedulerFn; var /** @type {?} */ errorFn = function (err) { return null; }; var /** @type {?} */ completeFn = function () { return null; }; if (generatorOrNext && typeof generatorOrNext === 'object') { schedulerFn = this.__isAsync ? function (value) { setTimeout(function () { return generatorOrNext.next(value); }); } : function (value) { generatorOrNext.next(value); }; if (generatorOrNext.error) { errorFn = this.__isAsync ? function (err) { setTimeout(function () { return generatorOrNext.error(err); }); } : function (err) { generatorOrNext.error(err); }; } if (generatorOrNext.complete) { completeFn = this.__isAsync ? function () { setTimeout(function () { return generatorOrNext.complete(); }); } : function () { generatorOrNext.complete(); }; } } else { schedulerFn = this.__isAsync ? function (value) { setTimeout(function () { return generatorOrNext(value); }); } : function (value) { generatorOrNext(value); }; if (error) { errorFn = this.__isAsync ? function (err) { setTimeout(function () { return error(err); }); } : function (err) { error(err); }; } if (complete) { completeFn = this.__isAsync ? function () { setTimeout(function () { return complete(); }); } : function () { complete(); }; } } return _super.prototype.subscribe.call(this, schedulerFn, errorFn, completeFn); }; return EventEmitter; }(rxjs_Subject.Subject)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$6 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /** * Indicates that a FormControl is valid, i.e. that no errors exist in the input value. */ var /** @type {?} */ VALID = 'VALID'; /** * Indicates that a FormControl is invalid, i.e. that an error exists in the input value. */ var /** @type {?} */ INVALID = 'INVALID'; /** * Indicates that a FormControl is pending, i.e. that async validation is occurring and * errors are not yet available for the input value. */ var /** @type {?} */ PENDING = 'PENDING'; /** * Indicates that a FormControl is disabled, i.e. that the control is exempt from ancestor * calculations of validity or value. */ var /** @type {?} */ DISABLED = 'DISABLED'; /** * @param {?} control * @param {?} path * @param {?} delimiter * @return {?} */ function _find(control, path, delimiter) { if (path == null) return null; if (!(path instanceof Array)) { path = ((path)).split(delimiter); } if (path instanceof Array && (path.length === 0)) return null; return ((path)).reduce(function (v, name) { if (v instanceof FormGroup) { return v.controls[name] || null; } if (v instanceof FormArray) { return v.at(/** @type {?} */ (name)) || null; } return null; }, control); } /** * @param {?} r * @return {?} */ function toObservable(r) { return isPromise(r) ? rxjs_observable_fromPromise.fromPromise(r) : r; } /** * @param {?} validator * @return {?} */ function coerceToValidator(validator) { return Array.isArray(validator) ? composeValidators(validator) : validator; } /** * @param {?} asyncValidator * @return {?} */ function coerceToAsyncValidator(asyncValidator) { return Array.isArray(asyncValidator) ? composeAsyncValidators(asyncValidator) : asyncValidator; } /** * {@link FormArray}. * * * It provides some of the shared behavior that all controls and groups of controls have, like * running validators, calculating status, and resetting state. It also defines the properties * that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be * instantiated directly. * * * @abstract */ var AbstractControl = (function () { /** * @param {?} validator * @param {?} asyncValidator */ function AbstractControl(validator, asyncValidator) { this.validator = validator; this.asyncValidator = asyncValidator; /** @internal */ this._onCollectionChange = function () { }; this._pristine = true; this._touched = false; /** @internal */ this._onDisabledChange = []; } Object.defineProperty(AbstractControl.prototype, "value", { /** * The value of the control. * @return {?} */ get: function () { return this._value; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "parent", { /** * The parent control. * @return {?} */ get: function () { return this._parent; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "status", { /** * The validation status of the control. There are four possible * validation statuses: * * * * **VALID**: control has passed all validation checks * * **INVALID**: control has failed at least one validation check * * **PENDING**: control is in the midst of conducting a validation check * * **DISABLED**: control is exempt from validation checks * * * These statuses are mutually exclusive, so a control cannot be * both valid AND invalid or invalid AND disabled. * @return {?} */ get: function () { return this._status; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "valid", { /** * A control is `valid` when its `status === VALID`. * * * In order to have this status, the control must have passed all its * validation checks. * @return {?} */ get: function () { return this._status === VALID; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "invalid", { /** * A control is `invalid` when its `status === INVALID`. * * * In order to have this status, the control must have failed * at least one of its validation checks. * @return {?} */ get: function () { return this._status === INVALID; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "pending", { /** * A control is `pending` when its `status === PENDING`. * * * In order to have this status, the control must be in the * middle of conducting a validation check. * @return {?} */ get: function () { return this._status == PENDING; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "disabled", { /** * A control is `disabled` when its `status === DISABLED`. * * * Disabled controls are exempt from validation checks and * are not included in the aggregate value of their ancestor * controls. * @return {?} */ get: function () { return this._status === DISABLED; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "enabled", { /** * A control is `enabled` as long as its `status !== DISABLED`. * * * In other words, it has a status of `VALID`, `INVALID`, or * `PENDING`. * @return {?} */ get: function () { return this._status !== DISABLED; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "errors", { /** * Returns any errors generated by failing validation. If there * are no errors, it will return null. * @return {?} */ get: function () { return this._errors; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "pristine", { /** * A control is `pristine` if the user has not yet changed * the value in the UI. * * * Note that programmatic changes to a control's value will * *not* mark it dirty. * @return {?} */ get: function () { return this._pristine; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "dirty", { /** * A control is `dirty` if the user has changed the value * in the UI. * * * Note that programmatic changes to a control's value will * *not* mark it dirty. * @return {?} */ get: function () { return !this.pristine; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "touched", { /** * A control is marked `touched` once the user has triggered * a `blur` event on it. * @return {?} */ get: function () { return this._touched; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "untouched", { /** * A control is `untouched` if the user has not yet triggered * a `blur` event on it. * @return {?} */ get: function () { return !this._touched; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "valueChanges", { /** * Emits an event every time the value of the control changes, in * the UI or programmatically. * @return {?} */ get: function () { return this._valueChanges; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractControl.prototype, "statusChanges", { /** * Emits an event every time the validation status of the control * is re-calculated. * @return {?} */ get: function () { return this._statusChanges; }, enumerable: true, configurable: true }); /** * Sets the synchronous validators that are active on this control. Calling * this will overwrite any existing sync validators. * @param {?} newValidator * @return {?} */ AbstractControl.prototype.setValidators = function (newValidator) { this.validator = coerceToValidator(newValidator); }; /** * Sets the async validators that are active on this control. Calling this * will overwrite any existing async validators. * @param {?} newValidator * @return {?} */ AbstractControl.prototype.setAsyncValidators = function (newValidator) { this.asyncValidator = coerceToAsyncValidator(newValidator); }; /** * Empties out the sync validator list. * @return {?} */ AbstractControl.prototype.clearValidators = function () { this.validator = null; }; /** * Empties out the async validator list. * @return {?} */ AbstractControl.prototype.clearAsyncValidators = function () { this.asyncValidator = null; }; /** * Marks the control as `touched`. * * * This will also mark all direct ancestors as `touched` to maintain * the model. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.markAsTouched = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._touched = true; if (this._parent && !onlySelf) { this._parent.markAsTouched({ onlySelf: onlySelf }); } }; /** * Marks the control as `untouched`. * * * If the control has any children, it will also mark all children as `untouched` * to maintain the model, and re-calculate the `touched` status of all parent * controls. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.markAsUntouched = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._touched = false; this._forEachChild(function (control) { control.markAsUntouched({ onlySelf: true }); }); if (this._parent && !onlySelf) { this._parent._updateTouched({ onlySelf: onlySelf }); } }; /** * Marks the control as `dirty`. * * * This will also mark all direct ancestors as `dirty` to maintain * the model. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.markAsDirty = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._pristine = false; if (this._parent && !onlySelf) { this._parent.markAsDirty({ onlySelf: onlySelf }); } }; /** * Marks the control as `pristine`. * * * If the control has any children, it will also mark all children as `pristine` * to maintain the model, and re-calculate the `pristine` status of all parent * controls. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.markAsPristine = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._pristine = true; this._forEachChild(function (control) { control.markAsPristine({ onlySelf: true }); }); if (this._parent && !onlySelf) { this._parent._updatePristine({ onlySelf: onlySelf }); } }; /** * Marks the control as `pending`. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.markAsPending = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._status = PENDING; if (this._parent && !onlySelf) { this._parent.markAsPending({ onlySelf: onlySelf }); } }; /** * Disables the control. This means the control will be exempt from validation checks and * excluded from the aggregate value of any parent. Its status is `DISABLED`. * * * If the control has children, all children will be disabled to maintain the model. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.disable = function (_a) { var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._status = DISABLED; this._errors = null; this._forEachChild(function (control) { control.disable({ onlySelf: true }); }); this._updateValue(); if (emitEvent !== false) { this._valueChanges.emit(this._value); this._statusChanges.emit(this._status); } this._updateAncestors(onlySelf); this._onDisabledChange.forEach(function (changeFn) { return changeFn(true); }); }; /** * Enables the control. This means the control will be included in validation checks and * the aggregate value of its parent. Its status is re-calculated based on its value and * its validators. * * * If the control has children, all children will be enabled. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.enable = function (_a) { var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._status = VALID; this._forEachChild(function (control) { control.enable({ onlySelf: true }); }); this.updateValueAndValidity({ onlySelf: true, emitEvent: emitEvent }); this._updateAncestors(onlySelf); this._onDisabledChange.forEach(function (changeFn) { return changeFn(false); }); }; /** * @param {?} onlySelf * @return {?} */ AbstractControl.prototype._updateAncestors = function (onlySelf) { if (this._parent && !onlySelf) { this._parent.updateValueAndValidity(); this._parent._updatePristine(); this._parent._updateTouched(); } }; /** * @param {?} parent * @return {?} */ AbstractControl.prototype.setParent = function (parent) { this._parent = parent; }; /** * Sets the value of the control. Abstract method (implemented in sub-classes). * @abstract * @param {?} value * @param {?=} options * @return {?} */ AbstractControl.prototype.setValue = function (value, options) { }; /** * Patches the value of the control. Abstract method (implemented in sub-classes). * @abstract * @param {?} value * @param {?=} options * @return {?} */ AbstractControl.prototype.patchValue = function (value, options) { }; /** * Resets the control. Abstract method (implemented in sub-classes). * @abstract * @param {?=} value * @param {?=} options * @return {?} */ AbstractControl.prototype.reset = function (value, options) { }; /** * Re-calculates the value and validation status of the control. * * * By default, it will also update the value and validity of its ancestors. * @param {?=} __0 * @return {?} */ AbstractControl.prototype.updateValueAndValidity = function (_a) { var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._setInitialStatus(); this._updateValue(); if (this.enabled) { this._errors = this._runValidator(); this._status = this._calculateStatus(); if (this._status === VALID || this._status === PENDING) { this._runAsyncValidator(emitEvent); } } if (emitEvent !== false) { this._valueChanges.emit(this._value); this._statusChanges.emit(this._status); } if (this._parent && !onlySelf) { this._parent.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); } }; /** * @param {?=} __0 * @return {?} */ AbstractControl.prototype._updateTreeValidity = function (_a) { var emitEvent = (_a === void 0 ? { emitEvent: true } : _a).emitEvent; this._forEachChild(function (ctrl) { return ctrl._updateTreeValidity({ emitEvent: emitEvent }); }); this.updateValueAndValidity({ onlySelf: true, emitEvent: emitEvent }); }; /** * @return {?} */ AbstractControl.prototype._setInitialStatus = function () { this._status = this._allControlsDisabled() ? DISABLED : VALID; }; /** * @return {?} */ AbstractControl.prototype._runValidator = function () { return this.validator ? this.validator(this) : null; }; /** * @param {?} emitEvent * @return {?} */ AbstractControl.prototype._runAsyncValidator = function (emitEvent) { var _this = this; if (this.asyncValidator) { this._status = PENDING; this._cancelExistingSubscription(); var /** @type {?} */ obs = toObservable(this.asyncValidator(this)); this._asyncValidationSubscription = obs.subscribe({ next: function (res) { return _this.setErrors(res, { emitEvent: emitEvent }); } }); } }; /** * @return {?} */ AbstractControl.prototype._cancelExistingSubscription = function () { if (this._asyncValidationSubscription) { this._asyncValidationSubscription.unsubscribe(); } }; /** * Sets errors on a form control. * * * This is used when validations are run manually by the user, rather than automatically. * * * Calling `setErrors` will also update the validity of the parent control. * * * ### Example * * * ``` * const login = new FormControl("someLogin"); * login.setErrors({ * "notUnique": true * }); * * * expect(login.valid).toEqual(false); * expect(login.errors).toEqual({"notUnique": true}); * * * login.setValue("someOtherLogin"); * * * expect(login.valid).toEqual(true); * ``` * @param {?} errors * @param {?=} __1 * @return {?} */ AbstractControl.prototype.setErrors = function (errors, _a) { var emitEvent = (_a === void 0 ? {} : _a).emitEvent; this._errors = errors; this._updateControlsErrors(emitEvent !== false); }; /** * Retrieves a child control given the control's name or path. * * * Paths can be passed in as an array or a string delimited by a dot. * * * To get a control nested within a `person` sub-group: * * * * `this.form.get('person.name');` * * * -OR- * * * * `this.form.get(['person', 'name']);` * @param {?} path * @return {?} */ AbstractControl.prototype.get = function (path) { return _find(this, path, '.'); }; /** * Returns true if the control with the given path has the error specified. Otherwise * returns null or undefined. * * * If no path is given, it checks for the error on the present control. * @param {?} errorCode * @param {?=} path * @return {?} */ AbstractControl.prototype.getError = function (errorCode, path) { if (path === void 0) { path = null; } var /** @type {?} */ control = path ? this.get(path) : this; return control && control._errors ? control._errors[errorCode] : null; }; /** * Returns true if the control with the given path has the error specified. Otherwise * returns false. * * * If no path is given, it checks for the error on the present control. * @param {?} errorCode * @param {?=} path * @return {?} */ AbstractControl.prototype.hasError = function (errorCode, path) { if (path === void 0) { path = null; } return !!this.getError(errorCode, path); }; Object.defineProperty(AbstractControl.prototype, "root", { /** * Retrieves the top-level ancestor of this control. * @return {?} */ get: function () { var /** @type {?} */ x = this; while (x._parent) { x = x._parent; } return x; }, enumerable: true, configurable: true }); /** * @param {?} emitEvent * @return {?} */ AbstractControl.prototype._updateControlsErrors = function (emitEvent) { this._status = this._calculateStatus(); if (emitEvent) { this._statusChanges.emit(this._status); } if (this._parent) { this._parent._updateControlsErrors(emitEvent); } }; /** * @return {?} */ AbstractControl.prototype._initObservables = function () { this._valueChanges = new EventEmitter(); this._statusChanges = new EventEmitter(); }; /** * @return {?} */ AbstractControl.prototype._calculateStatus = function () { if (this._allControlsDisabled()) return DISABLED; if (this._errors) return INVALID; if (this._anyControlsHaveStatus(PENDING)) return PENDING; if (this._anyControlsHaveStatus(INVALID)) return INVALID; return VALID; }; /** * @abstract * @return {?} */ AbstractControl.prototype._updateValue = function () { }; /** * @abstract * @param {?} cb * @return {?} */ AbstractControl.prototype._forEachChild = function (cb) { }; /** * @abstract * @param {?} condition * @return {?} */ AbstractControl.prototype._anyControls = function (condition) { }; /** * @abstract * @return {?} */ AbstractControl.prototype._allControlsDisabled = function () { }; /** * @param {?} status * @return {?} */ AbstractControl.prototype._anyControlsHaveStatus = function (status) { return this._anyControls(function (control) { return control.status === status; }); }; /** * @return {?} */ AbstractControl.prototype._anyControlsDirty = function () { return this._anyControls(function (control) { return control.dirty; }); }; /** * @return {?} */ AbstractControl.prototype._anyControlsTouched = function () { return this._anyControls(function (control) { return control.touched; }); }; /** * @param {?=} __0 * @return {?} */ AbstractControl.prototype._updatePristine = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._pristine = !this._anyControlsDirty(); if (this._parent && !onlySelf) { this._parent._updatePristine({ onlySelf: onlySelf }); } }; /** * @param {?=} __0 * @return {?} */ AbstractControl.prototype._updateTouched = function (_a) { var onlySelf = (_a === void 0 ? {} : _a).onlySelf; this._touched = this._anyControlsTouched(); if (this._parent && !onlySelf) { this._parent._updateTouched({ onlySelf: onlySelf }); } }; /** * @param {?} formState * @return {?} */ AbstractControl.prototype._isBoxedValue = function (formState) { return typeof formState === 'object' && formState !== null && Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState; }; /** * @param {?} fn * @return {?} */ AbstractControl.prototype._registerOnCollectionChange = function (fn) { this._onCollectionChange = fn; }; return AbstractControl; }()); /** * * * It is one of the three fundamental building blocks of Angular forms, along with * {@link FormGroup} and {@link FormArray}. * * * * * When instantiating a {@link FormControl}, you can pass in an initial value as the * first argument. Example: * * * ```ts * const ctrl = new FormControl('some value'); * console.log(ctrl.value); // 'some value' * *``` * * * You can also initialize the control with a form state object on instantiation, * which includes both the value and whether or not the control is disabled. * You can't use the value key without the disabled key; both are required * to use this way of initialization. * * * ```ts * const ctrl = new FormControl({value: 'n/a', disabled: true}); * console.log(ctrl.value); // 'n/a' * console.log(ctrl.status); // 'DISABLED' * ``` * * * To include a sync validator (or an array of sync validators) with the control, * pass it in as the second argument. Async validators are also supported, but * have to be passed in separately as the third arg. * * * ```ts * const ctrl = new FormControl('', Validators.required); * console.log(ctrl.value); // '' * console.log(ctrl.status); // 'INVALID' * ``` * * * See its superclass, {@link AbstractControl}, for more properties and methods. * * * * **npm package**: `@angular/forms` * * */ var FormControl = (function (_super) { __extends$6(FormControl, _super); /** * @param {?=} formState * @param {?=} validator * @param {?=} asyncValidator */ function FormControl(formState, validator, asyncValidator) { if (formState === void 0) { formState = null; } if (validator === void 0) { validator = null; } if (asyncValidator === void 0) { asyncValidator = null; } _super.call(this, coerceToValidator(validator), coerceToAsyncValidator(asyncValidator)); /** @internal */ this._onChange = []; this._applyFormState(formState); this.updateValueAndValidity({ onlySelf: true, emitEvent: false }); this._initObservables(); } /** * Set the value of the form control to `value`. * * * If `onlySelf` is `true`, this change will only affect the validation of this `FormControl` * and not its parent component. This defaults to false. * * * If `emitEvent` is `true`, this * change will cause a `valueChanges` event on the `FormControl` to be emitted. This defaults * to true (as it falls through to `updateValueAndValidity`). * * * If `emitModelToViewChange` is `true`, the view will be notified about the new value * via an `onChange` event. This is the default behavior if `emitModelToViewChange` is not * specified. * * * If `emitViewToModelChange` is `true`, an ngModelChange event will be fired to update the * model. This is the default behavior if `emitViewToModelChange` is not specified. * @param {?} value * @param {?=} __1 * @return {?} */ FormControl.prototype.setValue = function (value, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent, emitModelToViewChange = _b.emitModelToViewChange, emitViewToModelChange = _b.emitViewToModelChange; this._value = value; if (this._onChange.length && emitModelToViewChange !== false) { this._onChange.forEach(function (changeFn) { return changeFn(_this._value, emitViewToModelChange !== false); }); } this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); }; /** * Patches the value of a control. * * * This function is functionally the same as {@link FormControl.setValue} at this level. * It exists for symmetry with {@link FormGroup.patchValue} on `FormGroups` and `FormArrays`, * where it does behave differently. * @param {?} value * @param {?=} options * @return {?} */ FormControl.prototype.patchValue = function (value, options) { if (options === void 0) { options = {}; } this.setValue(value, options); }; /** * Resets the form control. This means by default: * * * * it is marked as `pristine` * * it is marked as `untouched` * * value is set to null * * * You can also reset to a specific form state by passing through a standalone * value or a form state object that contains both a value and a disabled state * (these are the only two properties that cannot be calculated). * * * Ex: * * * ```ts * this.control.reset('Nancy'); * * * console.log(this.control.value); // 'Nancy' * ``` * * * OR * * * ``` * this.control.reset({value: 'Nancy', disabled: true}); * * * console.log(this.control.value); // 'Nancy' * console.log(this.control.status); // 'DISABLED' * ``` * @param {?=} formState * @param {?=} __1 * @return {?} */ FormControl.prototype.reset = function (formState, _a) { if (formState === void 0) { formState = null; } var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._applyFormState(formState); this.markAsPristine({ onlySelf: onlySelf }); this.markAsUntouched({ onlySelf: onlySelf }); this.setValue(this._value, { onlySelf: onlySelf, emitEvent: emitEvent }); }; /** * @return {?} */ FormControl.prototype._updateValue = function () { }; /** * @param {?} condition * @return {?} */ FormControl.prototype._anyControls = function (condition) { return false; }; /** * @return {?} */ FormControl.prototype._allControlsDisabled = function () { return this.disabled; }; /** * Register a listener for change events. * @param {?} fn * @return {?} */ FormControl.prototype.registerOnChange = function (fn) { this._onChange.push(fn); }; /** * @return {?} */ FormControl.prototype._clearChangeFns = function () { this._onChange = []; this._onDisabledChange = []; this._onCollectionChange = function () { }; }; /** * Register a listener for disabled events. * @param {?} fn * @return {?} */ FormControl.prototype.registerOnDisabledChange = function (fn) { this._onDisabledChange.push(fn); }; /** * @param {?} cb * @return {?} */ FormControl.prototype._forEachChild = function (cb) { }; /** * @param {?} formState * @return {?} */ FormControl.prototype._applyFormState = function (formState) { if (this._isBoxedValue(formState)) { this._value = formState.value; formState.disabled ? this.disable({ onlySelf: true, emitEvent: false }) : this.enable({ onlySelf: true, emitEvent: false }); } else { this._value = formState; } }; return FormControl; }(AbstractControl)); /** * instances. * * * A `FormGroup` aggregates the values of each child {@link FormControl} into one object, * with each control name as the key. It calculates its status by reducing the statuses * of its children. For example, if one of the controls in a group is invalid, the entire * group becomes invalid. * * * `FormGroup` is one of the three fundamental building blocks used to define forms in Angular, * along with {@link FormControl} and {@link FormArray}. * * * * * When instantiating a {@link FormGroup}, pass in a collection of child controls as the first * argument. The key for each child will be the name under which it is registered. * * * ### Example * * * ``` * const form = new FormGroup({ * first: new FormControl('Nancy', Validators.minLength(2)), * last: new FormControl('Drew'), * }); * * * console.log(form.value); // {first: 'Nancy', last; 'Drew'} * console.log(form.status); // 'VALID' * ``` * * * You can also include group-level validators as the second arg, or group-level async * validators as the third arg. These come in handy when you want to perform validation * that considers the value of more than one child control. * * * ### Example * * * ``` * const form = new FormGroup({ * password: new FormControl('', Validators.minLength(2)), * passwordConfirm: new FormControl('', Validators.minLength(2)), * }, passwordMatchValidator); * * * * * function passwordMatchValidator(g: FormGroup) { * return g.get('password').value === g.get('passwordConfirm').value * ? null : {'mismatch': true}; * } * ``` * * * * **npm package**: `@angular/forms` * * */ var FormGroup = (function (_super) { __extends$6(FormGroup, _super); /** * @param {?} controls * @param {?=} validator * @param {?=} asyncValidator */ function FormGroup(controls, validator, asyncValidator) { if (validator === void 0) { validator = null; } if (asyncValidator === void 0) { asyncValidator = null; } _super.call(this, validator, asyncValidator); this.controls = controls; this._initObservables(); this._setUpControls(); this.updateValueAndValidity({ onlySelf: true, emitEvent: false }); } /** * Registers a control with the group's list of controls. * * * This method does not update value or validity of the control, so for * most cases you'll want to use {@link FormGroup.addControl} instead. * @param {?} name * @param {?} control * @return {?} */ FormGroup.prototype.registerControl = function (name, control) { if (this.controls[name]) return this.controls[name]; this.controls[name] = control; control.setParent(this); control._registerOnCollectionChange(this._onCollectionChange); return control; }; /** * Add a control to this group. * @param {?} name * @param {?} control * @return {?} */ FormGroup.prototype.addControl = function (name, control) { this.registerControl(name, control); this.updateValueAndValidity(); this._onCollectionChange(); }; /** * Remove a control from this group. * @param {?} name * @return {?} */ FormGroup.prototype.removeControl = function (name) { if (this.controls[name]) this.controls[name]._registerOnCollectionChange(function () { }); delete (this.controls[name]); this.updateValueAndValidity(); this._onCollectionChange(); }; /** * Replace an existing control. * @param {?} name * @param {?} control * @return {?} */ FormGroup.prototype.setControl = function (name, control) { if (this.controls[name]) this.controls[name]._registerOnCollectionChange(function () { }); delete (this.controls[name]); if (control) this.registerControl(name, control); this.updateValueAndValidity(); this._onCollectionChange(); }; /** * Check whether there is an enabled control with the given name in the group. * * * It will return false for disabled controls. If you'd like to check for * existence in the group only, use {@link AbstractControl.get} instead. * @param {?} controlName * @return {?} */ FormGroup.prototype.contains = function (controlName) { return this.controls.hasOwnProperty(controlName) && this.controls[controlName].enabled; }; /** * Sets the value of the {@link FormGroup}. It accepts an object that matches * the structure of the group, with control names as keys. * * * This method performs strict checks, so it will throw an error if you try * to set the value of a control that doesn't exist or if you exclude the * value of a control. * * * ### Example * * * ``` * const form = new FormGroup({ * first: new FormControl(), * last: new FormControl() * }); * console.log(form.value); // {first: null, last: null} * * * form.setValue({first: 'Nancy', last: 'Drew'}); * console.log(form.value); // {first: 'Nancy', last: 'Drew'} * * * ``` * @param {?} value * @param {?=} __1 * @return {?} */ FormGroup.prototype.setValue = function (value, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._checkAllValuesPresent(value); Object.keys(value).forEach(function (name) { _this._throwIfControlMissing(name); _this.controls[name].setValue(value[name], { onlySelf: true, emitEvent: emitEvent }); }); this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); }; /** * Patches the value of the {@link FormGroup}. It accepts an object with control * names as keys, and will do its best to match the values to the correct controls * in the group. * * * It accepts both super-sets and sub-sets of the group without throwing an error. * * * ### Example * * * ``` * const form = new FormGroup({ * first: new FormControl(), * last: new FormControl() * }); * console.log(form.value); // {first: null, last: null} * * * form.patchValue({first: 'Nancy'}); * console.log(form.value); // {first: 'Nancy', last: null} * * * ``` * @param {?} value * @param {?=} __1 * @return {?} */ FormGroup.prototype.patchValue = function (value, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; Object.keys(value).forEach(function (name) { if (_this.controls[name]) { _this.controls[name].patchValue(value[name], { onlySelf: true, emitEvent: emitEvent }); } }); this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); }; /** * Resets the {@link FormGroup}. This means by default: * * * * The group and all descendants are marked `pristine` * * The group and all descendants are marked `untouched` * * The value of all descendants will be null or null maps * * * You can also reset to a specific form state by passing in a map of states * that matches the structure of your form, with control names as keys. The state * can be a standalone value or a form state object with both a value and a disabled * status. * * * ### Example * * * ```ts * this.form.reset({first: 'name', last: 'last name'}); * * * console.log(this.form.value); // {first: 'name', last: 'last name'} * ``` * * * - OR - * * * ``` * this.form.reset({ * first: {value: 'name', disabled: true}, * last: 'last' * }); * * * console.log(this.form.value); // {first: 'name', last: 'last name'} * console.log(this.form.get('first').status); // 'DISABLED' * ``` * @param {?=} value * @param {?=} __1 * @return {?} */ FormGroup.prototype.reset = function (value, _a) { if (value === void 0) { value = {}; } var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._forEachChild(function (control, name) { control.reset(value[name], { onlySelf: true, emitEvent: emitEvent }); }); this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); this._updatePristine({ onlySelf: onlySelf }); this._updateTouched({ onlySelf: onlySelf }); }; /** * The aggregate value of the {@link FormGroup}, including any disabled controls. * * * If you'd like to include all values regardless of disabled status, use this method. * Otherwise, the `value` property is the best way to get the value of the group. * @return {?} */ FormGroup.prototype.getRawValue = function () { return this._reduceChildren({}, function (acc, control, name) { acc[name] = control.value; return acc; }); }; /** * @param {?} name * @return {?} */ FormGroup.prototype._throwIfControlMissing = function (name) { if (!Object.keys(this.controls).length) { throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n "); } if (!this.controls[name]) { throw new Error("Cannot find form control with name: " + name + "."); } }; /** * @param {?} cb * @return {?} */ FormGroup.prototype._forEachChild = function (cb) { var _this = this; Object.keys(this.controls).forEach(function (k) { return cb(_this.controls[k], k); }); }; /** * @return {?} */ FormGroup.prototype._setUpControls = function () { var _this = this; this._forEachChild(function (control) { control.setParent(_this); control._registerOnCollectionChange(_this._onCollectionChange); }); }; /** * @return {?} */ FormGroup.prototype._updateValue = function () { this._value = this._reduceValue(); }; /** * @param {?} condition * @return {?} */ FormGroup.prototype._anyControls = function (condition) { var _this = this; var /** @type {?} */ res = false; this._forEachChild(function (control, name) { res = res || (_this.contains(name) && condition(control)); }); return res; }; /** * @return {?} */ FormGroup.prototype._reduceValue = function () { var _this = this; return this._reduceChildren({}, function (acc, control, name) { if (control.enabled || _this.disabled) { acc[name] = control.value; } return acc; }); }; /** * @param {?} initValue * @param {?} fn * @return {?} */ FormGroup.prototype._reduceChildren = function (initValue, fn) { var /** @type {?} */ res = initValue; this._forEachChild(function (control, name) { res = fn(res, control, name); }); return res; }; /** * @return {?} */ FormGroup.prototype._allControlsDisabled = function () { for (var _i = 0, _a = Object.keys(this.controls); _i < _a.length; _i++) { var controlName = _a[_i]; if (this.controls[controlName].enabled) { return false; } } return Object.keys(this.controls).length > 0 || this.disabled; }; /** * @param {?} value * @return {?} */ FormGroup.prototype._checkAllValuesPresent = function (value) { this._forEachChild(function (control, name) { if (value[name] === undefined) { throw new Error("Must supply a value for form control with name: '" + name + "'."); } }); }; return FormGroup; }(AbstractControl)); /** * instances. * * * A `FormArray` aggregates the values of each child {@link FormControl} into an array. * It calculates its status by reducing the statuses of its children. For example, if one of * the controls in a `FormArray` is invalid, the entire array becomes invalid. * * * `FormArray` is one of the three fundamental building blocks used to define forms in Angular, * along with {@link FormControl} and {@link FormGroup}. * * * * * When instantiating a {@link FormArray}, pass in an array of child controls as the first * argument. * * * ### Example * * * ``` * const arr = new FormArray([ * new FormControl('Nancy', Validators.minLength(2)), * new FormControl('Drew'), * ]); * * * console.log(arr.value); // ['Nancy', 'Drew'] * console.log(arr.status); // 'VALID' * ``` * * * You can also include array-level validators as the second arg, or array-level async * validators as the third arg. These come in handy when you want to perform validation * that considers the value of more than one child control. * * * ### Adding or removing controls * * * To change the controls in the array, use the `push`, `insert`, or `removeAt` methods * in `FormArray` itself. These methods ensure the controls are properly tracked in the * form's hierarchy. Do not modify the array of `AbstractControl`s used to instantiate * the `FormArray` directly, as that will result in strange and unexpected behavior such * as broken change detection. * * * * **npm package**: `@angular/forms` * * */ var FormArray = (function (_super) { __extends$6(FormArray, _super); /** * @param {?} controls * @param {?=} validator * @param {?=} asyncValidator */ function FormArray(controls, validator, asyncValidator) { if (validator === void 0) { validator = null; } if (asyncValidator === void 0) { asyncValidator = null; } _super.call(this, validator, asyncValidator); this.controls = controls; this._initObservables(); this._setUpControls(); this.updateValueAndValidity({ onlySelf: true, emitEvent: false }); } /** * Get the {@link AbstractControl} at the given `index` in the array. * @param {?} index * @return {?} */ FormArray.prototype.at = function (index) { return this.controls[index]; }; /** * Insert a new {@link AbstractControl} at the end of the array. * @param {?} control * @return {?} */ FormArray.prototype.push = function (control) { this.controls.push(control); this._registerControl(control); this.updateValueAndValidity(); this._onCollectionChange(); }; /** * Insert a new {@link AbstractControl} at the given `index` in the array. * @param {?} index * @param {?} control * @return {?} */ FormArray.prototype.insert = function (index, control) { this.controls.splice(index, 0, control); this._registerControl(control); this.updateValueAndValidity(); this._onCollectionChange(); }; /** * Remove the control at the given `index` in the array. * @param {?} index * @return {?} */ FormArray.prototype.removeAt = function (index) { if (this.controls[index]) this.controls[index]._registerOnCollectionChange(function () { }); this.controls.splice(index, 1); this.updateValueAndValidity(); this._onCollectionChange(); }; /** * Replace an existing control. * @param {?} index * @param {?} control * @return {?} */ FormArray.prototype.setControl = function (index, control) { if (this.controls[index]) this.controls[index]._registerOnCollectionChange(function () { }); this.controls.splice(index, 1); if (control) { this.controls.splice(index, 0, control); this._registerControl(control); } this.updateValueAndValidity(); this._onCollectionChange(); }; Object.defineProperty(FormArray.prototype, "length", { /** * Length of the control array. * @return {?} */ get: function () { return this.controls.length; }, enumerable: true, configurable: true }); /** * Sets the value of the {@link FormArray}. It accepts an array that matches * the structure of the control. * * * This method performs strict checks, so it will throw an error if you try * to set the value of a control that doesn't exist or if you exclude the * value of a control. * * * ### Example * * * ``` * const arr = new FormArray([ * new FormControl(), * new FormControl() * ]); * console.log(arr.value); // [null, null] * * * arr.setValue(['Nancy', 'Drew']); * console.log(arr.value); // ['Nancy', 'Drew'] * ``` * @param {?} value * @param {?=} __1 * @return {?} */ FormArray.prototype.setValue = function (value, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._checkAllValuesPresent(value); value.forEach(function (newValue, index) { _this._throwIfControlMissing(index); _this.at(index).setValue(newValue, { onlySelf: true, emitEvent: emitEvent }); }); this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); }; /** * Patches the value of the {@link FormArray}. It accepts an array that matches the * structure of the control, and will do its best to match the values to the correct * controls in the group. * * * It accepts both super-sets and sub-sets of the array without throwing an error. * * * ### Example * * * ``` * const arr = new FormArray([ * new FormControl(), * new FormControl() * ]); * console.log(arr.value); // [null, null] * * * arr.patchValue(['Nancy']); * console.log(arr.value); // ['Nancy', null] * ``` * @param {?} value * @param {?=} __1 * @return {?} */ FormArray.prototype.patchValue = function (value, _a) { var _this = this; var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; value.forEach(function (newValue, index) { if (_this.at(index)) { _this.at(index).patchValue(newValue, { onlySelf: true, emitEvent: emitEvent }); } }); this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); }; /** * Resets the {@link FormArray}. This means by default: * * * * The array and all descendants are marked `pristine` * * The array and all descendants are marked `untouched` * * The value of all descendants will be null or null maps * * * You can also reset to a specific form state by passing in an array of states * that matches the structure of the control. The state can be a standalone value * or a form state object with both a value and a disabled status. * * * ### Example * * * ```ts * this.arr.reset(['name', 'last name']); * * * console.log(this.arr.value); // ['name', 'last name'] * ``` * * * - OR - * * * ``` * this.arr.reset([ * {value: 'name', disabled: true}, * 'last' * ]); * * * console.log(this.arr.value); // ['name', 'last name'] * console.log(this.arr.get(0).status); // 'DISABLED' * ``` * @param {?=} value * @param {?=} __1 * @return {?} */ FormArray.prototype.reset = function (value, _a) { if (value === void 0) { value = []; } var _b = _a === void 0 ? {} : _a, onlySelf = _b.onlySelf, emitEvent = _b.emitEvent; this._forEachChild(function (control, index) { control.reset(value[index], { onlySelf: true, emitEvent: emitEvent }); }); this.updateValueAndValidity({ onlySelf: onlySelf, emitEvent: emitEvent }); this._updatePristine({ onlySelf: onlySelf }); this._updateTouched({ onlySelf: onlySelf }); }; /** * The aggregate value of the array, including any disabled controls. * * * If you'd like to include all values regardless of disabled status, use this method. * Otherwise, the `value` property is the best way to get the value of the array. * @return {?} */ FormArray.prototype.getRawValue = function () { return this.controls.map(function (control) { return control.value; }); }; /** * @param {?} index * @return {?} */ FormArray.prototype._throwIfControlMissing = function (index) { if (!this.controls.length) { throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n "); } if (!this.at(index)) { throw new Error("Cannot find form control at index " + index); } }; /** * @param {?} cb * @return {?} */ FormArray.prototype._forEachChild = function (cb) { this.controls.forEach(function (control, index) { cb(control, index); }); }; /** * @return {?} */ FormArray.prototype._updateValue = function () { var _this = this; this._value = this.controls.filter(function (control) { return control.enabled || _this.disabled; }) .map(function (control) { return control.value; }); }; /** * @param {?} condition * @return {?} */ FormArray.prototype._anyControls = function (condition) { return this.controls.some(function (control) { return control.enabled && condition(control); }); }; /** * @return {?} */ FormArray.prototype._setUpControls = function () { var _this = this; this._forEachChild(function (control) { return _this._registerControl(control); }); }; /** * @param {?} value * @return {?} */ FormArray.prototype._checkAllValuesPresent = function (value) { this._forEachChild(function (control, i) { if (value[i] === undefined) { throw new Error("Must supply a value for form control at index: " + i + "."); } }); }; /** * @return {?} */ FormArray.prototype._allControlsDisabled = function () { for (var _i = 0, _a = this.controls; _i < _a.length; _i++) { var control = _a[_i]; if (control.enabled) return false; } return this.controls.length > 0 || this.disabled; }; /** * @param {?} control * @return {?} */ FormArray.prototype._registerControl = function (control) { control.setParent(this); control._registerOnCollectionChange(this._onCollectionChange); }; return FormArray; }(AbstractControl)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$4 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ formDirectiveProvider = { provide: ControlContainer, useExisting: _angular_core.forwardRef(function () { return NgForm; }) }; var /** @type {?} */ resolvedPromise = Promise.resolve(null); /** * to track aggregate form value and validation status. * * * * * As soon as you import the `FormsModule`, this directive becomes active by default on * all `<form>` tags. You don't need to add a special selector. * * * You can export the directive into a local template variable using `ngForm` as the key * (ex: `#myForm="ngForm"`). This is optional, but useful. Many properties from the underlying * {@link FormGroup} instance are duplicated on the directive itself, so a reference to it * will give you access to the aggregate value and validity status of the form, as well as * user interaction properties like `dirty` and `touched`. * * * To register child controls with the form, you'll want to use {@link NgModel} with a * `name` attribute. You can also use {@link NgModelGroup} if you'd like to create * sub-groups within the form. * * * You can listen to the directive's `ngSubmit` event to be notified when the user has * triggered a form submission. The `ngSubmit` event will be emitted with the original form * submission event. * * * {@example forms/ts/simpleForm/simple_form_example.ts region='Component'} * * * * **npm package**: `@angular/forms` * * * * **NgModule**: `FormsModule` * * * @stable */ var NgForm = (function (_super) { __extends$4(NgForm, _super); /** * @param {?} validators * @param {?} asyncValidators */ function NgForm(validators, asyncValidators) { _super.call(this); this._submitted = false; this.ngSubmit = new EventEmitter(); this.form = new FormGroup({}, composeValidators(validators), composeAsyncValidators(asyncValidators)); } Object.defineProperty(NgForm.prototype, "submitted", { /** * @return {?} */ get: function () { return this._submitted; }, enumerable: true, configurable: true }); Object.defineProperty(NgForm.prototype, "formDirective", { /** * @return {?} */ get: function () { return this; }, enumerable: true, configurable: true }); Object.defineProperty(NgForm.prototype, "control", { /** * @return {?} */ get: function () { return this.form; }, enumerable: true, configurable: true }); Object.defineProperty(NgForm.prototype, "path", { /** * @return {?} */ get: function () { return []; }, enumerable: true, configurable: true }); Object.defineProperty(NgForm.prototype, "controls", { /** * @return {?} */ get: function () { return this.form.controls; }, enumerable: true, configurable: true }); /** * @param {?} dir * @return {?} */ NgForm.prototype.addControl = function (dir) { var _this = this; resolvedPromise.then(function () { var /** @type {?} */ container = _this._findContainer(dir.path); dir._control = (container.registerControl(dir.name, dir.control)); setUpControl(dir.control, dir); dir.control.updateValueAndValidity({ emitEvent: false }); }); }; /** * @param {?} dir * @return {?} */ NgForm.prototype.getControl = function (dir) { return (this.form.get(dir.path)); }; /** * @param {?} dir * @return {?} */ NgForm.prototype.removeControl = function (dir) { var _this = this; resolvedPromise.then(function () { var /** @type {?} */ container = _this._findContainer(dir.path); if (container) { container.removeControl(dir.name); } }); }; /** * @param {?} dir * @return {?} */ NgForm.prototype.addFormGroup = function (dir) { var _this = this; resolvedPromise.then(function () { var /** @type {?} */ container = _this._findContainer(dir.path); var /** @type {?} */ group = new FormGroup({}); setUpFormContainer(group, dir); container.registerControl(dir.name, group); group.updateValueAndValidity({ emitEvent: false }); }); }; /** * @param {?} dir * @return {?} */ NgForm.prototype.removeFormGroup = function (dir) { var _this = this; resolvedPromise.then(function () { var /** @type {?} */ container = _this._findContainer(dir.path); if (container) { container.removeControl(dir.name); } }); }; /** * @param {?} dir * @return {?} */ NgForm.prototype.getFormGroup = function (dir) { return (this.form.get(dir.path)); }; /** * @param {?} dir * @param {?} value * @return {?} */ NgForm.prototype.updateModel = function (dir, value) { var _this = this; resolvedPromise.then(function () { var /** @type {?} */ ctrl = (_this.form.get(dir.path)); ctrl.setValue(value); }); }; /** * @param {?} value * @return {?} */ NgForm.prototype.setValue = function (value) { this.control.setValue(value); }; /** * @param {?} $event * @return {?} */ NgForm.prototype.onSubmit = function ($event) { this._submitted = true; this.ngSubmit.emit($event); return false; }; /** * @return {?} */ NgForm.prototype.onReset = function () { this.resetForm(); }; /** * @param {?=} value * @return {?} */ NgForm.prototype.resetForm = function (value) { if (value === void 0) { value = undefined; } this.form.reset(value); this._submitted = false; }; /** * @param {?} path * @return {?} */ NgForm.prototype._findContainer = function (path) { path.pop(); return path.length ? (this.form.get(path)) : this.form; }; NgForm.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]', providers: [formDirectiveProvider], host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' }, outputs: ['ngSubmit'], exportAs: 'ngForm' },] }, ]; /** @nocollapse */ NgForm.ctorParameters = function () { return [ { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, ]; }; return NgForm; }(ControlContainer)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var /** @type {?} */ Examples = { formControlName: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });", formGroupName: "\n <div [formGroup]=\"myGroup\">\n <div formGroupName=\"person\">\n <input formControlName=\"firstName\">\n </div>\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });", formArrayName: "\n <div [formGroup]=\"myGroup\">\n <div formArrayName=\"cities\">\n <div *ngFor=\"let city of cityArray.controls; let i=index\">\n <input [formControlName]=\"i\">\n </div>\n </div>\n </div>\n\n In your class:\n\n this.cityArray = new FormArray([new FormControl('SF')]);\n this.myGroup = new FormGroup({\n cities: this.cityArray\n });", ngModelGroup: "\n <form>\n <div ngModelGroup=\"person\">\n <input [(ngModel)]=\"person.name\" name=\"firstName\">\n </div>\n </form>", ngModelWithFormGroup: "\n <div [formGroup]=\"myGroup\">\n <input formControlName=\"firstName\">\n <input [(ngModel)]=\"showMoreControls\" [ngModelOptions]=\"{standalone: true}\">\n </div>\n " }; var TemplateDrivenErrors = (function () { function TemplateDrivenErrors() { } /** * @return {?} */ TemplateDrivenErrors.modelParentException = function () { throw new Error("\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup's partner directive \"formControlName\" instead. Example:\n\n " + Examples.formControlName + "\n\n Or, if you'd like to avoid registering this form control, indicate that it's standalone in ngModelOptions:\n\n Example:\n\n " + Examples.ngModelWithFormGroup); }; /** * @return {?} */ TemplateDrivenErrors.formGroupNameException = function () { throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n " + Examples.formGroupName + "\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n " + Examples.ngModelGroup); }; /** * @return {?} */ TemplateDrivenErrors.missingNameException = function () { throw new Error("If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as 'standalone' in ngModelOptions.\n\n Example 1: <input [(ngModel)]=\"person.firstName\" name=\"first\">\n Example 2: <input [(ngModel)]=\"person.firstName\" [ngModelOptions]=\"{standalone: true}\">"); }; /** * @return {?} */ TemplateDrivenErrors.modelGroupParentException = function () { throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n " + Examples.formGroupName + "\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n " + Examples.ngModelGroup); }; return TemplateDrivenErrors; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$8 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ modelGroupProvider = { provide: ControlContainer, useExisting: _angular_core.forwardRef(function () { return NgModelGroup; }) }; /** * * * * * This directive can only be used as a child of {@link NgForm} (or in other words, * within `<form>` tags). * * * Use this directive if you'd like to create a sub-group within a form. This can * come in handy if you want to validate a sub-group of your form separately from * the rest of your form, or if some values in your domain model make more sense to * consume together in a nested object. * * * Pass in the name you'd like this sub-group to have and it will become the key * for the sub-group in the form's full value. You can also export the directive into * a local template variable using `ngModelGroup` (ex: `#myGroup="ngModelGroup"`). * * * {@example forms/ts/ngModelGroup/ng_model_group_example.ts region='Component'} * * * * **npm package**: `@angular/forms` * * * * **NgModule**: `FormsModule` * * */ var NgModelGroup = (function (_super) { __extends$8(NgModelGroup, _super); /** * @param {?} parent * @param {?} validators * @param {?} asyncValidators */ function NgModelGroup(parent, validators, asyncValidators) { _super.call(this); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** * @return {?} */ NgModelGroup.prototype._checkParentType = function () { if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) { TemplateDrivenErrors.modelGroupParentException(); } }; NgModelGroup.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[ngModelGroup]', providers: [modelGroupProvider], exportAs: 'ngModelGroup' },] }, ]; /** @nocollapse */ NgModelGroup.ctorParameters = function () { return [ { type: ControlContainer, decorators: [{ type: _angular_core.Host }, { type: _angular_core.SkipSelf },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, ]; }; NgModelGroup.propDecorators = { 'name': [{ type: _angular_core.Input, args: ['ngModelGroup',] },], }; return NgModelGroup; }(AbstractFormGroupDirective)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$7 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ formControlBinding = { provide: NgControl, useExisting: _angular_core.forwardRef(function () { return NgModel; }) }; /** * `ngModel` forces an additional change detection run when its inputs change: * E.g.: * ``` * <div>{{myModel.valid}}</div> * <input [(ngModel)]="myValue" #myModel="ngModel"> * ``` * I.e. `ngModel` can export itself on the element and then be used in the template. * Normally, this would result in expressions before the `input` that use the exported directive * to have and old value as they have been * dirty checked before. As this is a very common case for `ngModel`, we added this second change * detection run. * * Notes: * - this is just one extra run no matter how many `ngModel` have been changed. * - this is a general problem when using `exportAs` for directives! */ var /** @type {?} */ resolvedPromise$1 = Promise.resolve(null); /** * to a form control element. * * * The {@link FormControl} instance will track the value, user interaction, and * validation status of the control and keep the view synced with the model. If used * within a parent form, the directive will also register itself with the form as a child * control. * * * * * This directive can be used by itself or as part of a larger form. All you need is the * `ngModel` selector to activate it. * * * It accepts a domain model as an optional {@link @Input}. If you have a one-way binding * to `ngModel` with `[]` syntax, changing the value of the domain model in the component * class will set the value in the view. If you have a two-way binding with `[()]` syntax * (also known as 'banana-box syntax'), the value in the UI will always be synced back to * the domain model in your class as well. * * * If you wish to inspect the properties of the associated {@link FormControl} (like * validity state), you can also export the directive into a local template variable using * `ngModel` as the key (ex: `#myVar="ngModel"`). You can then access the control using the * directive's `control` property, but most properties you'll need (like `valid` and `dirty`) * will fall through to the control anyway, so you can access them directly. You can see a * full list of properties directly available in {@link AbstractControlDirective}. * * * The following is an example of a simple standalone control using `ngModel`: * * * {@example forms/ts/simpleNgModel/simple_ng_model_example.ts region='Component'} * * * When using the `ngModel` within `<form>` tags, you'll also need to supply a `name` attribute * so that the control can be registered with the parent form under that name. * * * It's worth noting that in the context of a parent form, you often can skip one-way or * two-way binding because the parent form will sync the value for you. You can access * its properties by exporting it into a local template variable using `ngForm` (ex: * `#f="ngForm"`). Then you can pass it where it needs to go on submit. * * * If you do need to populate initial values into your form, using a one-way binding for * `ngModel` tends to be sufficient as long as you use the exported form's value rather * than the domain model's value on submit. * * * Take a look at an example of using `ngModel` within a form: * * * {@example forms/ts/simpleForm/simple_form_example.ts region='Component'} * * * To see `ngModel` examples with different form control types, see: * * * * Radio buttons: {@link RadioControlValueAccessor} * * Selects: {@link SelectControlValueAccessor} * * * **npm package**: `@angular/forms` * * * **NgModule**: `FormsModule` * * * @stable */ var NgModel = (function (_super) { __extends$7(NgModel, _super); /** * @param {?} parent * @param {?} validators * @param {?} asyncValidators * @param {?} valueAccessors */ function NgModel(parent, validators, asyncValidators, valueAccessors) { _super.call(this); /** @internal */ this._control = new FormControl(); /** @internal */ this._registered = false; this.update = new EventEmitter(); this._parent = parent; this._rawValidators = validators || []; this._rawAsyncValidators = asyncValidators || []; this.valueAccessor = selectValueAccessor(this, valueAccessors); } /** * @param {?} changes * @return {?} */ NgModel.prototype.ngOnChanges = function (changes) { this._checkForErrors(); if (!this._registered) this._setUpControl(); if ('isDisabled' in changes) { this._updateDisabled(changes); } if (isPropertyUpdated(changes, this.viewModel)) { this._updateValue(this.model); this.viewModel = this.model; } }; /** * @return {?} */ NgModel.prototype.ngOnDestroy = function () { this.formDirective && this.formDirective.removeControl(this); }; Object.defineProperty(NgModel.prototype, "control", { /** * @return {?} */ get: function () { return this._control; }, enumerable: true, configurable: true }); Object.defineProperty(NgModel.prototype, "path", { /** * @return {?} */ get: function () { return this._parent ? controlPath(this.name, this._parent) : [this.name]; }, enumerable: true, configurable: true }); Object.defineProperty(NgModel.prototype, "formDirective", { /** * @return {?} */ get: function () { return this._parent ? this._parent.formDirective : null; }, enumerable: true, configurable: true }); Object.defineProperty(NgModel.prototype, "validator", { /** * @return {?} */ get: function () { return composeValidators(this._rawValidators); }, enumerable: true, configurable: true }); Object.defineProperty(NgModel.prototype, "asyncValidator", { /** * @return {?} */ get: function () { return composeAsyncValidators(this._rawAsyncValidators); }, enumerable: true, configurable: true }); /** * @param {?} newValue * @return {?} */ NgModel.prototype.viewToModelUpdate = function (newValue) { this.viewModel = newValue; this.update.emit(newValue); }; /** * @return {?} */ NgModel.prototype._setUpControl = function () { this._isStandalone() ? this._setUpStandalone() : this.formDirective.addControl(this); this._registered = true; }; /** * @return {?} */ NgModel.prototype._isStandalone = function () { return !this._parent || (this.options && this.options.standalone); }; /** * @return {?} */ NgModel.prototype._setUpStandalone = function () { setUpControl(this._control, this); this._control.updateValueAndValidity({ emitEvent: false }); }; /** * @return {?} */ NgModel.prototype._checkForErrors = function () { if (!this._isStandalone()) { this._checkParentType(); } this._checkName(); }; /** * @return {?} */ NgModel.prototype._checkParentType = function () { if (!(this._parent instanceof NgModelGroup) && this._parent instanceof AbstractFormGroupDirective) { TemplateDrivenErrors.formGroupNameException(); } else if (!(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) { TemplateDrivenErrors.modelParentException(); } }; /** * @return {?} */ NgModel.prototype._checkName = function () { if (this.options && this.options.name) this.name = this.options.name; if (!this._isStandalone() && !this.name) { TemplateDrivenErrors.missingNameException(); } }; /** * @param {?} value * @return {?} */ NgModel.prototype._updateValue = function (value) { var _this = this; resolvedPromise$1.then(function () { _this.control.setValue(value, { emitViewToModelChange: false }); }); }; /** * @param {?} changes * @return {?} */ NgModel.prototype._updateDisabled = function (changes) { var _this = this; var /** @type {?} */ disabledValue = changes['isDisabled'].currentValue; var /** @type {?} */ isDisabled = disabledValue === '' || (disabledValue && disabledValue !== 'false'); resolvedPromise$1.then(function () { if (isDisabled && !_this.control.disabled) { _this.control.disable(); } else if (!isDisabled && _this.control.disabled) { _this.control.enable(); } }); }; NgModel.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[ngModel]:not([formControlName]):not([formControl])', providers: [formControlBinding], exportAs: 'ngModel' },] }, ]; /** @nocollapse */ NgModel.ctorParameters = function () { return [ { type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALUE_ACCESSOR,] },] }, ]; }; NgModel.propDecorators = { 'name': [{ type: _angular_core.Input },], 'isDisabled': [{ type: _angular_core.Input, args: ['disabled',] },], 'model': [{ type: _angular_core.Input, args: ['ngModel',] },], 'options': [{ type: _angular_core.Input, args: ['ngModelOptions',] },], 'update': [{ type: _angular_core.Output, args: ['ngModelChange',] },], }; return NgModel; }(NgControl)); var ReactiveErrors = (function () { function ReactiveErrors() { } /** * @return {?} */ ReactiveErrors.controlParentException = function () { throw new Error("formControlName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + Examples.formControlName); }; /** * @return {?} */ ReactiveErrors.ngModelGroupException = function () { throw new Error("formControlName cannot be used with an ngModelGroup parent. It is only compatible with parents\n that also have a \"form\" prefix: formGroupName, formArrayName, or formGroup.\n\n Option 1: Update the parent to be formGroupName (reactive form strategy)\n\n " + Examples.formGroupName + "\n\n Option 2: Use ngModel instead of formControlName (template-driven strategy)\n\n " + Examples.ngModelGroup); }; /** * @return {?} */ ReactiveErrors.missingFormException = function () { throw new Error("formGroup expects a FormGroup instance. Please pass one in.\n\n Example:\n\n " + Examples.formControlName); }; /** * @return {?} */ ReactiveErrors.groupParentException = function () { throw new Error("formGroupName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + Examples.formGroupName); }; /** * @return {?} */ ReactiveErrors.arrayParentException = function () { throw new Error("formArrayName must be used with a parent formGroup directive. You'll want to add a formGroup\n directive and pass it an existing FormGroup instance (you can create one in your class).\n\n Example:\n\n " + Examples.formArrayName); }; /** * @return {?} */ ReactiveErrors.disabledAttrWarning = function () { console.warn("\n It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true\n when you set up this control in your component class, the disabled attribute will actually be set in the DOM for\n you. We recommend using this approach to avoid 'changed after checked' errors.\n \n Example: \n form = new FormGroup({\n first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),\n last: new FormControl('Drew', Validators.required)\n });\n "); }; return ReactiveErrors; }()); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$9 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ formControlBinding$1 = { provide: NgControl, useExisting: _angular_core.forwardRef(function () { return FormControlDirective; }) }; /** * * * In other words, this directive ensures that any values written to the {@link FormControl} * instance programmatically will be written to the DOM element (model -> view). Conversely, * any values written to the DOM element through user input will be reflected in the * {@link FormControl} instance (view -> model). * * * * * Use this directive if you'd like to create and manage a {@link FormControl} instance directly. * Simply create a {@link FormControl}, save it to your component class, and pass it into the * {@link FormControlDirective}. * * * This directive is designed to be used as a standalone control. Unlike {@link FormControlName}, * it does not require that your {@link FormControl} instance be part of any parent * {@link FormGroup}, and it won't be registered to any {@link FormGroupDirective} that * exists above it. * * * **Get the value**: the `value` property is always synced and available on the * {@link FormControl} instance. See a full list of available properties in * {@link AbstractControl}. * * * **Set the value**: You can pass in an initial value when instantiating the {@link FormControl}, * or you can set it programmatically later using {@link AbstractControl.setValue} or * {@link AbstractControl.patchValue}. * * * **Listen to value**: If you want to listen to changes in the value of the control, you can * subscribe to the {@link AbstractControl.valueChanges} event. You can also listen to * {@link AbstractControl.statusChanges} to be notified when the validation status is * re-calculated. * * * ### Example * * * {@example forms/ts/simpleFormControl/simple_form_control_example.ts region='Component'} * * * * **npm package**: `@angular/forms` * * * * **NgModule**: `ReactiveFormsModule` * * * @stable */ var FormControlDirective = (function (_super) { __extends$9(FormControlDirective, _super); /** * @param {?} validators * @param {?} asyncValidators * @param {?} valueAccessors */ function FormControlDirective(validators, asyncValidators, valueAccessors) { _super.call(this); this.update = new EventEmitter(); this._rawValidators = validators || []; this._rawAsyncValidators = asyncValidators || []; this.valueAccessor = selectValueAccessor(this, valueAccessors); } Object.defineProperty(FormControlDirective.prototype, "isDisabled", { /** * @param {?} isDisabled * @return {?} */ set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); }, enumerable: true, configurable: true }); /** * @param {?} changes * @return {?} */ FormControlDirective.prototype.ngOnChanges = function (changes) { if (this._isControlChanged(changes)) { setUpControl(this.form, this); if (this.control.disabled && this.valueAccessor.setDisabledState) { this.valueAccessor.setDisabledState(true); } this.form.updateValueAndValidity({ emitEvent: false }); } if (isPropertyUpdated(changes, this.viewModel)) { this.form.setValue(this.model); this.viewModel = this.model; } }; Object.defineProperty(FormControlDirective.prototype, "path", { /** * @return {?} */ get: function () { return []; }, enumerable: true, configurable: true }); Object.defineProperty(FormControlDirective.prototype, "validator", { /** * @return {?} */ get: function () { return composeValidators(this._rawValidators); }, enumerable: true, configurable: true }); Object.defineProperty(FormControlDirective.prototype, "asyncValidator", { /** * @return {?} */ get: function () { return composeAsyncValidators(this._rawAsyncValidators); }, enumerable: true, configurable: true }); Object.defineProperty(FormControlDirective.prototype, "control", { /** * @return {?} */ get: function () { return this.form; }, enumerable: true, configurable: true }); /** * @param {?} newValue * @return {?} */ FormControlDirective.prototype.viewToModelUpdate = function (newValue) { this.viewModel = newValue; this.update.emit(newValue); }; /** * @param {?} changes * @return {?} */ FormControlDirective.prototype._isControlChanged = function (changes) { return changes.hasOwnProperty('form'); }; FormControlDirective.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formControl]', providers: [formControlBinding$1], exportAs: 'ngForm' },] }, ]; /** @nocollapse */ FormControlDirective.ctorParameters = function () { return [ { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALUE_ACCESSOR,] },] }, ]; }; FormControlDirective.propDecorators = { 'form': [{ type: _angular_core.Input, args: ['formControl',] },], 'model': [{ type: _angular_core.Input, args: ['ngModel',] },], 'update': [{ type: _angular_core.Output, args: ['ngModelChange',] },], 'isDisabled': [{ type: _angular_core.Input, args: ['disabled',] },], }; return FormControlDirective; }(NgControl)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$11 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ formDirectiveProvider$1 = { provide: ControlContainer, useExisting: _angular_core.forwardRef(function () { return FormGroupDirective; }) }; /** * * * * * This directive accepts an existing {@link FormGroup} instance. It will then use this * {@link FormGroup} instance to match any child {@link FormControl}, {@link FormGroup}, * and {@link FormArray} instances to child {@link FormControlName}, {@link FormGroupName}, * and {@link FormArrayName} directives. * * * **Set value**: You can set the form's initial value when instantiating the * {@link FormGroup}, or you can set it programmatically later using the {@link FormGroup}'s * {@link AbstractControl.setValue} or {@link AbstractControl.patchValue} methods. * * * **Listen to value**: If you want to listen to changes in the value of the form, you can subscribe * to the {@link FormGroup}'s {@link AbstractControl.valueChanges} event. You can also listen to * its {@link AbstractControl.statusChanges} event to be notified when the validation status is * re-calculated. * * * Furthermore, you can listen to the directive's `ngSubmit` event to be notified when the user has * triggered a form submission. The `ngSubmit` event will be emitted with the original form * submission event. * * * ### Example * * * In this example, we create form controls for first name and last name. * * * {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'} * * * **npm package**: `@angular/forms` * * * **NgModule**: {@link ReactiveFormsModule} * * * @stable */ var FormGroupDirective = (function (_super) { __extends$11(FormGroupDirective, _super); /** * @param {?} _validators * @param {?} _asyncValidators */ function FormGroupDirective(_validators, _asyncValidators) { _super.call(this); this._validators = _validators; this._asyncValidators = _asyncValidators; this._submitted = false; this.directives = []; this.form = null; this.ngSubmit = new EventEmitter(); } /** * @param {?} changes * @return {?} */ FormGroupDirective.prototype.ngOnChanges = function (changes) { this._checkFormPresent(); if (changes.hasOwnProperty('form')) { this._updateValidators(); this._updateDomValue(); this._updateRegistrations(); } }; Object.defineProperty(FormGroupDirective.prototype, "submitted", { /** * @return {?} */ get: function () { return this._submitted; }, enumerable: true, configurable: true }); Object.defineProperty(FormGroupDirective.prototype, "formDirective", { /** * @return {?} */ get: function () { return this; }, enumerable: true, configurable: true }); Object.defineProperty(FormGroupDirective.prototype, "control", { /** * @return {?} */ get: function () { return this.form; }, enumerable: true, configurable: true }); Object.defineProperty(FormGroupDirective.prototype, "path", { /** * @return {?} */ get: function () { return []; }, enumerable: true, configurable: true }); /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.addControl = function (dir) { var /** @type {?} */ ctrl = this.form.get(dir.path); setUpControl(ctrl, dir); ctrl.updateValueAndValidity({ emitEvent: false }); this.directives.push(dir); return ctrl; }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.getControl = function (dir) { return (this.form.get(dir.path)); }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.removeControl = function (dir) { ListWrapper.remove(this.directives, dir); }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.addFormGroup = function (dir) { var /** @type {?} */ ctrl = this.form.get(dir.path); setUpFormContainer(ctrl, dir); ctrl.updateValueAndValidity({ emitEvent: false }); }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.removeFormGroup = function (dir) { }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.getFormGroup = function (dir) { return (this.form.get(dir.path)); }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.addFormArray = function (dir) { var /** @type {?} */ ctrl = this.form.get(dir.path); setUpFormContainer(ctrl, dir); ctrl.updateValueAndValidity({ emitEvent: false }); }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.removeFormArray = function (dir) { }; /** * @param {?} dir * @return {?} */ FormGroupDirective.prototype.getFormArray = function (dir) { return (this.form.get(dir.path)); }; /** * @param {?} dir * @param {?} value * @return {?} */ FormGroupDirective.prototype.updateModel = function (dir, value) { var /** @type {?} */ ctrl = (this.form.get(dir.path)); ctrl.setValue(value); }; /** * @param {?} $event * @return {?} */ FormGroupDirective.prototype.onSubmit = function ($event) { this._submitted = true; this.ngSubmit.emit($event); return false; }; /** * @return {?} */ FormGroupDirective.prototype.onReset = function () { this.resetForm(); }; /** * @param {?=} value * @return {?} */ FormGroupDirective.prototype.resetForm = function (value) { if (value === void 0) { value = undefined; } this.form.reset(value); this._submitted = false; }; /** * @return {?} */ FormGroupDirective.prototype._updateDomValue = function () { var _this = this; this.directives.forEach(function (dir) { var /** @type {?} */ newCtrl = _this.form.get(dir.path); if (dir._control !== newCtrl) { cleanUpControl(dir._control, dir); if (newCtrl) setUpControl(newCtrl, dir); dir._control = newCtrl; } }); this.form._updateTreeValidity({ emitEvent: false }); }; /** * @return {?} */ FormGroupDirective.prototype._updateRegistrations = function () { var _this = this; this.form._registerOnCollectionChange(function () { return _this._updateDomValue(); }); if (this._oldForm) this._oldForm._registerOnCollectionChange(function () { }); this._oldForm = this.form; }; /** * @return {?} */ FormGroupDirective.prototype._updateValidators = function () { var /** @type {?} */ sync = composeValidators(this._validators); this.form.validator = Validators.compose([this.form.validator, sync]); var /** @type {?} */ async = composeAsyncValidators(this._asyncValidators); this.form.asyncValidator = Validators.composeAsync([this.form.asyncValidator, async]); }; /** * @return {?} */ FormGroupDirective.prototype._checkFormPresent = function () { if (!this.form) { ReactiveErrors.missingFormException(); } }; FormGroupDirective.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formGroup]', providers: [formDirectiveProvider$1], host: { '(submit)': 'onSubmit($event)', '(reset)': 'onReset()' }, exportAs: 'ngForm' },] }, ]; /** @nocollapse */ FormGroupDirective.ctorParameters = function () { return [ { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, ]; }; FormGroupDirective.propDecorators = { 'form': [{ type: _angular_core.Input, args: ['formGroup',] },], 'ngSubmit': [{ type: _angular_core.Output },], }; return FormGroupDirective; }(ControlContainer)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$12 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ formGroupNameProvider = { provide: ControlContainer, useExisting: _angular_core.forwardRef(function () { return FormGroupName; }) }; /** * * * * * This directive can only be used with a parent {@link FormGroupDirective} (selector: * `[formGroup]`). * * * It accepts the string name of the nested {@link FormGroup} you want to link, and * will look for a {@link FormGroup} registered with that name in the parent * {@link FormGroup} instance you passed into {@link FormGroupDirective}. * * * Nested form groups can come in handy when you want to validate a sub-group of a * form separately from the rest or when you'd like to group the values of certain * controls into their own nested object. * * * **Access the group**: You can access the associated {@link FormGroup} using the * {@link AbstractControl.get} method. Ex: `this.form.get('name')`. * * * You can also access individual controls within the group using dot syntax. * Ex: `this.form.get('name.first')` * * * **Get the value**: the `value` property is always synced and available on the * {@link FormGroup}. See a full list of available properties in {@link AbstractControl}. * * * **Set the value**: You can set an initial value for each child control when instantiating * the {@link FormGroup}, or you can set it programmatically later using * {@link AbstractControl.setValue} or {@link AbstractControl.patchValue}. * * * **Listen to value**: If you want to listen to changes in the value of the group, you can * subscribe to the {@link AbstractControl.valueChanges} event. You can also listen to * {@link AbstractControl.statusChanges} to be notified when the validation status is * re-calculated. * * * ### Example * * * {@example forms/ts/nestedFormGroup/nested_form_group_example.ts region='Component'} * * * * **npm package**: `@angular/forms` * * * * **NgModule**: `ReactiveFormsModule` * * */ var FormGroupName = (function (_super) { __extends$12(FormGroupName, _super); /** * @param {?} parent * @param {?} validators * @param {?} asyncValidators */ function FormGroupName(parent, validators, asyncValidators) { _super.call(this); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** * @return {?} */ FormGroupName.prototype._checkParentType = function () { if (_hasInvalidParent(this._parent)) { ReactiveErrors.groupParentException(); } }; FormGroupName.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formGroupName]', providers: [formGroupNameProvider] },] }, ]; /** @nocollapse */ FormGroupName.ctorParameters = function () { return [ { type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host }, { type: _angular_core.SkipSelf },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, ]; }; FormGroupName.propDecorators = { 'name': [{ type: _angular_core.Input, args: ['formGroupName',] },], }; return FormGroupName; }(AbstractFormGroupDirective)); var /** @type {?} */ formArrayNameProvider = { provide: ControlContainer, useExisting: _angular_core.forwardRef(function () { return FormArrayName; }) }; /** * * * * * This directive is designed to be used with a parent {@link FormGroupDirective} (selector: * `[formGroup]`). * * * It accepts the string name of the nested {@link FormArray} you want to link, and * will look for a {@link FormArray} registered with that name in the parent * {@link FormGroup} instance you passed into {@link FormGroupDirective}. * * * Nested form arrays can come in handy when you have a group of form controls but * you're not sure how many there will be. Form arrays allow you to create new * form controls dynamically. * * * **Access the array**: You can access the associated {@link FormArray} using the * {@link AbstractControl.get} method on the parent {@link FormGroup}. * Ex: `this.form.get('cities')`. * * * **Get the value**: the `value` property is always synced and available on the * {@link FormArray}. See a full list of available properties in {@link AbstractControl}. * * * **Set the value**: You can set an initial value for each child control when instantiating * the {@link FormArray}, or you can set the value programmatically later using the * {@link FormArray}'s {@link AbstractControl.setValue} or {@link AbstractControl.patchValue} * methods. * * * **Listen to value**: If you want to listen to changes in the value of the array, you can * subscribe to the {@link FormArray}'s {@link AbstractControl.valueChanges} event. You can also * listen to its {@link AbstractControl.statusChanges} event to be notified when the validation * status is re-calculated. * * * **Add new controls**: You can add new controls to the {@link FormArray} dynamically by * calling its {@link FormArray.push} method. * Ex: `this.form.get('cities').push(new FormControl());` * * * ### Example * * * {@example forms/ts/nestedFormArray/nested_form_array_example.ts region='Component'} * * * * **npm package**: `@angular/forms` * * * * **NgModule**: `ReactiveFormsModule` * * */ var FormArrayName = (function (_super) { __extends$12(FormArrayName, _super); /** * @param {?} parent * @param {?} validators * @param {?} asyncValidators */ function FormArrayName(parent, validators, asyncValidators) { _super.call(this); this._parent = parent; this._validators = validators; this._asyncValidators = asyncValidators; } /** * @return {?} */ FormArrayName.prototype.ngOnInit = function () { this._checkParentType(); this.formDirective.addFormArray(this); }; /** * @return {?} */ FormArrayName.prototype.ngOnDestroy = function () { if (this.formDirective) { this.formDirective.removeFormArray(this); } }; Object.defineProperty(FormArrayName.prototype, "control", { /** * @return {?} */ get: function () { return this.formDirective.getFormArray(this); }, enumerable: true, configurable: true }); Object.defineProperty(FormArrayName.prototype, "formDirective", { /** * @return {?} */ get: function () { return this._parent ? (this._parent.formDirective) : null; }, enumerable: true, configurable: true }); Object.defineProperty(FormArrayName.prototype, "path", { /** * @return {?} */ get: function () { return controlPath(this.name, this._parent); }, enumerable: true, configurable: true }); Object.defineProperty(FormArrayName.prototype, "validator", { /** * @return {?} */ get: function () { return composeValidators(this._validators); }, enumerable: true, configurable: true }); Object.defineProperty(FormArrayName.prototype, "asyncValidator", { /** * @return {?} */ get: function () { return composeAsyncValidators(this._asyncValidators); }, enumerable: true, configurable: true }); /** * @return {?} */ FormArrayName.prototype._checkParentType = function () { if (_hasInvalidParent(this._parent)) { ReactiveErrors.arrayParentException(); } }; FormArrayName.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formArrayName]', providers: [formArrayNameProvider] },] }, ]; /** @nocollapse */ FormArrayName.ctorParameters = function () { return [ { type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host }, { type: _angular_core.SkipSelf },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, ]; }; FormArrayName.propDecorators = { 'name': [{ type: _angular_core.Input, args: ['formArrayName',] },], }; return FormArrayName; }(ControlContainer)); /** * @param {?} parent * @return {?} */ function _hasInvalidParent(parent) { return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) && !(parent instanceof FormArrayName); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var __extends$10 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ controlNameBinding = { provide: NgControl, useExisting: _angular_core.forwardRef(function () { return FormControlName; }) }; /** * element by name. * * * In other words, this directive ensures that any values written to the {@link FormControl} * instance programmatically will be written to the DOM element (model -> view). Conversely, * any values written to the DOM element through user input will be reflected in the * {@link FormControl} instance (view -> model). * * * * * This directive is designed to be used with a parent {@link FormGroupDirective} (selector: * `[formGroup]`). * * * It accepts the string name of the {@link FormControl} instance you want to * link, and will look for a {@link FormControl} registered with that name in the * closest {@link FormGroup} or {@link FormArray} above it. * * * **Access the control**: You can access the {@link FormControl} associated with * this directive by using the {@link AbstractControl.get} method. * Ex: `this.form.get('first');` * * * **Get value**: the `value` property is always synced and available on the {@link FormControl}. * See a full list of available properties in {@link AbstractControl}. * * * **Set value**: You can set an initial value for the control when instantiating the * {@link FormControl}, or you can set it programmatically later using * {@link AbstractControl.setValue} or {@link AbstractControl.patchValue}. * * * **Listen to value**: If you want to listen to changes in the value of the control, you can * subscribe to the {@link AbstractControl.valueChanges} event. You can also listen to * {@link AbstractControl.statusChanges} to be notified when the validation status is * re-calculated. * * * ### Example * * * In this example, we create form controls for first name and last name. * * * {@example forms/ts/simpleFormGroup/simple_form_group_example.ts region='Component'} * * * To see `formControlName` examples with different form control types, see: * * * * Radio buttons: {@link RadioControlValueAccessor} * * Selects: {@link SelectControlValueAccessor} * * * **npm package**: `@angular/forms` * * * **NgModule**: {@link ReactiveFormsModule} * * * @stable */ var FormControlName = (function (_super) { __extends$10(FormControlName, _super); /** * @param {?} parent * @param {?} validators * @param {?} asyncValidators * @param {?} valueAccessors */ function FormControlName(parent, validators, asyncValidators, valueAccessors) { _super.call(this); this._added = false; this.update = new EventEmitter(); this._parent = parent; this._rawValidators = validators || []; this._rawAsyncValidators = asyncValidators || []; this.valueAccessor = selectValueAccessor(this, valueAccessors); } Object.defineProperty(FormControlName.prototype, "isDisabled", { /** * @param {?} isDisabled * @return {?} */ set: function (isDisabled) { ReactiveErrors.disabledAttrWarning(); }, enumerable: true, configurable: true }); /** * @param {?} changes * @return {?} */ FormControlName.prototype.ngOnChanges = function (changes) { if (!this._added) this._setUpControl(); if (isPropertyUpdated(changes, this.viewModel)) { this.viewModel = this.model; this.formDirective.updateModel(this, this.model); } }; /** * @return {?} */ FormControlName.prototype.ngOnDestroy = function () { if (this.formDirective) { this.formDirective.removeControl(this); } }; /** * @param {?} newValue * @return {?} */ FormControlName.prototype.viewToModelUpdate = function (newValue) { this.viewModel = newValue; this.update.emit(newValue); }; Object.defineProperty(FormControlName.prototype, "path", { /** * @return {?} */ get: function () { return controlPath(this.name, this._parent); }, enumerable: true, configurable: true }); Object.defineProperty(FormControlName.prototype, "formDirective", { /** * @return {?} */ get: function () { return this._parent ? this._parent.formDirective : null; }, enumerable: true, configurable: true }); Object.defineProperty(FormControlName.prototype, "validator", { /** * @return {?} */ get: function () { return composeValidators(this._rawValidators); }, enumerable: true, configurable: true }); Object.defineProperty(FormControlName.prototype, "asyncValidator", { /** * @return {?} */ get: function () { return composeAsyncValidators(this._rawAsyncValidators); }, enumerable: true, configurable: true }); Object.defineProperty(FormControlName.prototype, "control", { /** * @return {?} */ get: function () { return this._control; }, enumerable: true, configurable: true }); /** * @return {?} */ FormControlName.prototype._checkParentType = function () { if (!(this._parent instanceof FormGroupName) && this._parent instanceof AbstractFormGroupDirective) { ReactiveErrors.ngModelGroupException(); } else if (!(this._parent instanceof FormGroupName) && !(this._parent instanceof FormGroupDirective) && !(this._parent instanceof FormArrayName)) { ReactiveErrors.controlParentException(); } }; /** * @return {?} */ FormControlName.prototype._setUpControl = function () { this._checkParentType(); this._control = this.formDirective.addControl(this); if (this.control.disabled && this.valueAccessor.setDisabledState) { this.valueAccessor.setDisabledState(true); } this._added = true; }; FormControlName.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[formControlName]', providers: [controlNameBinding] },] }, ]; /** @nocollapse */ FormControlName.ctorParameters = function () { return [ { type: ControlContainer, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Host }, { type: _angular_core.SkipSelf },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_ASYNC_VALIDATORS,] },] }, { type: Array, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Self }, { type: _angular_core.Inject, args: [NG_VALUE_ACCESSOR,] },] }, ]; }; FormControlName.propDecorators = { 'name': [{ type: _angular_core.Input, args: ['formControlName',] },], 'model': [{ type: _angular_core.Input, args: ['ngModel',] },], 'update': [{ type: _angular_core.Output, args: ['ngModelChange',] },], 'isDisabled': [{ type: _angular_core.Input, args: ['disabled',] },], }; return FormControlName; }(NgControl)); var __extends$13 = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var /** @type {?} */ REQUIRED_VALIDATOR = { provide: NG_VALIDATORS, useExisting: _angular_core.forwardRef(function () { return RequiredValidator; }), multi: true }; var /** @type {?} */ CHECKBOX_REQUIRED_VALIDATOR = { provide: NG_VALIDATORS, useExisting: _angular_core.forwardRef(function () { return CheckboxRequiredValidator; }), multi: true }; /** * A Directive that adds the `required` validator to any controls marked with the * `required` attribute, via the {@link NG_VALIDATORS} binding. * * * ### Example * * * ``` * <input name="fullName" ngModel required> * ``` * * */ var RequiredValidator = (function () { function RequiredValidator() { } Object.defineProperty(RequiredValidator.prototype, "required", { /** * @return {?} */ get: function () { return this._required; }, /** * @param {?} value * @return {?} */ set: function (value) { this._required = value != null && value !== false && "" + value !== 'false'; if (this._onChange) this._onChange(); }, enumerable: true, configurable: true }); /** * @param {?} c * @return {?} */ RequiredValidator.prototype.validate = function (c) { return this.required ? Validators.required(c) : null; }; /** * @param {?} fn * @return {?} */ RequiredValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; }; RequiredValidator.decorators = [ { type: _angular_core.Directive, args: [{ selector: ':not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]', providers: [REQUIRED_VALIDATOR], host: { '[attr.required]': 'required ? "" : null' } },] }, ]; /** @nocollapse */ RequiredValidator.ctorParameters = function () { return []; }; RequiredValidator.propDecorators = { 'required': [{ type: _angular_core.Input },], }; return RequiredValidator; }()); /** * A Directive that adds the `required` validator to checkbox controls marked with the * `required` attribute, via the {@link NG_VALIDATORS} binding. * * * ### Example * * * ``` * <input type="checkbox" name="active" ngModel required> * ``` * * */ var CheckboxRequiredValidator = (function (_super) { __extends$13(CheckboxRequiredValidator, _super); function CheckboxRequiredValidator() { _super.apply(this, arguments); } /** * @param {?} c * @return {?} */ CheckboxRequiredValidator.prototype.validate = function (c) { return this.required ? Validators.requiredTrue(c) : null; }; CheckboxRequiredValidator.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'input[type=checkbox][required][formControlName],input[type=checkbox][required][formControl],input[type=checkbox][required][ngModel]', providers: [CHECKBOX_REQUIRED_VALIDATOR], host: { '[attr.required]': 'required ? "" : null' } },] }, ]; /** @nocollapse */ CheckboxRequiredValidator.ctorParameters = function () { return []; }; return CheckboxRequiredValidator; }(RequiredValidator)); /** * Provider which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}. * * ## Example: * * {@example common/forms/ts/validators/validators.ts region='min'} */ var /** @type {?} */ MIN_LENGTH_VALIDATOR = { provide: NG_VALIDATORS, useExisting: _angular_core.forwardRef(function () { return MinLengthValidator; }), multi: true }; /** * A directive which installs the {@link MinLengthValidator} for any `formControlName`, * `formControl`, or control with `ngModel` that also has a `minlength` attribute. * * */ var MinLengthValidator = (function () { function MinLengthValidator() { } /** * @param {?} changes * @return {?} */ MinLengthValidator.prototype.ngOnChanges = function (changes) { if ('minlength' in changes) { this._createValidator(); if (this._onChange) this._onChange(); } }; /** * @param {?} c * @return {?} */ MinLengthValidator.prototype.validate = function (c) { return this.minlength == null ? null : this._validator(c); }; /** * @param {?} fn * @return {?} */ MinLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; }; /** * @return {?} */ MinLengthValidator.prototype._createValidator = function () { this._validator = Validators.minLength(parseInt(this.minlength, 10)); }; MinLengthValidator.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[minlength][formControlName],[minlength][formControl],[minlength][ngModel]', providers: [MIN_LENGTH_VALIDATOR], host: { '[attr.minlength]': 'minlength ? minlength : null' } },] }, ]; /** @nocollapse */ MinLengthValidator.ctorParameters = function () { return []; }; MinLengthValidator.propDecorators = { 'minlength': [{ type: _angular_core.Input },], }; return MinLengthValidator; }()); /** * Provider which adds {@link MaxLengthValidator} to {@link NG_VALIDATORS}. * * ## Example: * * {@example common/forms/ts/validators/validators.ts region='max'} */ var /** @type {?} */ MAX_LENGTH_VALIDATOR = { provide: NG_VALIDATORS, useExisting: _angular_core.forwardRef(function () { return MaxLengthValidator; }), multi: true }; /** * A directive which installs the {@link MaxLengthValidator} for any `formControlName, * `formControl`, * or control with `ngModel` that also has a `maxlength` attribute. * * */ var MaxLengthValidator = (function () { function MaxLengthValidator() { } /** * @param {?} changes * @return {?} */ MaxLengthValidator.prototype.ngOnChanges = function (changes) { if ('maxlength' in changes) { this._createValidator(); if (this._onChange) this._onChange(); } }; /** * @param {?} c * @return {?} */ MaxLengthValidator.prototype.validate = function (c) { return this.maxlength != null ? this._validator(c) : null; }; /** * @param {?} fn * @return {?} */ MaxLengthValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; }; /** * @return {?} */ MaxLengthValidator.prototype._createValidator = function () { this._validator = Validators.maxLength(parseInt(this.maxlength, 10)); }; MaxLengthValidator.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]', providers: [MAX_LENGTH_VALIDATOR], host: { '[attr.maxlength]': 'maxlength ? maxlength : null' } },] }, ]; /** @nocollapse */ MaxLengthValidator.ctorParameters = function () { return []; }; MaxLengthValidator.propDecorators = { 'maxlength': [{ type: _angular_core.Input },], }; return MaxLengthValidator; }()); var /** @type {?} */ PATTERN_VALIDATOR = { provide: NG_VALIDATORS, useExisting: _angular_core.forwardRef(function () { return PatternValidator; }), multi: true }; /** * A Directive that adds the `pattern` validator to any controls marked with the * `pattern` attribute, via the {@link NG_VALIDATORS} binding. Uses attribute value * as the regex to validate Control value against. Follows pattern attribute * semantics; i.e. regex must match entire Control value. * * * ### Example * * * ``` * <input [name]="fullName" pattern="[a-zA-Z ]*" ngModel> * ``` */ var PatternValidator = (function () { function PatternValidator() { } /** * @param {?} changes * @return {?} */ PatternValidator.prototype.ngOnChanges = function (changes) { if ('pattern' in changes) { this._createValidator(); if (this._onChange) this._onChange(); } }; /** * @param {?} c * @return {?} */ PatternValidator.prototype.validate = function (c) { return this._validator(c); }; /** * @param {?} fn * @return {?} */ PatternValidator.prototype.registerOnValidatorChange = function (fn) { this._onChange = fn; }; /** * @return {?} */ PatternValidator.prototype._createValidator = function () { this._validator = Validators.pattern(this.pattern); }; PatternValidator.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[pattern][formControlName],[pattern][formControl],[pattern][ngModel]', providers: [PATTERN_VALIDATOR], host: { '[attr.pattern]': 'pattern ? pattern : null' } },] }, ]; /** @nocollapse */ PatternValidator.ctorParameters = function () { return []; }; PatternValidator.propDecorators = { 'pattern': [{ type: _angular_core.Input },], }; return PatternValidator; }()); /** * * * It is essentially syntactic sugar that shortens the `new FormGroup()`, * `new FormControl()`, and `new FormArray()` boilerplate that can build up in larger * forms. * * * * * To use, inject `FormBuilder` into your component class. You can then call its methods * directly. * * * {@example forms/ts/formBuilder/form_builder_example.ts region='Component'} * * * * **npm package**: `@angular/forms` * * * * **NgModule**: {@link ReactiveFormsModule} * * */ var FormBuilder = (function () { function FormBuilder() { } /** * Construct a new {@link FormGroup} with the given map of configuration. * Valid keys for the `extra` parameter map are `validator` and `asyncValidator`. * * * See the {@link FormGroup} constructor for more details. * @param {?} controlsConfig * @param {?=} extra * @return {?} */ FormBuilder.prototype.group = function (controlsConfig, extra) { if (extra === void 0) { extra = null; } var /** @type {?} */ controls = this._reduceControls(controlsConfig); var /** @type {?} */ validator = isPresent(extra) ? extra['validator'] : null; var /** @type {?} */ asyncValidator = isPresent(extra) ? extra['asyncValidator'] : null; return new FormGroup(controls, validator, asyncValidator); }; /** * Construct a new {@link FormControl} with the given `formState`,`validator`, and * `asyncValidator`. * * * `formState` can either be a standalone value for the form control or an object * that contains both a value and a disabled status. * * * @param {?} formState * @param {?=} validator * @param {?=} asyncValidator * @return {?} */ FormBuilder.prototype.control = function (formState, validator, asyncValidator) { if (validator === void 0) { validator = null; } if (asyncValidator === void 0) { asyncValidator = null; } return new FormControl(formState, validator, asyncValidator); }; /** * Construct a {@link FormArray} from the given `controlsConfig` array of * configuration, with the given optional `validator` and `asyncValidator`. * @param {?} controlsConfig * @param {?=} validator * @param {?=} asyncValidator * @return {?} */ FormBuilder.prototype.array = function (controlsConfig, validator, asyncValidator) { var _this = this; if (validator === void 0) { validator = null; } if (asyncValidator === void 0) { asyncValidator = null; } var /** @type {?} */ controls = controlsConfig.map(function (c) { return _this._createControl(c); }); return new FormArray(controls, validator, asyncValidator); }; /** * @param {?} controlsConfig * @return {?} */ FormBuilder.prototype._reduceControls = function (controlsConfig) { var _this = this; var /** @type {?} */ controls = {}; Object.keys(controlsConfig).forEach(function (controlName) { controls[controlName] = _this._createControl(controlsConfig[controlName]); }); return controls; }; /** * @param {?} controlConfig * @return {?} */ FormBuilder.prototype._createControl = function (controlConfig) { if (controlConfig instanceof FormControl || controlConfig instanceof FormGroup || controlConfig instanceof FormArray) { return controlConfig; } else if (Array.isArray(controlConfig)) { var /** @type {?} */ value = controlConfig[0]; var /** @type {?} */ validator = controlConfig.length > 1 ? controlConfig[1] : null; var /** @type {?} */ asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null; return this.control(value, validator, asyncValidator); } else { return this.control(controlConfig); } }; FormBuilder.decorators = [ { type: _angular_core.Injectable }, ]; /** @nocollapse */ FormBuilder.ctorParameters = function () { return []; }; return FormBuilder; }()); /** * @stable */ var /** @type {?} */ VERSION = new _angular_core.Version('2.4.3'); var /** @type {?} */ SHARED_FORM_DIRECTIVES = [ NgSelectOption, NgSelectMultipleOption, DefaultValueAccessor, NumberValueAccessor, RangeValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, SelectMultipleControlValueAccessor, RadioControlValueAccessor, NgControlStatus, NgControlStatusGroup, RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator, CheckboxRequiredValidator, ]; var /** @type {?} */ TEMPLATE_DRIVEN_DIRECTIVES = [NgModel, NgModelGroup, NgForm]; var /** @type {?} */ REACTIVE_DRIVEN_DIRECTIVES = [FormControlDirective, FormGroupDirective, FormControlName, FormGroupName, FormArrayName]; /** * Internal module used for sharing directives between FormsModule and ReactiveFormsModule */ var InternalFormsSharedModule = (function () { function InternalFormsSharedModule() { } InternalFormsSharedModule.decorators = [ { type: _angular_core.NgModule, args: [{ declarations: SHARED_FORM_DIRECTIVES, exports: SHARED_FORM_DIRECTIVES, },] }, ]; /** @nocollapse */ InternalFormsSharedModule.ctorParameters = function () { return []; }; return InternalFormsSharedModule; }()); /** * The ng module for forms. */ var FormsModule = (function () { function FormsModule() { } FormsModule.decorators = [ { type: _angular_core.NgModule, args: [{ declarations: TEMPLATE_DRIVEN_DIRECTIVES, providers: [RadioControlRegistry], exports: [InternalFormsSharedModule, TEMPLATE_DRIVEN_DIRECTIVES] },] }, ]; /** @nocollapse */ FormsModule.ctorParameters = function () { return []; }; return FormsModule; }()); /** * The ng module for reactive forms. */ var ReactiveFormsModule = (function () { function ReactiveFormsModule() { } ReactiveFormsModule.decorators = [ { type: _angular_core.NgModule, args: [{ declarations: [REACTIVE_DRIVEN_DIRECTIVES], providers: [FormBuilder, RadioControlRegistry], exports: [InternalFormsSharedModule, REACTIVE_DRIVEN_DIRECTIVES] },] }, ]; /** @nocollapse */ ReactiveFormsModule.ctorParameters = function () { return []; }; return ReactiveFormsModule; }()); exports.AbstractControlDirective = AbstractControlDirective; exports.AbstractFormGroupDirective = AbstractFormGroupDirective; exports.CheckboxControlValueAccessor = CheckboxControlValueAccessor; exports.ControlContainer = ControlContainer; exports.NG_VALUE_ACCESSOR = NG_VALUE_ACCESSOR; exports.DefaultValueAccessor = DefaultValueAccessor; exports.NgControl = NgControl; exports.NgControlStatus = NgControlStatus; exports.NgControlStatusGroup = NgControlStatusGroup; exports.NgForm = NgForm; exports.NgModel = NgModel; exports.NgModelGroup = NgModelGroup; exports.RadioControlValueAccessor = RadioControlValueAccessor; exports.FormControlDirective = FormControlDirective; exports.FormControlName = FormControlName; exports.FormGroupDirective = FormGroupDirective; exports.FormArrayName = FormArrayName; exports.FormGroupName = FormGroupName; exports.NgSelectOption = NgSelectOption; exports.SelectControlValueAccessor = SelectControlValueAccessor; exports.SelectMultipleControlValueAccessor = SelectMultipleControlValueAccessor; exports.CheckboxRequiredValidator = CheckboxRequiredValidator; exports.MaxLengthValidator = MaxLengthValidator; exports.MinLengthValidator = MinLengthValidator; exports.PatternValidator = PatternValidator; exports.RequiredValidator = RequiredValidator; exports.FormBuilder = FormBuilder; exports.AbstractControl = AbstractControl; exports.FormArray = FormArray; exports.FormControl = FormControl; exports.FormGroup = FormGroup; exports.NG_ASYNC_VALIDATORS = NG_ASYNC_VALIDATORS; exports.NG_VALIDATORS = NG_VALIDATORS; exports.Validators = Validators; exports.VERSION = VERSION; exports.FormsModule = FormsModule; exports.ReactiveFormsModule = ReactiveFormsModule; }));
src/app.js
morrishopkins/test_spa
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, Redirect, browserHistory } from 'react-router'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from './store/configureStore'; import routes from './routes'; injectTapEventPlugin(); const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); ReactDOM.render( <Provider store={store}> <Router history={history}> <Redirect from="/" to="main" /> {routes} </Router> </Provider>, document.getElementById('root') );
renderer/Flag.js
VishalRohra/chroma-tone
import React from 'react' export default class Flag extends React.Component { render() { let {icon, pos: {x, y}, zoom} = this.props return ( <g transform={`translate(${x} ${y})`}> {icon} </g> ); } }
src/ReactBoilerplate/Scripts/components/Spinner.js
pauldotknopf/react-aspnet-boilerplate
import React from 'react'; const fontAwesome = require('font-awesome/scss/font-awesome.scss'); const spinnerClass = fontAwesome.fa + ' ' + fontAwesome['fa-spinner'] + ' ' + fontAwesome['fa-spin'] + ' ' + fontAwesome['fa-5x']; export default () => ( <p style={{ textAlign: 'center' }}> <i className={spinnerClass} /> </p> );
tests/boilerplate_test.js
olivierrr/react-selection-popover
// import React from 'react'; // import { // renderIntoDocument, // findRenderedDOMComponentWithClass, // findRenderedDOMComponentWithTag, // Simulate //} from 'react-addons-test-utils'; describe('Boilerplate', function() { it('should do boilerplate things', function() { // TODO: test something now expect(true).to.equal(true); }); });
app/javascript/mastodon/features/account/components/header.js
Craftodon/Craftodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import IconButton from '../../../components/icon_button'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { autoPlayGif, me } from '../../../initial_state'; import classNames from 'classnames'; const messages = defineMessages({ unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' }, follow: { id: 'account.follow', defaultMessage: 'Follow' }, requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' }, }); class Avatar extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; state = { isHovered: false, }; handleMouseOver = () => { if (this.state.isHovered) return; this.setState({ isHovered: true }); } handleMouseOut = () => { if (!this.state.isHovered) return; this.setState({ isHovered: false }); } render () { const { account } = this.props; const { isHovered } = this.state; return ( <Motion defaultStyle={{ radius: 90 }} style={{ radius: spring(isHovered ? 30 : 90, { stiffness: 180, damping: 12 }) }}> {({ radius }) => <a href={account.get('url')} className='account__header__avatar' role='presentation' target='_blank' rel='noopener' style={{ borderRadius: `${radius}px`, backgroundImage: `url(${autoPlayGif || isHovered ? account.get('avatar') : account.get('avatar_static')})` }} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} onFocus={this.handleMouseOver} onBlur={this.handleMouseOut} > <span style={{ display: 'none' }}>{account.get('acct')}</span> </a> } </Motion> ); } } @injectIntl export default class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, onFollow: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { account, intl } = this.props; if (!account) { return null; } let info = ''; let actionBtn = ''; let lockedIcon = ''; if (me !== account.get('id') && account.getIn(['relationship', 'followed_by'])) { info = <span className='account--follows-info'><FormattedMessage id='account.follows_you' defaultMessage='Follows you' /></span>; } if (me !== account.get('id')) { if (account.getIn(['relationship', 'requested'])) { actionBtn = ( <div className='account--action-button'> <IconButton size={26} active icon='hourglass' title={intl.formatMessage(messages.requested)} onClick={this.props.onFollow} /> </div> ); } else if (!account.getIn(['relationship', 'blocking'])) { actionBtn = ( <div className='account--action-button'> <IconButton size={26} icon={account.getIn(['relationship', 'following']) ? 'user-times' : 'user-plus'} active={account.getIn(['relationship', 'following'])} title={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.props.onFollow} /> </div> ); } } if (account.get('moved')) { actionBtn = ''; } if (account.get('locked')) { lockedIcon = <i className='fa fa-lock' />; } const content = { __html: account.get('note_emojified') }; const displayNameHtml = { __html: account.get('display_name_html') }; return ( <div className={classNames('account__header', { inactive: !!account.get('moved') })} style={{ backgroundImage: `url(${account.get('header')})` }}> <div> <Avatar account={account} /> <span className='account__header__display-name' dangerouslySetInnerHTML={displayNameHtml} /> <span className='account__header__username'>@{account.get('acct')} {lockedIcon}</span> <div className='account__header__content' dangerouslySetInnerHTML={content} /> {info} {actionBtn} </div> </div> ); } }
src/components/Scroll.js
mattbanks/mattbanks
/* eslint-disable react/destructuring-assignment */ import smoothscroll from 'smoothscroll-polyfill'; import React from 'react'; import PropTypes from 'prop-types'; const Element = (props) => props.children; class Scroll extends React.Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); } componentDidMount() { smoothscroll.polyfill(); } handleClick(e) { e.preventDefault(); let elem = 0; let scroll = true; const { type, element, offset, timeout } = this.props; if (type && element) { switch (type) { case 'class': // eslint-disable-next-line prefer-destructuring elem = document.getElementsByClassName(element)[0]; scroll = !!elem; break; case 'id': elem = document.getElementById(element); scroll = !!elem; break; default: } } // eslint-disable-next-line no-unused-expressions scroll ? this.scrollTo(elem, offset, timeout) : console.log(`Element not found: ${element}`); } // eslint-disable-next-line class-methods-use-this scrollTo(element, offSet = 0, timeout = null) { const elemPos = element ? element.getBoundingClientRect().top + window.pageYOffset : 0; if (timeout) { setTimeout(() => { window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' }); }, timeout); } else { window.scroll({ top: elemPos + offSet, left: 0, behavior: 'smooth' }); } } render() { return ( <Element> {typeof this.props.children === 'object' ? ( React.cloneElement(this.props.children, { onClick: this.handleClick }) ) : ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions <span onClick={this.handleClick}>{this.props.children}</span> )} </Element> ); } } Scroll.propTypes = { type: PropTypes.string, element: PropTypes.string, offset: PropTypes.number, timeout: PropTypes.number, children: PropTypes.node.isRequired, }; export default Scroll;
__tests__/index.ios.js
khosimorafo/reactmastende
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
examples/with-fela/layout.js
arunoda/next.js
import { Provider } from 'react-fela' import felaRenderer from './fela-renderer' export default ({ children }) => <Provider renderer={felaRenderer}> {children} </Provider>
packages/reactor-tests/src/tests/props/SimplePropUpdate.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { Button } from '@extjs/ext-react'; export default class SimplePropUpdate extends Component { state = { count: 0 }; increment = () => this.setState({ count: this.state.count + 1 }); render() { return ( <Button itemId="button" text={`Count: ${this.state.count}`} handler={this.increment}/> ) } }
src/main/webapp/act/rest/libs/ext-2.0.2/ext-all-debug.js
youtops/jeesite-master
/* * Ext JS Library 2.0.2 * Copyright(c) 2006-2008, Ext JS, LLC. * licensing@extjs.com * * http://extjs.com/license */ Ext.DomHelper = function(){ var tempTableEl = null; var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i; var tableRe = /^table|tbody|tr|td$/i; var createHtml = function(o){ if(typeof o == 'string'){ return o; } var b = ""; if (Ext.isArray(o)) { for (var i = 0, l = o.length; i < l; i++) { b += createHtml(o[i]); } return b; } if(!o.tag){ o.tag = "div"; } b += "<" + o.tag; for(var attr in o){ if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue; if(attr == "style"){ var s = o["style"]; if(typeof s == "function"){ s = s.call(); } if(typeof s == "string"){ b += ' style="' + s + '"'; }else if(typeof s == "object"){ b += ' style="'; for(var key in s){ if(typeof s[key] != "function"){ b += key + ":" + s[key] + ";"; } } b += '"'; } }else{ if(attr == "cls"){ b += ' class="' + o["cls"] + '"'; }else if(attr == "htmlFor"){ b += ' for="' + o["htmlFor"] + '"'; }else{ b += " " + attr + '="' + o[attr] + '"'; } } } if(emptyTags.test(o.tag)){ b += "/>"; }else{ b += ">"; var cn = o.children || o.cn; if(cn){ b += createHtml(cn); } else if(o.html){ b += o.html; } b += "</" + o.tag + ">"; } return b; }; var createDom = function(o, parentNode){ var el; if (Ext.isArray(o)) { el = document.createDocumentFragment(); for(var i = 0, l = o.length; i < l; i++) { createDom(o[i], el); } } else if (typeof o == "string)") { el = document.createTextNode(o); } else { el = document.createElement(o.tag||'div'); var useSet = !!el.setAttribute; for(var attr in o){ if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else{ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } Ext.DomHelper.applyStyles(el, o.style); var cn = o.children || o.cn; if(cn){ createDom(cn, el); } else if(o.html){ el.innerHTML = o.html; } } if(parentNode){ parentNode.appendChild(el); } return el; }; var ieTable = function(depth, s, h, e){ tempTableEl.innerHTML = [s, h, e].join(''); var i = -1, el = tempTableEl; while(++i < depth){ el = el.firstChild; } return el; }; var ts = '<table>', te = '</table>', tbs = ts+'<tbody>', tbe = '</tbody>'+te, trs = tbs + '<tr>', tre = '</tr>'+tbe; var insertIntoTable = function(tag, where, el, html){ if(!tempTableEl){ tempTableEl = document.createElement('div'); } var node; var before = null; if(tag == 'td'){ if(where == 'afterbegin' || where == 'beforeend'){ return; } if(where == 'beforebegin'){ before = el; el = el.parentNode; } else{ before = el.nextSibling; el = el.parentNode; } node = ieTable(4, trs, html, tre); } else if(tag == 'tr'){ if(where == 'beforebegin'){ before = el; el = el.parentNode; node = ieTable(3, tbs, html, tbe); } else if(where == 'afterend'){ before = el.nextSibling; el = el.parentNode; node = ieTable(3, tbs, html, tbe); } else{ if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(4, trs, html, tre); } } else if(tag == 'tbody'){ if(where == 'beforebegin'){ before = el; el = el.parentNode; node = ieTable(2, ts, html, te); } else if(where == 'afterend'){ before = el.nextSibling; el = el.parentNode; node = ieTable(2, ts, html, te); } else{ if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(3, tbs, html, tbe); } } else{ if(where == 'beforebegin' || where == 'afterend'){ return; } if(where == 'afterbegin'){ before = el.firstChild; } node = ieTable(2, ts, html, te); } el.insertBefore(node, before); return node; }; return { useDom : false, markup : function(o){ return createHtml(o); }, applyStyles : function(el, styles){ if(styles){ el = Ext.fly(el); if(typeof styles == "string"){ var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi; var matches; while ((matches = re.exec(styles)) != null){ el.setStyle(matches[1], matches[2]); } }else if (typeof styles == "object"){ for (var style in styles){ el.setStyle(style, styles[style]); } }else if (typeof styles == "function"){ Ext.DomHelper.applyStyles(el, styles.call()); } } }, insertHtml : function(where, el, html){ where = where.toLowerCase(); if(el.insertAdjacentHTML){ if(tableRe.test(el.tagName)){ var rs; if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){ return rs; } } switch(where){ case "beforebegin": el.insertAdjacentHTML('BeforeBegin', html); return el.previousSibling; case "afterbegin": el.insertAdjacentHTML('AfterBegin', html); return el.firstChild; case "beforeend": el.insertAdjacentHTML('BeforeEnd', html); return el.lastChild; case "afterend": el.insertAdjacentHTML('AfterEnd', html); return el.nextSibling; } throw 'Illegal insertion point -> "' + where + '"'; } var range = el.ownerDocument.createRange(); var frag; switch(where){ case "beforebegin": range.setStartBefore(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el); return el.previousSibling; case "afterbegin": if(el.firstChild){ range.setStartBefore(el.firstChild); frag = range.createContextualFragment(html); el.insertBefore(frag, el.firstChild); return el.firstChild; }else{ el.innerHTML = html; return el.firstChild; } case "beforeend": if(el.lastChild){ range.setStartAfter(el.lastChild); frag = range.createContextualFragment(html); el.appendChild(frag); return el.lastChild; }else{ el.innerHTML = html; return el.lastChild; } case "afterend": range.setStartAfter(el); frag = range.createContextualFragment(html); el.parentNode.insertBefore(frag, el.nextSibling); return el.nextSibling; } throw 'Illegal insertion point -> "' + where + '"'; }, insertBefore : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "beforeBegin"); }, insertAfter : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling"); }, insertFirst : function(el, o, returnElement){ return this.doInsert(el, o, returnElement, "afterBegin", "firstChild"); }, doInsert : function(el, o, returnElement, pos, sibling){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); (sibling === "firstChild" ? el : el.parentNode).insertBefore(newNode, sibling ? el[sibling] : el); }else{ var html = createHtml(o); newNode = this.insertHtml(pos, el, html); } return returnElement ? Ext.get(newNode, true) : newNode; }, append : function(el, o, returnElement){ el = Ext.getDom(el); var newNode; if(this.useDom){ newNode = createDom(o, null); el.appendChild(newNode); }else{ var html = createHtml(o); newNode = this.insertHtml("beforeEnd", el, html); } return returnElement ? Ext.get(newNode, true) : newNode; }, overwrite : function(el, o, returnElement){ el = Ext.getDom(el); el.innerHTML = createHtml(o); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; }, createTemplate : function(o){ var html = createHtml(o); return new Ext.Template(html); } }; }(); Ext.Template = function(html){ var a = arguments; if(Ext.isArray(html)){ html = html.join(""); }else if(a.length > 1){ var buf = []; for(var i = 0, len = a.length; i < len; i++){ if(typeof a[i] == 'object'){ Ext.apply(this, a[i]); }else{ buf[buf.length] = a[i]; } } html = buf.join(''); } this.html = html; if(this.compiled){ this.compile(); } }; Ext.Template.prototype = { applyTemplate : function(values){ if(this.compiled){ return this.compiled(values); } var useF = this.disableFormats !== true; var fm = Ext.util.Format, tpl = this; var fn = function(m, name, format, args){ if(format && useF){ if(format.substr(0, 5) == "this."){ return tpl.call(format.substr(5), values[name], values); }else{ if(args){ var re = /^\s*['"](.*)["']\s*$/; args = args.split(','); for(var i = 0, len = args.length; i < len; i++){ args[i] = args[i].replace(re, "$1"); } args = [values[name]].concat(args); }else{ args = [values[name]]; } return fm[format].apply(fm, args); } }else{ return values[name] !== undefined ? values[name] : ""; } }; return this.html.replace(this.re, fn); }, set : function(html, compile){ this.html = html; this.compiled = null; if(compile){ this.compile(); } return this; }, disableFormats : false, re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, compile : function(){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args){ if(format && useF){ args = args ? ',' + args : ""; if(format.substr(0, 5) != "this."){ format = "fm." + format + '('; }else{ format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } }else{ args= ''; format = "(values['" + name + "'] == undefined ? '' : "; } return "'"+ sep + format + "values['" + name + "']" + args + ")"+sep+"'"; }; var body; if(Ext.isGecko){ body = "this.compiled = function(values){ return '" + this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn) + "';};"; }else{ body = ["this.compiled = function(values){ return ['"]; body.push(this.html.replace(/\\/g, '\\\\').replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, call : function(fnName, value, allValues){ return this[fnName](value, allValues); }, insertFirst: function(el, values, returnElement){ return this.doInsert('afterBegin', el, values, returnElement); }, insertBefore: function(el, values, returnElement){ return this.doInsert('beforeBegin', el, values, returnElement); }, insertAfter : function(el, values, returnElement){ return this.doInsert('afterEnd', el, values, returnElement); }, append : function(el, values, returnElement){ return this.doInsert('beforeEnd', el, values, returnElement); }, doInsert : function(where, el, values, returnEl){ el = Ext.getDom(el); var newNode = Ext.DomHelper.insertHtml(where, el, this.applyTemplate(values)); return returnEl ? Ext.get(newNode, true) : newNode; }, overwrite : function(el, values, returnElement){ el = Ext.getDom(el); el.innerHTML = this.applyTemplate(values); return returnElement ? Ext.get(el.firstChild, true) : el.firstChild; } }; Ext.Template.prototype.apply = Ext.Template.prototype.applyTemplate; Ext.DomHelper.Template = Ext.Template; Ext.Template.from = function(el, config){ el = Ext.getDom(el); return new Ext.Template(el.value || el.innerHTML, config || ''); }; Ext.DomQuery = function(){ var cache = {}, simpleCache = {}, valueCache = {}; var nonSpace = /\S/; var trimRe = /^\s+|\s+$/g; var tplRe = /\{(\d+)\}/g; var modeRe = /^(\s?[\/>+~]\s?|\s|$)/; var tagTokenRe = /^(#)?([\w-\*]+)/; var nthRe = /(\d*)n\+?(\d*)/, nthRe2 = /\D/; function child(p, index){ var i = 0; var n = p.firstChild; while(n){ if(n.nodeType == 1){ if(++i == index){ return n; } } n = n.nextSibling; } return null; }; function next(n){ while((n = n.nextSibling) && n.nodeType != 1); return n; }; function prev(n){ while((n = n.previousSibling) && n.nodeType != 1); return n; }; function children(d){ var n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !nonSpace.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } return this; }; function byClassName(c, a, v){ if(!v){ return c; } var r = [], ri = -1, cn; for(var i = 0, ci; ci = c[i]; i++){ if((' '+ci.className+' ').indexOf(v) != -1){ r[++ri] = ci; } } return r; }; function attrValue(n, attr){ if(!n.tagName && typeof n.length != "undefined"){ n = n[0]; } if(!n){ return null; } if(attr == "for"){ return n.htmlFor; } if(attr == "class" || attr == "className"){ return n.className; } return n.getAttribute(attr) || n[attr]; }; function getNodes(ns, mode, tagName){ var result = [], ri = -1, cs; if(!ns){ return result; } tagName = tagName || "*"; if(typeof ns.getElementsByTagName != "undefined"){ ns = [ns]; } if(!mode){ for(var i = 0, ni; ni = ns[i]; i++){ cs = ni.getElementsByTagName(tagName); for(var j = 0, ci; ci = cs[j]; j++){ result[++ri] = ci; } } }else if(mode == "/" || mode == ">"){ var utag = tagName.toUpperCase(); for(var i = 0, ni, cn; ni = ns[i]; i++){ cn = ni.children || ni.childNodes; for(var j = 0, cj; cj = cn[j]; j++){ if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){ result[++ri] = cj; } } } }else if(mode == "+"){ var utag = tagName.toUpperCase(); for(var i = 0, n; n = ns[i]; i++){ while((n = n.nextSibling) && n.nodeType != 1); if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){ result[++ri] = n; } } }else if(mode == "~"){ for(var i = 0, n; n = ns[i]; i++){ while((n = n.nextSibling) && (n.nodeType != 1 || (tagName == '*' || n.tagName.toLowerCase()!=tagName))); if(n){ result[++ri] = n; } } } return result; }; function concat(a, b){ if(b.slice){ return a.concat(b); } for(var i = 0, l = b.length; i < l; i++){ a[a.length] = b[i]; } return a; } function byTag(cs, tagName){ if(cs.tagName || cs == document){ cs = [cs]; } if(!tagName){ return cs; } var r = [], ri = -1; tagName = tagName.toLowerCase(); for(var i = 0, ci; ci = cs[i]; i++){ if(ci.nodeType == 1 && ci.tagName.toLowerCase()==tagName){ r[++ri] = ci; } } return r; }; function byId(cs, attr, id){ if(cs.tagName || cs == document){ cs = [cs]; } if(!id){ return cs; } var r = [], ri = -1; for(var i = 0,ci; ci = cs[i]; i++){ if(ci && ci.id == id){ r[++ri] = ci; return r; } } return r; }; function byAttribute(cs, attr, value, op, custom){ var r = [], ri = -1, st = custom=="{"; var f = Ext.DomQuery.operators[op]; for(var i = 0, ci; ci = cs[i]; i++){ var a; if(st){ a = Ext.DomQuery.getStyle(ci, attr); } else if(attr == "class" || attr == "className"){ a = ci.className; }else if(attr == "for"){ a = ci.htmlFor; }else if(attr == "href"){ a = ci.getAttribute("href", 2); }else{ a = ci.getAttribute(attr); } if((f && f(a, value)) || (!f && a)){ r[++ri] = ci; } } return r; }; function byPseudo(cs, name, value){ return Ext.DomQuery.pseudos[name](cs, value); }; var isIE = window.ActiveXObject ? true : false; eval("var batch = 30803;"); var key = 30803; function nodupIEXml(cs){ var d = ++key; cs[0].setAttribute("_nodup", d); var r = [cs[0]]; for(var i = 1, len = cs.length; i < len; i++){ var c = cs[i]; if(!c.getAttribute("_nodup") != d){ c.setAttribute("_nodup", d); r[r.length] = c; } } for(var i = 0, len = cs.length; i < len; i++){ cs[i].removeAttribute("_nodup"); } return r; } function nodup(cs){ if(!cs){ return []; } var len = cs.length, c, i, r = cs, cj, ri = -1; if(!len || typeof cs.nodeType != "undefined" || len == 1){ return cs; } if(isIE && typeof cs[0].selectSingleNode != "undefined"){ return nodupIEXml(cs); } var d = ++key; cs[0]._nodup = d; for(i = 1; c = cs[i]; i++){ if(c._nodup != d){ c._nodup = d; }else{ r = []; for(var j = 0; j < i; j++){ r[++ri] = cs[j]; } for(j = i+1; cj = cs[j]; j++){ if(cj._nodup != d){ cj._nodup = d; r[++ri] = cj; } } return r; } } return r; } function quickDiffIEXml(c1, c2){ var d = ++key; for(var i = 0, len = c1.length; i < len; i++){ c1[i].setAttribute("_qdiff", d); } var r = []; for(var i = 0, len = c2.length; i < len; i++){ if(c2[i].getAttribute("_qdiff") != d){ r[r.length] = c2[i]; } } for(var i = 0, len = c1.length; i < len; i++){ c1[i].removeAttribute("_qdiff"); } return r; } function quickDiff(c1, c2){ var len1 = c1.length; if(!len1){ return c2; } if(isIE && c1[0].selectSingleNode){ return quickDiffIEXml(c1, c2); } var d = ++key; for(var i = 0; i < len1; i++){ c1[i]._qdiff = d; } var r = []; for(var i = 0, len = c2.length; i < len; i++){ if(c2[i]._qdiff != d){ r[r.length] = c2[i]; } } return r; } function quickId(ns, mode, root, id){ if(ns == root){ var d = root.ownerDocument || root; return d.getElementById(id); } ns = getNodes(ns, mode, "*"); return byId(ns, null, id); } return { getStyle : function(el, name){ return Ext.fly(el).getStyle(name); }, compile : function(path, type){ type = type || "select"; var fn = ["var f = function(root){\n var mode; ++batch; var n = root || document;\n"]; var q = path, mode, lq; var tk = Ext.DomQuery.matchers; var tklen = tk.length; var mm; var lmode = q.match(modeRe); if(lmode && lmode[1]){ fn[fn.length] = 'mode="'+lmode[1].replace(trimRe, "")+'";'; q = q.replace(lmode[1], ""); } while(path.substr(0, 1)=="/"){ path = path.substr(1); } while(q && lq != q){ lq = q; var tm = q.match(tagTokenRe); if(type == "select"){ if(tm){ if(tm[1] == "#"){ fn[fn.length] = 'n = quickId(n, mode, root, "'+tm[2]+'");'; }else{ fn[fn.length] = 'n = getNodes(n, mode, "'+tm[2]+'");'; } q = q.replace(tm[0], ""); }else if(q.substr(0, 1) != '@'){ fn[fn.length] = 'n = getNodes(n, mode, "*");'; } }else{ if(tm){ if(tm[1] == "#"){ fn[fn.length] = 'n = byId(n, null, "'+tm[2]+'");'; }else{ fn[fn.length] = 'n = byTag(n, "'+tm[2]+'");'; } q = q.replace(tm[0], ""); } } while(!(mm = q.match(modeRe))){ var matched = false; for(var j = 0; j < tklen; j++){ var t = tk[j]; var m = q.match(t.re); if(m){ fn[fn.length] = t.select.replace(tplRe, function(x, i){ return m[i]; }); q = q.replace(m[0], ""); matched = true; break; } } if(!matched){ throw 'Error parsing selector, parsing failed at "' + q + '"'; } } if(mm[1]){ fn[fn.length] = 'mode="'+mm[1].replace(trimRe, "")+'";'; q = q.replace(mm[1], ""); } } fn[fn.length] = "return nodup(n);\n}"; eval(fn.join("")); return f; }, select : function(path, root, type){ if(!root || root == document){ root = document; } if(typeof root == "string"){ root = document.getElementById(root); } var paths = path.split(","); var results = []; for(var i = 0, len = paths.length; i < len; i++){ var p = paths[i].replace(trimRe, ""); if(!cache[p]){ cache[p] = Ext.DomQuery.compile(p); if(!cache[p]){ throw p + " is not a valid selector"; } } var result = cache[p](root); if(result && result != document){ results = results.concat(result); } } if(paths.length > 1){ return nodup(results); } return results; }, selectNode : function(path, root){ return Ext.DomQuery.select(path, root)[0]; }, selectValue : function(path, root, defaultValue){ path = path.replace(trimRe, ""); if(!valueCache[path]){ valueCache[path] = Ext.DomQuery.compile(path, "select"); } var n = valueCache[path](root); n = n[0] ? n[0] : n; var v = (n && n.firstChild ? n.firstChild.nodeValue : null); return ((v === null||v === undefined||v==='') ? defaultValue : v); }, selectNumber : function(path, root, defaultValue){ var v = Ext.DomQuery.selectValue(path, root, defaultValue || 0); return parseFloat(v); }, is : function(el, ss){ if(typeof el == "string"){ el = document.getElementById(el); } var isArray = Ext.isArray(el); var result = Ext.DomQuery.filter(isArray ? el : [el], ss); return isArray ? (result.length == el.length) : (result.length > 0); }, filter : function(els, ss, nonMatches){ ss = ss.replace(trimRe, ""); if(!simpleCache[ss]){ simpleCache[ss] = Ext.DomQuery.compile(ss, "simple"); } var result = simpleCache[ss](els); return nonMatches ? quickDiff(result, els) : result; }, matchers : [{ re: /^\.([\w-]+)/, select: 'n = byClassName(n, null, " {1} ");' }, { re: /^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/, select: 'n = byPseudo(n, "{1}", "{2}");' },{ re: /^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/, select: 'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");' }, { re: /^#([\w-]+)/, select: 'n = byId(n, null, "{1}");' },{ re: /^@([\w-]+)/, select: 'return {firstChild:{nodeValue:attrValue(n, "{1}")}};' } ], operators : { "=" : function(a, v){ return a == v; }, "!=" : function(a, v){ return a != v; }, "^=" : function(a, v){ return a && a.substr(0, v.length) == v; }, "$=" : function(a, v){ return a && a.substr(a.length-v.length) == v; }, "*=" : function(a, v){ return a && a.indexOf(v) !== -1; }, "%=" : function(a, v){ return (a % v) == 0; }, "|=" : function(a, v){ return a && (a == v || a.substr(0, v.length+1) == v+'-'); }, "~=" : function(a, v){ return a && (' '+a+' ').indexOf(' '+v+' ') != -1; } }, pseudos : { "first-child" : function(c){ var r = [], ri = -1, n; for(var i = 0, ci; ci = n = c[i]; i++){ while((n = n.previousSibling) && n.nodeType != 1); if(!n){ r[++ri] = ci; } } return r; }, "last-child" : function(c){ var r = [], ri = -1, n; for(var i = 0, ci; ci = n = c[i]; i++){ while((n = n.nextSibling) && n.nodeType != 1); if(!n){ r[++ri] = ci; } } return r; }, "nth-child" : function(c, a) { var r = [], ri = -1; var m = nthRe.exec(a == "even" && "2n" || a == "odd" && "2n+1" || !nthRe2.test(a) && "n+" + a || a); var f = (m[1] || 1) - 0, l = m[2] - 0; for(var i = 0, n; n = c[i]; i++){ var pn = n.parentNode; if (batch != pn._batch) { var j = 0; for(var cn = pn.firstChild; cn; cn = cn.nextSibling){ if(cn.nodeType == 1){ cn.nodeIndex = ++j; } } pn._batch = batch; } if (f == 1) { if (l == 0 || n.nodeIndex == l){ r[++ri] = n; } } else if ((n.nodeIndex + l) % f == 0){ r[++ri] = n; } } return r; }, "only-child" : function(c){ var r = [], ri = -1;; for(var i = 0, ci; ci = c[i]; i++){ if(!prev(ci) && !next(ci)){ r[++ri] = ci; } } return r; }, "empty" : function(c){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var cns = ci.childNodes, j = 0, cn, empty = true; while(cn = cns[j]){ ++j; if(cn.nodeType == 1 || cn.nodeType == 3){ empty = false; break; } } if(empty){ r[++ri] = ci; } } return r; }, "contains" : function(c, v){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if((ci.textContent||ci.innerText||'').indexOf(v) != -1){ r[++ri] = ci; } } return r; }, "nodeValue" : function(c, v){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(ci.firstChild && ci.firstChild.nodeValue == v){ r[++ri] = ci; } } return r; }, "checked" : function(c){ var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(ci.checked == true){ r[++ri] = ci; } } return r; }, "not" : function(c, ss){ return Ext.DomQuery.filter(c, ss, true); }, "any" : function(c, selectors){ var ss = selectors.split('|'); var r = [], ri = -1, s; for(var i = 0, ci; ci = c[i]; i++){ for(var j = 0; s = ss[j]; j++){ if(Ext.DomQuery.is(ci, s)){ r[++ri] = ci; break; } } } return r; }, "odd" : function(c){ return this["nth-child"](c, "odd"); }, "even" : function(c){ return this["nth-child"](c, "even"); }, "nth" : function(c, a){ return c[a-1] || []; }, "first" : function(c){ return c[0] || []; }, "last" : function(c){ return c[c.length-1] || []; }, "has" : function(c, ss){ var s = Ext.DomQuery.select; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ if(s(ss, ci).length > 0){ r[++ri] = ci; } } return r; }, "next" : function(c, ss){ var is = Ext.DomQuery.is; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var n = next(ci); if(n && is(n, ss)){ r[++ri] = ci; } } return r; }, "prev" : function(c, ss){ var is = Ext.DomQuery.is; var r = [], ri = -1; for(var i = 0, ci; ci = c[i]; i++){ var n = prev(ci); if(n && is(n, ss)){ r[++ri] = ci; } } return r; } } }; }(); Ext.query = Ext.DomQuery.select; Ext.util.Observable = function(){ if(this.listeners){ this.on(this.listeners); delete this.listeners; } }; Ext.util.Observable.prototype = { fireEvent : function(){ if(this.eventsSuspended !== true){ var ce = this.events[arguments[0].toLowerCase()]; if(typeof ce == "object"){ return ce.fire.apply(ce, Array.prototype.slice.call(arguments, 1)); } } return true; }, filterOptRe : /^(?:scope|delay|buffer|single)$/, addListener : function(eventName, fn, scope, o){ if(typeof eventName == "object"){ o = eventName; for(var e in o){ if(this.filterOptRe.test(e)){ continue; } if(typeof o[e] == "function"){ this.addListener(e, o[e], o.scope, o); }else{ this.addListener(e, o[e].fn, o[e].scope, o[e]); } } return; } o = (!o || typeof o == "boolean") ? {} : o; eventName = eventName.toLowerCase(); var ce = this.events[eventName] || true; if(typeof ce == "boolean"){ ce = new Ext.util.Event(this, eventName); this.events[eventName] = ce; } ce.addListener(fn, scope, o); }, removeListener : function(eventName, fn, scope){ var ce = this.events[eventName.toLowerCase()]; if(typeof ce == "object"){ ce.removeListener(fn, scope); } }, purgeListeners : function(){ for(var evt in this.events){ if(typeof this.events[evt] == "object"){ this.events[evt].clearListeners(); } } }, relayEvents : function(o, events){ var createHandler = function(ename){ return function(){ return this.fireEvent.apply(this, Ext.combine(ename, Array.prototype.slice.call(arguments, 0))); }; }; for(var i = 0, len = events.length; i < len; i++){ var ename = events[i]; if(!this.events[ename]){ this.events[ename] = true; }; o.on(ename, createHandler(ename), this); } }, addEvents : function(o){ if(!this.events){ this.events = {}; } if(typeof o == 'string'){ for(var i = 0, a = arguments, v; v = a[i]; i++){ if(!this.events[a[i]]){ o[a[i]] = true; } } }else{ Ext.applyIf(this.events, o); } }, hasListener : function(eventName){ var e = this.events[eventName]; return typeof e == "object" && e.listeners.length > 0; }, suspendEvents : function(){ this.eventsSuspended = true; }, resumeEvents : function(){ this.eventsSuspended = false; }, getMethodEvent : function(method){ if(!this.methodEvents){ this.methodEvents = {}; } var e = this.methodEvents[method]; if(!e){ e = {}; this.methodEvents[method] = e; e.originalFn = this[method]; e.methodName = method; e.before = []; e.after = []; var returnValue, v, cancel; var obj = this; var makeCall = function(fn, scope, args){ if((v = fn.apply(scope || obj, args)) !== undefined){ if(typeof v === 'object'){ if(v.returnValue !== undefined){ returnValue = v.returnValue; }else{ returnValue = v; } if(v.cancel === true){ cancel = true; } }else if(v === false){ cancel = true; }else { returnValue = v; } } } this[method] = function(){ returnValue = v = undefined; cancel = false; var args = Array.prototype.slice.call(arguments, 0); for(var i = 0, len = e.before.length; i < len; i++){ makeCall(e.before[i].fn, e.before[i].scope, args); if(cancel){ return returnValue; } } if((v = e.originalFn.apply(obj, args)) !== undefined){ returnValue = v; } for(var i = 0, len = e.after.length; i < len; i++){ makeCall(e.after[i].fn, e.after[i].scope, args); if(cancel){ return returnValue; } } return returnValue; }; } return e; }, beforeMethod : function(method, fn, scope){ var e = this.getMethodEvent(method); e.before.push({fn: fn, scope: scope}); }, afterMethod : function(method, fn, scope){ var e = this.getMethodEvent(method); e.after.push({fn: fn, scope: scope}); }, removeMethodListener : function(method, fn, scope){ var e = this.getMethodEvent(method); for(var i = 0, len = e.before.length; i < len; i++){ if(e.before[i].fn == fn && e.before[i].scope == scope){ e.before.splice(i, 1); return; } } for(var i = 0, len = e.after.length; i < len; i++){ if(e.after[i].fn == fn && e.after[i].scope == scope){ e.after.splice(i, 1); return; } } } }; Ext.util.Observable.prototype.on = Ext.util.Observable.prototype.addListener; Ext.util.Observable.prototype.un = Ext.util.Observable.prototype.removeListener; Ext.util.Observable.capture = function(o, fn, scope){ o.fireEvent = o.fireEvent.createInterceptor(fn, scope); }; Ext.util.Observable.releaseCapture = function(o){ o.fireEvent = Ext.util.Observable.prototype.fireEvent; }; (function(){ var createBuffered = function(h, o, scope){ var task = new Ext.util.DelayedTask(); return function(){ task.delay(o.buffer, h, scope, Array.prototype.slice.call(arguments, 0)); }; }; var createSingle = function(h, e, fn, scope){ return function(){ e.removeListener(fn, scope); return h.apply(scope, arguments); }; }; var createDelayed = function(h, o, scope){ return function(){ var args = Array.prototype.slice.call(arguments, 0); setTimeout(function(){ h.apply(scope, args); }, o.delay || 10); }; }; Ext.util.Event = function(obj, name){ this.name = name; this.obj = obj; this.listeners = []; }; Ext.util.Event.prototype = { addListener : function(fn, scope, options){ scope = scope || this.obj; if(!this.isListening(fn, scope)){ var l = this.createListener(fn, scope, options); if(!this.firing){ this.listeners.push(l); }else{ this.listeners = this.listeners.slice(0); this.listeners.push(l); } } }, createListener : function(fn, scope, o){ o = o || {}; scope = scope || this.obj; var l = {fn: fn, scope: scope, options: o}; var h = fn; if(o.delay){ h = createDelayed(h, o, scope); } if(o.single){ h = createSingle(h, this, fn, scope); } if(o.buffer){ h = createBuffered(h, o, scope); } l.fireFn = h; return l; }, findListener : function(fn, scope){ scope = scope || this.obj; var ls = this.listeners; for(var i = 0, len = ls.length; i < len; i++){ var l = ls[i]; if(l.fn == fn && l.scope == scope){ return i; } } return -1; }, isListening : function(fn, scope){ return this.findListener(fn, scope) != -1; }, removeListener : function(fn, scope){ var index; if((index = this.findListener(fn, scope)) != -1){ if(!this.firing){ this.listeners.splice(index, 1); }else{ this.listeners = this.listeners.slice(0); this.listeners.splice(index, 1); } return true; } return false; }, clearListeners : function(){ this.listeners = []; }, fire : function(){ var ls = this.listeners, scope, len = ls.length; if(len > 0){ this.firing = true; var args = Array.prototype.slice.call(arguments, 0); for(var i = 0; i < len; i++){ var l = ls[i]; if(l.fireFn.apply(l.scope||this.obj||window, arguments) === false){ this.firing = false; return false; } } this.firing = false; } return true; } }; })(); Ext.EventManager = function(){ var docReadyEvent, docReadyProcId, docReadyState = false; var resizeEvent, resizeTask, textEvent, textSize; var E = Ext.lib.Event; var D = Ext.lib.Dom; var fireDocReady = function(){ if(!docReadyState){ docReadyState = true; Ext.isReady = true; if(docReadyProcId){ clearInterval(docReadyProcId); } if(Ext.isGecko || Ext.isOpera) { document.removeEventListener("DOMContentLoaded", fireDocReady, false); } if(Ext.isIE){ var defer = document.getElementById("ie-deferred-loader"); if(defer){ defer.onreadystatechange = null; defer.parentNode.removeChild(defer); } } if(docReadyEvent){ docReadyEvent.fire(); docReadyEvent.clearListeners(); } } }; var initDocReady = function(){ docReadyEvent = new Ext.util.Event(); if(Ext.isGecko || Ext.isOpera) { document.addEventListener("DOMContentLoaded", fireDocReady, false); }else if(Ext.isIE){ document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>"); var defer = document.getElementById("ie-deferred-loader"); defer.onreadystatechange = function(){ if(this.readyState == "complete"){ fireDocReady(); } }; }else if(Ext.isSafari){ docReadyProcId = setInterval(function(){ var rs = document.readyState; if(rs == "complete") { fireDocReady(); } }, 10); } E.on(window, "load", fireDocReady); }; var createBuffered = function(h, o){ var task = new Ext.util.DelayedTask(h); return function(e){ e = new Ext.EventObjectImpl(e); task.delay(o.buffer, h, null, [e]); }; }; var createSingle = function(h, el, ename, fn){ return function(e){ Ext.EventManager.removeListener(el, ename, fn); h(e); }; }; var createDelayed = function(h, o){ return function(e){ e = new Ext.EventObjectImpl(e); setTimeout(function(){ h(e); }, o.delay || 10); }; }; var listen = function(element, ename, opt, fn, scope){ var o = (!opt || typeof opt == "boolean") ? {} : opt; fn = fn || o.fn; scope = scope || o.scope; var el = Ext.getDom(element); if(!el){ throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.'; } var h = function(e){ e = Ext.EventObject.setEvent(e); var t; if(o.delegate){ t = e.getTarget(o.delegate, el); if(!t){ return; } }else{ t = e.target; } if(o.stopEvent === true){ e.stopEvent(); } if(o.preventDefault === true){ e.preventDefault(); } if(o.stopPropagation === true){ e.stopPropagation(); } if(o.normalized === false){ e = e.browserEvent; } fn.call(scope || el, e, t, o); }; if(o.delay){ h = createDelayed(h, o); } if(o.single){ h = createSingle(h, el, ename, fn); } if(o.buffer){ h = createBuffered(h, o); } fn._handlers = fn._handlers || []; fn._handlers.push([Ext.id(el), ename, h]); E.on(el, ename, h); if(ename == "mousewheel" && el.addEventListener){ el.addEventListener("DOMMouseScroll", h, false); E.on(window, 'unload', function(){ el.removeEventListener("DOMMouseScroll", h, false); }); } if(ename == "mousedown" && el == document){ Ext.EventManager.stoppedMouseDownEvent.addListener(h); } return h; }; var stopListening = function(el, ename, fn){ var id = Ext.id(el), hds = fn._handlers, hd = fn; if(hds){ for(var i = 0, len = hds.length; i < len; i++){ var h = hds[i]; if(h[0] == id && h[1] == ename){ hd = h[2]; hds.splice(i, 1); break; } } } E.un(el, ename, hd); el = Ext.getDom(el); if(ename == "mousewheel" && el.addEventListener){ el.removeEventListener("DOMMouseScroll", hd, false); } if(ename == "mousedown" && el == document){ Ext.EventManager.stoppedMouseDownEvent.removeListener(hd); } }; var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/; var pub = { addListener : function(element, eventName, fn, scope, options){ if(typeof eventName == "object"){ var o = eventName; for(var e in o){ if(propRe.test(e)){ continue; } if(typeof o[e] == "function"){ listen(element, e, o, o[e], o.scope); }else{ listen(element, e, o[e]); } } return; } return listen(element, eventName, options, fn, scope); }, removeListener : function(element, eventName, fn){ return stopListening(element, eventName, fn); }, onDocumentReady : function(fn, scope, options){ if(docReadyState){ docReadyEvent.addListener(fn, scope, options); docReadyEvent.fire(); docReadyEvent.clearListeners(); return; } if(!docReadyEvent){ initDocReady(); } docReadyEvent.addListener(fn, scope, options); }, onWindowResize : function(fn, scope, options){ if(!resizeEvent){ resizeEvent = new Ext.util.Event(); resizeTask = new Ext.util.DelayedTask(function(){ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); }); E.on(window, "resize", this.fireWindowResize, this); } resizeEvent.addListener(fn, scope, options); }, fireWindowResize : function(){ if(resizeEvent){ if((Ext.isIE||Ext.isAir) && resizeTask){ resizeTask.delay(50); }else{ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); } } }, onTextResize : function(fn, scope, options){ if(!textEvent){ textEvent = new Ext.util.Event(); var textEl = new Ext.Element(document.createElement('div')); textEl.dom.className = 'x-text-resize'; textEl.dom.innerHTML = 'X'; textEl.appendTo(document.body); textSize = textEl.dom.offsetHeight; setInterval(function(){ if(textEl.dom.offsetHeight != textSize){ textEvent.fire(textSize, textSize = textEl.dom.offsetHeight); } }, this.textResizeInterval); } textEvent.addListener(fn, scope, options); }, removeResizeListener : function(fn, scope){ if(resizeEvent){ resizeEvent.removeListener(fn, scope); } }, fireResize : function(){ if(resizeEvent){ resizeEvent.fire(D.getViewWidth(), D.getViewHeight()); } }, ieDeferSrc : false, textResizeInterval : 50 }; pub.on = pub.addListener; pub.un = pub.removeListener; pub.stoppedMouseDownEvent = new Ext.util.Event(); return pub; }(); Ext.onReady = Ext.EventManager.onDocumentReady; Ext.onReady(function(){ var bd = Ext.getBody(); if(!bd){ return; } var cls = [ Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : 'ext-ie7') : Ext.isGecko ? "ext-gecko" : Ext.isOpera ? "ext-opera" : Ext.isSafari ? "ext-safari" : ""]; if(Ext.isMac){ cls.push("ext-mac"); } if(Ext.isLinux){ cls.push("ext-linux"); } if(Ext.isBorderBox){ cls.push('ext-border-box'); } if(Ext.isStrict){ var p = bd.dom.parentNode; if(p){ p.className += ' ext-strict'; } } bd.addClass(cls.join(' ')); }); Ext.EventObject = function(){ var E = Ext.lib.Event; var safariKeys = { 63234 : 37, 63235 : 39, 63232 : 38, 63233 : 40, 63276 : 33, 63277 : 34, 63272 : 46, 63273 : 36, 63275 : 35 }; var btnMap = Ext.isIE ? {1:0,4:1,2:2} : (Ext.isSafari ? {1:0,2:1,3:2} : {0:0,1:1,2:2}); Ext.EventObjectImpl = function(e){ if(e){ this.setEvent(e.browserEvent || e); } }; Ext.EventObjectImpl.prototype = { browserEvent : null, button : -1, shiftKey : false, ctrlKey : false, altKey : false, BACKSPACE : 8, TAB : 9, RETURN : 13, ENTER : 13, SHIFT : 16, CONTROL : 17, ESC : 27, SPACE : 32, PAGEUP : 33, PAGEDOWN : 34, END : 35, HOME : 36, LEFT : 37, UP : 38, RIGHT : 39, DOWN : 40, DELETE : 46, F5 : 116, setEvent : function(e){ if(e == this || (e && e.browserEvent)){ return e; } this.browserEvent = e; if(e){ this.button = e.button ? btnMap[e.button] : (e.which ? e.which-1 : -1); if(e.type == 'click' && this.button == -1){ this.button = 0; } this.type = e.type; this.shiftKey = e.shiftKey; this.ctrlKey = e.ctrlKey || e.metaKey; this.altKey = e.altKey; this.keyCode = e.keyCode; this.charCode = e.charCode; this.target = E.getTarget(e); this.xy = E.getXY(e); }else{ this.button = -1; this.shiftKey = false; this.ctrlKey = false; this.altKey = false; this.keyCode = 0; this.charCode =0; this.target = null; this.xy = [0, 0]; } return this; }, stopEvent : function(){ if(this.browserEvent){ if(this.browserEvent.type == 'mousedown'){ Ext.EventManager.stoppedMouseDownEvent.fire(this); } E.stopEvent(this.browserEvent); } }, preventDefault : function(){ if(this.browserEvent){ E.preventDefault(this.browserEvent); } }, isNavKeyPress : function(){ var k = this.keyCode; k = Ext.isSafari ? (safariKeys[k] || k) : k; return (k >= 33 && k <= 40) || k == this.RETURN || k == this.TAB || k == this.ESC; }, isSpecialKey : function(){ var k = this.keyCode; return (this.type == 'keypress' && this.ctrlKey) || k == 9 || k == 13 || k == 40 || k == 27 || (k == 16) || (k == 17) || (k >= 18 && k <= 20) || (k >= 33 && k <= 35) || (k >= 36 && k <= 39) || (k >= 44 && k <= 45); }, stopPropagation : function(){ if(this.browserEvent){ if(this.browserEvent.type == 'mousedown'){ Ext.EventManager.stoppedMouseDownEvent.fire(this); } E.stopPropagation(this.browserEvent); } }, getCharCode : function(){ return this.charCode || this.keyCode; }, getKey : function(){ var k = this.keyCode || this.charCode; return Ext.isSafari ? (safariKeys[k] || k) : k; }, getPageX : function(){ return this.xy[0]; }, getPageY : function(){ return this.xy[1]; }, getTime : function(){ if(this.browserEvent){ return E.getTime(this.browserEvent); } return null; }, getXY : function(){ return this.xy; }, getTarget : function(selector, maxDepth, returnEl){ var t = Ext.get(this.target); return selector ? t.findParent(selector, maxDepth, returnEl) : (returnEl ? t : this.target); }, getRelatedTarget : function(){ if(this.browserEvent){ return E.getRelatedTarget(this.browserEvent); } return null; }, getWheelDelta : function(){ var e = this.browserEvent; var delta = 0; if(e.wheelDelta){ delta = e.wheelDelta/120; }else if(e.detail){ delta = -e.detail/3; } return delta; }, hasModifier : function(){ return ((this.ctrlKey || this.altKey) || this.shiftKey) ? true : false; }, within : function(el, related){ var t = this[related ? "getRelatedTarget" : "getTarget"](); try { return t && Ext.fly(el).contains(t); } catch(e){} return false; }, getPoint : function(){ return new Ext.lib.Point(this.xy[0], this.xy[1]); } }; return new Ext.EventObjectImpl(); }(); (function(){ var D = Ext.lib.Dom; var E = Ext.lib.Event; var A = Ext.lib.Anim; var propCache = {}; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; var view = document.defaultView; Ext.Element = function(element, forceNew){ var dom = typeof element == "string" ? document.getElementById(element) : element; if(!dom){ return null; } var id = dom.id; if(forceNew !== true && id && Ext.Element.cache[id]){ return Ext.Element.cache[id]; } this.dom = dom; this.id = id || Ext.id(dom); }; var El = Ext.Element; El.prototype = { originalDisplay : "", visibilityMode : 1, defaultUnit : "px", setVisibilityMode : function(visMode){ this.visibilityMode = visMode; return this; }, enableDisplayMode : function(display){ this.setVisibilityMode(El.DISPLAY); if(typeof display != "undefined") this.originalDisplay = display; return this; }, findParent : function(simpleSelector, maxDepth, returnEl){ var p = this.dom, b = document.body, depth = 0, dq = Ext.DomQuery, stopEl; maxDepth = maxDepth || 50; if(typeof maxDepth != "number"){ stopEl = Ext.getDom(maxDepth); maxDepth = 10; } while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){ if(dq.is(p, simpleSelector)){ return returnEl ? Ext.get(p) : p; } depth++; p = p.parentNode; } return null; }, findParentNode : function(simpleSelector, maxDepth, returnEl){ var p = Ext.fly(this.dom.parentNode, '_internal'); return p ? p.findParent(simpleSelector, maxDepth, returnEl) : null; }, up : function(simpleSelector, maxDepth){ return this.findParentNode(simpleSelector, maxDepth, true); }, is : function(simpleSelector){ return Ext.DomQuery.is(this.dom, simpleSelector); }, animate : function(args, duration, onComplete, easing, animType){ this.anim(args, {duration: duration, callback: onComplete, easing: easing}, animType); return this; }, anim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); Ext.callback(opt.callback, opt.scope || this, [this, opt]); }, this ); opt.anim = anim; return anim; }, preanim : function(a, i){ return !a[i] ? false : (typeof a[i] == "object" ? a[i]: {duration: a[i+1], callback: a[i+2], easing: a[i+3]}); }, clean : function(forceReclean){ if(this.isCleaned && forceReclean !== true){ return this; } var ns = /\S/; var d = this.dom, n = d.firstChild, ni = -1; while(n){ var nx = n.nextSibling; if(n.nodeType == 3 && !ns.test(n.nodeValue)){ d.removeChild(n); }else{ n.nodeIndex = ++ni; } n = nx; } this.isCleaned = true; return this; }, scrollIntoView : function(container, hscroll){ var c = Ext.getDom(container) || Ext.getBody().dom; var el = this.dom; var o = this.getOffsetsTo(c), l = o[0] + c.scrollLeft, t = o[1] + c.scrollTop, b = t+el.offsetHeight, r = l+el.offsetWidth; var ch = c.clientHeight; var ct = parseInt(c.scrollTop, 10); var cl = parseInt(c.scrollLeft, 10); var cb = ct + ch; var cr = cl + c.clientWidth; if(el.offsetHeight > ch || t < ct){ c.scrollTop = t; }else if(b > cb){ c.scrollTop = b-ch; } c.scrollTop = c.scrollTop; if(hscroll !== false){ if(el.offsetWidth > c.clientWidth || l < cl){ c.scrollLeft = l; }else if(r > cr){ c.scrollLeft = r-c.clientWidth; } c.scrollLeft = c.scrollLeft; } return this; }, scrollChildIntoView : function(child, hscroll){ Ext.fly(child, '_scrollChildIntoView').scrollIntoView(this, hscroll); }, autoHeight : function(animate, duration, onComplete, easing){ var oldHeight = this.getHeight(); this.clip(); this.setHeight(1); setTimeout(function(){ var height = parseInt(this.dom.scrollHeight, 10); if(!animate){ this.setHeight(height); this.unclip(); if(typeof onComplete == "function"){ onComplete(); } }else{ this.setHeight(oldHeight); this.setHeight(height, animate, duration, function(){ this.unclip(); if(typeof onComplete == "function") onComplete(); }.createDelegate(this), easing); } }.createDelegate(this), 0); return this; }, contains : function(el){ if(!el){return false;} try { return D.isAncestor(this.dom, el.dom ? el.dom : el); } catch(e){} return false; }, isVisible : function(deep) { var vis = !(this.getStyle("visibility") == "hidden" || this.getStyle("display") == "none"); if(deep !== true || !vis){ return vis; } var p = this.dom.parentNode; while(p && p.tagName.toLowerCase() != "body"){ if(!Ext.fly(p, '_isVisible').isVisible()){ return false; } p = p.parentNode; } return true; }, select : function(selector, unique){ return El.select(selector, unique, this.dom); }, query : function(selector, unique){ return Ext.DomQuery.select(selector, this.dom); }, child : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(selector, this.dom); return returnDom ? n : Ext.get(n); }, down : function(selector, returnDom){ var n = Ext.DomQuery.selectNode(" > " + selector, this.dom); return returnDom ? n : Ext.get(n); }, initDD : function(group, config, overrides){ var dd = new Ext.dd.DD(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, initDDProxy : function(group, config, overrides){ var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, initDDTarget : function(group, config, overrides){ var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config); return Ext.apply(dd, overrides); }, setVisible : function(visible, animate){ if(!animate || !A){ if(this.visibilityMode == El.DISPLAY){ this.setDisplayed(visible); }else{ this.fixDisplay(); this.dom.style.visibility = visible ? "visible" : "hidden"; } }else{ var dom = this.dom; var visMode = this.visibilityMode; if(visible){ this.setOpacity(.01); this.setVisible(true); } this.anim({opacity: { to: (visible?1:0) }}, this.preanim(arguments, 1), null, .35, 'easeIn', function(){ if(!visible){ if(visMode == El.DISPLAY){ dom.style.display = "none"; }else{ dom.style.visibility = "hidden"; } Ext.get(dom).setOpacity(1); } }); } return this; }, isDisplayed : function() { return this.getStyle("display") != "none"; }, toggle : function(animate){ this.setVisible(!this.isVisible(), this.preanim(arguments, 0)); return this; }, setDisplayed : function(value) { if(typeof value == "boolean"){ value = value ? this.originalDisplay : "none"; } this.setStyle("display", value); return this; }, focus : function() { try{ this.dom.focus(); }catch(e){} return this; }, blur : function() { try{ this.dom.blur(); }catch(e){} return this; }, addClass : function(className){ if(Ext.isArray(className)){ for(var i = 0, len = className.length; i < len; i++) { this.addClass(className[i]); } }else{ if(className && !this.hasClass(className)){ this.dom.className = this.dom.className + " " + className; } } return this; }, radioClass : function(className){ var siblings = this.dom.parentNode.childNodes; for(var i = 0; i < siblings.length; i++) { var s = siblings[i]; if(s.nodeType == 1){ Ext.get(s).removeClass(className); } } this.addClass(className); return this; }, removeClass : function(className){ if(!className || !this.dom.className){ return this; } if(Ext.isArray(className)){ for(var i = 0, len = className.length; i < len; i++) { this.removeClass(className[i]); } }else{ if(this.hasClass(className)){ var re = this.classReCache[className]; if (!re) { re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g"); this.classReCache[className] = re; } this.dom.className = this.dom.className.replace(re, " "); } } return this; }, classReCache: {}, toggleClass : function(className){ if(this.hasClass(className)){ this.removeClass(className); }else{ this.addClass(className); } return this; }, hasClass : function(className){ return className && (' '+this.dom.className+' ').indexOf(' '+className+' ') != -1; }, replaceClass : function(oldClassName, newClassName){ this.removeClass(oldClassName); this.addClass(newClassName); return this; }, getStyles : function(){ var a = arguments, len = a.length, r = {}; for(var i = 0; i < len; i++){ r[a[i]] = this.getStyle(a[i]); } return r; }, getStyle : function(){ return view && view.getComputedStyle ? function(prop){ var el = this.dom, v, cs, camel; if(prop == 'float'){ prop = "cssFloat"; } if(v = el.style[prop]){ return v; } if(cs = view.getComputedStyle(el, "")){ if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } return cs[camel]; } return null; } : function(prop){ var el = this.dom, v, cs, camel; if(prop == 'opacity'){ if(typeof el.style.filter == 'string'){ var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i); if(m){ var fv = parseFloat(m[1]); if(!isNaN(fv)){ return fv ? fv / 100 : 0; } } } return 1; }else if(prop == 'float'){ prop = "styleFloat"; } if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(v = el.style[camel]){ return v; } if(cs = el.currentStyle){ return cs[camel]; } return null; }; }(), setStyle : function(prop, value){ if(typeof prop == "string"){ var camel; if(!(camel = propCache[prop])){ camel = propCache[prop] = prop.replace(camelRe, camelFn); } if(camel == 'opacity') { this.setOpacity(value); }else{ this.dom.style[camel] = value; } }else{ for(var style in prop){ if(typeof prop[style] != "function"){ this.setStyle(style, prop[style]); } } } return this; }, applyStyles : function(style){ Ext.DomHelper.applyStyles(this.dom, style); return this; }, getX : function(){ return D.getX(this.dom); }, getY : function(){ return D.getY(this.dom); }, getXY : function(){ return D.getXY(this.dom); }, getOffsetsTo : function(el){ var o = this.getXY(); var e = Ext.fly(el, '_internal').getXY(); return [o[0]-e[0],o[1]-e[1]]; }, setX : function(x, animate){ if(!animate || !A){ D.setX(this.dom, x); }else{ this.setXY([x, this.getY()], this.preanim(arguments, 1)); } return this; }, setY : function(y, animate){ if(!animate || !A){ D.setY(this.dom, y); }else{ this.setXY([this.getX(), y], this.preanim(arguments, 1)); } return this; }, setLeft : function(left){ this.setStyle("left", this.addUnits(left)); return this; }, setTop : function(top){ this.setStyle("top", this.addUnits(top)); return this; }, setRight : function(right){ this.setStyle("right", this.addUnits(right)); return this; }, setBottom : function(bottom){ this.setStyle("bottom", this.addUnits(bottom)); return this; }, setXY : function(pos, animate){ if(!animate || !A){ D.setXY(this.dom, pos); }else{ this.anim({points: {to: pos}}, this.preanim(arguments, 1), 'motion'); } return this; }, setLocation : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, moveTo : function(x, y, animate){ this.setXY([x, y], this.preanim(arguments, 2)); return this; }, getRegion : function(){ return D.getRegion(this.dom); }, getHeight : function(contentHeight){ var h = this.dom.offsetHeight || 0; h = contentHeight !== true ? h : h-this.getBorderWidth("tb")-this.getPadding("tb"); return h < 0 ? 0 : h; }, getWidth : function(contentWidth){ var w = this.dom.offsetWidth || 0; w = contentWidth !== true ? w : w-this.getBorderWidth("lr")-this.getPadding("lr"); return w < 0 ? 0 : w; }, getComputedHeight : function(){ var h = Math.max(this.dom.offsetHeight, this.dom.clientHeight); if(!h){ h = parseInt(this.getStyle('height'), 10) || 0; if(!this.isBorderBox()){ h += this.getFrameWidth('tb'); } } return h; }, getComputedWidth : function(){ var w = Math.max(this.dom.offsetWidth, this.dom.clientWidth); if(!w){ w = parseInt(this.getStyle('width'), 10) || 0; if(!this.isBorderBox()){ w += this.getFrameWidth('lr'); } } return w; }, getSize : function(contentSize){ return {width: this.getWidth(contentSize), height: this.getHeight(contentSize)}; }, getStyleSize : function(){ var w, h, d = this.dom, s = d.style; if(s.width && s.width != 'auto'){ w = parseInt(s.width, 10); if(Ext.isBorderBox){ w -= this.getFrameWidth('lr'); } } if(s.height && s.height != 'auto'){ h = parseInt(s.height, 10); if(Ext.isBorderBox){ h -= this.getFrameWidth('tb'); } } return {width: w || this.getWidth(true), height: h || this.getHeight(true)}; }, getViewSize : function(){ var d = this.dom, doc = document, aw = 0, ah = 0; if(d == doc || d == doc.body){ return {width : D.getViewWidth(), height: D.getViewHeight()}; }else{ return { width : d.clientWidth, height: d.clientHeight }; } }, getValue : function(asNumber){ return asNumber ? parseInt(this.dom.value, 10) : this.dom.value; }, adjustWidth : function(width){ if(typeof width == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ width -= (this.getBorderWidth("lr") + this.getPadding("lr")); } if(width < 0){ width = 0; } } return width; }, adjustHeight : function(height){ if(typeof height == "number"){ if(this.autoBoxAdjust && !this.isBorderBox()){ height -= (this.getBorderWidth("tb") + this.getPadding("tb")); } if(height < 0){ height = 0; } } return height; }, setWidth : function(width, animate){ width = this.adjustWidth(width); if(!animate || !A){ this.dom.style.width = this.addUnits(width); }else{ this.anim({width: {to: width}}, this.preanim(arguments, 1)); } return this; }, setHeight : function(height, animate){ height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.height = this.addUnits(height); }else{ this.anim({height: {to: height}}, this.preanim(arguments, 1)); } return this; }, setSize : function(width, height, animate){ if(typeof width == "object"){ height = width.height; width = width.width; } width = this.adjustWidth(width); height = this.adjustHeight(height); if(!animate || !A){ this.dom.style.width = this.addUnits(width); this.dom.style.height = this.addUnits(height); }else{ this.anim({width: {to: width}, height: {to: height}}, this.preanim(arguments, 2)); } return this; }, setBounds : function(x, y, width, height, animate){ if(!animate || !A){ this.setSize(width, height); this.setLocation(x, y); }else{ width = this.adjustWidth(width); height = this.adjustHeight(height); this.anim({points: {to: [x, y]}, width: {to: width}, height: {to: height}}, this.preanim(arguments, 4), 'motion'); } return this; }, setRegion : function(region, animate){ this.setBounds(region.left, region.top, region.right-region.left, region.bottom-region.top, this.preanim(arguments, 1)); return this; }, addListener : function(eventName, fn, scope, options){ Ext.EventManager.on(this.dom, eventName, fn, scope || this, options); }, removeListener : function(eventName, fn){ Ext.EventManager.removeListener(this.dom, eventName, fn); return this; }, removeAllListeners : function(){ E.purgeElement(this.dom); return this; }, relayEvent : function(eventName, observable){ this.on(eventName, function(e){ observable.fireEvent(eventName, e); }); }, setOpacity : function(opacity, animate){ if(!animate || !A){ var s = this.dom.style; if(Ext.isIE){ s.zoom = 1; s.filter = (s.filter || '').replace(/alpha\([^\)]*\)/gi,"") + (opacity == 1 ? "" : " alpha(opacity=" + opacity * 100 + ")"); }else{ s.opacity = opacity; } }else{ this.anim({opacity: {to: opacity}}, this.preanim(arguments, 1), null, .35, 'easeIn'); } return this; }, getLeft : function(local){ if(!local){ return this.getX(); }else{ return parseInt(this.getStyle("left"), 10) || 0; } }, getRight : function(local){ if(!local){ return this.getX() + this.getWidth(); }else{ return (this.getLeft(true) + this.getWidth()) || 0; } }, getTop : function(local) { if(!local){ return this.getY(); }else{ return parseInt(this.getStyle("top"), 10) || 0; } }, getBottom : function(local){ if(!local){ return this.getY() + this.getHeight(); }else{ return (this.getTop(true) + this.getHeight()) || 0; } }, position : function(pos, zIndex, x, y){ if(!pos){ if(this.getStyle('position') == 'static'){ this.setStyle('position', 'relative'); } }else{ this.setStyle("position", pos); } if(zIndex){ this.setStyle("z-index", zIndex); } if(x !== undefined && y !== undefined){ this.setXY([x, y]); }else if(x !== undefined){ this.setX(x); }else if(y !== undefined){ this.setY(y); } }, clearPositioning : function(value){ value = value ||''; this.setStyle({ "left": value, "right": value, "top": value, "bottom": value, "z-index": "", "position" : "static" }); return this; }, getPositioning : function(){ var l = this.getStyle("left"); var t = this.getStyle("top"); return { "position" : this.getStyle("position"), "left" : l, "right" : l ? "" : this.getStyle("right"), "top" : t, "bottom" : t ? "" : this.getStyle("bottom"), "z-index" : this.getStyle("z-index") }; }, getBorderWidth : function(side){ return this.addStyles(side, El.borders); }, getPadding : function(side){ return this.addStyles(side, El.paddings); }, setPositioning : function(pc){ this.applyStyles(pc); if(pc.right == "auto"){ this.dom.style.right = ""; } if(pc.bottom == "auto"){ this.dom.style.bottom = ""; } return this; }, fixDisplay : function(){ if(this.getStyle("display") == "none"){ this.setStyle("visibility", "hidden"); this.setStyle("display", this.originalDisplay); if(this.getStyle("display") == "none"){ this.setStyle("display", "block"); } } }, setOverflow : function(v){ if(v=='auto' && Ext.isMac && Ext.isGecko){ this.dom.style.overflow = 'hidden'; (function(){this.dom.style.overflow = 'auto';}).defer(1, this); }else{ this.dom.style.overflow = v; } }, setLeftTop : function(left, top){ this.dom.style.left = this.addUnits(left); this.dom.style.top = this.addUnits(top); return this; }, move : function(direction, distance, animate){ var xy = this.getXY(); direction = direction.toLowerCase(); switch(direction){ case "l": case "left": this.moveTo(xy[0]-distance, xy[1], this.preanim(arguments, 2)); break; case "r": case "right": this.moveTo(xy[0]+distance, xy[1], this.preanim(arguments, 2)); break; case "t": case "top": case "up": this.moveTo(xy[0], xy[1]-distance, this.preanim(arguments, 2)); break; case "b": case "bottom": case "down": this.moveTo(xy[0], xy[1]+distance, this.preanim(arguments, 2)); break; } return this; }, clip : function(){ if(!this.isClipped){ this.isClipped = true; this.originalClip = { "o": this.getStyle("overflow"), "x": this.getStyle("overflow-x"), "y": this.getStyle("overflow-y") }; this.setStyle("overflow", "hidden"); this.setStyle("overflow-x", "hidden"); this.setStyle("overflow-y", "hidden"); } return this; }, unclip : function(){ if(this.isClipped){ this.isClipped = false; var o = this.originalClip; if(o.o){this.setStyle("overflow", o.o);} if(o.x){this.setStyle("overflow-x", o.x);} if(o.y){this.setStyle("overflow-y", o.y);} } return this; }, getAnchorXY : function(anchor, local, s){ var w, h, vp = false; if(!s){ var d = this.dom; if(d == document.body || d == document){ vp = true; w = D.getViewWidth(); h = D.getViewHeight(); }else{ w = this.getWidth(); h = this.getHeight(); } }else{ w = s.width; h = s.height; } var x = 0, y = 0, r = Math.round; switch((anchor || "tl").toLowerCase()){ case "c": x = r(w*.5); y = r(h*.5); break; case "t": x = r(w*.5); y = 0; break; case "l": x = 0; y = r(h*.5); break; case "r": x = w; y = r(h*.5); break; case "b": x = r(w*.5); y = h; break; case "tl": x = 0; y = 0; break; case "bl": x = 0; y = h; break; case "br": x = w; y = h; break; case "tr": x = w; y = 0; break; } if(local === true){ return [x, y]; } if(vp){ var sc = this.getScroll(); return [x + sc.left, y + sc.top]; } var o = this.getXY(); return [x+o[0], y+o[1]]; }, getAlignToXY : function(el, p, o){ el = Ext.get(el); if(!el || !el.dom){ throw "Element.alignToXY with an element that doesn't exist"; } var d = this.dom; var c = false; var p1 = "", p2 = ""; o = o || [0,0]; if(!p){ p = "tl-bl"; }else if(p == "?"){ p = "tl-bl?"; }else if(p.indexOf("-") == -1){ p = "tl-" + p; } p = p.toLowerCase(); var m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/); if(!m){ throw "Element.alignTo with an invalid alignment " + p; } p1 = m[1]; p2 = m[2]; c = !!m[3]; var a1 = this.getAnchorXY(p1, true); var a2 = el.getAnchorXY(p2, false); var x = a2[0] - a1[0] + o[0]; var y = a2[1] - a1[1] + o[1]; if(c){ var w = this.getWidth(), h = this.getHeight(), r = el.getRegion(); var dw = D.getViewWidth()-5, dh = D.getViewHeight()-5; var p1y = p1.charAt(0), p1x = p1.charAt(p1.length-1); var p2y = p2.charAt(0), p2x = p2.charAt(p2.length-1); var swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t")); var swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r")); var doc = document; var scrollX = (doc.documentElement.scrollLeft || doc.body.scrollLeft || 0)+5; var scrollY = (doc.documentElement.scrollTop || doc.body.scrollTop || 0)+5; if((x+w) > dw + scrollX){ x = swapX ? r.left-w : dw+scrollX-w; } if(x < scrollX){ x = swapX ? r.right : scrollX; } if((y+h) > dh + scrollY){ y = swapY ? r.top-h : dh+scrollY-h; } if (y < scrollY){ y = swapY ? r.bottom : scrollY; } } return [x,y]; }, getConstrainToXY : function(){ var os = {top:0, left:0, bottom:0, right: 0}; return function(el, local, offsets, proposedXY){ el = Ext.get(el); offsets = offsets ? Ext.applyIf(offsets, os) : os; var vw, vh, vx = 0, vy = 0; if(el.dom == document.body || el.dom == document){ vw = Ext.lib.Dom.getViewWidth(); vh = Ext.lib.Dom.getViewHeight(); }else{ vw = el.dom.clientWidth; vh = el.dom.clientHeight; if(!local){ var vxy = el.getXY(); vx = vxy[0]; vy = vxy[1]; } } var s = el.getScroll(); vx += offsets.left + s.left; vy += offsets.top + s.top; vw -= offsets.right; vh -= offsets.bottom; var vr = vx+vw; var vb = vy+vh; var xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth, h = this.dom.offsetHeight; var moved = false; if((x + w) > vr){ x = vr - w; moved = true; } if((y + h) > vb){ y = vb - h; moved = true; } if(x < vx){ x = vx; moved = true; } if(y < vy){ y = vy; moved = true; } return moved ? [x, y] : false; }; }(), adjustForConstraints : function(xy, parent, offsets){ return this.getConstrainToXY(parent || document, false, offsets, xy) || xy; }, alignTo : function(element, position, offsets, animate){ var xy = this.getAlignToXY(element, position, offsets); this.setXY(xy, this.preanim(arguments, 3)); return this; }, anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){ var action = function(){ this.alignTo(el, alignment, offsets, animate); Ext.callback(callback, this); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); return this; }, clearOpacity : function(){ if (window.ActiveXObject) { if(typeof this.dom.style.filter == 'string' && (/alpha/i).test(this.dom.style.filter)){ this.dom.style.filter = ""; } } else { this.dom.style.opacity = ""; this.dom.style["-moz-opacity"] = ""; this.dom.style["-khtml-opacity"] = ""; } return this; }, hide : function(animate){ this.setVisible(false, this.preanim(arguments, 0)); return this; }, show : function(animate){ this.setVisible(true, this.preanim(arguments, 0)); return this; }, addUnits : function(size){ return Ext.Element.addUnits(size, this.defaultUnit); }, update : function(html, loadScripts, callback){ if(typeof html == "undefined"){ html = ""; } if(loadScripts !== true){ this.dom.innerHTML = html; if(typeof callback == "function"){ callback(); } return this; } var id = Ext.id(); var dom = this.dom; html += '<span id="' + id + '"></span>'; E.onAvailable(id, function(){ var hd = document.getElementsByTagName("head")[0]; var re = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig; var srcRe = /\ssrc=([\'\"])(.*?)\1/i; var typeRe = /\stype=([\'\"])(.*?)\1/i; var match; while(match = re.exec(html)){ var attrs = match[1]; var srcMatch = attrs ? attrs.match(srcRe) : false; if(srcMatch && srcMatch[2]){ var s = document.createElement("script"); s.src = srcMatch[2]; var typeMatch = attrs.match(typeRe); if(typeMatch && typeMatch[2]){ s.type = typeMatch[2]; } hd.appendChild(s); }else if(match[2] && match[2].length > 0){ if(window.execScript) { window.execScript(match[2]); } else { window.eval(match[2]); } } } var el = document.getElementById(id); if(el){Ext.removeNode(el);} if(typeof callback == "function"){ callback(); } }); dom.innerHTML = html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, ""); return this; }, load : function(){ var um = this.getUpdater(); um.update.apply(um, arguments); return this; }, getUpdater : function(){ if(!this.updateManager){ this.updateManager = new Ext.Updater(this); } return this.updateManager; }, unselectable : function(){ this.dom.unselectable = "on"; this.swallowEvent("selectstart", true); this.applyStyles("-moz-user-select:none;-khtml-user-select:none;"); this.addClass("x-unselectable"); return this; }, getCenterXY : function(){ return this.getAlignToXY(document, 'c-c'); }, center : function(centerIn){ this.alignTo(centerIn || document, 'c-c'); return this; }, isBorderBox : function(){ return noBoxAdjust[this.dom.tagName.toLowerCase()] || Ext.isBorderBox; }, getBox : function(contentBox, local){ var xy; if(!local){ xy = this.getXY(); }else{ var left = parseInt(this.getStyle("left"), 10) || 0; var top = parseInt(this.getStyle("top"), 10) || 0; xy = [left, top]; } var el = this.dom, w = el.offsetWidth, h = el.offsetHeight, bx; if(!contentBox){ bx = {x: xy[0], y: xy[1], 0: xy[0], 1: xy[1], width: w, height: h}; }else{ var l = this.getBorderWidth("l")+this.getPadding("l"); var r = this.getBorderWidth("r")+this.getPadding("r"); var t = this.getBorderWidth("t")+this.getPadding("t"); var b = this.getBorderWidth("b")+this.getPadding("b"); bx = {x: xy[0]+l, y: xy[1]+t, 0: xy[0]+l, 1: xy[1]+t, width: w-(l+r), height: h-(t+b)}; } bx.right = bx.x + bx.width; bx.bottom = bx.y + bx.height; return bx; }, getFrameWidth : function(sides, onlyContentBox){ return onlyContentBox && Ext.isBorderBox ? 0 : (this.getPadding(sides) + this.getBorderWidth(sides)); }, setBox : function(box, adjust, animate){ var w = box.width, h = box.height; if((adjust && !this.autoBoxAdjust) && !this.isBorderBox()){ w -= (this.getBorderWidth("lr") + this.getPadding("lr")); h -= (this.getBorderWidth("tb") + this.getPadding("tb")); } this.setBounds(box.x, box.y, w, h, this.preanim(arguments, 2)); return this; }, repaint : function(){ var dom = this.dom; this.addClass("x-repaint"); setTimeout(function(){ Ext.get(dom).removeClass("x-repaint"); }, 1); return this; }, getMargins : function(side){ if(!side){ return { top: parseInt(this.getStyle("margin-top"), 10) || 0, left: parseInt(this.getStyle("margin-left"), 10) || 0, bottom: parseInt(this.getStyle("margin-bottom"), 10) || 0, right: parseInt(this.getStyle("margin-right"), 10) || 0 }; }else{ return this.addStyles(side, El.margins); } }, addStyles : function(sides, styles){ var val = 0, v, w; for(var i = 0, len = sides.length; i < len; i++){ v = this.getStyle(styles[sides.charAt(i)]); if(v){ w = parseInt(v, 10); if(w){ val += (w >= 0 ? w : -1 * w); } } } return val; }, createProxy : function(config, renderTo, matchBox){ config = typeof config == "object" ? config : {tag : "div", cls: config}; var proxy; if(renderTo){ proxy = Ext.DomHelper.append(renderTo, config, true); }else { proxy = Ext.DomHelper.insertBefore(this.dom, config, true); } if(matchBox){ proxy.setBox(this.getBox()); } return proxy; }, mask : function(msg, msgCls){ if(this.getStyle("position") == "static"){ this.setStyle("position", "relative"); } if(this._maskMsg){ this._maskMsg.remove(); } if(this._mask){ this._mask.remove(); } this._mask = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask"}, true); this.addClass("x-masked"); this._mask.setDisplayed(true); if(typeof msg == 'string'){ this._maskMsg = Ext.DomHelper.append(this.dom, {cls:"ext-el-mask-msg", cn:{tag:'div'}}, true); var mm = this._maskMsg; mm.dom.className = msgCls ? "ext-el-mask-msg " + msgCls : "ext-el-mask-msg"; mm.dom.firstChild.innerHTML = msg; mm.setDisplayed(true); mm.center(this); } if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ this._mask.setSize(this.dom.clientWidth, this.getHeight()); } return this._mask; }, unmask : function(){ if(this._mask){ if(this._maskMsg){ this._maskMsg.remove(); delete this._maskMsg; } this._mask.remove(); delete this._mask; } this.removeClass("x-masked"); }, isMasked : function(){ return this._mask && this._mask.isVisible(); }, createShim : function(){ var el = document.createElement('iframe'); el.frameBorder = 'no'; el.className = 'ext-shim'; if(Ext.isIE && Ext.isSecure){ el.src = Ext.SSL_SECURE_URL; } var shim = Ext.get(this.dom.parentNode.insertBefore(el, this.dom)); shim.autoBoxAdjust = false; return shim; }, remove : function(){ Ext.removeNode(this.dom); delete El.cache[this.dom.id]; }, hover : function(overFn, outFn, scope){ var preOverFn = function(e){ if(!e.within(this, true)){ overFn.apply(scope || this, arguments); } }; var preOutFn = function(e){ if(!e.within(this, true)){ outFn.apply(scope || this, arguments); } }; this.on("mouseover", preOverFn, this.dom); this.on("mouseout", preOutFn, this.dom); return this; }, addClassOnOver : function(className, preventFlicker){ this.hover( function(){ Ext.fly(this, '_internal').addClass(className); }, function(){ Ext.fly(this, '_internal').removeClass(className); } ); return this; }, addClassOnFocus : function(className){ this.on("focus", function(){ Ext.fly(this, '_internal').addClass(className); }, this.dom); this.on("blur", function(){ Ext.fly(this, '_internal').removeClass(className); }, this.dom); return this; }, addClassOnClick : function(className){ var dom = this.dom; this.on("mousedown", function(){ Ext.fly(dom, '_internal').addClass(className); var d = Ext.getDoc(); var fn = function(){ Ext.fly(dom, '_internal').removeClass(className); d.removeListener("mouseup", fn); }; d.on("mouseup", fn); }); return this; }, swallowEvent : function(eventName, preventDefault){ var fn = function(e){ e.stopPropagation(); if(preventDefault){ e.preventDefault(); } }; if(Ext.isArray(eventName)){ for(var i = 0, len = eventName.length; i < len; i++){ this.on(eventName[i], fn); } return this; } this.on(eventName, fn); return this; }, parent : function(selector, returnDom){ return this.matchNode('parentNode', 'parentNode', selector, returnDom); }, next : function(selector, returnDom){ return this.matchNode('nextSibling', 'nextSibling', selector, returnDom); }, prev : function(selector, returnDom){ return this.matchNode('previousSibling', 'previousSibling', selector, returnDom); }, first : function(selector, returnDom){ return this.matchNode('nextSibling', 'firstChild', selector, returnDom); }, last : function(selector, returnDom){ return this.matchNode('previousSibling', 'lastChild', selector, returnDom); }, matchNode : function(dir, start, selector, returnDom){ var n = this.dom[start]; while(n){ if(n.nodeType == 1 && (!selector || Ext.DomQuery.is(n, selector))){ return !returnDom ? Ext.get(n) : n; } n = n[dir]; } return null; }, appendChild: function(el){ el = Ext.get(el); el.appendTo(this); return this; }, createChild: function(config, insertBefore, returnDom){ config = config || {tag:'div'}; if(insertBefore){ return Ext.DomHelper.insertBefore(insertBefore, config, returnDom !== true); } return Ext.DomHelper[!this.dom.firstChild ? 'overwrite' : 'append'](this.dom, config, returnDom !== true); }, appendTo: function(el){ el = Ext.getDom(el); el.appendChild(this.dom); return this; }, insertBefore: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el); return this; }, insertAfter: function(el){ el = Ext.getDom(el); el.parentNode.insertBefore(this.dom, el.nextSibling); return this; }, insertFirst: function(el, returnDom){ el = el || {}; if(typeof el == 'object' && !el.nodeType && !el.dom){ return this.createChild(el, this.dom.firstChild, returnDom); }else{ el = Ext.getDom(el); this.dom.insertBefore(el, this.dom.firstChild); return !returnDom ? Ext.get(el) : el; } }, insertSibling: function(el, where, returnDom){ var rt; if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++){ rt = this.insertSibling(el[i], where, returnDom); } return rt; } where = where ? where.toLowerCase() : 'before'; el = el || {}; var refNode = where == 'before' ? this.dom : this.dom.nextSibling; if(typeof el == 'object' && !el.nodeType && !el.dom){ if(where == 'after' && !this.dom.nextSibling){ rt = Ext.DomHelper.append(this.dom.parentNode, el, !returnDom); }else{ rt = Ext.DomHelper[where == 'after' ? 'insertAfter' : 'insertBefore'](this.dom, el, !returnDom); } }else{ rt = this.dom.parentNode.insertBefore(Ext.getDom(el), refNode); if(!returnDom){ rt = Ext.get(rt); } } return rt; }, wrap: function(config, returnDom){ if(!config){ config = {tag: "div"}; } var newEl = Ext.DomHelper.insertBefore(this.dom, config, !returnDom); newEl.dom ? newEl.dom.appendChild(this.dom) : newEl.appendChild(this.dom); return newEl; }, replace: function(el){ el = Ext.get(el); this.insertBefore(el); el.remove(); return this; }, replaceWith: function(el){ if(typeof el == 'object' && !el.nodeType && !el.dom){ el = this.insertSibling(el, 'before'); }else{ el = Ext.getDom(el); this.dom.parentNode.insertBefore(el, this.dom); } El.uncache(this.id); this.dom.parentNode.removeChild(this.dom); this.dom = el; this.id = Ext.id(el); El.cache[this.id] = this; return this; }, insertHtml : function(where, html, returnEl){ var el = Ext.DomHelper.insertHtml(where, this.dom, html); return returnEl ? Ext.get(el) : el; }, set : function(o, useSet){ var el = this.dom; useSet = typeof useSet == 'undefined' ? (el.setAttribute ? true : false) : useSet; for(var attr in o){ if(attr == "style" || typeof o[attr] == "function") continue; if(attr=="cls"){ el.className = o["cls"]; }else if(o.hasOwnProperty(attr)){ if(useSet) el.setAttribute(attr, o[attr]); else el[attr] = o[attr]; } } if(o.style){ Ext.DomHelper.applyStyles(el, o.style); } return this; }, addKeyListener : function(key, fn, scope){ var config; if(typeof key != "object" || Ext.isArray(key)){ config = { key: key, fn: fn, scope: scope }; }else{ config = { key : key.key, shift : key.shift, ctrl : key.ctrl, alt : key.alt, fn: fn, scope: scope }; } return new Ext.KeyMap(this, config); }, addKeyMap : function(config){ return new Ext.KeyMap(this, config); }, isScrollable : function(){ var dom = this.dom; return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth; }, scrollTo : function(side, value, animate){ var prop = side.toLowerCase() == "left" ? "scrollLeft" : "scrollTop"; if(!animate || !A){ this.dom[prop] = value; }else{ var to = prop == "scrollLeft" ? [value, this.dom.scrollTop] : [this.dom.scrollLeft, value]; this.anim({scroll: {"to": to}}, this.preanim(arguments, 2), 'scroll'); } return this; }, scroll : function(direction, distance, animate){ if(!this.isScrollable()){ return; } var el = this.dom; var l = el.scrollLeft, t = el.scrollTop; var w = el.scrollWidth, h = el.scrollHeight; var cw = el.clientWidth, ch = el.clientHeight; direction = direction.toLowerCase(); var scrolled = false; var a = this.preanim(arguments, 2); switch(direction){ case "l": case "left": if(w - l > cw){ var v = Math.min(l + distance, w-cw); this.scrollTo("left", v, a); scrolled = true; } break; case "r": case "right": if(l > 0){ var v = Math.max(l - distance, 0); this.scrollTo("left", v, a); scrolled = true; } break; case "t": case "top": case "up": if(t > 0){ var v = Math.max(t - distance, 0); this.scrollTo("top", v, a); scrolled = true; } break; case "b": case "bottom": case "down": if(h - t > ch){ var v = Math.min(t + distance, h-ch); this.scrollTo("top", v, a); scrolled = true; } break; } return scrolled; }, translatePoints : function(x, y){ if(typeof x == 'object' || Ext.isArray(x)){ y = x[1]; x = x[0]; } var p = this.getStyle('position'); var o = this.getXY(); var l = parseInt(this.getStyle('left'), 10); var t = parseInt(this.getStyle('top'), 10); if(isNaN(l)){ l = (p == "relative") ? 0 : this.dom.offsetLeft; } if(isNaN(t)){ t = (p == "relative") ? 0 : this.dom.offsetTop; } return {left: (x - o[0] + l), top: (y - o[1] + t)}; }, getScroll : function(){ var d = this.dom, doc = document; if(d == doc || d == doc.body){ var l, t; if(Ext.isIE && Ext.isStrict){ l = doc.documentElement.scrollLeft || (doc.body.scrollLeft || 0); t = doc.documentElement.scrollTop || (doc.body.scrollTop || 0); }else{ l = window.pageXOffset || (doc.body.scrollLeft || 0); t = window.pageYOffset || (doc.body.scrollTop || 0); } return {left: l, top: t}; }else{ return {left: d.scrollLeft, top: d.scrollTop}; } }, getColor : function(attr, defaultValue, prefix){ var v = this.getStyle(attr); if(!v || v == "transparent" || v == "inherit") { return defaultValue; } var color = typeof prefix == "undefined" ? "#" : prefix; if(v.substr(0, 4) == "rgb("){ var rvs = v.slice(4, v.length -1).split(","); for(var i = 0; i < 3; i++){ var h = parseInt(rvs[i]); var s = h.toString(16); if(h < 16){ s = "0" + s; } color += s; } } else { if(v.substr(0, 1) == "#"){ if(v.length == 4) { for(var i = 1; i < 4; i++){ var c = v.charAt(i); color += c + c; } }else if(v.length == 7){ color += v.substr(1); } } } return(color.length > 5 ? color.toLowerCase() : defaultValue); }, boxWrap : function(cls){ cls = cls || 'x-box'; var el = Ext.get(this.insertHtml('beforeBegin', String.format('<div class="{0}">'+El.boxMarkup+'</div>', cls))); el.child('.'+cls+'-mc').dom.appendChild(this.dom); return el; }, getAttributeNS : Ext.isIE ? function(ns, name){ var d = this.dom; var type = typeof d[ns+":"+name]; if(type != 'undefined' && type != 'unknown'){ return d[ns+":"+name]; } return d[name]; } : function(ns, name){ var d = this.dom; return d.getAttributeNS(ns, name) || d.getAttribute(ns+":"+name) || d.getAttribute(name) || d[name]; }, getTextWidth : function(text, min, max){ return (Ext.util.TextMetrics.measure(this.dom, Ext.value(text, this.dom.innerHTML, true)).width).constrain(min || 0, max || 1000000); } }; var ep = El.prototype; ep.on = ep.addListener; ep.mon = ep.addListener; ep.getUpdateManager = ep.getUpdater; ep.un = ep.removeListener; ep.autoBoxAdjust = true; El.unitPattern = /\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i; El.addUnits = function(v, defaultUnit){ if(v === "" || v == "auto"){ return v; } if(v === undefined){ return ''; } if(typeof v == "number" || !El.unitPattern.test(v)){ return v + (defaultUnit || 'px'); } return v; }; El.boxMarkup = '<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>'; El.VISIBILITY = 1; El.DISPLAY = 2; El.borders = {l: "border-left-width", r: "border-right-width", t: "border-top-width", b: "border-bottom-width"}; El.paddings = {l: "padding-left", r: "padding-right", t: "padding-top", b: "padding-bottom"}; El.margins = {l: "margin-left", r: "margin-right", t: "margin-top", b: "margin-bottom"}; El.cache = {}; var docEl; El.get = function(el){ var ex, elm, id; if(!el){ return null; } if(typeof el == "string"){ if(!(elm = document.getElementById(el))){ return null; } if(ex = El.cache[el]){ ex.dom = elm; }else{ ex = El.cache[el] = new El(elm); } return ex; }else if(el.tagName){ if(!(id = el.id)){ id = Ext.id(el); } if(ex = El.cache[id]){ ex.dom = el; }else{ ex = El.cache[id] = new El(el); } return ex; }else if(el instanceof El){ if(el != docEl){ el.dom = document.getElementById(el.id) || el.dom; El.cache[el.id] = el; } return el; }else if(el.isComposite){ return el; }else if(Ext.isArray(el)){ return El.select(el); }else if(el == document){ if(!docEl){ var f = function(){}; f.prototype = El.prototype; docEl = new f(); docEl.dom = document; } return docEl; } return null; }; El.uncache = function(el){ for(var i = 0, a = arguments, len = a.length; i < len; i++) { if(a[i]){ delete El.cache[a[i].id || a[i]]; } } }; El.garbageCollect = function(){ if(!Ext.enableGarbageCollector){ clearInterval(El.collectorThread); return; } for(var eid in El.cache){ var el = El.cache[eid], d = el.dom; if(!d || !d.parentNode || (!d.offsetParent && !document.getElementById(eid))){ delete El.cache[eid]; if(d && Ext.enableListenerCollection){ E.purgeElement(d); } } } } El.collectorThreadId = setInterval(El.garbageCollect, 30000); var flyFn = function(){}; flyFn.prototype = El.prototype; var _cls = new flyFn(); El.Flyweight = function(dom){ this.dom = dom; }; El.Flyweight.prototype = _cls; El.Flyweight.prototype.isFlyweight = true; El._flyweights = {}; El.fly = function(el, named){ named = named || '_global'; el = Ext.getDom(el); if(!el){ return null; } if(!El._flyweights[named]){ El._flyweights[named] = new El.Flyweight(); } El._flyweights[named].dom = el; return El._flyweights[named]; }; Ext.get = El.get; Ext.fly = El.fly; var noBoxAdjust = Ext.isStrict ? { select:1 } : { input:1, select:1, textarea:1 }; if(Ext.isIE || Ext.isGecko){ noBoxAdjust['button'] = 1; } Ext.EventManager.on(window, 'unload', function(){ delete El.cache; delete El._flyweights; }); })(); Ext.enableFx = true; Ext.Fx = { slideIn : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "t"; this.fixDisplay(); var r = this.getFxRestore(); var b = this.getBox(); this.setSize(b); var wrap = this.fxWrap(r.pos, o, "hidden"); var st = this.dom.style; st.visibility = "visible"; st.position = "absolute"; var after = function(){ el.fxUnwrap(wrap, r.pos, o); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a, pt = {to: [b.x, b.y]}, bw = {to: b.width}, bh = {to: b.height}; switch(anchor.toLowerCase()){ case "t": wrap.setSize(b.width, 0); st.left = st.bottom = "0"; a = {height: bh}; break; case "l": wrap.setSize(0, b.height); st.right = st.top = "0"; a = {width: bw}; break; case "r": wrap.setSize(0, b.height); wrap.setX(b.right); st.left = st.top = "0"; a = {width: bw, points: pt}; break; case "b": wrap.setSize(b.width, 0); wrap.setY(b.bottom); st.left = st.top = "0"; a = {height: bh, points: pt}; break; case "tl": wrap.setSize(0, 0); st.right = st.bottom = "0"; a = {width: bw, height: bh}; break; case "bl": wrap.setSize(0, 0); wrap.setY(b.y+b.height); st.right = st.top = "0"; a = {width: bw, height: bh, points: pt}; break; case "br": wrap.setSize(0, 0); wrap.setXY([b.right, b.bottom]); st.left = st.top = "0"; a = {width: bw, height: bh, points: pt}; break; case "tr": wrap.setSize(0, 0); wrap.setX(b.x+b.width); st.left = st.bottom = "0"; a = {width: bw, height: bh, points: pt}; break; } this.dom.style.visibility = "visible"; wrap.show(); arguments.callee.anim = wrap.fxanim(a, o, 'motion', .5, 'easeOut', after); }); return this; }, slideOut : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "t"; var r = this.getFxRestore(); var b = this.getBox(); this.setSize(b); var wrap = this.fxWrap(r.pos, o, "visible"); var st = this.dom.style; st.visibility = "visible"; st.position = "absolute"; wrap.setSize(b); var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.fxUnwrap(wrap, r.pos, o); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a, zero = {to: 0}; switch(anchor.toLowerCase()){ case "t": st.left = st.bottom = "0"; a = {height: zero}; break; case "l": st.right = st.top = "0"; a = {width: zero}; break; case "r": st.left = st.top = "0"; a = {width: zero, points: {to:[b.right, b.y]}}; break; case "b": st.left = st.top = "0"; a = {height: zero, points: {to:[b.x, b.bottom]}}; break; case "tl": st.right = st.bottom = "0"; a = {width: zero, height: zero}; break; case "bl": st.right = st.top = "0"; a = {width: zero, height: zero, points: {to:[b.x, b.bottom]}}; break; case "br": st.left = st.top = "0"; a = {width: zero, height: zero, points: {to:[b.x+b.width, b.bottom]}}; break; case "tr": st.left = st.bottom = "0"; a = {width: zero, height: zero, points: {to:[b.right, b.y]}}; break; } arguments.callee.anim = wrap.fxanim(a, o, 'motion', .5, "easeOut", after); }); return this; }, puff : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.clearOpacity(); this.show(); var r = this.getFxRestore(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; st.fontSize = ''; el.afterFx(o); }; var width = this.getWidth(); var height = this.getHeight(); arguments.callee.anim = this.fxanim({ width : {to: this.adjustWidth(width * 2)}, height : {to: this.adjustHeight(height * 2)}, points : {by: [-(width * .5), -(height * .5)]}, opacity : {to: 0}, fontSize: {to:200, unit: "%"} }, o, 'motion', .5, "easeOut", after); }); return this; }, switchOff : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.clearOpacity(); this.clip(); var r = this.getFxRestore(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; el.afterFx(o); }; this.fxanim({opacity:{to:0.3}}, null, null, .1, null, function(){ this.clearOpacity(); (function(){ this.fxanim({ height:{to:1}, points:{by:[0, this.getHeight() * .5]} }, o, 'motion', 0.3, 'easeIn', after); }).defer(100, this); }); }); return this; }, highlight : function(color, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ color = color || "ffff9c"; var attr = o.attr || "backgroundColor"; this.clearOpacity(); this.show(); var origColor = this.getColor(attr); var restoreColor = this.dom.style[attr]; var endColor = (o.endColor || origColor) || "ffffff"; var after = function(){ el.dom.style[attr] = restoreColor; el.afterFx(o); }; var a = {}; a[attr] = {from: color, to: endColor}; arguments.callee.anim = this.fxanim(a, o, 'color', 1, 'easeIn', after); }); return this; }, frame : function(color, count, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ color = color || "#C3DAF9"; if(color.length == 6){ color = "#" + color; } count = count || 1; var duration = o.duration || 1; this.show(); var b = this.getBox(); var animFn = function(){ var proxy = Ext.getBody().createChild({ style:{ visbility:"hidden", position:"absolute", "z-index":"35000", border:"0px solid " + color } }); var scale = Ext.isBorderBox ? 2 : 1; proxy.animate({ top:{from:b.y, to:b.y - 20}, left:{from:b.x, to:b.x - 20}, borderWidth:{from:0, to:10}, opacity:{from:1, to:0}, height:{from:b.height, to:(b.height + (20*scale))}, width:{from:b.width, to:(b.width + (20*scale))} }, duration, function(){ proxy.remove(); if(--count > 0){ animFn(); }else{ el.afterFx(o); } }); }; animFn.call(this); }); return this; }, pause : function(seconds){ var el = this.getFxEl(); var o = {}; el.queueFx(o, function(){ setTimeout(function(){ el.afterFx(o); }, seconds * 1000); }); return this; }, fadeIn : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ this.setOpacity(0); this.fixDisplay(); this.dom.style.visibility = 'visible'; var to = o.endOpacity || 1; arguments.callee.anim = this.fxanim({opacity:{to:to}}, o, null, .5, "easeOut", function(){ if(to == 1){ this.clearOpacity(); } el.afterFx(o); }); }); return this; }, fadeOut : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ arguments.callee.anim = this.fxanim({opacity:{to:o.endOpacity || 0}}, o, null, .5, "easeOut", function(){ if(this.visibilityMode == Ext.Element.DISPLAY || o.useDisplay){ this.dom.style.display = "none"; }else{ this.dom.style.visibility = "hidden"; } this.clearOpacity(); el.afterFx(o); }); }); return this; }, scale : function(w, h, o){ this.shift(Ext.apply({}, o, { width: w, height: h })); return this; }, shift : function(o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ var a = {}, w = o.width, h = o.height, x = o.x, y = o.y, op = o.opacity; if(w !== undefined){ a.width = {to: this.adjustWidth(w)}; } if(h !== undefined){ a.height = {to: this.adjustHeight(h)}; } if(x !== undefined || y !== undefined){ a.points = {to: [ x !== undefined ? x : this.getX(), y !== undefined ? y : this.getY() ]}; } if(op !== undefined){ a.opacity = {to: op}; } if(o.xy !== undefined){ a.points = {to: o.xy}; } arguments.callee.anim = this.fxanim(a, o, 'motion', .35, "easeOut", function(){ el.afterFx(o); }); }); return this; }, ghost : function(anchor, o){ var el = this.getFxEl(); o = o || {}; el.queueFx(o, function(){ anchor = anchor || "b"; var r = this.getFxRestore(); var w = this.getWidth(), h = this.getHeight(); var st = this.dom.style; var after = function(){ if(o.useDisplay){ el.setDisplayed(false); }else{ el.hide(); } el.clearOpacity(); el.setPositioning(r.pos); st.width = r.width; st.height = r.height; el.afterFx(o); }; var a = {opacity: {to: 0}, points: {}}, pt = a.points; switch(anchor.toLowerCase()){ case "t": pt.by = [0, -h]; break; case "l": pt.by = [-w, 0]; break; case "r": pt.by = [w, 0]; break; case "b": pt.by = [0, h]; break; case "tl": pt.by = [-w, -h]; break; case "bl": pt.by = [-w, h]; break; case "br": pt.by = [w, h]; break; case "tr": pt.by = [w, -h]; break; } arguments.callee.anim = this.fxanim(a, o, 'motion', .5, "easeOut", after); }); return this; }, syncFx : function(){ this.fxDefaults = Ext.apply(this.fxDefaults || {}, { block : false, concurrent : true, stopFx : false }); return this; }, sequenceFx : function(){ this.fxDefaults = Ext.apply(this.fxDefaults || {}, { block : false, concurrent : false, stopFx : false }); return this; }, nextFx : function(){ var ef = this.fxQueue[0]; if(ef){ ef.call(this); } }, hasActiveFx : function(){ return this.fxQueue && this.fxQueue[0]; }, stopFx : function(){ if(this.hasActiveFx()){ var cur = this.fxQueue[0]; if(cur && cur.anim && cur.anim.isAnimated()){ this.fxQueue = [cur]; cur.anim.stop(true); } } return this; }, beforeFx : function(o){ if(this.hasActiveFx() && !o.concurrent){ if(o.stopFx){ this.stopFx(); return true; } return false; } return true; }, hasFxBlock : function(){ var q = this.fxQueue; return q && q[0] && q[0].block; }, queueFx : function(o, fn){ if(!this.fxQueue){ this.fxQueue = []; } if(!this.hasFxBlock()){ Ext.applyIf(o, this.fxDefaults); if(!o.concurrent){ var run = this.beforeFx(o); fn.block = o.block; this.fxQueue.push(fn); if(run){ this.nextFx(); } }else{ fn.call(this); } } return this; }, fxWrap : function(pos, o, vis){ var wrap; if(!o.wrap || !(wrap = Ext.get(o.wrap))){ var wrapXY; if(o.fixPosition){ wrapXY = this.getXY(); } var div = document.createElement("div"); div.style.visibility = vis; wrap = Ext.get(this.dom.parentNode.insertBefore(div, this.dom)); wrap.setPositioning(pos); if(wrap.getStyle("position") == "static"){ wrap.position("relative"); } this.clearPositioning('auto'); wrap.clip(); wrap.dom.appendChild(this.dom); if(wrapXY){ wrap.setXY(wrapXY); } } return wrap; }, fxUnwrap : function(wrap, pos, o){ this.clearPositioning(); this.setPositioning(pos); if(!o.wrap){ wrap.dom.parentNode.insertBefore(this.dom, wrap.dom); wrap.remove(); } }, getFxRestore : function(){ var st = this.dom.style; return {pos: this.getPositioning(), width: st.width, height : st.height}; }, afterFx : function(o){ if(o.afterStyle){ this.applyStyles(o.afterStyle); } if(o.afterCls){ this.addClass(o.afterCls); } if(o.remove === true){ this.remove(); } Ext.callback(o.callback, o.scope, [this]); if(!o.concurrent){ this.fxQueue.shift(); this.nextFx(); } }, getFxEl : function(){ return Ext.get(this.dom); }, fxanim : function(args, opt, animType, defaultDur, defaultEase, cb){ animType = animType || 'run'; opt = opt || {}; var anim = Ext.lib.Anim[animType]( this.dom, args, (opt.duration || defaultDur) || .35, (opt.easing || defaultEase) || 'easeOut', function(){ Ext.callback(cb, this); }, this ); opt.anim = anim; return anim; } }; Ext.Fx.resize = Ext.Fx.scale; Ext.apply(Ext.Element.prototype, Ext.Fx); Ext.CompositeElement = function(els){ this.elements = []; this.addElements(els); }; Ext.CompositeElement.prototype = { isComposite: true, addElements : function(els){ if(!els) return this; if(typeof els == "string"){ els = Ext.Element.selectorFunction(els); } var yels = this.elements; var index = yels.length-1; for(var i = 0, len = els.length; i < len; i++) { yels[++index] = Ext.get(els[i]); } return this; }, fill : function(els){ this.elements = []; this.add(els); return this; }, filter : function(selector){ var els = []; this.each(function(el){ if(el.is(selector)){ els[els.length] = el.dom; } }); this.fill(els); return this; }, invoke : function(fn, args){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++) { Ext.Element.prototype[fn].apply(els[i], args); } return this; }, add : function(els){ if(typeof els == "string"){ this.addElements(Ext.Element.selectorFunction(els)); }else if(els.length !== undefined){ this.addElements(els); }else{ this.addElements([els]); } return this; }, each : function(fn, scope){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++){ if(fn.call(scope || els[i], els[i], this, i) === false) { break; } } return this; }, item : function(index){ return this.elements[index] || null; }, first : function(){ return this.item(0); }, last : function(){ return this.item(this.elements.length-1); }, getCount : function(){ return this.elements.length; }, contains : function(el){ return this.indexOf(el) !== -1; }, indexOf : function(el){ return this.elements.indexOf(Ext.get(el)); }, removeElement : function(el, removeDom){ if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++){ this.removeElement(el[i]); } return this; } var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1 && this.elements[index]){ if(removeDom){ var d = this.elements[index]; if(d.dom){ d.remove(); }else{ Ext.removeNode(d); } } this.elements.splice(index, 1); } return this; }, replaceElement : function(el, replacement, domReplace){ var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1){ if(domReplace){ this.elements[index].replaceWith(replacement); }else{ this.elements.splice(index, 1, Ext.get(replacement)) } } return this; }, clear : function(){ this.elements = []; } }; (function(){ Ext.CompositeElement.createCall = function(proto, fnName){ if(!proto[fnName]){ proto[fnName] = function(){ return this.invoke(fnName, arguments); }; } }; for(var fnName in Ext.Element.prototype){ if(typeof Ext.Element.prototype[fnName] == "function"){ Ext.CompositeElement.createCall(Ext.CompositeElement.prototype, fnName); } }; })(); Ext.CompositeElementLite = function(els){ Ext.CompositeElementLite.superclass.constructor.call(this, els); this.el = new Ext.Element.Flyweight(); }; Ext.extend(Ext.CompositeElementLite, Ext.CompositeElement, { addElements : function(els){ if(els){ if(Ext.isArray(els)){ this.elements = this.elements.concat(els); }else{ var yels = this.elements; var index = yels.length-1; for(var i = 0, len = els.length; i < len; i++) { yels[++index] = els[i]; } } } return this; }, invoke : function(fn, args){ var els = this.elements; var el = this.el; for(var i = 0, len = els.length; i < len; i++) { el.dom = els[i]; Ext.Element.prototype[fn].apply(el, args); } return this; }, item : function(index){ if(!this.elements[index]){ return null; } this.el.dom = this.elements[index]; return this.el; }, addListener : function(eventName, handler, scope, opt){ var els = this.elements; for(var i = 0, len = els.length; i < len; i++) { Ext.EventManager.on(els[i], eventName, handler, scope || els[i], opt); } return this; }, each : function(fn, scope){ var els = this.elements; var el = this.el; for(var i = 0, len = els.length; i < len; i++){ el.dom = els[i]; if(fn.call(scope || el, el, this, i) === false){ break; } } return this; }, indexOf : function(el){ return this.elements.indexOf(Ext.getDom(el)); }, replaceElement : function(el, replacement, domReplace){ var index = typeof el == 'number' ? el : this.indexOf(el); if(index !== -1){ replacement = Ext.getDom(replacement); if(domReplace){ var d = this.elements[index]; d.parentNode.insertBefore(replacement, d); Ext.removeNode(d); } this.elements.splice(index, 1, replacement); } return this; } }); Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener; if(Ext.DomQuery){ Ext.Element.selectorFunction = Ext.DomQuery.select; } Ext.Element.select = function(selector, unique, root){ var els; if(typeof selector == "string"){ els = Ext.Element.selectorFunction(selector, root); }else if(selector.length !== undefined){ els = selector; }else{ throw "Invalid selector"; } if(unique === true){ return new Ext.CompositeElement(els); }else{ return new Ext.CompositeElementLite(els); } }; Ext.select = Ext.Element.select; Ext.data.Connection = function(config){ Ext.apply(this, config); this.addEvents( "beforerequest", "requestcomplete", "requestexception" ); Ext.data.Connection.superclass.constructor.call(this); }; Ext.extend(Ext.data.Connection, Ext.util.Observable, { timeout : 30000, autoAbort:false, disableCaching: true, request : function(o){ if(this.fireEvent("beforerequest", this, o) !== false){ var p = o.params; if(typeof p == "function"){ p = p.call(o.scope||window, o); } if(typeof p == "object"){ p = Ext.urlEncode(p); } if(this.extraParams){ var extras = Ext.urlEncode(this.extraParams); p = p ? (p + '&' + extras) : extras; } var url = o.url || this.url; if(typeof url == 'function'){ url = url.call(o.scope||window, o); } if(o.form){ var form = Ext.getDom(o.form); url = url || form.action; var enctype = form.getAttribute("enctype"); if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){ return this.doFormUpload(o, p, url); } var f = Ext.lib.Ajax.serializeForm(form); p = p ? (p + '&' + f) : f; } var hs = o.headers; if(this.defaultHeaders){ hs = Ext.apply(hs || {}, this.defaultHeaders); if(!o.headers){ o.headers = hs; } } var cb = { success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {options: o}, timeout : o.timeout || this.timeout }; var method = o.method||this.method||(p ? "POST" : "GET"); if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){ url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime()); } if(typeof o.autoAbort == 'boolean'){ if(o.autoAbort){ this.abort(); } }else if(this.autoAbort !== false){ this.abort(); } if((method == 'GET' && p) || o.xmlData || o.jsonData){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; p = ''; } this.transId = Ext.lib.Ajax.request(method, url, cb, p, o); return this.transId; }else{ Ext.callback(o.callback, o.scope, [o, null, null]); return null; } }, isLoading : function(transId){ if(transId){ return Ext.lib.Ajax.isCallInProgress(transId); }else{ return this.transId ? true : false; } }, abort : function(transId){ if(transId || this.isLoading()){ Ext.lib.Ajax.abort(transId || this.transId); } }, handleResponse : function(response){ this.transId = false; var options = response.argument.options; response.argument = options ? options.argument : null; this.fireEvent("requestcomplete", this, response, options); Ext.callback(options.success, options.scope, [response, options]); Ext.callback(options.callback, options.scope, [options, true, response]); }, handleFailure : function(response, e){ this.transId = false; var options = response.argument.options; response.argument = options ? options.argument : null; this.fireEvent("requestexception", this, response, options, e); Ext.callback(options.failure, options.scope, [response, options]); Ext.callback(options.callback, options.scope, [options, false, response]); }, doFormUpload : function(o, ps, url){ var id = Ext.id(); var frame = document.createElement('iframe'); frame.id = id; frame.name = id; frame.className = 'x-hidden'; if(Ext.isIE){ frame.src = Ext.SSL_SECURE_URL; } document.body.appendChild(frame); if(Ext.isIE){ document.frames[id].name = id; } var form = Ext.getDom(o.form); form.target = id; form.method = 'POST'; form.enctype = form.encoding = 'multipart/form-data'; if(url){ form.action = url; } var hiddens, hd; if(ps){ hiddens = []; ps = Ext.urlDecode(ps, false); for(var k in ps){ if(ps.hasOwnProperty(k)){ hd = document.createElement('input'); hd.type = 'hidden'; hd.name = k; hd.value = ps[k]; form.appendChild(hd); hiddens.push(hd); } } } function cb(){ var r = { responseText : '', responseXML : null }; r.argument = o ? o.argument : null; try { var doc; if(Ext.isIE){ doc = frame.contentWindow.document; }else { doc = (frame.contentDocument || window.frames[id].document); } if(doc && doc.body){ r.responseText = doc.body.innerHTML; } if(doc && doc.XMLDocument){ r.responseXML = doc.XMLDocument; }else { r.responseXML = doc; } } catch(e) { } Ext.EventManager.removeListener(frame, 'load', cb, this); this.fireEvent("requestcomplete", this, r, o); Ext.callback(o.success, o.scope, [r, o]); Ext.callback(o.callback, o.scope, [o, true, r]); setTimeout(function(){Ext.removeNode(frame);}, 100); } Ext.EventManager.on(frame, 'load', cb, this); form.submit(); if(hiddens){ for(var i = 0, len = hiddens.length; i < len; i++){ Ext.removeNode(hiddens[i]); } } } }); Ext.Ajax = new Ext.data.Connection({ autoAbort : false, serializeForm : function(form){ return Ext.lib.Ajax.serializeForm(form); } }); Ext.Updater = function(el, forceNew){ el = Ext.get(el); if(!forceNew && el.updateManager){ return el.updateManager; } this.el = el; this.defaultUrl = null; this.addEvents( "beforeupdate", "update", "failure" ); var d = Ext.Updater.defaults; this.sslBlankUrl = d.sslBlankUrl; this.disableCaching = d.disableCaching; this.indicatorText = d.indicatorText; this.showLoadIndicator = d.showLoadIndicator; this.timeout = d.timeout; this.loadScripts = d.loadScripts; this.transaction = null; this.autoRefreshProcId = null; this.refreshDelegate = this.refresh.createDelegate(this); this.updateDelegate = this.update.createDelegate(this); this.formUpdateDelegate = this.formUpdate.createDelegate(this); if(!this.renderer){ this.renderer = new Ext.Updater.BasicRenderer(); } Ext.Updater.superclass.constructor.call(this); }; Ext.extend(Ext.Updater, Ext.util.Observable, { getEl : function(){ return this.el; }, update : function(url, params, callback, discardUrl){ if(this.fireEvent("beforeupdate", this.el, url, params) !== false){ var method = this.method, cfg, callerScope; if(typeof url == "object"){ cfg = url; url = cfg.url; params = params || cfg.params; callback = callback || cfg.callback; discardUrl = discardUrl || cfg.discardUrl; callerScope = cfg.scope; if(typeof cfg.method != "undefined"){method = cfg.method;}; if(typeof cfg.nocache != "undefined"){this.disableCaching = cfg.nocache;}; if(typeof cfg.text != "undefined"){this.indicatorText = '<div class="loading-indicator">'+cfg.text+"</div>";}; if(typeof cfg.scripts != "undefined"){this.loadScripts = cfg.scripts;}; if(typeof cfg.timeout != "undefined"){this.timeout = cfg.timeout;}; } this.showLoading(); if(!discardUrl){ this.defaultUrl = url; } if(typeof url == "function"){ url = url.call(this); } method = method || (params ? "POST" : "GET"); if(method == "GET"){ url = this.prepareUrl(url); } var o = Ext.apply(cfg ||{}, { url : url, params: (typeof params == "function" && callerScope) ? params.createDelegate(callerScope) : params, success: this.processSuccess, failure: this.processFailure, scope: this, callback: undefined, timeout: (this.timeout*1000), argument: { "options": cfg, "url": url, "form": null, "callback": callback, "scope": callerScope || window, "params": params } }); this.transaction = Ext.Ajax.request(o); } }, formUpdate : function(form, url, reset, callback){ if(this.fireEvent("beforeupdate", this.el, form, url) !== false){ if(typeof url == "function"){ url = url.call(this); } form = Ext.getDom(form) this.transaction = Ext.Ajax.request({ form: form, url:url, success: this.processSuccess, failure: this.processFailure, scope: this, timeout: (this.timeout*1000), argument: { "url": url, "form": form, "callback": callback, "reset": reset } }); this.showLoading.defer(1, this); } }, refresh : function(callback){ if(this.defaultUrl == null){ return; } this.update(this.defaultUrl, null, callback, true); }, startAutoRefresh : function(interval, url, params, callback, refreshNow){ if(refreshNow){ this.update(url || this.defaultUrl, params, callback, true); } if(this.autoRefreshProcId){ clearInterval(this.autoRefreshProcId); } this.autoRefreshProcId = setInterval(this.update.createDelegate(this, [url || this.defaultUrl, params, callback, true]), interval*1000); }, stopAutoRefresh : function(){ if(this.autoRefreshProcId){ clearInterval(this.autoRefreshProcId); delete this.autoRefreshProcId; } }, isAutoRefreshing : function(){ return this.autoRefreshProcId ? true : false; }, showLoading : function(){ if(this.showLoadIndicator){ this.el.update(this.indicatorText); } }, prepareUrl : function(url){ if(this.disableCaching){ var append = "_dc=" + (new Date().getTime()); if(url.indexOf("?") !== -1){ url += "&" + append; }else{ url += "?" + append; } } return url; }, processSuccess : function(response){ this.transaction = null; if(response.argument.form && response.argument.reset){ try{ response.argument.form.reset(); }catch(e){} } if(this.loadScripts){ this.renderer.render(this.el, response, this, this.updateComplete.createDelegate(this, [response])); }else{ this.renderer.render(this.el, response, this); this.updateComplete(response); } }, updateComplete : function(response){ this.fireEvent("update", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback.call(response.argument.scope, this.el, true, response, response.argument.options); } }, processFailure : function(response){ this.transaction = null; this.fireEvent("failure", this.el, response); if(typeof response.argument.callback == "function"){ response.argument.callback.call(response.argument.scope, this.el, false, response, response.argument.options); } }, setRenderer : function(renderer){ this.renderer = renderer; }, getRenderer : function(){ return this.renderer; }, setDefaultUrl : function(defaultUrl){ this.defaultUrl = defaultUrl; }, abort : function(){ if(this.transaction){ Ext.Ajax.abort(this.transaction); } }, isUpdating : function(){ if(this.transaction){ return Ext.Ajax.isLoading(this.transaction); } return false; } }); Ext.Updater.defaults = { timeout : 30, loadScripts : false, sslBlankUrl : (Ext.SSL_SECURE_URL || "javascript:false"), disableCaching : false, showLoadIndicator : true, indicatorText : '<div class="loading-indicator">Loading...</div>' }; Ext.Updater.updateElement = function(el, url, params, options){ var um = Ext.get(el).getUpdater(); Ext.apply(um, options); um.update(url, params, options ? options.callback : null); }; Ext.Updater.update = Ext.Updater.updateElement; Ext.Updater.BasicRenderer = function(){}; Ext.Updater.BasicRenderer.prototype = { render : function(el, response, updateManager, callback){ el.update(response.responseText, updateManager.loadScripts, callback); } }; Ext.UpdateManager = Ext.Updater; Date.parseFunctions = {count:0}; Date.parseRegexes = []; Date.formatFunctions = {count:0}; Date.prototype.dateFormat = function(format) { if (Date.formatFunctions[format] == null) { Date.createNewFormat(format); } var func = Date.formatFunctions[format]; return this[func](); }; Date.prototype.format = Date.prototype.dateFormat; Date.createNewFormat = function(format) { var funcName = "format" + Date.formatFunctions.count++; Date.formatFunctions[format] = funcName; var code = "Date.prototype." + funcName + " = function(){return "; var special = false; var ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; code += "'" + String.escape(ch) + "' + "; } else { code += Date.getFormatCode(ch); } } eval(code.substring(0, code.length - 3) + ";}"); }; Date.getFormatCode = function(character) { switch (character) { case "d": return "String.leftPad(this.getDate(), 2, '0') + "; case "D": return "Date.getShortDayName(this.getDay()) + "; case "j": return "this.getDate() + "; case "l": return "Date.dayNames[this.getDay()] + "; case "N": return "(this.getDay() ? this.getDay() : 7) + "; case "S": return "this.getSuffix() + "; case "w": return "this.getDay() + "; case "z": return "this.getDayOfYear() + "; case "W": return "String.leftPad(this.getWeekOfYear(), 2, '0') + "; case "F": return "Date.monthNames[this.getMonth()] + "; case "m": return "String.leftPad(this.getMonth() + 1, 2, '0') + "; case "M": return "Date.getShortMonthName(this.getMonth()) + "; case "n": return "(this.getMonth() + 1) + "; case "t": return "this.getDaysInMonth() + "; case "L": return "(this.isLeapYear() ? 1 : 0) + "; case "o": return "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0))) + "; case "Y": return "this.getFullYear() + "; case "y": return "('' + this.getFullYear()).substring(2, 4) + "; case "a": return "(this.getHours() < 12 ? 'am' : 'pm') + "; case "A": return "(this.getHours() < 12 ? 'AM' : 'PM') + "; case "g": return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + "; case "G": return "this.getHours() + "; case "h": return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + "; case "H": return "String.leftPad(this.getHours(), 2, '0') + "; case "i": return "String.leftPad(this.getMinutes(), 2, '0') + "; case "s": return "String.leftPad(this.getSeconds(), 2, '0') + "; case "u": return "String.leftPad(this.getMilliseconds(), 3, '0') + "; case "O": return "this.getGMTOffset() + "; case "P": return "this.getGMTOffset(true) + "; case "T": return "this.getTimezone() + "; case "Z": return "(this.getTimezoneOffset() * -60) + "; case "c": for (var df = Date.getFormatCode, c = "Y-m-dTH:i:sP", code = "", i = 0, l = c.length; i < l; ++i) { var e = c.charAt(i); code += e == "T" ? "'T' + " : df(e); } return code; case "U": return "Math.round(this.getTime() / 1000) + "; default: return "'" + String.escape(character) + "' + "; } }; Date.parseDate = function(input, format) { if (Date.parseFunctions[format] == null) { Date.createParser(format); } var func = Date.parseFunctions[format]; return Date[func](input); }; Date.createParser = function(format) { var funcName = "parse" + Date.parseFunctions.count++; var regexNum = Date.parseRegexes.length; var currentGroup = 1; Date.parseFunctions[format] = funcName; var code = "Date." + funcName + " = function(input){\n" + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, ms = -1, o, z, u, v;\n" + "input = String(input);var d = new Date();\n" + "y = d.getFullYear();\n" + "m = d.getMonth();\n" + "d = d.getDate();\n" + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n" + "if (results && results.length > 0) {"; var regex = ""; var special = false; var ch = ''; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true; } else if (special) { special = false; regex += String.escape(ch); } else { var obj = Date.formatCodeToRegex(ch, currentGroup); currentGroup += obj.g; regex += obj.s; if (obj.g && obj.c) { code += obj.c; } } } code += "if (u)\n" + "{v = new Date(u * 1000);}" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0 && ms >= 0)\n" + "{v = new Date(y, m, d, h, i, s, ms);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n" + "{v = new Date(y, m, d, h, i, s);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n" + "{v = new Date(y, m, d, h, i);}\n" + "else if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n" + "{v = new Date(y, m, d, h);}\n" + "else if (y >= 0 && m >= 0 && d > 0)\n" + "{v = new Date(y, m, d);}\n" + "else if (y >= 0 && m >= 0)\n" + "{v = new Date(y, m);}\n" + "else if (y >= 0)\n" + "{v = new Date(y);}\n" + "}return (v && (z || o))?\n" + " (z ? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n" + " v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n" + ";}"; Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$", "i"); eval(code); }; Date.formatCodeToRegex = function(character, currentGroup) { switch (character) { case "d": return {g:1, c:"d = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "D": for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i); return {g:0, c:null, s:"(?:" + a.join("|") +")"}; case "j": return {g:1, c:"d = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{1,2})"}; case "l": return {g:0, c:null, s:"(?:" + Date.dayNames.join("|") + ")"}; case "N": return {g:0, c:null, s:"[1-7]"}; case "S": return {g:0, c:null, s:"(?:st|nd|rd|th)"}; case "w": return {g:0, c:null, s:"[0-6]"}; case "z": return {g:0, c:null, s:"(?:\\d{1,3}"}; case "W": return {g:0, c:null, s:"(?:\\d{2})"}; case "F": return {g:1, c:"m = parseInt(Date.getMonthNumber(results[" + currentGroup + "]), 10);\n", s:"(" + Date.monthNames.join("|") + ")"}; case "m": return {g:1, c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s:"(\\d{2})"}; case "M": for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i); return {g:1, c:"m = parseInt(Date.getMonthNumber(results[" + currentGroup + "]), 10);\n", s:"(" + a.join("|") + ")"}; case "n": return {g:1, c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s:"(\\d{1,2})"}; case "t": return {g:0, c:null, s:"(?:\\d{2})"}; case "L": return {g:0, c:null, s:"(?:1|0)"}; case "o": case "Y": return {g:1, c:"y = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{4})"}; case "y": return {g:1, c:"var ty = parseInt(results[" + currentGroup + "], 10);\n" + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", s:"(\\d{1,2})"}; case "a": return {g:1, c:"if (results[" + currentGroup + "] == 'am') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}", s:"(am|pm)"}; case "A": return {g:1, c:"if (results[" + currentGroup + "] == 'AM') {\n" + "if (h == 12) { h = 0; }\n" + "} else { if (h < 12) { h += 12; }}", s:"(AM|PM)"}; case "g": case "G": return {g:1, c:"h = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{1,2})"}; case "h": case "H": return {g:1, c:"h = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "i": return {g:1, c:"i = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "s": return {g:1, c:"s = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{2})"}; case "u": return {g:1, c:"ms = parseInt(results[" + currentGroup + "], 10);\n", s:"(\\d{3})"}; case "O": return {g:1, c:[ "o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", "var mn = o.substring(3,5) % 60;\n", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", " (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" ].join(""), s: "([+\-]\\d{4})"}; case "P": return {g:1, c:[ "o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n", "var mn = o.substring(4,6) % 60;\n", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", " (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n" ].join(""), s: "([+\-]\\d{2}:\\d{2})"}; case "T": return {g:0, c:null, s:"[A-Z]{1,4}"}; case "Z": return {g:1, c:"z = results[" + currentGroup + "] * 1;\n" + "z = (-43200 <= z && z <= 50400)? z : null;\n", s:"([+\-]?\\d{1,5})"}; case "c": var df = Date.formatCodeToRegex, calc = []; var arr = [df("Y", 1), df("m", 2), df("d", 3), df("h", 4), df("i", 5), df("s", 6), df("P", 7)]; for (var i = 0, l = arr.length; i < l; ++i) { calc.push(arr[i].c); } return {g:1, c:calc.join(""), s:arr[0].s + "-" + arr[1].s + "-" + arr[2].s + "T" + arr[3].s + ":" + arr[4].s + ":" + arr[5].s + arr[6].s}; case "U": return {g:1, c:"u = parseInt(results[" + currentGroup + "], 10);\n", s:"(-?\\d+)"}; default: return {g:0, c:null, s:Ext.escapeRe(character)}; } }; Date.prototype.getTimezone = function() { return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); }; Date.prototype.getGMTOffset = function(colon) { return (this.getTimezoneOffset() > 0 ? "-" : "+") + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0") + (colon ? ":" : "") + String.leftPad(this.getTimezoneOffset() % 60, 2, "0"); }; Date.prototype.getDayOfYear = function() { var num = 0; Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; for (var i = 0; i < this.getMonth(); ++i) { num += Date.daysInMonth[i]; } return num + this.getDate() - 1; }; Date.prototype.getWeekOfYear = function() { var ms1d = 864e5; var ms7d = 7 * ms1d; var DC3 = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / ms1d; var AWN = Math.floor(DC3 / 7); var Wyr = new Date(AWN * ms7d).getUTCFullYear(); return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1; }; Date.prototype.isLeapYear = function() { var year = this.getFullYear(); return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year))); }; Date.prototype.getFirstDayOfMonth = function() { var day = (this.getDay() - (this.getDate() - 1)) % 7; return (day < 0) ? (day + 7) : day; }; Date.prototype.getLastDayOfMonth = function() { var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7; return (day < 0) ? (day + 7) : day; }; Date.prototype.getFirstDateOfMonth = function() { return new Date(this.getFullYear(), this.getMonth(), 1); }; Date.prototype.getLastDateOfMonth = function() { return new Date(this.getFullYear(), this.getMonth(), this.getDaysInMonth()); }; Date.prototype.getDaysInMonth = function() { Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; return Date.daysInMonth[this.getMonth()]; }; Date.prototype.getSuffix = function() { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }; Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31]; Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; Date.getShortMonthName = function(month) { return Date.monthNames[month].substring(0, 3); } Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; Date.getShortDayName = function(day) { return Date.dayNames[day].substring(0, 3); } Date.y2kYear = 50; Date.monthNumbers = { Jan:0, Feb:1, Mar:2, Apr:3, May:4, Jun:5, Jul:6, Aug:7, Sep:8, Oct:9, Nov:10, Dec:11}; Date.getMonthNumber = function(name) { return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()]; } Date.prototype.clone = function() { return new Date(this.getTime()); }; Date.prototype.clearTime = function(clone){ if(clone){ return this.clone().clearTime(); } this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); return this; }; if(Ext.isSafari){ Date.brokenSetMonth = Date.prototype.setMonth; Date.prototype.setMonth = function(num){ if(num <= -1){ var n = Math.ceil(-num); var back_year = Math.ceil(n/12); var month = (n % 12) ? 12 - n % 12 : 0 ; this.setFullYear(this.getFullYear() - back_year); return Date.brokenSetMonth.call(this, month); } else { return Date.brokenSetMonth.apply(this, arguments); } }; } Date.MILLI = "ms"; Date.SECOND = "s"; Date.MINUTE = "mi"; Date.HOUR = "h"; Date.DAY = "d"; Date.MONTH = "mo"; Date.YEAR = "y"; Date.prototype.add = function(interval, value){ var d = this.clone(); if (!interval || value === 0) return d; switch(interval.toLowerCase()){ case Date.MILLI: d.setMilliseconds(this.getMilliseconds() + value); break; case Date.SECOND: d.setSeconds(this.getSeconds() + value); break; case Date.MINUTE: d.setMinutes(this.getMinutes() + value); break; case Date.HOUR: d.setHours(this.getHours() + value); break; case Date.DAY: d.setDate(this.getDate() + value); break; case Date.MONTH: var day = this.getDate(); if(day > 28){ day = Math.min(day, this.getFirstDateOfMonth().add('mo', value).getLastDateOfMonth().getDate()); } d.setDate(day); d.setMonth(this.getMonth() + value); break; case Date.YEAR: d.setFullYear(this.getFullYear() + value); break; } return d; }; Date.prototype.between = function(start, end){ var t = this.getTime(); return start.getTime() <= t && t <= end.getTime(); } Ext.util.DelayedTask = function(fn, scope, args){ var id = null, d, t; var call = function(){ var now = new Date().getTime(); if(now - t >= d){ clearInterval(id); id = null; fn.apply(scope, args || []); } }; this.delay = function(delay, newFn, newScope, newArgs){ if(id && delay != d){ this.cancel(); } d = delay; t = new Date().getTime(); fn = newFn || fn; scope = newScope || scope; args = newArgs || args; if(!id){ id = setInterval(call, d); } }; this.cancel = function(){ if(id){ clearInterval(id); id = null; } }; }; Ext.util.TaskRunner = function(interval){ interval = interval || 10; var tasks = [], removeQueue = []; var id = 0; var running = false; var stopThread = function(){ running = false; clearInterval(id); id = 0; }; var startThread = function(){ if(!running){ running = true; id = setInterval(runTasks, interval); } }; var removeTask = function(t){ removeQueue.push(t); if(t.onStop){ t.onStop.apply(t.scope || t); } }; var runTasks = function(){ if(removeQueue.length > 0){ for(var i = 0, len = removeQueue.length; i < len; i++){ tasks.remove(removeQueue[i]); } removeQueue = []; if(tasks.length < 1){ stopThread(); return; } } var now = new Date().getTime(); for(var i = 0, len = tasks.length; i < len; ++i){ var t = tasks[i]; var itime = now - t.taskRunTime; if(t.interval <= itime){ var rt = t.run.apply(t.scope || t, t.args || [++t.taskRunCount]); t.taskRunTime = now; if(rt === false || t.taskRunCount === t.repeat){ removeTask(t); return; } } if(t.duration && t.duration <= (now - t.taskStartTime)){ removeTask(t); } } }; this.start = function(task){ tasks.push(task); task.taskStartTime = new Date().getTime(); task.taskRunTime = 0; task.taskRunCount = 0; startThread(); return task; }; this.stop = function(task){ removeTask(task); return task; }; this.stopAll = function(){ stopThread(); for(var i = 0, len = tasks.length; i < len; i++){ if(tasks[i].onStop){ tasks[i].onStop(); } } tasks = []; removeQueue = []; }; }; Ext.TaskMgr = new Ext.util.TaskRunner(); Ext.util.MixedCollection = function(allowFunctions, keyFn){ this.items = []; this.map = {}; this.keys = []; this.length = 0; this.addEvents( "clear", "add", "replace", "remove", "sort" ); this.allowFunctions = allowFunctions === true; if(keyFn){ this.getKey = keyFn; } Ext.util.MixedCollection.superclass.constructor.call(this); }; Ext.extend(Ext.util.MixedCollection, Ext.util.Observable, { allowFunctions : false, add : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } if(typeof key == "undefined" || key === null){ this.length++; this.items.push(o); this.keys.push(null); }else{ var old = this.map[key]; if(old){ return this.replace(key, o); } this.length++; this.items.push(o); this.map[key] = o; this.keys.push(key); } this.fireEvent("add", this.length-1, o, key); return o; }, getKey : function(o){ return o.id; }, replace : function(key, o){ if(arguments.length == 1){ o = arguments[0]; key = this.getKey(o); } var old = this.item(key); if(typeof key == "undefined" || key === null || typeof old == "undefined"){ return this.add(key, o); } var index = this.indexOfKey(key); this.items[index] = o; this.map[key] = o; this.fireEvent("replace", key, old, o); return o; }, addAll : function(objs){ if(arguments.length > 1 || Ext.isArray(objs)){ var args = arguments.length > 1 ? arguments : objs; for(var i = 0, len = args.length; i < len; i++){ this.add(args[i]); } }else{ for(var key in objs){ if(this.allowFunctions || typeof objs[key] != "function"){ this.add(key, objs[key]); } } } }, each : function(fn, scope){ var items = [].concat(this.items); for(var i = 0, len = items.length; i < len; i++){ if(fn.call(scope || items[i], items[i], i, len) === false){ break; } } }, eachKey : function(fn, scope){ for(var i = 0, len = this.keys.length; i < len; i++){ fn.call(scope || window, this.keys[i], this.items[i], i, len); } }, find : function(fn, scope){ for(var i = 0, len = this.items.length; i < len; i++){ if(fn.call(scope || window, this.items[i], this.keys[i])){ return this.items[i]; } } return null; }, insert : function(index, key, o){ if(arguments.length == 2){ o = arguments[1]; key = this.getKey(o); } if(index >= this.length){ return this.add(key, o); } this.length++; this.items.splice(index, 0, o); if(typeof key != "undefined" && key != null){ this.map[key] = o; } this.keys.splice(index, 0, key); this.fireEvent("add", index, o, key); return o; }, remove : function(o){ return this.removeAt(this.indexOf(o)); }, removeAt : function(index){ if(index < this.length && index >= 0){ this.length--; var o = this.items[index]; this.items.splice(index, 1); var key = this.keys[index]; if(typeof key != "undefined"){ delete this.map[key]; } this.keys.splice(index, 1); this.fireEvent("remove", o, key); return o; } return false; }, removeKey : function(key){ return this.removeAt(this.indexOfKey(key)); }, getCount : function(){ return this.length; }, indexOf : function(o){ return this.items.indexOf(o); }, indexOfKey : function(key){ return this.keys.indexOf(key); }, item : function(key){ var item = typeof this.map[key] != "undefined" ? this.map[key] : this.items[key]; return typeof item != 'function' || this.allowFunctions ? item : null; }, itemAt : function(index){ return this.items[index]; }, key : function(key){ return this.map[key]; }, contains : function(o){ return this.indexOf(o) != -1; }, containsKey : function(key){ return typeof this.map[key] != "undefined"; }, clear : function(){ this.length = 0; this.items = []; this.keys = []; this.map = {}; this.fireEvent("clear"); }, first : function(){ return this.items[0]; }, last : function(){ return this.items[this.length-1]; }, _sort : function(property, dir, fn){ var dsc = String(dir).toUpperCase() == "DESC" ? -1 : 1; fn = fn || function(a, b){ return a-b; }; var c = [], k = this.keys, items = this.items; for(var i = 0, len = items.length; i < len; i++){ c[c.length] = {key: k[i], value: items[i], index: i}; } c.sort(function(a, b){ var v = fn(a[property], b[property]) * dsc; if(v == 0){ v = (a.index < b.index ? -1 : 1); } return v; }); for(var i = 0, len = c.length; i < len; i++){ items[i] = c[i].value; k[i] = c[i].key; } this.fireEvent("sort", this); }, sort : function(dir, fn){ this._sort("value", dir, fn); }, keySort : function(dir, fn){ this._sort("key", dir, fn || function(a, b){ return String(a).toUpperCase()-String(b).toUpperCase(); }); }, getRange : function(start, end){ var items = this.items; if(items.length < 1){ return []; } start = start || 0; end = Math.min(typeof end == "undefined" ? this.length-1 : end, this.length-1); var r = []; if(start <= end){ for(var i = start; i <= end; i++) { r[r.length] = items[i]; } }else{ for(var i = start; i >= end; i--) { r[r.length] = items[i]; } } return r; }, filter : function(property, value, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return this.clone(); } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.filterBy(function(o){ return o && value.test(o[property]); }); }, filterBy : function(fn, scope){ var r = new Ext.util.MixedCollection(); r.getKey = this.getKey; var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ r.add(k[i], it[i]); } } return r; }, findIndex : function(property, value, start, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return -1; } value = this.createValueMatcher(value, anyMatch, caseSensitive); return this.findIndexBy(function(o){ return o && value.test(o[property]); }, null, start); }, findIndexBy : function(fn, scope, start){ var k = this.keys, it = this.items; for(var i = (start||0), len = it.length; i < len; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } if(typeof start == 'number' && start > 0){ for(var i = 0; i < start; i++){ if(fn.call(scope||this, it[i], k[i])){ return i; } } } return -1; }, createValueMatcher : function(value, anyMatch, caseSensitive){ if(!value.exec){ value = String(value); value = new RegExp((anyMatch === true ? '' : '^') + Ext.escapeRe(value), caseSensitive ? '' : 'i'); } return value; }, clone : function(){ var r = new Ext.util.MixedCollection(); var k = this.keys, it = this.items; for(var i = 0, len = it.length; i < len; i++){ r.add(k[i], it[i]); } r.getKey = this.getKey; return r; } }); Ext.util.MixedCollection.prototype.get = Ext.util.MixedCollection.prototype.item; Ext.util.JSON = new (function(){ var useHasOwn = {}.hasOwnProperty ? true : false; var pad = function(n) { return n < 10 ? "0" + n : n; }; var m = { "\b": '\\b', "\t": '\\t', "\n": '\\n', "\f": '\\f', "\r": '\\r', '"' : '\\"', "\\": '\\\\' }; var encodeString = function(s){ if (/["\\\x00-\x1f]/.test(s)) { return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if(c){ return c; } c = b.charCodeAt(); return "\\u00" + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + s + '"'; }; var encodeArray = function(o){ var a = ["["], b, i, l = o.length, v; for (i = 0; i < l; i += 1) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if (b) { a.push(','); } a.push(v === null ? "null" : Ext.util.JSON.encode(v)); b = true; } } a.push("]"); return a.join(""); }; var encodeDate = function(o){ return '"' + o.getFullYear() + "-" + pad(o.getMonth() + 1) + "-" + pad(o.getDate()) + "T" + pad(o.getHours()) + ":" + pad(o.getMinutes()) + ":" + pad(o.getSeconds()) + '"'; }; this.encode = function(o){ if(typeof o == "undefined" || o === null){ return "null"; }else if(Ext.isArray(o)){ return encodeArray(o); }else if(Ext.isDate(o)){ return encodeDate(o); }else if(typeof o == "string"){ return encodeString(o); }else if(typeof o == "number"){ return isFinite(o) ? String(o) : "null"; }else if(typeof o == "boolean"){ return String(o); }else { var a = ["{"], b, i, v; for (i in o) { if(!useHasOwn || o.hasOwnProperty(i)) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if(b){ a.push(','); } a.push(this.encode(i), ":", v === null ? "null" : this.encode(v)); b = true; } } } a.push("}"); return a.join(""); } }; this.decode = function(json){ return eval("(" + json + ')'); }; })(); Ext.encode = Ext.util.JSON.encode; Ext.decode = Ext.util.JSON.decode; Ext.util.Format = function(){ var trimRe = /^\s+|\s+$/g; return { ellipsis : function(value, len){ if(value && value.length > len){ return value.substr(0, len-3)+"..."; } return value; }, undef : function(value){ return value !== undefined ? value : ""; }, defaultValue : function(value, defaultValue){ return value !== undefined && value !== '' ? value : defaultValue; }, htmlEncode : function(value){ return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;"); }, htmlDecode : function(value){ return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"'); }, trim : function(value){ return String(value).replace(trimRe, ""); }, substr : function(value, start, length){ return String(value).substr(start, length); }, lowercase : function(value){ return String(value).toLowerCase(); }, uppercase : function(value){ return String(value).toUpperCase(); }, capitalize : function(value){ return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase(); }, call : function(value, fn){ if(arguments.length > 2){ var args = Array.prototype.slice.call(arguments, 2); args.unshift(value); return eval(fn).apply(window, args); }else{ return eval(fn).call(window, value); } }, usMoney : function(v){ v = (Math.round((v-0)*100))/100; v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v); v = String(v); var ps = v.split('.'); var whole = ps[0]; var sub = ps[1] ? '.'+ ps[1] : '.00'; var r = /(\d+)(\d{3})/; while (r.test(whole)) { whole = whole.replace(r, '$1' + ',' + '$2'); } v = whole + sub; if(v.charAt(0) == '-'){ return '-$' + v.substr(1); } return "$" + v; }, date : function(v, format){ if(!v){ return ""; } if(!Ext.isDate(v)){ v = new Date(Date.parse(v)); } return v.dateFormat(format || "m/d/Y"); }, dateRenderer : function(format){ return function(v){ return Ext.util.Format.date(v, format); }; }, stripTagsRE : /<\/?[^>]+>/gi, stripTags : function(v){ return !v ? v : String(v).replace(this.stripTagsRE, ""); }, stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig, stripScripts : function(v){ return !v ? v : String(v).replace(this.stripScriptsRe, ""); }, fileSize : function(size){ if(size < 1024) { return size + " bytes"; } else if(size < 1048576) { return (Math.round(((size*10) / 1024))/10) + " KB"; } else { return (Math.round(((size*10) / 1048576))/10) + " MB"; } }, math : function(){ var fns = {}; return function(v, a){ if(!fns[a]){ fns[a] = new Function('v', 'return v ' + a + ';'); } return fns[a](v); } }() }; }(); Ext.XTemplate = function(){ Ext.XTemplate.superclass.constructor.apply(this, arguments); var s = this.html; s = ['<tpl>', s, '</tpl>'].join(''); var re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/; var nameRe = /^<tpl\b[^>]*?for="(.*?)"/; var ifRe = /^<tpl\b[^>]*?if="(.*?)"/; var execRe = /^<tpl\b[^>]*?exec="(.*?)"/; var m, id = 0; var tpls = []; while(m = s.match(re)){ var m2 = m[0].match(nameRe); var m3 = m[0].match(ifRe); var m4 = m[0].match(execRe); var exp = null, fn = null, exec = null; var name = m2 && m2[1] ? m2[1] : ''; if(m3){ exp = m3 && m3[1] ? m3[1] : null; if(exp){ fn = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ return '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(m4){ exp = m4 && m4[1] ? m4[1] : null; if(exp){ exec = new Function('values', 'parent', 'xindex', 'xcount', 'with(values){ '+(Ext.util.Format.htmlDecode(exp))+'; }'); } } if(name){ switch(name){ case '.': name = new Function('values', 'parent', 'with(values){ return values; }'); break; case '..': name = new Function('values', 'parent', 'with(values){ return parent; }'); break; default: name = new Function('values', 'parent', 'with(values){ return '+name+'; }'); } } tpls.push({ id: id, target: name, exec: exec, test: fn, body: m[1]||'' }); s = s.replace(m[0], '{xtpl'+ id + '}'); ++id; } for(var i = tpls.length-1; i >= 0; --i){ this.compileTpl(tpls[i]); } this.master = tpls[tpls.length-1]; this.tpls = tpls; }; Ext.extend(Ext.XTemplate, Ext.Template, { re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g, codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g, applySubTemplate : function(id, values, parent, xindex, xcount){ var t = this.tpls[id]; if(t.test && !t.test.call(this, values, parent, xindex, xcount)){ return ''; } if(t.exec && t.exec.call(this, values, parent, xindex, xcount)){ return ''; } var vs = t.target ? t.target.call(this, values, parent) : values; parent = t.target ? values : parent; if(t.target && Ext.isArray(vs)){ var buf = []; for(var i = 0, len = vs.length; i < len; i++){ buf[buf.length] = t.compiled.call(this, vs[i], parent, i+1, len); } return buf.join(''); } return t.compiled.call(this, vs, parent, xindex, xcount); }, compileTpl : function(tpl){ var fm = Ext.util.Format; var useF = this.disableFormats !== true; var sep = Ext.isGecko ? "+" : ","; var fn = function(m, name, format, args, math){ if(name.substr(0, 4) == 'xtpl'){ return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'"; } var v; if(name === '.'){ v = 'values'; }else if(name === '#'){ v = 'xindex'; }else if(name.indexOf('.') != -1){ v = name; }else{ v = "values['" + name + "']"; } if(math){ v = '(' + v + math + ')'; } if(format && useF){ args = args ? ',' + args : ""; if(format.substr(0, 5) != "this."){ format = "fm." + format + '('; }else{ format = 'this.call("'+ format.substr(5) + '", '; args = ", values"; } }else{ args= ''; format = "("+v+" === undefined ? '' : "; } return "'"+ sep + format + v + args + ")"+sep+"'"; }; var codeFn = function(m, code){ return "'"+ sep +'('+code+')'+sep+"'"; }; var body; if(Ext.isGecko){ body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" + tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) + "';};"; }else{ body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"]; body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn)); body.push("'].join('');};"); body = body.join(''); } eval(body); return this; }, apply : function(values){ return this.master.compiled.call(this, values, {}, 1, 1); }, applyTemplate : function(values){ return this.master.compiled.call(this, values, {}, 1, 1); }, compile : function(){return this;} }); Ext.XTemplate.from = function(el){ el = Ext.getDom(el); return new Ext.XTemplate(el.value || el.innerHTML); }; Ext.util.CSS = function(){ var rules = null; var doc = document; var camelRe = /(-[a-z])/gi; var camelFn = function(m, a){ return a.charAt(1).toUpperCase(); }; return { createStyleSheet : function(cssText, id){ var ss; var head = doc.getElementsByTagName("head")[0]; var rules = doc.createElement("style"); rules.setAttribute("type", "text/css"); if(id){ rules.setAttribute("id", id); } if(Ext.isIE){ head.appendChild(rules); ss = rules.styleSheet; ss.cssText = cssText; }else{ try{ rules.appendChild(doc.createTextNode(cssText)); }catch(e){ rules.cssText = cssText; } head.appendChild(rules); ss = rules.styleSheet ? rules.styleSheet : (rules.sheet || doc.styleSheets[doc.styleSheets.length-1]); } this.cacheStyleSheet(ss); return ss; }, removeStyleSheet : function(id){ var existing = doc.getElementById(id); if(existing){ existing.parentNode.removeChild(existing); } }, swapStyleSheet : function(id, url){ this.removeStyleSheet(id); var ss = doc.createElement("link"); ss.setAttribute("rel", "stylesheet"); ss.setAttribute("type", "text/css"); ss.setAttribute("id", id); ss.setAttribute("href", url); doc.getElementsByTagName("head")[0].appendChild(ss); }, refreshCache : function(){ return this.getRules(true); }, cacheStyleSheet : function(ss){ if(!rules){ rules = {}; } try{ var ssRules = ss.cssRules || ss.rules; for(var j = ssRules.length-1; j >= 0; --j){ rules[ssRules[j].selectorText] = ssRules[j]; } }catch(e){} }, getRules : function(refreshCache){ if(rules == null || refreshCache){ rules = {}; var ds = doc.styleSheets; for(var i =0, len = ds.length; i < len; i++){ try{ this.cacheStyleSheet(ds[i]); }catch(e){} } } return rules; }, getRule : function(selector, refreshCache){ var rs = this.getRules(refreshCache); if(!Ext.isArray(selector)){ return rs[selector]; } for(var i = 0; i < selector.length; i++){ if(rs[selector[i]]){ return rs[selector[i]]; } } return null; }, updateRule : function(selector, property, value){ if(!Ext.isArray(selector)){ var rule = this.getRule(selector); if(rule){ rule.style[property.replace(camelRe, camelFn)] = value; return true; } }else{ for(var i = 0; i < selector.length; i++){ if(this.updateRule(selector[i], property, value)){ return true; } } } return false; } }; }(); Ext.util.ClickRepeater = function(el, config) { this.el = Ext.get(el); this.el.unselectable(); Ext.apply(this, config); this.addEvents( "mousedown", "click", "mouseup" ); this.el.on("mousedown", this.handleMouseDown, this); if(this.preventDefault || this.stopDefault){ this.el.on("click", function(e){ if(this.preventDefault){ e.preventDefault(); } if(this.stopDefault){ e.stopEvent(); } }, this); } if(this.handler){ this.on("click", this.handler, this.scope || this); } Ext.util.ClickRepeater.superclass.constructor.call(this); }; Ext.extend(Ext.util.ClickRepeater, Ext.util.Observable, { interval : 20, delay: 250, preventDefault : true, stopDefault : false, timer : 0, handleMouseDown : function(){ clearTimeout(this.timer); this.el.blur(); if(this.pressClass){ this.el.addClass(this.pressClass); } this.mousedownTime = new Date(); Ext.getDoc().on("mouseup", this.handleMouseUp, this); this.el.on("mouseout", this.handleMouseOut, this); this.fireEvent("mousedown", this); this.fireEvent("click", this); if (this.accelerate) { this.delay = 400; } this.timer = this.click.defer(this.delay || this.interval, this); }, click : function(){ this.fireEvent("click", this); this.timer = this.click.defer(this.accelerate ? this.easeOutExpo(this.mousedownTime.getElapsed(), 400, -390, 12000) : this.interval, this); }, easeOutExpo : function (t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, handleMouseOut : function(){ clearTimeout(this.timer); if(this.pressClass){ this.el.removeClass(this.pressClass); } this.el.on("mouseover", this.handleMouseReturn, this); }, handleMouseReturn : function(){ this.el.un("mouseover", this.handleMouseReturn); if(this.pressClass){ this.el.addClass(this.pressClass); } this.click(); }, handleMouseUp : function(){ clearTimeout(this.timer); this.el.un("mouseover", this.handleMouseReturn); this.el.un("mouseout", this.handleMouseOut); Ext.getDoc().un("mouseup", this.handleMouseUp); this.el.removeClass(this.pressClass); this.fireEvent("mouseup", this); } }); Ext.KeyNav = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(!this.disabled){ this.disabled = true; this.enable(); } }; Ext.KeyNav.prototype = { disabled : false, defaultEventAction: "stopEvent", forceKeyDown : false, prepareEvent : function(e){ var k = e.getKey(); var h = this.keyToHandler[k]; if(Ext.isSafari && h && k >= 37 && k <= 40){ e.stopEvent(); } }, relay : function(e){ var k = e.getKey(); var h = this.keyToHandler[k]; if(h && this[h]){ if(this.doRelay(e, this[h], h) !== true){ e[this.defaultEventAction](); } } }, doRelay : function(e, h, hname){ return h.call(this.scope || this, e); }, enter : false, left : false, right : false, up : false, down : false, tab : false, esc : false, pageUp : false, pageDown : false, del : false, home : false, end : false, keyToHandler : { 37 : "left", 39 : "right", 38 : "up", 40 : "down", 33 : "pageUp", 34 : "pageDown", 46 : "del", 36 : "home", 35 : "end", 13 : "enter", 27 : "esc", 9 : "tab" }, enable: function(){ if(this.disabled){ if(this.forceKeyDown || Ext.isIE || Ext.isAir){ this.el.on("keydown", this.relay, this); }else{ this.el.on("keydown", this.prepareEvent, this); this.el.on("keypress", this.relay, this); } this.disabled = false; } }, disable: function(){ if(!this.disabled){ if(this.forceKeyDown || Ext.isIE || Ext.isAir){ this.el.un("keydown", this.relay); }else{ this.el.un("keydown", this.prepareEvent); this.el.un("keypress", this.relay); } this.disabled = true; } } }; Ext.KeyMap = function(el, config, eventName){ this.el = Ext.get(el); this.eventName = eventName || "keydown"; this.bindings = []; if(config){ this.addBinding(config); } this.enable(); }; Ext.KeyMap.prototype = { stopEvent : false, addBinding : function(config){ if(Ext.isArray(config)){ for(var i = 0, len = config.length; i < len; i++){ this.addBinding(config[i]); } return; } var keyCode = config.key, shift = config.shift, ctrl = config.ctrl, alt = config.alt, fn = config.fn || config.handler, scope = config.scope; if(typeof keyCode == "string"){ var ks = []; var keyString = keyCode.toUpperCase(); for(var j = 0, len = keyString.length; j < len; j++){ ks.push(keyString.charCodeAt(j)); } keyCode = ks; } var keyArray = Ext.isArray(keyCode); var handler = function(e){ if((!shift || e.shiftKey) && (!ctrl || e.ctrlKey) && (!alt || e.altKey)){ var k = e.getKey(); if(keyArray){ for(var i = 0, len = keyCode.length; i < len; i++){ if(keyCode[i] == k){ if(this.stopEvent){ e.stopEvent(); } fn.call(scope || window, k, e); return; } } }else{ if(k == keyCode){ if(this.stopEvent){ e.stopEvent(); } fn.call(scope || window, k, e); } } } }; this.bindings.push(handler); }, on : function(key, fn, scope){ var keyCode, shift, ctrl, alt; if(typeof key == "object" && !Ext.isArray(key)){ keyCode = key.key; shift = key.shift; ctrl = key.ctrl; alt = key.alt; }else{ keyCode = key; } this.addBinding({ key: keyCode, shift: shift, ctrl: ctrl, alt: alt, fn: fn, scope: scope }) }, handleKeyDown : function(e){ if(this.enabled){ var b = this.bindings; for(var i = 0, len = b.length; i < len; i++){ b[i].call(this, e); } } }, isEnabled : function(){ return this.enabled; }, enable: function(){ if(!this.enabled){ this.el.on(this.eventName, this.handleKeyDown, this); this.enabled = true; } }, disable: function(){ if(this.enabled){ this.el.removeListener(this.eventName, this.handleKeyDown, this); this.enabled = false; } } }; Ext.util.TextMetrics = function(){ var shared; return { measure : function(el, text, fixedWidth){ if(!shared){ shared = Ext.util.TextMetrics.Instance(el, fixedWidth); } shared.bind(el); shared.setFixedWidth(fixedWidth || 'auto'); return shared.getSize(text); }, createInstance : function(el, fixedWidth){ return Ext.util.TextMetrics.Instance(el, fixedWidth); } }; }(); Ext.util.TextMetrics.Instance = function(bindTo, fixedWidth){ var ml = new Ext.Element(document.createElement('div')); document.body.appendChild(ml.dom); ml.position('absolute'); ml.setLeftTop(-1000, -1000); ml.hide(); if(fixedWidth){ ml.setWidth(fixedWidth); } var instance = { getSize : function(text){ ml.update(text); var s = ml.getSize(); ml.update(''); return s; }, bind : function(el){ ml.setStyle( Ext.fly(el).getStyles('font-size','font-style', 'font-weight', 'font-family','line-height') ); }, setFixedWidth : function(width){ ml.setWidth(width); }, getWidth : function(text){ ml.dom.style.width = 'auto'; return this.getSize(text).width; }, getHeight : function(text){ return this.getSize(text).height; } }; instance.bind(bindTo); return instance; }; Ext.Element.measureText = Ext.util.TextMetrics.measure; (function() { var Event=Ext.EventManager; var Dom=Ext.lib.Dom; Ext.dd.DragDrop = function(id, sGroup, config) { if(id) { this.init(id, sGroup, config); } }; Ext.dd.DragDrop.prototype = { id: null, config: null, dragElId: null, handleElId: null, invalidHandleTypes: null, invalidHandleIds: null, invalidHandleClasses: null, startPageX: 0, startPageY: 0, groups: null, locked: false, lock: function() { this.locked = true; }, unlock: function() { this.locked = false; }, isTarget: true, padding: null, _domRef: null, __ygDragDrop: true, constrainX: false, constrainY: false, minX: 0, maxX: 0, minY: 0, maxY: 0, maintainOffset: false, xTicks: null, yTicks: null, primaryButtonOnly: true, available: false, hasOuterHandles: false, b4StartDrag: function(x, y) { }, startDrag: function(x, y) { }, b4Drag: function(e) { }, onDrag: function(e) { }, onDragEnter: function(e, id) { }, b4DragOver: function(e) { }, onDragOver: function(e, id) { }, b4DragOut: function(e) { }, onDragOut: function(e, id) { }, b4DragDrop: function(e) { }, onDragDrop: function(e, id) { }, onInvalidDrop: function(e) { }, b4EndDrag: function(e) { }, endDrag: function(e) { }, b4MouseDown: function(e) { }, onMouseDown: function(e) { }, onMouseUp: function(e) { }, onAvailable: function () { }, defaultPadding : {left:0, right:0, top:0, bottom:0}, constrainTo : function(constrainTo, pad, inContent){ if(typeof pad == "number"){ pad = {left: pad, right:pad, top:pad, bottom:pad}; } pad = pad || this.defaultPadding; var b = Ext.get(this.getEl()).getBox(); var ce = Ext.get(constrainTo); var s = ce.getScroll(); var c, cd = ce.dom; if(cd == document.body){ c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight()}; }else{ var xy = ce.getXY(); c = {x : xy[0]+s.left, y: xy[1]+s.top, width: cd.clientWidth, height: cd.clientHeight}; } var topSpace = b.y - c.y; var leftSpace = b.x - c.x; this.resetConstraints(); this.setXConstraint(leftSpace - (pad.left||0), c.width - leftSpace - b.width - (pad.right||0), this.xTickSize ); this.setYConstraint(topSpace - (pad.top||0), c.height - topSpace - b.height - (pad.bottom||0), this.yTickSize ); }, getEl: function() { if (!this._domRef) { this._domRef = Ext.getDom(this.id); } return this._domRef; }, getDragEl: function() { return Ext.getDom(this.dragElId); }, init: function(id, sGroup, config) { this.initTarget(id, sGroup, config); Event.on(this.id, "mousedown", this.handleMouseDown, this); }, initTarget: function(id, sGroup, config) { this.config = config || {}; this.DDM = Ext.dd.DDM; this.groups = {}; if (typeof id !== "string") { id = Ext.id(id); } this.id = id; this.addToGroup((sGroup) ? sGroup : "default"); this.handleElId = id; this.setDragElId(id); this.invalidHandleTypes = { A: "A" }; this.invalidHandleIds = {}; this.invalidHandleClasses = []; this.applyConfig(); this.handleOnAvailable(); }, applyConfig: function() { this.padding = this.config.padding || [0, 0, 0, 0]; this.isTarget = (this.config.isTarget !== false); this.maintainOffset = (this.config.maintainOffset); this.primaryButtonOnly = (this.config.primaryButtonOnly !== false); }, handleOnAvailable: function() { this.available = true; this.resetConstraints(); this.onAvailable(); }, setPadding: function(iTop, iRight, iBot, iLeft) { if (!iRight && 0 !== iRight) { this.padding = [iTop, iTop, iTop, iTop]; } else if (!iBot && 0 !== iBot) { this.padding = [iTop, iRight, iTop, iRight]; } else { this.padding = [iTop, iRight, iBot, iLeft]; } }, setInitPosition: function(diffX, diffY) { var el = this.getEl(); if (!this.DDM.verifyEl(el)) { return; } var dx = diffX || 0; var dy = diffY || 0; var p = Dom.getXY( el ); this.initPageX = p[0] - dx; this.initPageY = p[1] - dy; this.lastPageX = p[0]; this.lastPageY = p[1]; this.setStartPosition(p); }, setStartPosition: function(pos) { var p = pos || Dom.getXY( this.getEl() ); this.deltaSetXY = null; this.startPageX = p[0]; this.startPageY = p[1]; }, addToGroup: function(sGroup) { this.groups[sGroup] = true; this.DDM.regDragDrop(this, sGroup); }, removeFromGroup: function(sGroup) { if (this.groups[sGroup]) { delete this.groups[sGroup]; } this.DDM.removeDDFromGroup(this, sGroup); }, setDragElId: function(id) { this.dragElId = id; }, setHandleElId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } this.handleElId = id; this.DDM.regHandle(this.id, id); }, setOuterHandleElId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } Event.on(id, "mousedown", this.handleMouseDown, this); this.setHandleElId(id); this.hasOuterHandles = true; }, unreg: function() { Event.un(this.id, "mousedown", this.handleMouseDown); this._domRef = null; this.DDM._remove(this); }, destroy : function(){ this.unreg(); }, isLocked: function() { return (this.DDM.isLocked() || this.locked); }, handleMouseDown: function(e, oDD){ if (this.primaryButtonOnly && e.button != 0) { return; } if (this.isLocked()) { return; } this.DDM.refreshCache(this.groups); var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e)); if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) { } else { if (this.clickValidator(e)) { this.setStartPosition(); this.b4MouseDown(e); this.onMouseDown(e); this.DDM.handleMouseDown(e, this); this.DDM.stopEvent(e); } else { } } }, clickValidator: function(e) { var target = e.getTarget(); return ( this.isValidHandleChild(target) && (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) ); }, addInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); this.invalidHandleTypes[type] = type; }, addInvalidHandleId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } this.invalidHandleIds[id] = id; }, addInvalidHandleClass: function(cssClass) { this.invalidHandleClasses.push(cssClass); }, removeInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); delete this.invalidHandleTypes[type]; }, removeInvalidHandleId: function(id) { if (typeof id !== "string") { id = Ext.id(id); } delete this.invalidHandleIds[id]; }, removeInvalidHandleClass: function(cssClass) { for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) { if (this.invalidHandleClasses[i] == cssClass) { delete this.invalidHandleClasses[i]; } } }, isValidHandleChild: function(node) { var valid = true; var nodeName; try { nodeName = node.nodeName.toUpperCase(); } catch(e) { nodeName = node.nodeName; } valid = valid && !this.invalidHandleTypes[nodeName]; valid = valid && !this.invalidHandleIds[node.id]; for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) { valid = !Dom.hasClass(node, this.invalidHandleClasses[i]); } return valid; }, setXTicks: function(iStartX, iTickSize) { this.xTicks = []; this.xTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } this.xTicks.sort(this.DDM.numericSort) ; }, setYTicks: function(iStartY, iTickSize) { this.yTicks = []; this.yTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } this.yTicks.sort(this.DDM.numericSort) ; }, setXConstraint: function(iLeft, iRight, iTickSize) { this.leftConstraint = iLeft; this.rightConstraint = iRight; this.minX = this.initPageX - iLeft; this.maxX = this.initPageX + iRight; if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); } this.constrainX = true; }, clearConstraints: function() { this.constrainX = false; this.constrainY = false; this.clearTicks(); }, clearTicks: function() { this.xTicks = null; this.yTicks = null; this.xTickSize = 0; this.yTickSize = 0; }, setYConstraint: function(iUp, iDown, iTickSize) { this.topConstraint = iUp; this.bottomConstraint = iDown; this.minY = this.initPageY - iUp; this.maxY = this.initPageY + iDown; if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); } this.constrainY = true; }, resetConstraints: function() { if (this.initPageX || this.initPageX === 0) { var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0; var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0; this.setInitPosition(dx, dy); } else { this.setInitPosition(); } if (this.constrainX) { this.setXConstraint( this.leftConstraint, this.rightConstraint, this.xTickSize ); } if (this.constrainY) { this.setYConstraint( this.topConstraint, this.bottomConstraint, this.yTickSize ); } }, getTick: function(val, tickArray) { if (!tickArray) { return val; } else if (tickArray[0] >= val) { return tickArray[0]; } else { for (var i=0, len=tickArray.length; i<len; ++i) { var next = i + 1; if (tickArray[next] && tickArray[next] >= val) { var diff1 = val - tickArray[i]; var diff2 = tickArray[next] - val; return (diff2 > diff1) ? tickArray[i] : tickArray[next]; } } return tickArray[tickArray.length - 1]; } }, toString: function() { return ("DragDrop " + this.id); } }; })(); if (!Ext.dd.DragDropMgr) { Ext.dd.DragDropMgr = function() { var Event = Ext.EventManager; return { ids: {}, handleIds: {}, dragCurrent: null, dragOvers: {}, deltaX: 0, deltaY: 0, preventDefault: true, stopPropagation: true, initalized: false, locked: false, init: function() { this.initialized = true; }, POINT: 0, INTERSECT: 1, mode: 0, _execOnAll: function(sMethod, args) { for (var i in this.ids) { for (var j in this.ids[i]) { var oDD = this.ids[i][j]; if (! this.isTypeOfDD(oDD)) { continue; } oDD[sMethod].apply(oDD, args); } } }, _onLoad: function() { this.init(); Event.on(document, "mouseup", this.handleMouseUp, this, true); Event.on(document, "mousemove", this.handleMouseMove, this, true); Event.on(window, "unload", this._onUnload, this, true); Event.on(window, "resize", this._onResize, this, true); }, _onResize: function(e) { this._execOnAll("resetConstraints", []); }, lock: function() { this.locked = true; }, unlock: function() { this.locked = false; }, isLocked: function() { return this.locked; }, locationCache: {}, useCache: true, clickPixelThresh: 3, clickTimeThresh: 350, dragThreshMet: false, clickTimeout: null, startX: 0, startY: 0, regDragDrop: function(oDD, sGroup) { if (!this.initialized) { this.init(); } if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } this.ids[sGroup][oDD.id] = oDD; }, removeDDFromGroup: function(oDD, sGroup) { if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } var obj = this.ids[sGroup]; if (obj && obj[oDD.id]) { delete obj[oDD.id]; } }, _remove: function(oDD) { for (var g in oDD.groups) { if (g && this.ids[g][oDD.id]) { delete this.ids[g][oDD.id]; } } delete this.handleIds[oDD.id]; }, regHandle: function(sDDId, sHandleId) { if (!this.handleIds[sDDId]) { this.handleIds[sDDId] = {}; } this.handleIds[sDDId][sHandleId] = sHandleId; }, isDragDrop: function(id) { return ( this.getDDById(id) ) ? true : false; }, getRelated: function(p_oDD, bTargetsOnly) { var oDDs = []; for (var i in p_oDD.groups) { for (j in this.ids[i]) { var dd = this.ids[i][j]; if (! this.isTypeOfDD(dd)) { continue; } if (!bTargetsOnly || dd.isTarget) { oDDs[oDDs.length] = dd; } } } return oDDs; }, isLegalTarget: function (oDD, oTargetDD) { var targets = this.getRelated(oDD, true); for (var i=0, len=targets.length;i<len;++i) { if (targets[i].id == oTargetDD.id) { return true; } } return false; }, isTypeOfDD: function (oDD) { return (oDD && oDD.__ygDragDrop); }, isHandle: function(sDDId, sHandleId) { return ( this.handleIds[sDDId] && this.handleIds[sDDId][sHandleId] ); }, getDDById: function(id) { for (var i in this.ids) { if (this.ids[i][id]) { return this.ids[i][id]; } } return null; }, handleMouseDown: function(e, oDD) { if(Ext.QuickTips){ Ext.QuickTips.disable(); } this.currentTarget = e.getTarget(); this.dragCurrent = oDD; var el = oDD.getEl(); this.startX = e.getPageX(); this.startY = e.getPageY(); this.deltaX = this.startX - el.offsetLeft; this.deltaY = this.startY - el.offsetTop; this.dragThreshMet = false; this.clickTimeout = setTimeout( function() { var DDM = Ext.dd.DDM; DDM.startDrag(DDM.startX, DDM.startY); }, this.clickTimeThresh ); }, startDrag: function(x, y) { clearTimeout(this.clickTimeout); if (this.dragCurrent) { this.dragCurrent.b4StartDrag(x, y); this.dragCurrent.startDrag(x, y); } this.dragThreshMet = true; }, handleMouseUp: function(e) { if(Ext.QuickTips){ Ext.QuickTips.enable(); } if (! this.dragCurrent) { return; } clearTimeout(this.clickTimeout); if (this.dragThreshMet) { this.fireEvents(e, true); } else { } this.stopDrag(e); this.stopEvent(e); }, stopEvent: function(e){ if(this.stopPropagation) { e.stopPropagation(); } if (this.preventDefault) { e.preventDefault(); } }, stopDrag: function(e) { if (this.dragCurrent) { if (this.dragThreshMet) { this.dragCurrent.b4EndDrag(e); this.dragCurrent.endDrag(e); } this.dragCurrent.onMouseUp(e); } this.dragCurrent = null; this.dragOvers = {}; }, handleMouseMove: function(e) { if (! this.dragCurrent) { return true; } if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) { this.stopEvent(e); return this.handleMouseUp(e); } if (!this.dragThreshMet) { var diffX = Math.abs(this.startX - e.getPageX()); var diffY = Math.abs(this.startY - e.getPageY()); if (diffX > this.clickPixelThresh || diffY > this.clickPixelThresh) { this.startDrag(this.startX, this.startY); } } if (this.dragThreshMet) { this.dragCurrent.b4Drag(e); this.dragCurrent.onDrag(e); if(!this.dragCurrent.moveOnly){ this.fireEvents(e, false); } } this.stopEvent(e); return true; }, fireEvents: function(e, isDrop) { var dc = this.dragCurrent; if (!dc || dc.isLocked()) { return; } var pt = e.getPoint(); var oldOvers = []; var outEvts = []; var overEvts = []; var dropEvts = []; var enterEvts = []; for (var i in this.dragOvers) { var ddo = this.dragOvers[i]; if (! this.isTypeOfDD(ddo)) { continue; } if (! this.isOverTarget(pt, ddo, this.mode)) { outEvts.push( ddo ); } oldOvers[i] = true; delete this.dragOvers[i]; } for (var sGroup in dc.groups) { if ("string" != typeof sGroup) { continue; } for (i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (! this.isTypeOfDD(oDD)) { continue; } if (oDD.isTarget && !oDD.isLocked() && oDD != dc) { if (this.isOverTarget(pt, oDD, this.mode)) { if (isDrop) { dropEvts.push( oDD ); } else { if (!oldOvers[oDD.id]) { enterEvts.push( oDD ); } else { overEvts.push( oDD ); } this.dragOvers[oDD.id] = oDD; } } } } } if (this.mode) { if (outEvts.length) { dc.b4DragOut(e, outEvts); dc.onDragOut(e, outEvts); } if (enterEvts.length) { dc.onDragEnter(e, enterEvts); } if (overEvts.length) { dc.b4DragOver(e, overEvts); dc.onDragOver(e, overEvts); } if (dropEvts.length) { dc.b4DragDrop(e, dropEvts); dc.onDragDrop(e, dropEvts); } } else { var len = 0; for (i=0, len=outEvts.length; i<len; ++i) { dc.b4DragOut(e, outEvts[i].id); dc.onDragOut(e, outEvts[i].id); } for (i=0,len=enterEvts.length; i<len; ++i) { dc.onDragEnter(e, enterEvts[i].id); } for (i=0,len=overEvts.length; i<len; ++i) { dc.b4DragOver(e, overEvts[i].id); dc.onDragOver(e, overEvts[i].id); } for (i=0, len=dropEvts.length; i<len; ++i) { dc.b4DragDrop(e, dropEvts[i].id); dc.onDragDrop(e, dropEvts[i].id); } } if (isDrop && !dropEvts.length) { dc.onInvalidDrop(e); } }, getBestMatch: function(dds) { var winner = null; var len = dds.length; if (len == 1) { winner = dds[0]; } else { for (var i=0; i<len; ++i) { var dd = dds[i]; if (dd.cursorIsOver) { winner = dd; break; } else { if (!winner || winner.overlap.getArea() < dd.overlap.getArea()) { winner = dd; } } } } return winner; }, refreshCache: function(groups) { for (var sGroup in groups) { if ("string" != typeof sGroup) { continue; } for (var i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (this.isTypeOfDD(oDD)) { var loc = this.getLocation(oDD); if (loc) { this.locationCache[oDD.id] = loc; } else { delete this.locationCache[oDD.id]; } } } } }, verifyEl: function(el) { if (el) { var parent; if(Ext.isIE){ try{ parent = el.offsetParent; }catch(e){} }else{ parent = el.offsetParent; } if (parent) { return true; } } return false; }, getLocation: function(oDD) { if (! this.isTypeOfDD(oDD)) { return null; } var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l; try { pos= Ext.lib.Dom.getXY(el); } catch (e) { } if (!pos) { return null; } x1 = pos[0]; x2 = x1 + el.offsetWidth; y1 = pos[1]; y2 = y1 + el.offsetHeight; t = y1 - oDD.padding[0]; r = x2 + oDD.padding[1]; b = y2 + oDD.padding[2]; l = x1 - oDD.padding[3]; return new Ext.lib.Region( t, r, b, l ); }, isOverTarget: function(pt, oTarget, intersect) { var loc = this.locationCache[oTarget.id]; if (!loc || !this.useCache) { loc = this.getLocation(oTarget); this.locationCache[oTarget.id] = loc; } if (!loc) { return false; } oTarget.cursorIsOver = loc.contains( pt ); var dc = this.dragCurrent; if (!dc || !dc.getTargetCoord || (!intersect && !dc.constrainX && !dc.constrainY)) { return oTarget.cursorIsOver; } oTarget.overlap = null; var pos = dc.getTargetCoord(pt.x, pt.y); var el = dc.getDragEl(); var curRegion = new Ext.lib.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ); var overlap = curRegion.intersect(loc); if (overlap) { oTarget.overlap = overlap; return (intersect) ? true : oTarget.cursorIsOver; } else { return false; } }, _onUnload: function(e, me) { Ext.dd.DragDropMgr.unregAll(); }, unregAll: function() { if (this.dragCurrent) { this.stopDrag(); this.dragCurrent = null; } this._execOnAll("unreg", []); for (var i in this.elementCache) { delete this.elementCache[i]; } this.elementCache = {}; this.ids = {}; }, elementCache: {}, getElWrapper: function(id) { var oWrapper = this.elementCache[id]; if (!oWrapper || !oWrapper.el) { oWrapper = this.elementCache[id] = new this.ElementWrapper(Ext.getDom(id)); } return oWrapper; }, getElement: function(id) { return Ext.getDom(id); }, getCss: function(id) { var el = Ext.getDom(id); return (el) ? el.style : null; }, ElementWrapper: function(el) { this.el = el || null; this.id = this.el && el.id; this.css = this.el && el.style; }, getPosX: function(el) { return Ext.lib.Dom.getX(el); }, getPosY: function(el) { return Ext.lib.Dom.getY(el); }, swapNode: function(n1, n2) { if (n1.swapNode) { n1.swapNode(n2); } else { var p = n2.parentNode; var s = n2.nextSibling; if (s == n1) { p.insertBefore(n1, n2); } else if (n2 == n1.nextSibling) { p.insertBefore(n2, n1); } else { n1.parentNode.replaceChild(n2, n1); p.insertBefore(n1, s); } } }, getScroll: function () { var t, l, dde=document.documentElement, db=document.body; if (dde && (dde.scrollTop || dde.scrollLeft)) { t = dde.scrollTop; l = dde.scrollLeft; } else if (db) { t = db.scrollTop; l = db.scrollLeft; } else { } return { top: t, left: l }; }, getStyle: function(el, styleProp) { return Ext.fly(el).getStyle(styleProp); }, getScrollTop: function () { return this.getScroll().top; }, getScrollLeft: function () { return this.getScroll().left; }, moveToEl: function (moveEl, targetEl) { var aCoord = Ext.lib.Dom.getXY(targetEl); Ext.lib.Dom.setXY(moveEl, aCoord); }, numericSort: function(a, b) { return (a - b); }, _timeoutCount: 0, _addListeners: function() { var DDM = Ext.dd.DDM; if ( Ext.lib.Event && document ) { DDM._onLoad(); } else { if (DDM._timeoutCount > 2000) { } else { setTimeout(DDM._addListeners, 10); if (document && document.body) { DDM._timeoutCount += 1; } } } }, handleWasClicked: function(node, id) { if (this.isHandle(id, node.id)) { return true; } else { var p = node.parentNode; while (p) { if (this.isHandle(id, p.id)) { return true; } else { p = p.parentNode; } } } return false; } }; }(); Ext.dd.DDM = Ext.dd.DragDropMgr; Ext.dd.DDM._addListeners(); } Ext.dd.DD = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, { scroll: true, autoOffset: function(iPageX, iPageY) { var x = iPageX - this.startPageX; var y = iPageY - this.startPageY; this.setDelta(x, y); }, setDelta: function(iDeltaX, iDeltaY) { this.deltaX = iDeltaX; this.deltaY = iDeltaY; }, setDragElPos: function(iPageX, iPageY) { var el = this.getDragEl(); this.alignElWithMouse(el, iPageX, iPageY); }, alignElWithMouse: function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); var fly = el.dom ? el : Ext.fly(el, '_dd'); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; fly.setXY(aCoord); var newLeft = fly.getLeft(true); var newTop = fly.getTop(true); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]); } this.cachePosition(oCoord.x, oCoord.y); this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); return oCoord; }, cachePosition: function(iPageX, iPageY) { if (iPageX) { this.lastPageX = iPageX; this.lastPageY = iPageY; } else { var aCoord = Ext.lib.Dom.getXY(this.getEl()); this.lastPageX = aCoord[0]; this.lastPageY = aCoord[1]; } }, autoScroll: function(x, y, h, w) { if (this.scroll) { var clientH = Ext.lib.Dom.getViewHeight(); var clientW = Ext.lib.Dom.getViewWidth(); var st = this.DDM.getScrollTop(); var sl = this.DDM.getScrollLeft(); var bot = h + y; var right = w + x; var toBot = (clientH + st - y - this.deltaY); var toRight = (clientW + sl - x - this.deltaX); var thresh = 40; var scrAmt = (document.all) ? 80 : 30; if ( bot > clientH && toBot < thresh ) { window.scrollTo(sl, st + scrAmt); } if ( y < st && st > 0 && y - st < thresh ) { window.scrollTo(sl, st - scrAmt); } if ( right > clientW && toRight < thresh ) { window.scrollTo(sl + scrAmt, st); } if ( x < sl && sl > 0 && x - sl < thresh ) { window.scrollTo(sl - scrAmt, st); } } }, getTargetCoord: function(iPageX, iPageY) { var x = iPageX - this.deltaX; var y = iPageY - this.deltaY; if (this.constrainX) { if (x < this.minX) { x = this.minX; } if (x > this.maxX) { x = this.maxX; } } if (this.constrainY) { if (y < this.minY) { y = this.minY; } if (y > this.maxY) { y = this.maxY; } } x = this.getTick(x, this.xTicks); y = this.getTick(y, this.yTicks); return {x:x, y:y}; }, applyConfig: function() { Ext.dd.DD.superclass.applyConfig.call(this); this.scroll = (this.config.scroll !== false); }, b4MouseDown: function(e) { this.autoOffset(e.getPageX(), e.getPageY()); }, b4Drag: function(e) { this.setDragElPos(e.getPageX(), e.getPageY()); }, toString: function() { return ("DD " + this.id); } }); Ext.dd.DDProxy = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); this.initFrame(); } }; Ext.dd.DDProxy.dragElId = "ygddfdiv"; Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, { resizeFrame: true, centerFrame: false, createFrame: function() { var self = this; var body = document.body; if (!body || !body.firstChild) { setTimeout( function() { self.createFrame(); }, 50 ); return; } var div = this.getDragEl(); if (!div) { div = document.createElement("div"); div.id = this.dragElId; var s = div.style; s.position = "absolute"; s.visibility = "hidden"; s.cursor = "move"; s.border = "2px solid #aaa"; s.zIndex = 999; body.insertBefore(div, body.firstChild); } }, initFrame: function() { this.createFrame(); }, applyConfig: function() { Ext.dd.DDProxy.superclass.applyConfig.call(this); this.resizeFrame = (this.config.resizeFrame !== false); this.centerFrame = (this.config.centerFrame); this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId); }, showFrame: function(iPageX, iPageY) { var el = this.getEl(); var dragEl = this.getDragEl(); var s = dragEl.style; this._resizeProxy(); if (this.centerFrame) { this.setDelta( Math.round(parseInt(s.width, 10)/2), Math.round(parseInt(s.height, 10)/2) ); } this.setDragElPos(iPageX, iPageY); Ext.fly(dragEl).show(); }, _resizeProxy: function() { if (this.resizeFrame) { var el = this.getEl(); Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight); } }, b4MouseDown: function(e) { var x = e.getPageX(); var y = e.getPageY(); this.autoOffset(x, y); this.setDragElPos(x, y); }, b4StartDrag: function(x, y) { this.showFrame(x, y); }, b4EndDrag: function(e) { Ext.fly(this.getDragEl()).hide(); }, endDrag: function(e) { var lel = this.getEl(); var del = this.getDragEl(); del.style.visibility = ""; this.beforeMove(); lel.style.visibility = "hidden"; Ext.dd.DDM.moveToEl(lel, del); del.style.visibility = "hidden"; lel.style.visibility = ""; this.afterDrag(); }, beforeMove : function(){ }, afterDrag : function(){ }, toString: function() { return ("DDProxy " + this.id); } }); Ext.dd.DDTarget = function(id, sGroup, config) { if (id) { this.initTarget(id, sGroup, config); } }; Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, { toString: function() { return ("DDTarget " + this.id); } }); Ext.dd.DragTracker = function(config){ Ext.apply(this, config); this.addEvents( 'mousedown', 'mouseup', 'mousemove', 'dragstart', 'dragend', 'drag' ); this.dragRegion = new Ext.lib.Region(0,0,0,0); if(this.el){ this.initEl(this.el); } } Ext.extend(Ext.dd.DragTracker, Ext.util.Observable, { active: false, tolerance: 5, autoStart: false, initEl: function(el){ this.el = Ext.get(el); el.on('mousedown', this.onMouseDown, this, this.delegate ? {delegate: this.delegate} : undefined); }, destroy : function(){ this.el.un('mousedown', this.onMouseDown, this); }, onMouseDown: function(e, target){ if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){ this.startXY = this.lastXY = e.getXY(); this.dragTarget = this.delegate ? target : this.el.dom; e.preventDefault(); var doc = Ext.getDoc(); doc.on('mouseup', this.onMouseUp, this); doc.on('mousemove', this.onMouseMove, this); doc.on('selectstart', this.stopSelect, this); if(this.autoStart){ this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this); } } }, onMouseMove: function(e, target){ e.preventDefault(); var xy = e.getXY(), s = this.startXY; this.lastXY = xy; if(!this.active){ if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){ this.triggerStart(); }else{ return; } } this.fireEvent('mousemove', this, e); this.onDrag(e); this.fireEvent('drag', this, e); }, onMouseUp: function(e){ var doc = Ext.getDoc(); doc.un('mousemove', this.onMouseMove, this); doc.un('mouseup', this.onMouseUp, this); doc.un('selectstart', this.stopSelect, this); e.preventDefault(); this.clearStart(); this.active = false; delete this.elRegion; this.fireEvent('mouseup', this, e); this.onEnd(e); this.fireEvent('dragend', this, e); }, triggerStart: function(isTimer){ this.clearStart(); this.active = true; this.onStart(this.startXY); this.fireEvent('dragstart', this, this.startXY); }, clearStart : function(){ if(this.timer){ clearTimeout(this.timer); delete this.timer; } }, stopSelect : function(e){ e.stopEvent(); return false; }, onBeforeStart : function(e){ }, onStart : function(xy){ }, onDrag : function(e){ }, onEnd : function(e){ }, getDragTarget : function(){ return this.dragTarget; }, getDragCt : function(){ return this.el; }, getXY : function(constrain){ return constrain ? this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY; }, getOffset : function(constrain){ var xy = this.getXY(constrain); var s = this.startXY; return [s[0]-xy[0], s[1]-xy[1]]; }, constrainModes: { 'point' : function(xy){ if(!this.elRegion){ this.elRegion = this.getDragCt().getRegion(); } var dr = this.dragRegion; dr.left = xy[0]; dr.top = xy[1]; dr.right = xy[0]; dr.bottom = xy[1]; dr.constrainTo(this.elRegion); return [dr.left, dr.top]; } } }); Ext.dd.ScrollManager = function(){ var ddm = Ext.dd.DragDropMgr; var els = {}; var dragEl = null; var proc = {}; var onStop = function(e){ dragEl = null; clearProc(); }; var triggerRefresh = function(){ if(ddm.dragCurrent){ ddm.refreshCache(ddm.dragCurrent.groups); } }; var doScroll = function(){ if(ddm.dragCurrent){ var dds = Ext.dd.ScrollManager; var inc = proc.el.ddScrollConfig ? proc.el.ddScrollConfig.increment : dds.increment; if(!dds.animate){ if(proc.el.scroll(proc.dir, inc)){ triggerRefresh(); } }else{ proc.el.scroll(proc.dir, inc, true, dds.animDuration, triggerRefresh); } } }; var clearProc = function(){ if(proc.id){ clearInterval(proc.id); } proc.id = 0; proc.el = null; proc.dir = ""; }; var startProc = function(el, dir){ clearProc(); proc.el = el; proc.dir = dir; proc.id = setInterval(doScroll, Ext.dd.ScrollManager.frequency); }; var onFire = function(e, isDrop){ if(isDrop || !ddm.dragCurrent){ return; } var dds = Ext.dd.ScrollManager; if(!dragEl || dragEl != ddm.dragCurrent){ dragEl = ddm.dragCurrent; dds.refreshCache(); } var xy = Ext.lib.Event.getXY(e); var pt = new Ext.lib.Point(xy[0], xy[1]); for(var id in els){ var el = els[id], r = el._region; var c = el.ddScrollConfig ? el.ddScrollConfig : dds; if(r && r.contains(pt) && el.isScrollable()){ if(r.bottom - pt.y <= c.vthresh){ if(proc.el != el){ startProc(el, "down"); } return; }else if(r.right - pt.x <= c.hthresh){ if(proc.el != el){ startProc(el, "left"); } return; }else if(pt.y - r.top <= c.vthresh){ if(proc.el != el){ startProc(el, "up"); } return; }else if(pt.x - r.left <= c.hthresh){ if(proc.el != el){ startProc(el, "right"); } return; } } } clearProc(); }; ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm); ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm); return { register : function(el){ if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++) { this.register(el[i]); } }else{ el = Ext.get(el); els[el.id] = el; } }, unregister : function(el){ if(Ext.isArray(el)){ for(var i = 0, len = el.length; i < len; i++) { this.unregister(el[i]); } }else{ el = Ext.get(el); delete els[el.id]; } }, vthresh : 25, hthresh : 25, increment : 100, frequency : 500, animate: true, animDuration: .4, refreshCache : function(){ for(var id in els){ if(typeof els[id] == 'object'){ els[id]._region = els[id].getRegion(); } } } }; }(); Ext.dd.Registry = function(){ var elements = {}; var handles = {}; var autoIdSeed = 0; var getId = function(el, autogen){ if(typeof el == "string"){ return el; } var id = el.id; if(!id && autogen !== false){ id = "extdd-" + (++autoIdSeed); el.id = id; } return id; }; return { register : function(el, data){ data = data || {}; if(typeof el == "string"){ el = document.getElementById(el); } data.ddel = el; elements[getId(el)] = data; if(data.isHandle !== false){ handles[data.ddel.id] = data; } if(data.handles){ var hs = data.handles; for(var i = 0, len = hs.length; i < len; i++){ handles[getId(hs[i])] = data; } } }, unregister : function(el){ var id = getId(el, false); var data = elements[id]; if(data){ delete elements[id]; if(data.handles){ var hs = data.handles; for(var i = 0, len = hs.length; i < len; i++){ delete handles[getId(hs[i], false)]; } } } }, getHandle : function(id){ if(typeof id != "string"){ id = id.id; } return handles[id]; }, getHandleFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); return t ? handles[t.id] : null; }, getTarget : function(id){ if(typeof id != "string"){ id = id.id; } return elements[id]; }, getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); return t ? elements[t.id] || handles[t.id] : null; } }; }(); Ext.dd.StatusProxy = function(config){ Ext.apply(this, config); this.id = this.id || Ext.id(); this.el = new Ext.Layer({ dh: { id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [ {tag: "div", cls: "x-dd-drop-icon"}, {tag: "div", cls: "x-dd-drag-ghost"} ] }, shadow: !config || config.shadow !== false }); this.ghost = Ext.get(this.el.dom.childNodes[1]); this.dropStatus = this.dropNotAllowed; }; Ext.dd.StatusProxy.prototype = { dropAllowed : "x-dd-drop-ok", dropNotAllowed : "x-dd-drop-nodrop", setStatus : function(cssClass){ cssClass = cssClass || this.dropNotAllowed; if(this.dropStatus != cssClass){ this.el.replaceClass(this.dropStatus, cssClass); this.dropStatus = cssClass; } }, reset : function(clearGhost){ this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed; this.dropStatus = this.dropNotAllowed; if(clearGhost){ this.ghost.update(""); } }, update : function(html){ if(typeof html == "string"){ this.ghost.update(html); }else{ this.ghost.update(""); html.style.margin = "0"; this.ghost.dom.appendChild(html); } }, getEl : function(){ return this.el; }, getGhost : function(){ return this.ghost; }, hide : function(clear){ this.el.hide(); if(clear){ this.reset(true); } }, stop : function(){ if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){ this.anim.stop(); } }, show : function(){ this.el.show(); }, sync : function(){ this.el.sync(); }, repair : function(xy, callback, scope){ this.callback = callback; this.scope = scope; if(xy && this.animRepair !== false){ this.el.addClass("x-dd-drag-repair"); this.el.hideUnders(true); this.anim = this.el.shift({ duration: this.repairDuration || .5, easing: 'easeOut', xy: xy, stopFx: true, callback: this.afterRepair, scope: this }); }else{ this.afterRepair(); } }, afterRepair : function(){ this.hide(true); if(typeof this.callback == "function"){ this.callback.call(this.scope || this); } this.callback = null; this.scope = null; } }; Ext.dd.DragSource = function(el, config){ this.el = Ext.get(el); if(!this.dragData){ this.dragData = {}; } Ext.apply(this, config); if(!this.proxy){ this.proxy = new Ext.dd.StatusProxy(); } Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group, {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true}); this.dragging = false; }; Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, { dropAllowed : "x-dd-drop-ok", dropNotAllowed : "x-dd-drop-nodrop", getDragData : function(e){ return this.dragData; }, onDragEnter : function(e, id){ var target = Ext.dd.DragDropMgr.getDDById(id); this.cachedTarget = target; if(this.beforeDragEnter(target, e, id) !== false){ if(target.isNotifyTarget){ var status = target.notifyEnter(this, e, this.dragData); this.proxy.setStatus(status); }else{ this.proxy.setStatus(this.dropAllowed); } if(this.afterDragEnter){ this.afterDragEnter(target, e, id); } } }, beforeDragEnter : function(target, e, id){ return true; }, alignElWithMouse: function() { Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments); this.proxy.sync(); }, onDragOver : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragOver(target, e, id) !== false){ if(target.isNotifyTarget){ var status = target.notifyOver(this, e, this.dragData); this.proxy.setStatus(status); } if(this.afterDragOver){ this.afterDragOver(target, e, id); } } }, beforeDragOver : function(target, e, id){ return true; }, onDragOut : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragOut(target, e, id) !== false){ if(target.isNotifyTarget){ target.notifyOut(this, e, this.dragData); } this.proxy.reset(); if(this.afterDragOut){ this.afterDragOut(target, e, id); } } this.cachedTarget = null; }, beforeDragOut : function(target, e, id){ return true; }, onDragDrop : function(e, id){ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id); if(this.beforeDragDrop(target, e, id) !== false){ if(target.isNotifyTarget){ if(target.notifyDrop(this, e, this.dragData)){ this.onValidDrop(target, e, id); }else{ this.onInvalidDrop(target, e, id); } }else{ this.onValidDrop(target, e, id); } if(this.afterDragDrop){ this.afterDragDrop(target, e, id); } } delete this.cachedTarget; }, beforeDragDrop : function(target, e, id){ return true; }, onValidDrop : function(target, e, id){ this.hideProxy(); if(this.afterValidDrop){ this.afterValidDrop(target, e, id); } }, getRepairXY : function(e, data){ return this.el.getXY(); }, onInvalidDrop : function(target, e, id){ this.beforeInvalidDrop(target, e, id); if(this.cachedTarget){ if(this.cachedTarget.isNotifyTarget){ this.cachedTarget.notifyOut(this, e, this.dragData); } this.cacheTarget = null; } this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this); if(this.afterInvalidDrop){ this.afterInvalidDrop(e, id); } }, afterRepair : function(){ if(Ext.enableFx){ this.el.highlight(this.hlColor || "c3daf9"); } this.dragging = false; }, beforeInvalidDrop : function(target, e, id){ return true; }, handleMouseDown : function(e){ if(this.dragging) { return; } var data = this.getDragData(e); if(data && this.onBeforeDrag(data, e) !== false){ this.dragData = data; this.proxy.stop(); Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments); } }, onBeforeDrag : function(data, e){ return true; }, onStartDrag : Ext.emptyFn, startDrag : function(x, y){ this.proxy.reset(); this.dragging = true; this.proxy.update(""); this.onInitDrag(x, y); this.proxy.show(); }, onInitDrag : function(x, y){ var clone = this.el.dom.cloneNode(true); clone.id = Ext.id(); this.proxy.update(clone); this.onStartDrag(x, y); return true; }, getProxy : function(){ return this.proxy; }, hideProxy : function(){ this.proxy.hide(); this.proxy.reset(true); this.dragging = false; }, triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); }, b4EndDrag: function(e) { }, endDrag : function(e){ this.onEndDrag(this.dragData, e); }, onEndDrag : function(data, e){ }, autoOffset : function(x, y) { this.setDelta(-12, -20); } }); Ext.dd.DropTarget = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.el); } Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group, {isTarget: true}); }; Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, { dropAllowed : "x-dd-drop-ok", dropNotAllowed : "x-dd-drop-nodrop", isTarget : true, isNotifyTarget : true, notifyEnter : function(dd, e, data){ if(this.overClass){ this.el.addClass(this.overClass); } return this.dropAllowed; }, notifyOver : function(dd, e, data){ return this.dropAllowed; }, notifyOut : function(dd, e, data){ if(this.overClass){ this.el.removeClass(this.overClass); } }, notifyDrop : function(dd, e, data){ return false; } }); Ext.dd.DragZone = function(el, config){ Ext.dd.DragZone.superclass.constructor.call(this, el, config); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.el); } }; Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, { getDragData : function(e){ return Ext.dd.Registry.getHandleFromEvent(e); }, onInitDrag : function(x, y){ this.proxy.update(this.dragData.ddel.cloneNode(true)); this.onStartDrag(x, y); return true; }, afterRepair : function(){ if(Ext.enableFx){ Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9"); } this.dragging = false; }, getRepairXY : function(e){ return Ext.Element.fly(this.dragData.ddel).getXY(); } }); Ext.dd.DropZone = function(el, config){ Ext.dd.DropZone.superclass.constructor.call(this, el, config); }; Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, { getTargetFromEvent : function(e){ return Ext.dd.Registry.getTargetFromEvent(e); }, onNodeEnter : function(n, dd, e, data){ }, onNodeOver : function(n, dd, e, data){ return this.dropAllowed; }, onNodeOut : function(n, dd, e, data){ }, onNodeDrop : function(n, dd, e, data){ return false; }, onContainerOver : function(dd, e, data){ return this.dropNotAllowed; }, onContainerDrop : function(dd, e, data){ return false; }, notifyEnter : function(dd, e, data){ return this.dropNotAllowed; }, notifyOver : function(dd, e, data){ var n = this.getTargetFromEvent(e); if(!n){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } return this.onContainerOver(dd, e, data); } if(this.lastOverNode != n){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); } this.onNodeEnter(n, dd, e, data); this.lastOverNode = n; } return this.onNodeOver(n, dd, e, data); }, notifyOut : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } }, notifyDrop : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } var n = this.getTargetFromEvent(e); return n ? this.onNodeDrop(n, dd, e, data) : this.onContainerDrop(dd, e, data); }, triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); } }); Ext.data.SortTypes = { none : function(s){ return s; }, stripTagsRE : /<\/?[^>]+>/gi, asText : function(s){ return String(s).replace(this.stripTagsRE, ""); }, asUCText : function(s){ return String(s).toUpperCase().replace(this.stripTagsRE, ""); }, asUCString : function(s) { return String(s).toUpperCase(); }, asDate : function(s) { if(!s){ return 0; } if(Ext.isDate(s)){ return s.getTime(); } return Date.parse(String(s)); }, asFloat : function(s) { var val = parseFloat(String(s).replace(/,/g, "")); if(isNaN(val)) val = 0; return val; }, asInt : function(s) { var val = parseInt(String(s).replace(/,/g, "")); if(isNaN(val)) val = 0; return val; } }; Ext.data.Record = function(data, id){ this.id = (id || id === 0) ? id : ++Ext.data.Record.AUTO_ID; this.data = data; }; Ext.data.Record.create = function(o){ var f = Ext.extend(Ext.data.Record, {}); var p = f.prototype; p.fields = new Ext.util.MixedCollection(false, function(field){ return field.name; }); for(var i = 0, len = o.length; i < len; i++){ p.fields.add(new Ext.data.Field(o[i])); } f.getField = function(name){ return p.fields.get(name); }; return f; }; Ext.data.Record.AUTO_ID = 1000; Ext.data.Record.EDIT = 'edit'; Ext.data.Record.REJECT = 'reject'; Ext.data.Record.COMMIT = 'commit'; Ext.data.Record.prototype = { dirty : false, editing : false, error: null, modified: null, join : function(store){ this.store = store; }, set : function(name, value){ if(String(this.data[name]) == String(value)){ return; } this.dirty = true; if(!this.modified){ this.modified = {}; } if(typeof this.modified[name] == 'undefined'){ this.modified[name] = this.data[name]; } this.data[name] = value; if(!this.editing && this.store){ this.store.afterEdit(this); } }, get : function(name){ return this.data[name]; }, beginEdit : function(){ this.editing = true; this.modified = {}; }, cancelEdit : function(){ this.editing = false; delete this.modified; }, endEdit : function(){ this.editing = false; if(this.dirty && this.store){ this.store.afterEdit(this); } }, reject : function(silent){ var m = this.modified; for(var n in m){ if(typeof m[n] != "function"){ this.data[n] = m[n]; } } this.dirty = false; delete this.modified; this.editing = false; if(this.store && silent !== true){ this.store.afterReject(this); } }, commit : function(silent){ this.dirty = false; delete this.modified; this.editing = false; if(this.store && silent !== true){ this.store.afterCommit(this); } }, getChanges : function(){ var m = this.modified, cs = {}; for(var n in m){ if(m.hasOwnProperty(n)){ cs[n] = this.data[n]; } } return cs; }, hasError : function(){ return this.error != null; }, clearError : function(){ this.error = null; }, copy : function(newId) { return new this.constructor(Ext.apply({}, this.data), newId || this.id); }, isModified : function(fieldName){ return this.modified && this.modified.hasOwnProperty(fieldName); } }; Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), { register : function(){ for(var i = 0, s; s = arguments[i]; i++){ this.add(s); } }, unregister : function(){ for(var i = 0, s; s = arguments[i]; i++){ this.remove(this.lookup(s)); } }, lookup : function(id){ return typeof id == "object" ? id : this.get(id); }, getKey : function(o){ return o.storeId || o.id; } }); Ext.data.Store = function(config){ this.data = new Ext.util.MixedCollection(false); this.data.getKey = function(o){ return o.id; }; this.baseParams = {}; this.paramNames = { "start" : "start", "limit" : "limit", "sort" : "sort", "dir" : "dir" }; if(config && config.data){ this.inlineData = config.data; delete config.data; } Ext.apply(this, config); if(this.url && !this.proxy){ this.proxy = new Ext.data.HttpProxy({url: this.url}); } if(this.reader){ if(!this.recordType){ this.recordType = this.reader.recordType; } if(this.reader.onMetaChange){ this.reader.onMetaChange = this.onMetaChange.createDelegate(this); } } if(this.recordType){ this.fields = this.recordType.prototype.fields; } this.modified = []; this.addEvents( 'datachanged', 'metachange', 'add', 'remove', 'update', 'clear', 'beforeload', 'load', 'loadexception' ); if(this.proxy){ this.relayEvents(this.proxy, ["loadexception"]); } this.sortToggle = {}; if(this.sortInfo){ this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction); } Ext.data.Store.superclass.constructor.call(this); if(this.storeId || this.id){ Ext.StoreMgr.register(this); } if(this.inlineData){ this.loadData(this.inlineData); delete this.inlineData; }else if(this.autoLoad){ this.load.defer(10, this, [ typeof this.autoLoad == 'object' ? this.autoLoad : undefined]); } }; Ext.extend(Ext.data.Store, Ext.util.Observable, { remoteSort : false, pruneModifiedRecords : false, lastOptions : null, destroy : function(){ if(this.id){ Ext.StoreMgr.unregister(this); } this.data = null; this.purgeListeners(); }, add : function(records){ records = [].concat(records); if(records.length < 1){ return; } for(var i = 0, len = records.length; i < len; i++){ records[i].join(this); } var index = this.data.length; this.data.addAll(records); if(this.snapshot){ this.snapshot.addAll(records); } this.fireEvent("add", this, records, index); }, addSorted : function(record){ var index = this.findInsertIndex(record); this.insert(index, record); }, remove : function(record){ var index = this.data.indexOf(record); this.data.removeAt(index); if(this.pruneModifiedRecords){ this.modified.remove(record); } if(this.snapshot){ this.snapshot.remove(record); } this.fireEvent("remove", this, record, index); }, removeAll : function(){ this.data.clear(); if(this.snapshot){ this.snapshot.clear(); } if(this.pruneModifiedRecords){ this.modified = []; } this.fireEvent("clear", this); }, insert : function(index, records){ records = [].concat(records); for(var i = 0, len = records.length; i < len; i++){ this.data.insert(index, records[i]); records[i].join(this); } this.fireEvent("add", this, records, index); }, indexOf : function(record){ return this.data.indexOf(record); }, indexOfId : function(id){ return this.data.indexOfKey(id); }, getById : function(id){ return this.data.key(id); }, getAt : function(index){ return this.data.itemAt(index); }, getRange : function(start, end){ return this.data.getRange(start, end); }, storeOptions : function(o){ o = Ext.apply({}, o); delete o.callback; delete o.scope; this.lastOptions = o; }, load : function(options){ options = options || {}; if(this.fireEvent("beforeload", this, options) !== false){ this.storeOptions(options); var p = Ext.apply(options.params || {}, this.baseParams); if(this.sortInfo && this.remoteSort){ var pn = this.paramNames; p[pn["sort"]] = this.sortInfo.field; p[pn["dir"]] = this.sortInfo.direction; } this.proxy.load(p, this.reader, this.loadRecords, this, options); return true; } else { return false; } }, reload : function(options){ this.load(Ext.applyIf(options||{}, this.lastOptions)); }, loadRecords : function(o, options, success){ if(!o || success === false){ if(success !== false){ this.fireEvent("load", this, [], options); } if(options.callback){ options.callback.call(options.scope || this, [], options, false); } return; } var r = o.records, t = o.totalRecords || r.length; if(!options || options.add !== true){ if(this.pruneModifiedRecords){ this.modified = []; } for(var i = 0, len = r.length; i < len; i++){ r[i].join(this); } if(this.snapshot){ this.data = this.snapshot; delete this.snapshot; } this.data.clear(); this.data.addAll(r); this.totalLength = t; this.applySort(); this.fireEvent("datachanged", this); }else{ this.totalLength = Math.max(t, this.data.length+r.length); this.add(r); } this.fireEvent("load", this, r, options); if(options.callback){ options.callback.call(options.scope || this, r, options, true); } }, loadData : function(o, append){ var r = this.reader.readRecords(o); this.loadRecords(r, {add: append}, true); }, getCount : function(){ return this.data.length || 0; }, getTotalCount : function(){ return this.totalLength || 0; }, getSortState : function(){ return this.sortInfo; }, applySort : function(){ if(this.sortInfo && !this.remoteSort){ var s = this.sortInfo, f = s.field; this.sortData(f, s.direction); } }, sortData : function(f, direction){ direction = direction || 'ASC'; var st = this.fields.get(f).sortType; var fn = function(r1, r2){ var v1 = st(r1.data[f]), v2 = st(r2.data[f]); return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0); }; this.data.sort(direction, fn); if(this.snapshot && this.snapshot != this.data){ this.snapshot.sort(direction, fn); } }, setDefaultSort : function(field, dir){ dir = dir ? dir.toUpperCase() : "ASC"; this.sortInfo = {field: field, direction: dir}; this.sortToggle[field] = dir; }, sort : function(fieldName, dir){ var f = this.fields.get(fieldName); if(!f){ return false; } if(!dir){ if(this.sortInfo && this.sortInfo.field == f.name){ dir = (this.sortToggle[f.name] || "ASC").toggle("ASC", "DESC"); }else{ dir = f.sortDir; } } var st = (this.sortToggle) ? this.sortToggle[f.name] : null; var si = (this.sortInfo) ? this.sortInfo : null; this.sortToggle[f.name] = dir; this.sortInfo = {field: f.name, direction: dir}; if(!this.remoteSort){ this.applySort(); this.fireEvent("datachanged", this); }else{ if (!this.load(this.lastOptions)) { if (st) { this.sortToggle[f.name] = st; } if (si) { this.sortInfo = si; } } } }, each : function(fn, scope){ this.data.each(fn, scope); }, getModifiedRecords : function(){ return this.modified; }, createFilterFn : function(property, value, anyMatch, caseSensitive){ if(Ext.isEmpty(value, false)){ return false; } value = this.data.createValueMatcher(value, anyMatch, caseSensitive); return function(r){ return value.test(r.data[property]); }; }, sum : function(property, start, end){ var rs = this.data.items, v = 0; start = start || 0; end = (end || end === 0) ? end : rs.length-1; for(var i = start; i <= end; i++){ v += (rs[i].data[property] || 0); } return v; }, filter : function(property, value, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.filterBy(fn) : this.clearFilter(); }, filterBy : function(fn, scope){ this.snapshot = this.snapshot || this.data; this.data = this.queryBy(fn, scope||this); this.fireEvent("datachanged", this); }, query : function(property, value, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.queryBy(fn) : this.data.clone(); }, queryBy : function(fn, scope){ var data = this.snapshot || this.data; return data.filterBy(fn, scope||this); }, find : function(property, value, start, anyMatch, caseSensitive){ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive); return fn ? this.data.findIndexBy(fn, null, start) : -1; }, findBy : function(fn, scope, start){ return this.data.findIndexBy(fn, scope, start); }, collect : function(dataIndex, allowNull, bypassFilter){ var d = (bypassFilter === true && this.snapshot) ? this.snapshot.items : this.data.items; var v, sv, r = [], l = {}; for(var i = 0, len = d.length; i < len; i++){ v = d[i].data[dataIndex]; sv = String(v); if((allowNull || !Ext.isEmpty(v)) && !l[sv]){ l[sv] = true; r[r.length] = v; } } return r; }, clearFilter : function(suppressEvent){ if(this.isFiltered()){ this.data = this.snapshot; delete this.snapshot; if(suppressEvent !== true){ this.fireEvent("datachanged", this); } } }, isFiltered : function(){ return this.snapshot && this.snapshot != this.data; }, afterEdit : function(record){ if(this.modified.indexOf(record) == -1){ this.modified.push(record); } this.fireEvent("update", this, record, Ext.data.Record.EDIT); }, afterReject : function(record){ this.modified.remove(record); this.fireEvent("update", this, record, Ext.data.Record.REJECT); }, afterCommit : function(record){ this.modified.remove(record); this.fireEvent("update", this, record, Ext.data.Record.COMMIT); }, commitChanges : function(){ var m = this.modified.slice(0); this.modified = []; for(var i = 0, len = m.length; i < len; i++){ m[i].commit(); } }, rejectChanges : function(){ var m = this.modified.slice(0); this.modified = []; for(var i = 0, len = m.length; i < len; i++){ m[i].reject(); } }, onMetaChange : function(meta, rtype, o){ this.recordType = rtype; this.fields = rtype.prototype.fields; delete this.snapshot; this.sortInfo = meta.sortInfo; this.modified = []; this.fireEvent('metachange', this, this.reader.meta); }, findInsertIndex : function(record){ this.suspendEvents(); var data = this.data.clone(); this.data.add(record); this.applySort(); var index = this.data.indexOf(record); this.data = data; this.resumeEvents(); return index; } }); Ext.data.SimpleStore = function(config){ Ext.data.SimpleStore.superclass.constructor.call(this, Ext.apply(config, { reader: new Ext.data.ArrayReader({ id: config.id }, Ext.data.Record.create(config.fields) ) })); }; Ext.extend(Ext.data.SimpleStore, Ext.data.Store, { loadData : function(data, append){ if(this.expandData === true){ var r = []; for(var i = 0, len = data.length; i < len; i++){ r[r.length] = [data[i]]; } data = r; } Ext.data.SimpleStore.superclass.loadData.call(this, data, append); } }); Ext.data.JsonStore = function(c){ Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(c, { proxy: !c.data ? new Ext.data.HttpProxy({url: c.url}) : undefined, reader: new Ext.data.JsonReader(c, c.fields) })); }; Ext.extend(Ext.data.JsonStore, Ext.data.Store); Ext.data.Field = function(config){ if(typeof config == "string"){ config = {name: config}; } Ext.apply(this, config); if(!this.type){ this.type = "auto"; } var st = Ext.data.SortTypes; if(typeof this.sortType == "string"){ this.sortType = st[this.sortType]; } if(!this.sortType){ switch(this.type){ case "string": this.sortType = st.asUCString; break; case "date": this.sortType = st.asDate; break; default: this.sortType = st.none; } } var stripRe = /[\$,%]/g; if(!this.convert){ var cv, dateFormat = this.dateFormat; switch(this.type){ case "": case "auto": case undefined: cv = function(v){ return v; }; break; case "string": cv = function(v){ return (v === undefined || v === null) ? '' : String(v); }; break; case "int": cv = function(v){ return v !== undefined && v !== null && v !== '' ? parseInt(String(v).replace(stripRe, ""), 10) : ''; }; break; case "float": cv = function(v){ return v !== undefined && v !== null && v !== '' ? parseFloat(String(v).replace(stripRe, ""), 10) : ''; }; break; case "bool": case "boolean": cv = function(v){ return v === true || v === "true" || v == 1; }; break; case "date": cv = function(v){ if(!v){ return ''; } if(Ext.isDate(v)){ return v; } if(dateFormat){ if(dateFormat == "timestamp"){ return new Date(v*1000); } if(dateFormat == "time"){ return new Date(parseInt(v, 10)); } return Date.parseDate(v, dateFormat); } var parsed = Date.parse(v); return parsed ? new Date(parsed) : null; }; break; } this.convert = cv; } }; Ext.data.Field.prototype = { dateFormat: null, defaultValue: "", mapping: null, sortType : null, sortDir : "ASC" }; Ext.data.DataReader = function(meta, recordType){ this.meta = meta; this.recordType = Ext.isArray(recordType) ? Ext.data.Record.create(recordType) : recordType; }; Ext.data.DataReader.prototype = { }; Ext.data.DataProxy = function(){ this.addEvents( 'beforeload', 'load', 'loadexception' ); Ext.data.DataProxy.superclass.constructor.call(this); }; Ext.extend(Ext.data.DataProxy, Ext.util.Observable); Ext.data.MemoryProxy = function(data){ Ext.data.MemoryProxy.superclass.constructor.call(this); this.data = data; }; Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, { load : function(params, reader, callback, scope, arg){ params = params || {}; var result; try { result = reader.readRecords(this.data); }catch(e){ this.fireEvent("loadexception", this, arg, null, e); callback.call(scope, null, arg, false); return; } callback.call(scope, result, arg, true); }, update : function(params, records){ } }); Ext.data.HttpProxy = function(conn){ Ext.data.HttpProxy.superclass.constructor.call(this); this.conn = conn; this.useAjax = !conn || !conn.events; }; Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, { getConnection : function(){ return this.useAjax ? Ext.Ajax : this.conn; }, load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var o = { params : params || {}, request: { callback : callback, scope : scope, arg : arg }, reader: reader, callback : this.loadResponse, scope: this }; if(this.useAjax){ Ext.applyIf(o, this.conn); if(this.activeRequest){ Ext.Ajax.abort(this.activeRequest); } this.activeRequest = Ext.Ajax.request(o); }else{ this.conn.request(o); } }else{ callback.call(scope||this, null, arg, false); } }, loadResponse : function(o, success, response){ delete this.activeRequest; if(!success){ this.fireEvent("loadexception", this, o, response); o.request.callback.call(o.request.scope, null, o.request.arg, false); return; } var result; try { result = o.reader.read(response); }catch(e){ this.fireEvent("loadexception", this, o, response, e); o.request.callback.call(o.request.scope, null, o.request.arg, false); return; } this.fireEvent("load", this, o, o.request.arg); o.request.callback.call(o.request.scope, result, o.request.arg, true); }, update : function(dataSet){ }, updateResponse : function(dataSet){ } }); Ext.data.ScriptTagProxy = function(config){ Ext.data.ScriptTagProxy.superclass.constructor.call(this); Ext.apply(this, config); this.head = document.getElementsByTagName("head")[0]; }; Ext.data.ScriptTagProxy.TRANS_ID = 1000; Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, { timeout : 30000, callbackParam : "callback", nocache : true, load : function(params, reader, callback, scope, arg){ if(this.fireEvent("beforeload", this, params) !== false){ var p = Ext.urlEncode(Ext.apply(params, this.extraParams)); var url = this.url; url += (url.indexOf("?") != -1 ? "&" : "?") + p; if(this.nocache){ url += "&_dc=" + (new Date().getTime()); } var transId = ++Ext.data.ScriptTagProxy.TRANS_ID; var trans = { id : transId, cb : "stcCallback"+transId, scriptId : "stcScript"+transId, params : params, arg : arg, url : url, callback : callback, scope : scope, reader : reader }; var conn = this; window[trans.cb] = function(o){ conn.handleResponse(o, trans); }; url += String.format("&{0}={1}", this.callbackParam, trans.cb); if(this.autoAbort !== false){ this.abort(); } trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]); var script = document.createElement("script"); script.setAttribute("src", url); script.setAttribute("type", "text/javascript"); script.setAttribute("id", trans.scriptId); this.head.appendChild(script); this.trans = trans; }else{ callback.call(scope||this, null, arg, false); } }, isLoading : function(){ return this.trans ? true : false; }, abort : function(){ if(this.isLoading()){ this.destroyTrans(this.trans); } }, destroyTrans : function(trans, isLoaded){ this.head.removeChild(document.getElementById(trans.scriptId)); clearTimeout(trans.timeoutId); if(isLoaded){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }else{ window[trans.cb] = function(){ window[trans.cb] = undefined; try{ delete window[trans.cb]; }catch(e){} }; } }, handleResponse : function(o, trans){ this.trans = false; this.destroyTrans(trans, true); var result; try { result = trans.reader.readRecords(o); }catch(e){ this.fireEvent("loadexception", this, o, trans.arg, e); trans.callback.call(trans.scope||window, null, trans.arg, false); return; } this.fireEvent("load", this, o, trans.arg); trans.callback.call(trans.scope||window, result, trans.arg, true); }, handleFailure : function(trans){ this.trans = false; this.destroyTrans(trans, false); this.fireEvent("loadexception", this, null, trans.arg); trans.callback.call(trans.scope||window, null, trans.arg, false); } }); Ext.data.JsonReader = function(meta, recordType){ meta = meta || {}; Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, { read : function(response){ var json = response.responseText; var o = eval("("+json+")"); if(!o) { throw {message: "JsonReader.read: Json object not found"}; } if(o.metaData){ delete this.ef; this.meta = o.metaData; this.recordType = Ext.data.Record.create(o.metaData.fields); this.onMetaChange(this.meta, this.recordType, o); } return this.readRecords(o); }, onMetaChange : function(meta, recordType, o){ }, simpleAccess: function(obj, subsc) { return obj[subsc]; }, getJsonAccessor: function(){ var re = /[\[\.]/; return function(expr) { try { return(re.test(expr)) ? new Function("obj", "return obj." + expr) : function(obj){ return obj[expr]; }; } catch(e){} return Ext.emptyFn; }; }(), readRecords : function(o){ this.jsonData = o; var s = this.meta, Record = this.recordType, f = Record.prototype.fields, fi = f.items, fl = f.length; if (!this.ef) { if(s.totalProperty) { this.getTotal = this.getJsonAccessor(s.totalProperty); } if(s.successProperty) { this.getSuccess = this.getJsonAccessor(s.successProperty); } this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;}; if (s.id) { var g = this.getJsonAccessor(s.id); this.getId = function(rec) { var r = g(rec); return (r === undefined || r === "") ? null : r; }; } else { this.getId = function(){return null;}; } this.ef = []; for(var i = 0; i < fl; i++){ f = fi[i]; var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name; this.ef[i] = this.getJsonAccessor(map); } } var root = this.getRoot(o), c = root.length, totalRecords = c, success = true; if(s.totalProperty){ var v = parseInt(this.getTotal(o), 10); if(!isNaN(v)){ totalRecords = v; } } if(s.successProperty){ var v = this.getSuccess(o); if(v === false || v === 'false'){ success = false; } } var records = []; for(var i = 0; i < c; i++){ var n = root[i]; var values = {}; var id = this.getId(n); for(var j = 0; j < fl; j++){ f = fi[j]; var v = this.ef[j](n); values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, n); } var record = new Record(values, id); record.json = n; records[i] = record; } return { success : success, records : records, totalRecords : totalRecords }; } }); Ext.data.XmlReader = function(meta, recordType){ meta = meta || {}; Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields); }; Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, { read : function(response){ var doc = response.responseXML; if(!doc) { throw {message: "XmlReader.read: XML Document not available"}; } return this.readRecords(doc); }, readRecords : function(doc){ this.xmlData = doc; var root = doc.documentElement || doc; var q = Ext.DomQuery; var recordType = this.recordType, fields = recordType.prototype.fields; var sid = this.meta.id; var totalRecords = 0, success = true; if(this.meta.totalRecords){ totalRecords = q.selectNumber(this.meta.totalRecords, root, 0); } if(this.meta.success){ var sv = q.selectValue(this.meta.success, root, true); success = sv !== false && sv !== 'false'; } var records = []; var ns = q.select(this.meta.record, root); for(var i = 0, len = ns.length; i < len; i++) { var n = ns[i]; var values = {}; var id = sid ? q.selectValue(sid, n) : undefined; for(var j = 0, jlen = fields.length; j < jlen; j++){ var f = fields.items[j]; var v = q.selectValue(f.mapping || f.name, n, f.defaultValue); v = f.convert(v, n); values[f.name] = v; } var record = new recordType(values, id); record.node = n; records[records.length] = record; } return { success : success, records : records, totalRecords : totalRecords || records.length }; } }); Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, { readRecords : function(o){ var sid = this.meta ? this.meta.id : null; var recordType = this.recordType, fields = recordType.prototype.fields; var records = []; var root = o; for(var i = 0; i < root.length; i++){ var n = root[i]; var values = {}; var id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null); for(var j = 0, jlen = fields.length; j < jlen; j++){ var f = fields.items[j]; var k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j; var v = n[k] !== undefined ? n[k] : f.defaultValue; v = f.convert(v, n); values[f.name] = v; } var record = new recordType(values, id); record.json = n; records[records.length] = record; } return { records : records, totalRecords : records.length }; } }); Ext.data.Tree = function(root){ this.nodeHash = {}; this.root = null; if(root){ this.setRootNode(root); } this.addEvents( "append", "remove", "move", "insert", "beforeappend", "beforeremove", "beforemove", "beforeinsert" ); Ext.data.Tree.superclass.constructor.call(this); }; Ext.extend(Ext.data.Tree, Ext.util.Observable, { pathSeparator: "/", proxyNodeEvent : function(){ return this.fireEvent.apply(this, arguments); }, getRootNode : function(){ return this.root; }, setRootNode : function(node){ this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); return node; }, getNodeById : function(id){ return this.nodeHash[id]; }, registerNode : function(node){ this.nodeHash[node.id] = node; }, unregisterNode : function(node){ delete this.nodeHash[node.id]; }, toString : function(){ return "[Tree"+(this.id?" "+this.id:"")+"]"; } }); Ext.data.Node = function(attributes){ this.attributes = attributes || {}; this.leaf = this.attributes.leaf; this.id = this.attributes.id; if(!this.id){ this.id = Ext.id(null, "ynode-"); this.attributes.id = this.id; } this.childNodes = []; if(!this.childNodes.indexOf){ this.childNodes.indexOf = function(o){ for(var i = 0, len = this.length; i < len; i++){ if(this[i] == o) return i; } return -1; }; } this.parentNode = null; this.firstChild = null; this.lastChild = null; this.previousSibling = null; this.nextSibling = null; this.addEvents({ "append" : true, "remove" : true, "move" : true, "insert" : true, "beforeappend" : true, "beforeremove" : true, "beforemove" : true, "beforeinsert" : true }); this.listeners = this.attributes.listeners; Ext.data.Node.superclass.constructor.call(this); }; Ext.extend(Ext.data.Node, Ext.util.Observable, { fireEvent : function(evtName){ if(Ext.data.Node.superclass.fireEvent.apply(this, arguments) === false){ return false; } var ot = this.getOwnerTree(); if(ot){ if(ot.proxyNodeEvent.apply(ot, arguments) === false){ return false; } } return true; }, isLeaf : function(){ return this.leaf === true; }, setFirstChild : function(node){ this.firstChild = node; }, setLastChild : function(node){ this.lastChild = node; }, isLast : function(){ return (!this.parentNode ? true : this.parentNode.lastChild == this); }, isFirst : function(){ return (!this.parentNode ? true : this.parentNode.firstChild == this); }, hasChildNodes : function(){ return !this.isLeaf() && this.childNodes.length > 0; }, appendChild : function(node){ var multi = false; if(Ext.isArray(node)){ multi = node; }else if(arguments.length > 1){ multi = arguments; } if(multi){ for(var i = 0, len = multi.length; i < len; i++) { this.appendChild(multi[i]); } }else{ if(this.fireEvent("beforeappend", this.ownerTree, this, node) === false){ return false; } var index = this.childNodes.length; var oldParent = node.parentNode; if(oldParent){ if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index) === false){ return false; } oldParent.removeChild(node); } index = this.childNodes.length; if(index == 0){ this.setFirstChild(node); } this.childNodes.push(node); node.parentNode = this; var ps = this.childNodes[index-1]; if(ps){ node.previousSibling = ps; ps.nextSibling = node; }else{ node.previousSibling = null; } node.nextSibling = null; this.setLastChild(node); node.setOwnerTree(this.getOwnerTree()); this.fireEvent("append", this.ownerTree, this, node, index); if(oldParent){ node.fireEvent("move", this.ownerTree, node, oldParent, this, index); } return node; } }, removeChild : function(node){ var index = this.childNodes.indexOf(node); if(index == -1){ return false; } if(this.fireEvent("beforeremove", this.ownerTree, this, node) === false){ return false; } this.childNodes.splice(index, 1); if(node.previousSibling){ node.previousSibling.nextSibling = node.nextSibling; } if(node.nextSibling){ node.nextSibling.previousSibling = node.previousSibling; } if(this.firstChild == node){ this.setFirstChild(node.nextSibling); } if(this.lastChild == node){ this.setLastChild(node.previousSibling); } node.setOwnerTree(null); node.parentNode = null; node.previousSibling = null; node.nextSibling = null; this.fireEvent("remove", this.ownerTree, this, node); return node; }, insertBefore : function(node, refNode){ if(!refNode){ return this.appendChild(node); } if(node == refNode){ return false; } if(this.fireEvent("beforeinsert", this.ownerTree, this, node, refNode) === false){ return false; } var index = this.childNodes.indexOf(refNode); var oldParent = node.parentNode; var refIndex = index; if(oldParent == this && this.childNodes.indexOf(node) < index){ refIndex--; } if(oldParent){ if(node.fireEvent("beforemove", node.getOwnerTree(), node, oldParent, this, index, refNode) === false){ return false; } oldParent.removeChild(node); } if(refIndex == 0){ this.setFirstChild(node); } this.childNodes.splice(refIndex, 0, node); node.parentNode = this; var ps = this.childNodes[refIndex-1]; if(ps){ node.previousSibling = ps; ps.nextSibling = node; }else{ node.previousSibling = null; } node.nextSibling = refNode; refNode.previousSibling = node; node.setOwnerTree(this.getOwnerTree()); this.fireEvent("insert", this.ownerTree, this, node, refNode); if(oldParent){ node.fireEvent("move", this.ownerTree, node, oldParent, this, refIndex, refNode); } return node; }, remove : function(){ this.parentNode.removeChild(this); return this; }, item : function(index){ return this.childNodes[index]; }, replaceChild : function(newChild, oldChild){ this.insertBefore(newChild, oldChild); this.removeChild(oldChild); return oldChild; }, indexOf : function(child){ return this.childNodes.indexOf(child); }, getOwnerTree : function(){ if(!this.ownerTree){ var p = this; while(p){ if(p.ownerTree){ this.ownerTree = p.ownerTree; break; } p = p.parentNode; } } return this.ownerTree; }, getDepth : function(){ var depth = 0; var p = this; while(p.parentNode){ ++depth; p = p.parentNode; } return depth; }, setOwnerTree : function(tree){ if(tree != this.ownerTree){ if(this.ownerTree){ this.ownerTree.unregisterNode(this); } this.ownerTree = tree; var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].setOwnerTree(tree); } if(tree){ tree.registerNode(this); } } }, getPath : function(attr){ attr = attr || "id"; var p = this.parentNode; var b = [this.attributes[attr]]; while(p){ b.unshift(p.attributes[attr]); p = p.parentNode; } var sep = this.getOwnerTree().pathSeparator; return sep + b.join(sep); }, bubble : function(fn, scope, args){ var p = this; while(p){ if(fn.apply(scope || p, args || [p]) === false){ break; } p = p.parentNode; } }, cascade : function(fn, scope, args){ if(fn.apply(scope || this, args || [this]) !== false){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].cascade(fn, scope, args); } } }, eachChild : function(fn, scope, args){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(fn.apply(scope || this, args || [cs[i]]) === false){ break; } } }, findChild : function(attribute, value){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(cs[i].attributes[attribute] == value){ return cs[i]; } } return null; }, findChildBy : function(fn, scope){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { if(fn.call(scope||cs[i], cs[i]) === true){ return cs[i]; } } return null; }, sort : function(fn, scope){ var cs = this.childNodes; var len = cs.length; if(len > 0){ var sortFn = scope ? function(){fn.apply(scope, arguments);} : fn; cs.sort(sortFn); for(var i = 0; i < len; i++){ var n = cs[i]; n.previousSibling = cs[i-1]; n.nextSibling = cs[i+1]; if(i == 0){ this.setFirstChild(n); } if(i == len-1){ this.setLastChild(n); } } } }, contains : function(node){ return node.isAncestor(this); }, isAncestor : function(node){ var p = this.parentNode; while(p){ if(p == node){ return true; } p = p.parentNode; } return false; }, toString : function(){ return "[Node"+(this.id?" "+this.id:"")+"]"; } }); Ext.data.GroupingStore = Ext.extend(Ext.data.Store, { remoteGroup : false, groupOnSort:false, clearGrouping : function(){ this.groupField = false; if(this.remoteGroup){ if(this.baseParams){ delete this.baseParams.groupBy; } this.reload(); }else{ this.applySort(); this.fireEvent('datachanged', this); } }, groupBy : function(field, forceRegroup){ if(this.groupField == field && !forceRegroup){ return; } this.groupField = field; if(this.remoteGroup){ if(!this.baseParams){ this.baseParams = {}; } this.baseParams['groupBy'] = field; } if(this.groupOnSort){ this.sort(field); return; } if(this.remoteGroup){ this.reload(); }else{ var si = this.sortInfo || {}; if(si.field != field){ this.applySort(); }else{ this.sortData(field); } this.fireEvent('datachanged', this); } }, applySort : function(){ Ext.data.GroupingStore.superclass.applySort.call(this); if(!this.groupOnSort && !this.remoteGroup){ var gs = this.getGroupState(); if(gs && gs != this.sortInfo.field){ this.sortData(this.groupField); } } }, applyGrouping : function(alwaysFireChange){ if(this.groupField !== false){ this.groupBy(this.groupField, true); return true; }else{ if(alwaysFireChange === true){ this.fireEvent('datachanged', this); } return false; } }, getGroupState : function(){ return this.groupOnSort && this.groupField !== false ? (this.sortInfo ? this.sortInfo.field : undefined) : this.groupField; } }); Ext.ComponentMgr = function(){ var all = new Ext.util.MixedCollection(); var types = {}; return { register : function(c){ all.add(c); }, unregister : function(c){ all.remove(c); }, get : function(id){ return all.get(id); }, onAvailable : function(id, fn, scope){ all.on("add", function(index, o){ if(o.id == id){ fn.call(scope || o, o); all.un("add", fn, scope); } }); }, all : all, registerType : function(xtype, cls){ types[xtype] = cls; cls.xtype = xtype; }, create : function(config, defaultType){ return new types[config.xtype || defaultType](config); } }; }(); Ext.reg = Ext.ComponentMgr.registerType; Ext.Component = function(config){ config = config || {}; if(config.initialConfig){ if(config.isAction){ this.baseAction = config; } config = config.initialConfig; }else if(config.tagName || config.dom || typeof config == "string"){ config = {applyTo: config, id: config.id || config}; } this.initialConfig = config; Ext.apply(this, config); this.addEvents( 'disable', 'enable', 'beforeshow', 'show', 'beforehide', 'hide', 'beforerender', 'render', 'beforedestroy', 'destroy', 'beforestaterestore', 'staterestore', 'beforestatesave', 'statesave' ); this.getId(); Ext.ComponentMgr.register(this); Ext.Component.superclass.constructor.call(this); if(this.baseAction){ this.baseAction.addComponent(this); } this.initComponent(); if(this.plugins){ if(Ext.isArray(this.plugins)){ for(var i = 0, len = this.plugins.length; i < len; i++){ this.plugins[i].init(this); } }else{ this.plugins.init(this); } } if(this.stateful !== false){ this.initState(config); } if(this.applyTo){ this.applyToMarkup(this.applyTo); delete this.applyTo; }else if(this.renderTo){ this.render(this.renderTo); delete this.renderTo; } }; Ext.Component.AUTO_ID = 1000; Ext.extend(Ext.Component, Ext.util.Observable, { disabledClass : "x-item-disabled", allowDomMove : true, autoShow : false, hideMode: 'display', hideParent: false, hidden : false, disabled : false, rendered : false, ctype : "Ext.Component", actionMode : "el", getActionEl : function(){ return this[this.actionMode]; }, initComponent : Ext.emptyFn, render : function(container, position){ if(!this.rendered && this.fireEvent("beforerender", this) !== false){ if(!container && this.el){ this.el = Ext.get(this.el); container = this.el.dom.parentNode; this.allowDomMove = false; } this.container = Ext.get(container); if(this.ctCls){ this.container.addClass(this.ctCls); } this.rendered = true; if(position !== undefined){ if(typeof position == 'number'){ position = this.container.dom.childNodes[position]; }else{ position = Ext.getDom(position); } } this.onRender(this.container, position || null); if(this.autoShow){ this.el.removeClass(['x-hidden','x-hide-' + this.hideMode]); } if(this.cls){ this.el.addClass(this.cls); delete this.cls; } if(this.style){ this.el.applyStyles(this.style); delete this.style; } this.fireEvent("render", this); this.afterRender(this.container); if(this.hidden){ this.hide(); } if(this.disabled){ this.disable(); } this.initStateEvents(); } return this; }, initState : function(config){ if(Ext.state.Manager){ var state = Ext.state.Manager.get(this.stateId || this.id); if(state){ if(this.fireEvent('beforestaterestore', this, state) !== false){ this.applyState(state); this.fireEvent('staterestore', this, state); } } } }, initStateEvents : function(){ if(this.stateEvents){ for(var i = 0, e; e = this.stateEvents[i]; i++){ this.on(e, this.saveState, this, {delay:100}); } } }, applyState : function(state, config){ if(state){ Ext.apply(this, state); } }, getState : function(){ return null; }, saveState : function(){ if(Ext.state.Manager){ var state = this.getState(); if(this.fireEvent('beforestatesave', this, state) !== false){ Ext.state.Manager.set(this.stateId || this.id, state); this.fireEvent('statesave', this, state); } } }, applyToMarkup : function(el){ this.allowDomMove = false; this.el = Ext.get(el); this.render(this.el.dom.parentNode); }, addClass : function(cls){ if(this.el){ this.el.addClass(cls); }else{ this.cls = this.cls ? this.cls + ' ' + cls : cls; } }, removeClass : function(cls){ if(this.el){ this.el.removeClass(cls); }else if(this.cls){ this.cls = this.cls.split(' ').remove(cls).join(' '); } }, onRender : function(ct, position){ if(this.autoEl){ if(typeof this.autoEl == 'string'){ this.el = document.createElement(this.autoEl); }else{ var div = document.createElement('div'); Ext.DomHelper.overwrite(div, this.autoEl); this.el = div.firstChild; } if (!this.el.id) { this.el.id = this.getId(); } } if(this.el){ this.el = Ext.get(this.el); if(this.allowDomMove !== false){ ct.dom.insertBefore(this.el.dom, position); } } }, getAutoCreate : function(){ var cfg = typeof this.autoCreate == "object" ? this.autoCreate : Ext.apply({}, this.defaultAutoCreate); if(this.id && !cfg.id){ cfg.id = this.id; } return cfg; }, afterRender : Ext.emptyFn, destroy : function(){ if(this.fireEvent("beforedestroy", this) !== false){ this.beforeDestroy(); if(this.rendered){ this.el.removeAllListeners(); this.el.remove(); if(this.actionMode == "container"){ this.container.remove(); } } this.onDestroy(); Ext.ComponentMgr.unregister(this); this.fireEvent("destroy", this); this.purgeListeners(); } }, beforeDestroy : Ext.emptyFn, onDestroy : Ext.emptyFn, getEl : function(){ return this.el; }, getId : function(){ return this.id || (this.id = "ext-comp-" + (++Ext.Component.AUTO_ID)); }, getItemId : function(){ return this.itemId || this.getId(); }, focus : function(selectText, delay){ if(delay){ this.focus.defer(typeof delay == 'number' ? delay : 10, this, [selectText, false]); return; } if(this.rendered){ this.el.focus(); if(selectText === true){ this.el.dom.select(); } } return this; }, blur : function(){ if(this.rendered){ this.el.blur(); } return this; }, disable : function(){ if(this.rendered){ this.onDisable(); } this.disabled = true; this.fireEvent("disable", this); return this; }, onDisable : function(){ this.getActionEl().addClass(this.disabledClass); this.el.dom.disabled = true; }, enable : function(){ if(this.rendered){ this.onEnable(); } this.disabled = false; this.fireEvent("enable", this); return this; }, onEnable : function(){ this.getActionEl().removeClass(this.disabledClass); this.el.dom.disabled = false; }, setDisabled : function(disabled){ this[disabled ? "disable" : "enable"](); }, show: function(){ if(this.fireEvent("beforeshow", this) !== false){ this.hidden = false; if(this.autoRender){ this.render(typeof this.autoRender == 'boolean' ? Ext.getBody() : this.autoRender); } if(this.rendered){ this.onShow(); } this.fireEvent("show", this); } return this; }, onShow : function(){ if(this.hideParent){ this.container.removeClass('x-hide-' + this.hideMode); }else{ this.getActionEl().removeClass('x-hide-' + this.hideMode); } }, hide: function(){ if(this.fireEvent("beforehide", this) !== false){ this.hidden = true; if(this.rendered){ this.onHide(); } this.fireEvent("hide", this); } return this; }, onHide : function(){ if(this.hideParent){ this.container.addClass('x-hide-' + this.hideMode); }else{ this.getActionEl().addClass('x-hide-' + this.hideMode); } }, setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } return this; }, isVisible : function(){ return this.rendered && this.getActionEl().isVisible(); }, cloneConfig : function(overrides){ overrides = overrides || {}; var id = overrides.id || Ext.id(); var cfg = Ext.applyIf(overrides, this.initialConfig); cfg.id = id; return new this.constructor(cfg); }, getXType : function(){ return this.constructor.xtype; }, isXType : function(xtype, shallow){ return !shallow ? ('/' + this.getXTypes() + '/').indexOf('/' + xtype + '/') != -1 : this.constructor.xtype == xtype; }, getXTypes : function(){ var tc = this.constructor; if(!tc.xtypes){ var c = [], sc = this; while(sc && sc.constructor.xtype){ c.unshift(sc.constructor.xtype); sc = sc.constructor.superclass; } tc.xtypeChain = c; tc.xtypes = c.join('/'); } return tc.xtypes; }, findParentBy: function(fn) { for (var p = this.ownerCt; (p != null) && !fn(p, this); p = p.ownerCt); return p || null; }, findParentByType: function(xtype) { return typeof xtype == 'function' ? this.findParentBy(function(p){ return p.constructor === xtype; }) : this.findParentBy(function(p){ return p.constructor.xtype === xtype; }); } }); Ext.reg('component', Ext.Component); Ext.Action = function(config){ this.initialConfig = config; this.items = []; } Ext.Action.prototype = { isAction : true, setText : function(text){ this.initialConfig.text = text; this.callEach('setText', [text]); }, getText : function(){ return this.initialConfig.text; }, setIconClass : function(cls){ this.initialConfig.iconCls = cls; this.callEach('setIconClass', [cls]); }, getIconClass : function(){ return this.initialConfig.iconCls; }, setDisabled : function(v){ this.initialConfig.disabled = v; this.callEach('setDisabled', [v]); }, enable : function(){ this.setDisabled(false); }, disable : function(){ this.setDisabled(true); }, isDisabled : function(){ return this.initialConfig.disabled; }, setHidden : function(v){ this.initialConfig.hidden = v; this.callEach('setVisible', [!v]); }, show : function(){ this.setHidden(false); }, hide : function(){ this.setHidden(true); }, isHidden : function(){ return this.initialConfig.hidden; }, setHandler : function(fn, scope){ this.initialConfig.handler = fn; this.initialConfig.scope = scope; this.callEach('setHandler', [fn, scope]); }, each : function(fn, scope){ Ext.each(this.items, fn, scope); }, callEach : function(fnName, args){ var cs = this.items; for(var i = 0, len = cs.length; i < len; i++){ cs[i][fnName].apply(cs[i], args); } }, addComponent : function(comp){ this.items.push(comp); comp.on('destroy', this.removeComponent, this); }, removeComponent : function(comp){ this.items.remove(comp); }, execute : function(){ this.initialConfig.handler.apply(this.initialConfig.scope || window, arguments); } }; (function(){ Ext.Layer = function(config, existingEl){ config = config || {}; var dh = Ext.DomHelper; var cp = config.parentEl, pel = cp ? Ext.getDom(cp) : document.body; if(existingEl){ this.dom = Ext.getDom(existingEl); } if(!this.dom){ var o = config.dh || {tag: "div", cls: "x-layer"}; this.dom = dh.append(pel, o); } if(config.cls){ this.addClass(config.cls); } this.constrain = config.constrain !== false; this.visibilityMode = Ext.Element.VISIBILITY; if(config.id){ this.id = this.dom.id = config.id; }else{ this.id = Ext.id(this.dom); } this.zindex = config.zindex || this.getZIndex(); this.position("absolute", this.zindex); if(config.shadow){ this.shadowOffset = config.shadowOffset || 4; this.shadow = new Ext.Shadow({ offset : this.shadowOffset, mode : config.shadow }); }else{ this.shadowOffset = 0; } this.useShim = config.shim !== false && Ext.useShims; this.useDisplay = config.useDisplay; this.hide(); }; var supr = Ext.Element.prototype; var shims = []; Ext.extend(Ext.Layer, Ext.Element, { getZIndex : function(){ return this.zindex || parseInt(this.getStyle("z-index"), 10) || 11000; }, getShim : function(){ if(!this.useShim){ return null; } if(this.shim){ return this.shim; } var shim = shims.shift(); if(!shim){ shim = this.createShim(); shim.enableDisplayMode('block'); shim.dom.style.display = 'none'; shim.dom.style.visibility = 'visible'; } var pn = this.dom.parentNode; if(shim.dom.parentNode != pn){ pn.insertBefore(shim.dom, this.dom); } shim.setStyle('z-index', this.getZIndex()-2); this.shim = shim; return shim; }, hideShim : function(){ if(this.shim){ this.shim.setDisplayed(false); shims.push(this.shim); delete this.shim; } }, disableShadow : function(){ if(this.shadow){ this.shadowDisabled = true; this.shadow.hide(); this.lastShadowOffset = this.shadowOffset; this.shadowOffset = 0; } }, enableShadow : function(show){ if(this.shadow){ this.shadowDisabled = false; this.shadowOffset = this.lastShadowOffset; delete this.lastShadowOffset; if(show){ this.sync(true); } } }, sync : function(doShow){ var sw = this.shadow; if(!this.updating && this.isVisible() && (sw || this.useShim)){ var sh = this.getShim(); var w = this.getWidth(), h = this.getHeight(); var l = this.getLeft(true), t = this.getTop(true); if(sw && !this.shadowDisabled){ if(doShow && !sw.isVisible()){ sw.show(this); }else{ sw.realign(l, t, w, h); } if(sh){ if(doShow){ sh.show(); } var a = sw.adjusts, s = sh.dom.style; s.left = (Math.min(l, l+a.l))+"px"; s.top = (Math.min(t, t+a.t))+"px"; s.width = (w+a.w)+"px"; s.height = (h+a.h)+"px"; } }else if(sh){ if(doShow){ sh.show(); } sh.setSize(w, h); sh.setLeftTop(l, t); } } }, destroy : function(){ this.hideShim(); if(this.shadow){ this.shadow.hide(); } this.removeAllListeners(); Ext.removeNode(this.dom); Ext.Element.uncache(this.id); }, remove : function(){ this.destroy(); }, beginUpdate : function(){ this.updating = true; }, endUpdate : function(){ this.updating = false; this.sync(true); }, hideUnders : function(negOffset){ if(this.shadow){ this.shadow.hide(); } this.hideShim(); }, constrainXY : function(){ if(this.constrain){ var vw = Ext.lib.Dom.getViewWidth(), vh = Ext.lib.Dom.getViewHeight(); var s = Ext.getDoc().getScroll(); var xy = this.getXY(); var x = xy[0], y = xy[1]; var w = this.dom.offsetWidth+this.shadowOffset, h = this.dom.offsetHeight+this.shadowOffset; var moved = false; if((x + w) > vw+s.left){ x = vw - w - this.shadowOffset; moved = true; } if((y + h) > vh+s.top){ y = vh - h - this.shadowOffset; moved = true; } if(x < s.left){ x = s.left; moved = true; } if(y < s.top){ y = s.top; moved = true; } if(moved){ if(this.avoidY){ var ay = this.avoidY; if(y <= ay && (y+h) >= ay){ y = ay-h-5; } } xy = [x, y]; this.storeXY(xy); supr.setXY.call(this, xy); this.sync(); } } }, isVisible : function(){ return this.visible; }, showAction : function(){ this.visible = true; if(this.useDisplay === true){ this.setDisplayed(""); }else if(this.lastXY){ supr.setXY.call(this, this.lastXY); }else if(this.lastLT){ supr.setLeftTop.call(this, this.lastLT[0], this.lastLT[1]); } }, hideAction : function(){ this.visible = false; if(this.useDisplay === true){ this.setDisplayed(false); }else{ this.setLeftTop(-10000,-10000); } }, setVisible : function(v, a, d, c, e){ if(v){ this.showAction(); } if(a && v){ var cb = function(){ this.sync(true); if(c){ c(); } }.createDelegate(this); supr.setVisible.call(this, true, true, d, cb, e); }else{ if(!v){ this.hideUnders(true); } var cb = c; if(a){ cb = function(){ this.hideAction(); if(c){ c(); } }.createDelegate(this); } supr.setVisible.call(this, v, a, d, cb, e); if(v){ this.sync(true); }else if(!a){ this.hideAction(); } } }, storeXY : function(xy){ delete this.lastLT; this.lastXY = xy; }, storeLeftTop : function(left, top){ delete this.lastXY; this.lastLT = [left, top]; }, beforeFx : function(){ this.beforeAction(); return Ext.Layer.superclass.beforeFx.apply(this, arguments); }, afterFx : function(){ Ext.Layer.superclass.afterFx.apply(this, arguments); this.sync(this.isVisible()); }, beforeAction : function(){ if(!this.updating && this.shadow){ this.shadow.hide(); } }, setLeft : function(left){ this.storeLeftTop(left, this.getTop(true)); supr.setLeft.apply(this, arguments); this.sync(); }, setTop : function(top){ this.storeLeftTop(this.getLeft(true), top); supr.setTop.apply(this, arguments); this.sync(); }, setLeftTop : function(left, top){ this.storeLeftTop(left, top); supr.setLeftTop.apply(this, arguments); this.sync(); }, setXY : function(xy, a, d, c, e){ this.fixDisplay(); this.beforeAction(); this.storeXY(xy); var cb = this.createCB(c); supr.setXY.call(this, xy, a, d, cb, e); if(!a){ cb(); } }, createCB : function(c){ var el = this; return function(){ el.constrainXY(); el.sync(true); if(c){ c(); } }; }, setX : function(x, a, d, c, e){ this.setXY([x, this.getY()], a, d, c, e); }, setY : function(y, a, d, c, e){ this.setXY([this.getX(), y], a, d, c, e); }, setSize : function(w, h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setSize.call(this, w, h, a, d, cb, e); if(!a){ cb(); } }, setWidth : function(w, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setWidth.call(this, w, a, d, cb, e); if(!a){ cb(); } }, setHeight : function(h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); supr.setHeight.call(this, h, a, d, cb, e); if(!a){ cb(); } }, setBounds : function(x, y, w, h, a, d, c, e){ this.beforeAction(); var cb = this.createCB(c); if(!a){ this.storeXY([x, y]); supr.setXY.call(this, [x, y]); supr.setSize.call(this, w, h, a, d, cb, e); cb(); }else{ supr.setBounds.call(this, x, y, w, h, a, d, cb, e); } return this; }, setZIndex : function(zindex){ this.zindex = zindex; this.setStyle("z-index", zindex + 2); if(this.shadow){ this.shadow.setZIndex(zindex + 1); } if(this.shim){ this.shim.setStyle("z-index", zindex); } } }); })(); Ext.Shadow = function(config){ Ext.apply(this, config); if(typeof this.mode != "string"){ this.mode = this.defaultMode; } var o = this.offset, a = {h: 0}; var rad = Math.floor(this.offset/2); switch(this.mode.toLowerCase()){ case "drop": a.w = 0; a.l = a.t = o; a.t -= 1; if(Ext.isIE){ a.l -= this.offset + rad; a.t -= this.offset + rad; a.w -= rad; a.h -= rad; a.t += 1; } break; case "sides": a.w = (o*2); a.l = -o; a.t = o-1; if(Ext.isIE){ a.l -= (this.offset - rad); a.t -= this.offset + rad; a.l += 1; a.w -= (this.offset - rad)*2; a.w -= rad + 1; a.h -= 1; } break; case "frame": a.w = a.h = (o*2); a.l = a.t = -o; a.t += 1; a.h -= 2; if(Ext.isIE){ a.l -= (this.offset - rad); a.t -= (this.offset - rad); a.l += 1; a.w -= (this.offset + rad + 1); a.h -= (this.offset + rad); a.h += 1; } break; }; this.adjusts = a; }; Ext.Shadow.prototype = { offset: 4, defaultMode: "drop", show : function(target){ target = Ext.get(target); if(!this.el){ this.el = Ext.Shadow.Pool.pull(); if(this.el.dom.nextSibling != target.dom){ this.el.insertBefore(target); } } this.el.setStyle("z-index", this.zIndex || parseInt(target.getStyle("z-index"), 10)-1); if(Ext.isIE){ this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")"; } this.realign( target.getLeft(true), target.getTop(true), target.getWidth(), target.getHeight() ); this.el.dom.style.display = "block"; }, isVisible : function(){ return this.el ? true : false; }, realign : function(l, t, w, h){ if(!this.el){ return; } var a = this.adjusts, d = this.el.dom, s = d.style; var iea = 0; s.left = (l+a.l)+"px"; s.top = (t+a.t)+"px"; var sw = (w+a.w), sh = (h+a.h), sws = sw +"px", shs = sh + "px"; if(s.width != sws || s.height != shs){ s.width = sws; s.height = shs; if(!Ext.isIE){ var cn = d.childNodes; var sww = Math.max(0, (sw-12))+"px"; cn[0].childNodes[1].style.width = sww; cn[1].childNodes[1].style.width = sww; cn[2].childNodes[1].style.width = sww; cn[1].style.height = Math.max(0, (sh-12))+"px"; } } }, hide : function(){ if(this.el){ this.el.dom.style.display = "none"; Ext.Shadow.Pool.push(this.el); delete this.el; } }, setZIndex : function(z){ this.zIndex = z; if(this.el){ this.el.setStyle("z-index", z); } } }; Ext.Shadow.Pool = function(){ var p = []; var markup = Ext.isIE ? '<div class="x-ie-shadow"></div>' : '<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>'; return { pull : function(){ var sh = p.shift(); if(!sh){ sh = Ext.get(Ext.DomHelper.insertHtml("beforeBegin", document.body.firstChild, markup)); sh.autoBoxAdjust = false; } return sh; }, push : function(sh){ p.push(sh); } }; }(); Ext.BoxComponent = Ext.extend(Ext.Component, { initComponent : function(){ Ext.BoxComponent.superclass.initComponent.call(this); this.addEvents( 'resize', 'move' ); }, boxReady : false, deferHeight: false, setSize : function(w, h){ if(typeof w == 'object'){ h = w.height; w = w.width; } if(!this.boxReady){ this.width = w; this.height = h; return this; } if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){ return this; } this.lastSize = {width: w, height: h}; var adj = this.adjustSize(w, h); var aw = adj.width, ah = adj.height; if(aw !== undefined || ah !== undefined){ var rz = this.getResizeEl(); if(!this.deferHeight && aw !== undefined && ah !== undefined){ rz.setSize(aw, ah); }else if(!this.deferHeight && ah !== undefined){ rz.setHeight(ah); }else if(aw !== undefined){ rz.setWidth(aw); } this.onResize(aw, ah, w, h); this.fireEvent('resize', this, aw, ah, w, h); } return this; }, setWidth : function(width){ return this.setSize(width); }, setHeight : function(height){ return this.setSize(undefined, height); }, getSize : function(){ return this.el.getSize(); }, getPosition : function(local){ if(local === true){ return [this.el.getLeft(true), this.el.getTop(true)]; } return this.xy || this.el.getXY(); }, getBox : function(local){ var s = this.el.getSize(); if(local === true){ s.x = this.el.getLeft(true); s.y = this.el.getTop(true); }else{ var xy = this.xy || this.el.getXY(); s.x = xy[0]; s.y = xy[1]; } return s; }, updateBox : function(box){ this.setSize(box.width, box.height); this.setPagePosition(box.x, box.y); return this; }, getResizeEl : function(){ return this.resizeEl || this.el; }, getPositionEl : function(){ return this.positionEl || this.el; }, setPosition : function(x, y){ if(x && typeof x[1] == 'number'){ y = x[1]; x = x[0]; } this.x = x; this.y = y; if(!this.boxReady){ return this; } var adj = this.adjustPosition(x, y); var ax = adj.x, ay = adj.y; var el = this.getPositionEl(); if(ax !== undefined || ay !== undefined){ if(ax !== undefined && ay !== undefined){ el.setLeftTop(ax, ay); }else if(ax !== undefined){ el.setLeft(ax); }else if(ay !== undefined){ el.setTop(ay); } this.onPosition(ax, ay); this.fireEvent('move', this, ax, ay); } return this; }, setPagePosition : function(x, y){ if(x && typeof x[1] == 'number'){ y = x[1]; x = x[0]; } this.pageX = x; this.pageY = y; if(!this.boxReady){ return; } if(x === undefined || y === undefined){ return; } var p = this.el.translatePoints(x, y); this.setPosition(p.left, p.top); return this; }, onRender : function(ct, position){ Ext.BoxComponent.superclass.onRender.call(this, ct, position); if(this.resizeEl){ this.resizeEl = Ext.get(this.resizeEl); } if(this.positionEl){ this.positionEl = Ext.get(this.positionEl); } }, afterRender : function(){ Ext.BoxComponent.superclass.afterRender.call(this); this.boxReady = true; this.setSize(this.width, this.height); if(this.x || this.y){ this.setPosition(this.x, this.y); }else if(this.pageX || this.pageY){ this.setPagePosition(this.pageX, this.pageY); } }, syncSize : function(){ delete this.lastSize; this.setSize(this.autoWidth ? undefined : this.el.getWidth(), this.autoHeight ? undefined : this.el.getHeight()); return this; }, onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){ }, onPosition : function(x, y){ }, adjustSize : function(w, h){ if(this.autoWidth){ w = 'auto'; } if(this.autoHeight){ h = 'auto'; } return {width : w, height: h}; }, adjustPosition : function(x, y){ return {x : x, y: y}; } }); Ext.reg('box', Ext.BoxComponent); Ext.SplitBar = function(dragElement, resizingElement, orientation, placement, existingProxy){ this.el = Ext.get(dragElement, true); this.el.dom.unselectable = "on"; this.resizingEl = Ext.get(resizingElement, true); this.orientation = orientation || Ext.SplitBar.HORIZONTAL; this.minSize = 0; this.maxSize = 2000; this.animate = false; this.useShim = false; this.shim = null; if(!existingProxy){ this.proxy = Ext.SplitBar.createProxy(this.orientation); }else{ this.proxy = Ext.get(existingProxy).dom; } this.dd = new Ext.dd.DDProxy(this.el.dom.id, "XSplitBars", {dragElId : this.proxy.id}); this.dd.b4StartDrag = this.onStartProxyDrag.createDelegate(this); this.dd.endDrag = this.onEndProxyDrag.createDelegate(this); this.dragSpecs = {}; this.adapter = new Ext.SplitBar.BasicLayoutAdapter(); this.adapter.init(this); if(this.orientation == Ext.SplitBar.HORIZONTAL){ this.placement = placement || (this.el.getX() > this.resizingEl.getX() ? Ext.SplitBar.LEFT : Ext.SplitBar.RIGHT); this.el.addClass("x-splitbar-h"); }else{ this.placement = placement || (this.el.getY() > this.resizingEl.getY() ? Ext.SplitBar.TOP : Ext.SplitBar.BOTTOM); this.el.addClass("x-splitbar-v"); } this.addEvents( "resize", "moved", "beforeresize", "beforeapply" ); Ext.SplitBar.superclass.constructor.call(this); }; Ext.extend(Ext.SplitBar, Ext.util.Observable, { onStartProxyDrag : function(x, y){ this.fireEvent("beforeresize", this); this.overlay = Ext.DomHelper.append(document.body, {cls: "x-drag-overlay", html: "&#160;"}, true); this.overlay.unselectable(); this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.overlay.show(); Ext.get(this.proxy).setDisplayed("block"); var size = this.adapter.getElementSize(this); this.activeMinSize = this.getMinimumSize();; this.activeMaxSize = this.getMaximumSize();; var c1 = size - this.activeMinSize; var c2 = Math.max(this.activeMaxSize - size, 0); if(this.orientation == Ext.SplitBar.HORIZONTAL){ this.dd.resetConstraints(); this.dd.setXConstraint( this.placement == Ext.SplitBar.LEFT ? c1 : c2, this.placement == Ext.SplitBar.LEFT ? c2 : c1 ); this.dd.setYConstraint(0, 0); }else{ this.dd.resetConstraints(); this.dd.setXConstraint(0, 0); this.dd.setYConstraint( this.placement == Ext.SplitBar.TOP ? c1 : c2, this.placement == Ext.SplitBar.TOP ? c2 : c1 ); } this.dragSpecs.startSize = size; this.dragSpecs.startPoint = [x, y]; Ext.dd.DDProxy.prototype.b4StartDrag.call(this.dd, x, y); }, onEndProxyDrag : function(e){ Ext.get(this.proxy).setDisplayed(false); var endPoint = Ext.lib.Event.getXY(e); if(this.overlay){ this.overlay.remove(); delete this.overlay; } var newSize; if(this.orientation == Ext.SplitBar.HORIZONTAL){ newSize = this.dragSpecs.startSize + (this.placement == Ext.SplitBar.LEFT ? endPoint[0] - this.dragSpecs.startPoint[0] : this.dragSpecs.startPoint[0] - endPoint[0] ); }else{ newSize = this.dragSpecs.startSize + (this.placement == Ext.SplitBar.TOP ? endPoint[1] - this.dragSpecs.startPoint[1] : this.dragSpecs.startPoint[1] - endPoint[1] ); } newSize = Math.min(Math.max(newSize, this.activeMinSize), this.activeMaxSize); if(newSize != this.dragSpecs.startSize){ if(this.fireEvent('beforeapply', this, newSize) !== false){ this.adapter.setElementSize(this, newSize); this.fireEvent("moved", this, newSize); this.fireEvent("resize", this, newSize); } } }, getAdapter : function(){ return this.adapter; }, setAdapter : function(adapter){ this.adapter = adapter; this.adapter.init(this); }, getMinimumSize : function(){ return this.minSize; }, setMinimumSize : function(minSize){ this.minSize = minSize; }, getMaximumSize : function(){ return this.maxSize; }, setMaximumSize : function(maxSize){ this.maxSize = maxSize; }, setCurrentSize : function(size){ var oldAnimate = this.animate; this.animate = false; this.adapter.setElementSize(this, size); this.animate = oldAnimate; }, destroy : function(removeEl){ if(this.shim){ this.shim.remove(); } this.dd.unreg(); Ext.removeNode(this.proxy); if(removeEl){ this.el.remove(); } } }); Ext.SplitBar.createProxy = function(dir){ var proxy = new Ext.Element(document.createElement("div")); proxy.unselectable(); var cls = 'x-splitbar-proxy'; proxy.addClass(cls + ' ' + (dir == Ext.SplitBar.HORIZONTAL ? cls +'-h' : cls + '-v')); document.body.appendChild(proxy.dom); return proxy.dom; }; Ext.SplitBar.BasicLayoutAdapter = function(){ }; Ext.SplitBar.BasicLayoutAdapter.prototype = { init : function(s){ }, getElementSize : function(s){ if(s.orientation == Ext.SplitBar.HORIZONTAL){ return s.resizingEl.getWidth(); }else{ return s.resizingEl.getHeight(); } }, setElementSize : function(s, newSize, onComplete){ if(s.orientation == Ext.SplitBar.HORIZONTAL){ if(!s.animate){ s.resizingEl.setWidth(newSize); if(onComplete){ onComplete(s, newSize); } }else{ s.resizingEl.setWidth(newSize, true, .1, onComplete, 'easeOut'); } }else{ if(!s.animate){ s.resizingEl.setHeight(newSize); if(onComplete){ onComplete(s, newSize); } }else{ s.resizingEl.setHeight(newSize, true, .1, onComplete, 'easeOut'); } } } }; Ext.SplitBar.AbsoluteLayoutAdapter = function(container){ this.basic = new Ext.SplitBar.BasicLayoutAdapter(); this.container = Ext.get(container); }; Ext.SplitBar.AbsoluteLayoutAdapter.prototype = { init : function(s){ this.basic.init(s); }, getElementSize : function(s){ return this.basic.getElementSize(s); }, setElementSize : function(s, newSize, onComplete){ this.basic.setElementSize(s, newSize, this.moveSplitter.createDelegate(this, [s])); }, moveSplitter : function(s){ var yes = Ext.SplitBar; switch(s.placement){ case yes.LEFT: s.el.setX(s.resizingEl.getRight()); break; case yes.RIGHT: s.el.setStyle("right", (this.container.getWidth() - s.resizingEl.getLeft()) + "px"); break; case yes.TOP: s.el.setY(s.resizingEl.getBottom()); break; case yes.BOTTOM: s.el.setY(s.resizingEl.getTop() - s.el.getHeight()); break; } } }; Ext.SplitBar.VERTICAL = 1; Ext.SplitBar.HORIZONTAL = 2; Ext.SplitBar.LEFT = 1; Ext.SplitBar.RIGHT = 2; Ext.SplitBar.TOP = 3; Ext.SplitBar.BOTTOM = 4; Ext.Container = Ext.extend(Ext.BoxComponent, { autoDestroy: true, defaultType: 'panel', initComponent : function(){ Ext.Container.superclass.initComponent.call(this); this.addEvents( 'afterlayout', 'beforeadd', 'beforeremove', 'add', 'remove' ); var items = this.items; if(items){ delete this.items; if(Ext.isArray(items)){ this.add.apply(this, items); }else{ this.add(items); } } }, initItems : function(){ if(!this.items){ this.items = new Ext.util.MixedCollection(false, this.getComponentId); this.getLayout(); } }, setLayout : function(layout){ if(this.layout && this.layout != layout){ this.layout.setContainer(null); } this.initItems(); this.layout = layout; layout.setContainer(this); }, render : function(){ Ext.Container.superclass.render.apply(this, arguments); if(this.layout){ if(typeof this.layout == 'string'){ this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig); } this.setLayout(this.layout); if(this.activeItem !== undefined){ var item = this.activeItem; delete this.activeItem; this.layout.setActiveItem(item); return; } } if(!this.ownerCt){ this.doLayout(); } if(this.monitorResize === true){ Ext.EventManager.onWindowResize(this.doLayout, this, [false]); } }, getLayoutTarget : function(){ return this.el; }, getComponentId : function(comp){ return comp.itemId || comp.id; }, add : function(comp){ if(!this.items){ this.initItems(); } var a = arguments, len = a.length; if(len > 1){ for(var i = 0; i < len; i++) { this.add(a[i]); } return; } var c = this.lookupComponent(this.applyDefaults(comp)); var pos = this.items.length; if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){ this.items.add(c); c.ownerCt = this; this.fireEvent('add', this, c, pos); } return c; }, insert : function(index, comp){ if(!this.items){ this.initItems(); } var a = arguments, len = a.length; if(len > 2){ for(var i = len-1; i >= 1; --i) { this.insert(index, a[i]); } return; } var c = this.lookupComponent(this.applyDefaults(comp)); if(c.ownerCt == this && this.items.indexOf(c) < index){ --index; } if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){ this.items.insert(index, c); c.ownerCt = this; this.fireEvent('add', this, c, index); } return c; }, applyDefaults : function(c){ if(this.defaults){ if(typeof c == 'string'){ c = Ext.ComponentMgr.get(c); Ext.apply(c, this.defaults); }else if(!c.events){ Ext.applyIf(c, this.defaults); }else{ Ext.apply(c, this.defaults); } } return c; }, onBeforeAdd : function(item){ if(item.ownerCt){ item.ownerCt.remove(item, false); } if(this.hideBorders === true){ item.border = (item.border === true); } }, remove : function(comp, autoDestroy){ var c = this.getComponent(comp); if(c && this.fireEvent('beforeremove', this, c) !== false){ this.items.remove(c); delete c.ownerCt; if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){ c.destroy(); } if(this.layout && this.layout.activeItem == c){ delete this.layout.activeItem; } this.fireEvent('remove', this, c); } return c; }, getComponent : function(comp){ if(typeof comp == 'object'){ return comp; } return this.items.get(comp); }, lookupComponent : function(comp){ if(typeof comp == 'string'){ return Ext.ComponentMgr.get(comp); }else if(!comp.events){ return this.createComponent(comp); } return comp; }, createComponent : function(config){ return Ext.ComponentMgr.create(config, this.defaultType); }, doLayout : function(shallow){ if(this.rendered && this.layout){ this.layout.layout(); } if(shallow !== false && this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++) { var c = cs[i]; if(c.doLayout){ c.doLayout(); } } } }, getLayout : function(){ if(!this.layout){ var layout = new Ext.layout.ContainerLayout(this.layoutConfig); this.setLayout(layout); } return this.layout; }, onDestroy : function(){ if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++) { Ext.destroy(cs[i]); } } if(this.monitorResize){ Ext.EventManager.removeResizeListener(this.doLayout, this); } Ext.Container.superclass.onDestroy.call(this); }, bubble : function(fn, scope, args){ var p = this; while(p){ if(fn.apply(scope || p, args || [p]) === false){ break; } p = p.ownerCt; } }, cascade : function(fn, scope, args){ if(fn.apply(scope || this, args || [this]) !== false){ if(this.items){ var cs = this.items.items; for(var i = 0, len = cs.length; i < len; i++){ if(cs[i].cascade){ cs[i].cascade(fn, scope, args); }else{ fn.apply(scope || this, args || [cs[i]]); } } } } }, findById : function(id){ var m, ct = this; this.cascade(function(c){ if(ct != c && c.id === id){ m = c; return false; } }); return m || null; }, findByType : function(xtype){ return typeof xtype == 'function' ? this.findBy(function(c){ return c.constructor === xtype; }) : this.findBy(function(c){ return c.constructor.xtype === xtype; }); }, find : function(prop, value){ return this.findBy(function(c){ return c[prop] === value; }); }, findBy : function(fn, scope){ var m = [], ct = this; this.cascade(function(c){ if(ct != c && fn.call(scope || c, c, ct) === true){ m.push(c); } }); return m; } }); Ext.Container.LAYOUTS = {}; Ext.reg('container', Ext.Container); Ext.layout.ContainerLayout = function(config){ Ext.apply(this, config); }; Ext.layout.ContainerLayout.prototype = { monitorResize:false, activeItem : null, layout : function(){ var target = this.container.getLayoutTarget(); this.onLayout(this.container, target); this.container.fireEvent('afterlayout', this.container, this); }, onLayout : function(ct, target){ this.renderAll(ct, target); }, isValidParent : function(c, target){ var el = c.getPositionEl ? c.getPositionEl() : c.getEl(); return el.dom.parentNode == target.dom; }, renderAll : function(ct, target){ var items = ct.items.items; for(var i = 0, len = items.length; i < len; i++) { var c = items[i]; if(c && (!c.rendered || !this.isValidParent(c, target))){ this.renderItem(c, i, target); } } }, renderItem : function(c, position, target){ if(c && !c.rendered){ c.render(target, position); if(this.extraCls){ var t = c.getPositionEl ? c.getPositionEl() : c; t.addClass(this.extraCls); } if (this.renderHidden && c != this.activeItem) { c.hide(); } }else if(c && !this.isValidParent(c, target)){ if(this.extraCls){ c.addClass(this.extraCls); } if(typeof position == 'number'){ position = target.dom.childNodes[position]; } target.dom.insertBefore(c.getEl().dom, position || null); if (this.renderHidden && c != this.activeItem) { c.hide(); } } }, onResize: function(){ if(this.container.collapsed){ return; } var b = this.container.bufferResize; if(b){ if(!this.resizeTask){ this.resizeTask = new Ext.util.DelayedTask(this.layout, this); this.resizeBuffer = typeof b == 'number' ? b : 100; } this.resizeTask.delay(this.resizeBuffer); }else{ this.layout(); } }, setContainer : function(ct){ if(this.monitorResize && ct != this.container){ if(this.container){ this.container.un('resize', this.onResize, this); } if(ct){ ct.on('resize', this.onResize, this); } } this.container = ct; }, parseMargins : function(v){ var ms = v.split(' '); var len = ms.length; if(len == 1){ ms[1] = ms[0]; ms[2] = ms[0]; ms[3] = ms[0]; } if(len == 2){ ms[2] = ms[0]; ms[3] = ms[1]; } return { top:parseInt(ms[0], 10) || 0, right:parseInt(ms[1], 10) || 0, bottom:parseInt(ms[2], 10) || 0, left:parseInt(ms[3], 10) || 0 }; } }; Ext.Container.LAYOUTS['auto'] = Ext.layout.ContainerLayout; Ext.layout.FitLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, onLayout : function(ct, target){ Ext.layout.FitLayout.superclass.onLayout.call(this, ct, target); if(!this.container.collapsed){ this.setItemSize(this.activeItem || ct.items.itemAt(0), target.getStyleSize()); } }, setItemSize : function(item, size){ if(item && size.height > 0){ item.setSize(size); } } }); Ext.Container.LAYOUTS['fit'] = Ext.layout.FitLayout; Ext.layout.CardLayout = Ext.extend(Ext.layout.FitLayout, { deferredRender : false, renderHidden : true, setActiveItem : function(item){ item = this.container.getComponent(item); if(this.activeItem != item){ if(this.activeItem){ this.activeItem.hide(); } this.activeItem = item; item.show(); this.layout(); } }, renderAll : function(ct, target){ if(this.deferredRender){ this.renderItem(this.activeItem, undefined, target); }else{ Ext.layout.CardLayout.superclass.renderAll.call(this, ct, target); } } }); Ext.Container.LAYOUTS['card'] = Ext.layout.CardLayout; Ext.layout.AnchorLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, getAnchorViewSize : function(ct, target){ return target.dom == document.body ? target.getViewSize() : target.getStyleSize(); }, onLayout : function(ct, target){ Ext.layout.AnchorLayout.superclass.onLayout.call(this, ct, target); var size = this.getAnchorViewSize(ct, target); var w = size.width, h = size.height; if(w < 20 || h < 20){ return; } var aw, ah; if(ct.anchorSize){ if(typeof ct.anchorSize == 'number'){ aw = ct.anchorSize; }else{ aw = ct.anchorSize.width; ah = ct.anchorSize.height; } }else{ aw = ct.initialConfig.width; ah = ct.initialConfig.height; } var cs = ct.items.items, len = cs.length, i, c, a, cw, ch; for(i = 0; i < len; i++){ c = cs[i]; if(c.anchor){ a = c.anchorSpec; if(!a){ var vs = c.anchor.split(' '); c.anchorSpec = a = { right: this.parseAnchor(vs[0], c.initialConfig.width, aw), bottom: this.parseAnchor(vs[1], c.initialConfig.height, ah) }; } cw = a.right ? this.adjustWidthAnchor(a.right(w), c) : undefined; ch = a.bottom ? this.adjustHeightAnchor(a.bottom(h), c) : undefined; if(cw || ch){ c.setSize(cw || undefined, ch || undefined); } } } }, parseAnchor : function(a, start, cstart){ if(a && a != 'none'){ var last; if(/^(r|right|b|bottom)$/i.test(a)){ var diff = cstart - start; return function(v){ if(v !== last){ last = v; return v - diff; } } }else if(a.indexOf('%') != -1){ var ratio = parseFloat(a.replace('%', ''))*.01; return function(v){ if(v !== last){ last = v; return Math.floor(v*ratio); } } }else{ a = parseInt(a, 10); if(!isNaN(a)){ return function(v){ if(v !== last){ last = v; return v + a; } } } } } return false; }, adjustWidthAnchor : function(value, comp){ return value; }, adjustHeightAnchor : function(value, comp){ return value; } }); Ext.Container.LAYOUTS['anchor'] = Ext.layout.AnchorLayout; Ext.layout.ColumnLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, extraCls: 'x-column', scrollOffset : 0, isValidParent : function(c, target){ return c.getEl().dom.parentNode == this.innerCt.dom; }, onLayout : function(ct, target){ var cs = ct.items.items, len = cs.length, c, i; if(!this.innerCt){ target.addClass('x-column-layout-ct'); this.innerCt = target.createChild({cls:'x-column-inner'}); this.innerCt.createChild({cls:'x-clear'}); } this.renderAll(ct, this.innerCt); var size = target.getViewSize(); if(size.width < 1 && size.height < 1){ return; } var w = size.width - target.getPadding('lr') - this.scrollOffset, h = size.height - target.getPadding('tb'), pw = w; this.innerCt.setWidth(w); for(i = 0; i < len; i++){ c = cs[i]; if(!c.columnWidth){ pw -= (c.getSize().width + c.getEl().getMargins('lr')); } } pw = pw < 0 ? 0 : pw; for(i = 0; i < len; i++){ c = cs[i]; if(c.columnWidth){ c.setSize(Math.floor(c.columnWidth*pw) - c.getEl().getMargins('lr')); } } } }); Ext.Container.LAYOUTS['column'] = Ext.layout.ColumnLayout; Ext.layout.BorderLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:true, rendered : false, onLayout : function(ct, target){ var collapsed; if(!this.rendered){ target.position(); target.addClass('x-border-layout-ct'); var items = ct.items.items; collapsed = []; for(var i = 0, len = items.length; i < len; i++) { var c = items[i]; var pos = c.region; if(c.collapsed){ collapsed.push(c); } c.collapsed = false; if(!c.rendered){ c.cls = c.cls ? c.cls +' x-border-panel' : 'x-border-panel'; c.render(target, i); } this[pos] = pos != 'center' && c.split ? new Ext.layout.BorderLayout.SplitRegion(this, c.initialConfig, pos) : new Ext.layout.BorderLayout.Region(this, c.initialConfig, pos); this[pos].render(target, c); } this.rendered = true; } var size = target.getViewSize(); if(size.width < 20 || size.height < 20){ if(collapsed){ this.restoreCollapsed = collapsed; } return; }else if(this.restoreCollapsed){ collapsed = this.restoreCollapsed; delete this.restoreCollapsed; } var w = size.width, h = size.height; var centerW = w, centerH = h, centerY = 0, centerX = 0; var n = this.north, s = this.south, west = this.west, e = this.east, c = this.center; if(!c){ throw 'No center region defined in BorderLayout ' + ct.id; } if(n && n.isVisible()){ var b = n.getSize(); var m = n.getMargins(); b.width = w - (m.left+m.right); b.x = m.left; b.y = m.top; centerY = b.height + b.y + m.bottom; centerH -= centerY; n.applyLayout(b); } if(s && s.isVisible()){ var b = s.getSize(); var m = s.getMargins(); b.width = w - (m.left+m.right); b.x = m.left; var totalHeight = (b.height + m.top + m.bottom); b.y = h - totalHeight + m.top; centerH -= totalHeight; s.applyLayout(b); } if(west && west.isVisible()){ var b = west.getSize(); var m = west.getMargins(); b.height = centerH - (m.top+m.bottom); b.x = m.left; b.y = centerY + m.top; var totalWidth = (b.width + m.left + m.right); centerX += totalWidth; centerW -= totalWidth; west.applyLayout(b); } if(e && e.isVisible()){ var b = e.getSize(); var m = e.getMargins(); b.height = centerH - (m.top+m.bottom); var totalWidth = (b.width + m.left + m.right); b.x = w - totalWidth + m.left; b.y = centerY + m.top; centerW -= totalWidth; e.applyLayout(b); } var m = c.getMargins(); var centerBox = { x: centerX + m.left, y: centerY + m.top, width: centerW - (m.left+m.right), height: centerH - (m.top+m.bottom) }; c.applyLayout(centerBox); if(collapsed){ for(var i = 0, len = collapsed.length; i < len; i++){ collapsed[i].collapse(false); } } if(Ext.isIE && Ext.isStrict){ target.repaint(); } } }); Ext.layout.BorderLayout.Region = function(layout, config, pos){ Ext.apply(this, config); this.layout = layout; this.position = pos; this.state = {}; if(typeof this.margins == 'string'){ this.margins = this.layout.parseMargins(this.margins); } this.margins = Ext.applyIf(this.margins || {}, this.defaultMargins); if(this.collapsible){ if(typeof this.cmargins == 'string'){ this.cmargins = this.layout.parseMargins(this.cmargins); } if(this.collapseMode == 'mini' && !this.cmargins){ this.cmargins = {left:0,top:0,right:0,bottom:0}; }else{ this.cmargins = Ext.applyIf(this.cmargins || {}, pos == 'north' || pos == 'south' ? this.defaultNSCMargins : this.defaultEWCMargins); } } }; Ext.layout.BorderLayout.Region.prototype = { collapsible : false, split:false, floatable: true, minWidth:50, minHeight:50, defaultMargins : {left:0,top:0,right:0,bottom:0}, defaultNSCMargins : {left:5,top:5,right:5,bottom:5}, defaultEWCMargins : {left:5,top:0,right:5,bottom:0}, isCollapsed : false, render : function(ct, p){ this.panel = p; p.el.enableDisplayMode(); this.targetEl = ct; this.el = p.el; var gs = p.getState, ps = this.position; p.getState = function(){ return Ext.apply(gs.call(p) || {}, this.state); }.createDelegate(this); if(ps != 'center'){ p.allowQueuedExpand = false; p.on({ beforecollapse: this.beforeCollapse, collapse: this.onCollapse, beforeexpand: this.beforeExpand, expand: this.onExpand, hide: this.onHide, show: this.onShow, scope: this }); if(this.collapsible){ p.collapseEl = 'el'; p.slideAnchor = this.getSlideAnchor(); } if(p.tools && p.tools.toggle){ p.tools.toggle.addClass('x-tool-collapse-'+ps); p.tools.toggle.addClassOnOver('x-tool-collapse-'+ps+'-over'); } } }, getCollapsedEl : function(){ if(!this.collapsedEl){ if(!this.toolTemplate){ var tt = new Ext.Template( '<div class="x-tool x-tool-{id}">&#160;</div>' ); tt.disableFormats = true; tt.compile(); Ext.layout.BorderLayout.Region.prototype.toolTemplate = tt; } this.collapsedEl = this.targetEl.createChild({ cls: "x-layout-collapsed x-layout-collapsed-"+this.position, id: this.panel.id + '-xcollapsed' }); this.collapsedEl.enableDisplayMode('block'); if(this.collapseMode == 'mini'){ this.collapsedEl.addClass('x-layout-cmini-'+this.position); this.miniCollapsedEl = this.collapsedEl.createChild({ cls: "x-layout-mini x-layout-mini-"+this.position, html: "&#160;" }); this.miniCollapsedEl.addClassOnOver('x-layout-mini-over'); this.collapsedEl.addClassOnOver("x-layout-collapsed-over"); this.collapsedEl.on('click', this.onExpandClick, this, {stopEvent:true}); }else { var t = this.toolTemplate.append( this.collapsedEl.dom, {id:'expand-'+this.position}, true); t.addClassOnOver('x-tool-expand-'+this.position+'-over'); t.on('click', this.onExpandClick, this, {stopEvent:true}); if(this.floatable !== false){ this.collapsedEl.addClassOnOver("x-layout-collapsed-over"); this.collapsedEl.on("click", this.collapseClick, this); } } } return this.collapsedEl; }, onExpandClick : function(e){ if(this.isSlid){ this.afterSlideIn(); this.panel.expand(false); }else{ this.panel.expand(); } }, onCollapseClick : function(e){ this.panel.collapse(); }, beforeCollapse : function(p, animate){ this.lastAnim = animate; if(this.splitEl){ this.splitEl.hide(); } this.getCollapsedEl().show(); this.panel.el.setStyle('z-index', 100); this.isCollapsed = true; this.layout.layout(); }, onCollapse : function(animate){ this.panel.el.setStyle('z-index', 1); if(this.lastAnim === false || this.panel.animCollapse === false){ this.getCollapsedEl().dom.style.visibility = 'visible'; }else{ this.getCollapsedEl().slideIn(this.panel.slideAnchor, {duration:.2}); } this.state.collapsed = true; this.panel.saveState(); }, beforeExpand : function(animate){ var c = this.getCollapsedEl(); this.el.show(); if(this.position == 'east' || this.position == 'west'){ this.panel.setSize(undefined, c.getHeight()); }else{ this.panel.setSize(c.getWidth(), undefined); } c.hide(); c.dom.style.visibility = 'hidden'; this.panel.el.setStyle('z-index', 100); }, onExpand : function(){ this.isCollapsed = false; if(this.splitEl){ this.splitEl.show(); } this.layout.layout(); this.panel.el.setStyle('z-index', 1); this.state.collapsed = false; this.panel.saveState(); }, collapseClick : function(e){ if(this.isSlid){ e.stopPropagation(); this.slideIn(); }else{ e.stopPropagation(); this.slideOut(); } }, onHide : function(){ if(this.isCollapsed){ this.getCollapsedEl().hide(); }else if(this.splitEl){ this.splitEl.hide(); } }, onShow : function(){ if(this.isCollapsed){ this.getCollapsedEl().show(); }else if(this.splitEl){ this.splitEl.show(); } }, isVisible : function(){ return !this.panel.hidden; }, getMargins : function(){ return this.isCollapsed && this.cmargins ? this.cmargins : this.margins; }, getSize : function(){ return this.isCollapsed ? this.getCollapsedEl().getSize() : this.panel.getSize(); }, setPanel : function(panel){ this.panel = panel; }, getMinWidth: function(){ return this.minWidth; }, getMinHeight: function(){ return this.minHeight; }, applyLayoutCollapsed : function(box){ var ce = this.getCollapsedEl(); ce.setLeftTop(box.x, box.y); ce.setSize(box.width, box.height); }, applyLayout : function(box){ if(this.isCollapsed){ this.applyLayoutCollapsed(box); }else{ this.panel.setPosition(box.x, box.y); this.panel.setSize(box.width, box.height); } }, beforeSlide: function(){ this.panel.beforeEffect(); }, afterSlide : function(){ this.panel.afterEffect(); }, initAutoHide : function(){ if(this.autoHide !== false){ if(!this.autoHideHd){ var st = new Ext.util.DelayedTask(this.slideIn, this); this.autoHideHd = { "mouseout": function(e){ if(!e.within(this.el, true)){ st.delay(500); } }, "mouseover" : function(e){ st.cancel(); }, scope : this }; } this.el.on(this.autoHideHd); } }, clearAutoHide : function(){ if(this.autoHide !== false){ this.el.un("mouseout", this.autoHideHd.mouseout); this.el.un("mouseover", this.autoHideHd.mouseover); } }, clearMonitor : function(){ Ext.getDoc().un("click", this.slideInIf, this); }, slideOut : function(){ if(this.isSlid || this.el.hasActiveFx()){ return; } this.isSlid = true; var ts = this.panel.tools; if(ts && ts.toggle){ ts.toggle.hide(); } this.el.show(); if(this.position == 'east' || this.position == 'west'){ this.panel.setSize(undefined, this.collapsedEl.getHeight()); }else{ this.panel.setSize(this.collapsedEl.getWidth(), undefined); } this.restoreLT = [this.el.dom.style.left, this.el.dom.style.top]; this.el.alignTo(this.collapsedEl, this.getCollapseAnchor()); this.el.setStyle("z-index", 102); if(this.animFloat !== false){ this.beforeSlide(); this.el.slideIn(this.getSlideAnchor(), { callback: function(){ this.afterSlide(); this.initAutoHide(); Ext.getDoc().on("click", this.slideInIf, this); }, scope: this, block: true }); }else{ this.initAutoHide(); Ext.getDoc().on("click", this.slideInIf, this); } }, afterSlideIn : function(){ this.clearAutoHide(); this.isSlid = false; this.clearMonitor(); this.el.setStyle("z-index", ""); this.el.dom.style.left = this.restoreLT[0]; this.el.dom.style.top = this.restoreLT[1]; var ts = this.panel.tools; if(ts && ts.toggle){ ts.toggle.show(); } }, slideIn : function(cb){ if(!this.isSlid || this.el.hasActiveFx()){ Ext.callback(cb); return; } this.isSlid = false; if(this.animFloat !== false){ this.beforeSlide(); this.el.slideOut(this.getSlideAnchor(), { callback: function(){ this.el.hide(); this.afterSlide(); this.afterSlideIn(); Ext.callback(cb); }, scope: this, block: true }); }else{ this.el.hide(); this.afterSlideIn(); } }, slideInIf : function(e){ if(!e.within(this.el)){ this.slideIn(); } }, anchors : { "west" : "left", "east" : "right", "north" : "top", "south" : "bottom" }, sanchors : { "west" : "l", "east" : "r", "north" : "t", "south" : "b" }, canchors : { "west" : "tl-tr", "east" : "tr-tl", "north" : "tl-bl", "south" : "bl-tl" }, getAnchor : function(){ return this.anchors[this.position]; }, getCollapseAnchor : function(){ return this.canchors[this.position]; }, getSlideAnchor : function(){ return this.sanchors[this.position]; }, getAlignAdj : function(){ var cm = this.cmargins; switch(this.position){ case "west": return [0, 0]; break; case "east": return [0, 0]; break; case "north": return [0, 0]; break; case "south": return [0, 0]; break; } }, getExpandAdj : function(){ var c = this.collapsedEl, cm = this.cmargins; switch(this.position){ case "west": return [-(cm.right+c.getWidth()+cm.left), 0]; break; case "east": return [cm.right+c.getWidth()+cm.left, 0]; break; case "north": return [0, -(cm.top+cm.bottom+c.getHeight())]; break; case "south": return [0, cm.top+cm.bottom+c.getHeight()]; break; } } }; Ext.layout.BorderLayout.SplitRegion = function(layout, config, pos){ Ext.layout.BorderLayout.SplitRegion.superclass.constructor.call(this, layout, config, pos); this.applyLayout = this.applyFns[pos]; }; Ext.extend(Ext.layout.BorderLayout.SplitRegion, Ext.layout.BorderLayout.Region, { splitTip : "Drag to resize.", collapsibleSplitTip : "Drag to resize. Double click to hide.", useSplitTips : false, splitSettings : { north : { orientation: Ext.SplitBar.VERTICAL, placement: Ext.SplitBar.TOP, maxFn : 'getVMaxSize', minProp: 'minHeight', maxProp: 'maxHeight' }, south : { orientation: Ext.SplitBar.VERTICAL, placement: Ext.SplitBar.BOTTOM, maxFn : 'getVMaxSize', minProp: 'minHeight', maxProp: 'maxHeight' }, east : { orientation: Ext.SplitBar.HORIZONTAL, placement: Ext.SplitBar.RIGHT, maxFn : 'getHMaxSize', minProp: 'minWidth', maxProp: 'maxWidth' }, west : { orientation: Ext.SplitBar.HORIZONTAL, placement: Ext.SplitBar.LEFT, maxFn : 'getHMaxSize', minProp: 'minWidth', maxProp: 'maxWidth' } }, applyFns : { west : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; this.panel.setPosition(box.x, box.y); var sw = sd.offsetWidth; s.left = (box.x+box.width-sw)+'px'; s.top = (box.y)+'px'; s.height = Math.max(0, box.height)+'px'; this.panel.setSize(box.width-sw, box.height); }, east : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; var sw = sd.offsetWidth; this.panel.setPosition(box.x+sw, box.y); s.left = (box.x)+'px'; s.top = (box.y)+'px'; s.height = Math.max(0, box.height)+'px'; this.panel.setSize(box.width-sw, box.height); }, north : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; var sh = sd.offsetHeight; this.panel.setPosition(box.x, box.y); s.left = (box.x)+'px'; s.top = (box.y+box.height-sh)+'px'; s.width = Math.max(0, box.width)+'px'; this.panel.setSize(box.width, box.height-sh); }, south : function(box){ if(this.isCollapsed){ return this.applyLayoutCollapsed(box); } var sd = this.splitEl.dom, s = sd.style; var sh = sd.offsetHeight; this.panel.setPosition(box.x, box.y+sh); s.left = (box.x)+'px'; s.top = (box.y)+'px'; s.width = Math.max(0, box.width)+'px'; this.panel.setSize(box.width, box.height-sh); } }, render : function(ct, p){ Ext.layout.BorderLayout.SplitRegion.superclass.render.call(this, ct, p); var ps = this.position; this.splitEl = ct.createChild({ cls: "x-layout-split x-layout-split-"+ps, html: "&#160;", id: this.panel.id + '-xsplit' }); if(this.collapseMode == 'mini'){ this.miniSplitEl = this.splitEl.createChild({ cls: "x-layout-mini x-layout-mini-"+ps, html: "&#160;" }); this.miniSplitEl.addClassOnOver('x-layout-mini-over'); this.miniSplitEl.on('click', this.onCollapseClick, this, {stopEvent:true}); } var s = this.splitSettings[ps]; this.split = new Ext.SplitBar(this.splitEl.dom, p.el, s.orientation); this.split.placement = s.placement; this.split.getMaximumSize = this[s.maxFn].createDelegate(this); this.split.minSize = this.minSize || this[s.minProp]; this.split.on("beforeapply", this.onSplitMove, this); this.split.useShim = this.useShim === true; this.maxSize = this.maxSize || this[s.maxProp]; if(p.hidden){ this.splitEl.hide(); } if(this.useSplitTips){ this.splitEl.dom.title = this.collapsible ? this.collapsibleSplitTip : this.splitTip; } if(this.collapsible){ this.splitEl.on("dblclick", this.onCollapseClick, this); } }, getSize : function(){ if(this.isCollapsed){ return this.collapsedEl.getSize(); } var s = this.panel.getSize(); if(this.position == 'north' || this.position == 'south'){ s.height += this.splitEl.dom.offsetHeight; }else{ s.width += this.splitEl.dom.offsetWidth; } return s; }, getHMaxSize : function(){ var cmax = this.maxSize || 10000; var center = this.layout.center; return Math.min(cmax, (this.el.getWidth()+center.el.getWidth())-center.getMinWidth()); }, getVMaxSize : function(){ var cmax = this.maxSize || 10000; var center = this.layout.center; return Math.min(cmax, (this.el.getHeight()+center.el.getHeight())-center.getMinHeight()); }, onSplitMove : function(split, newSize){ var s = this.panel.getSize(); this.lastSplitSize = newSize; if(this.position == 'north' || this.position == 'south'){ this.panel.setSize(s.width, newSize); this.state.height = newSize; }else{ this.panel.setSize(newSize, s.height); this.state.width = newSize; } this.layout.layout(); this.panel.saveState(); return false; }, getSplitBar : function(){ return this.split; } }); Ext.Container.LAYOUTS['border'] = Ext.layout.BorderLayout; Ext.layout.FormLayout = Ext.extend(Ext.layout.AnchorLayout, { labelSeparator : ':', getAnchorViewSize : function(ct, target){ return ct.body.getStyleSize(); }, setContainer : function(ct){ Ext.layout.FormLayout.superclass.setContainer.call(this, ct); if(ct.labelAlign){ ct.addClass('x-form-label-'+ct.labelAlign); } if(ct.hideLabels){ this.labelStyle = "display:none"; this.elementStyle = "padding-left:0;"; this.labelAdjust = 0; }else{ this.labelSeparator = ct.labelSeparator || this.labelSeparator; ct.labelWidth = ct.labelWidth || 100; if(typeof ct.labelWidth == 'number'){ var pad = (typeof ct.labelPad == 'number' ? ct.labelPad : 5); this.labelAdjust = ct.labelWidth+pad; this.labelStyle = "width:"+ct.labelWidth+"px;"; this.elementStyle = "padding-left:"+(ct.labelWidth+pad)+'px'; } if(ct.labelAlign == 'top'){ this.labelStyle = "width:auto;"; this.labelAdjust = 0; this.elementStyle = "padding-left:0;"; } } if(!this.fieldTpl){ var t = new Ext.Template( '<div class="x-form-item {5}" tabIndex="-1">', '<label for="{0}" style="{2}" class="x-form-item-label">{1}{4}</label>', '<div class="x-form-element" id="x-form-el-{0}" style="{3}">', '</div><div class="{6}"></div>', '</div>' ); t.disableFormats = true; t.compile(); Ext.layout.FormLayout.prototype.fieldTpl = t; } }, renderItem : function(c, position, target){ if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){ var args = [ c.id, c.fieldLabel, c.labelStyle||this.labelStyle||'', this.elementStyle||'', typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator, (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''), c.clearCls || 'x-form-clear-left' ]; if(typeof position == 'number'){ position = target.dom.childNodes[position] || null; } if(position){ this.fieldTpl.insertBefore(position, args); }else{ this.fieldTpl.append(target, args); } c.render('x-form-el-'+c.id); }else { Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments); } }, adjustWidthAnchor : function(value, comp){ return value - (comp.isFormField ? (comp.hideLabel ? 0 : this.labelAdjust) : 0); }, isValidParent : function(c, target){ return true; } }); Ext.Container.LAYOUTS['form'] = Ext.layout.FormLayout; Ext.layout.Accordion = Ext.extend(Ext.layout.FitLayout, { fill : true, autoWidth : true, titleCollapse : true, hideCollapseTool : false, collapseFirst : false, animate : false, sequence : false, activeOnTop : false, renderItem : function(c){ if(this.animate === false){ c.animCollapse = false; } c.collapsible = true; if(this.autoWidth){ c.autoWidth = true; } if(this.titleCollapse){ c.titleCollapse = true; } if(this.hideCollapseTool){ c.hideCollapseTool = true; } if(this.collapseFirst !== undefined){ c.collapseFirst = this.collapseFirst; } if(!this.activeItem && !c.collapsed){ this.activeItem = c; }else if(this.activeItem){ c.collapsed = true; } Ext.layout.Accordion.superclass.renderItem.apply(this, arguments); c.header.addClass('x-accordion-hd'); c.on('beforeexpand', this.beforeExpand, this); }, beforeExpand : function(p, anim){ var ai = this.activeItem; if(ai){ if(this.sequence){ delete this.activeItem; ai.collapse({callback:function(){ p.expand(anim || true); }, scope: this}); return false; }else{ ai.collapse(this.animate); } } this.activeItem = p; if(this.activeOnTop){ p.el.dom.parentNode.insertBefore(p.el.dom, p.el.dom.parentNode.firstChild); } this.layout(); }, setItemSize : function(item, size){ if(this.fill && item){ var items = this.container.items.items; var hh = 0; for(var i = 0, len = items.length; i < len; i++){ var p = items[i]; if(p != item){ hh += (p.getSize().height - p.bwrap.getHeight()); } } size.height -= hh; item.setSize(size); } } }); Ext.Container.LAYOUTS['accordion'] = Ext.layout.Accordion; Ext.layout.TableLayout = Ext.extend(Ext.layout.ContainerLayout, { monitorResize:false, setContainer : function(ct){ Ext.layout.TableLayout.superclass.setContainer.call(this, ct); this.currentRow = 0; this.currentColumn = 0; this.cells = []; }, onLayout : function(ct, target){ var cs = ct.items.items, len = cs.length, c, i; if(!this.table){ target.addClass('x-table-layout-ct'); this.table = target.createChild( {tag:'table', cls:'x-table-layout', cellspacing: 0, cn: {tag: 'tbody'}}, null, true); this.renderAll(ct, target); } }, getRow : function(index){ var row = this.table.tBodies[0].childNodes[index]; if(!row){ row = document.createElement('tr'); this.table.tBodies[0].appendChild(row); } return row; }, getNextCell : function(c){ var cell = this.getNextNonSpan(this.currentColumn, this.currentRow); var curCol = this.currentColumn = cell[0], curRow = this.currentRow = cell[1]; for(var rowIndex = curRow; rowIndex < curRow + (c.rowspan || 1); rowIndex++){ if(!this.cells[rowIndex]){ this.cells[rowIndex] = []; } for(var colIndex = curCol; colIndex < curCol + (c.colspan || 1); colIndex++){ this.cells[rowIndex][colIndex] = true; } } var td = document.createElement('td'); if(c.cellId){ td.id = c.cellId; } var cls = 'x-table-layout-cell'; if(c.cellCls){ cls += ' ' + c.cellCls; } td.className = cls; if(c.colspan){ td.colSpan = c.colspan; } if(c.rowspan){ td.rowSpan = c.rowspan; } this.getRow(curRow).appendChild(td); return td; }, getNextNonSpan: function(colIndex, rowIndex){ var cols = this.columns; while((cols && colIndex >= cols) || (this.cells[rowIndex] && this.cells[rowIndex][colIndex])) { if(cols && colIndex >= cols){ rowIndex++; colIndex = 0; }else{ colIndex++; } } return [colIndex, rowIndex]; }, renderItem : function(c, position, target){ if(c && !c.rendered){ c.render(this.getNextCell(c)); } }, isValidParent : function(c, target){ return true; } }); Ext.Container.LAYOUTS['table'] = Ext.layout.TableLayout; Ext.layout.AbsoluteLayout = Ext.extend(Ext.layout.AnchorLayout, { extraCls: 'x-abs-layout-item', isForm: false, setContainer : function(ct){ Ext.layout.AbsoluteLayout.superclass.setContainer.call(this, ct); if(ct.isXType('form')){ this.isForm = true; } }, onLayout : function(ct, target){ if(this.isForm){ ct.body.position(); } else { target.position(); } Ext.layout.AbsoluteLayout.superclass.onLayout.call(this, ct, target); }, getAnchorViewSize : function(ct, target){ return this.isForm ? ct.body.getStyleSize() : Ext.layout.AbsoluteLayout.superclass.getAnchorViewSize.call(this, ct, target); }, isValidParent : function(c, target){ return this.isForm ? true : Ext.layout.AbsoluteLayout.superclass.isValidParent.call(this, c, target); }, adjustWidthAnchor : function(value, comp){ return value ? value - comp.getPosition(true)[0] : value; }, adjustHeightAnchor : function(value, comp){ return value ? value - comp.getPosition(true)[1] : value; } }); Ext.Container.LAYOUTS['absolute'] = Ext.layout.AbsoluteLayout; Ext.Viewport = Ext.extend(Ext.Container, { initComponent : function() { Ext.Viewport.superclass.initComponent.call(this); document.getElementsByTagName('html')[0].className += ' x-viewport'; this.el = Ext.getBody(); this.el.setHeight = Ext.emptyFn; this.el.setWidth = Ext.emptyFn; this.el.setSize = Ext.emptyFn; this.el.dom.scroll = 'no'; this.allowDomMove = false; this.autoWidth = true; this.autoHeight = true; Ext.EventManager.onWindowResize(this.fireResize, this); this.renderTo = this.el; }, fireResize : function(w, h){ this.fireEvent('resize', this, w, h, w, h); } }); Ext.reg('viewport', Ext.Viewport); Ext.Panel = Ext.extend(Ext.Container, { baseCls : 'x-panel', collapsedCls : 'x-panel-collapsed', maskDisabled: true, animCollapse: Ext.enableFx, headerAsText: true, buttonAlign: 'right', collapsed : false, collapseFirst: true, minButtonWidth:75, elements : 'body', toolTarget : 'header', collapseEl : 'bwrap', slideAnchor : 't', deferHeight: true, expandDefaults: { duration:.25 }, collapseDefaults: { duration:.25 }, initComponent : function(){ Ext.Panel.superclass.initComponent.call(this); this.addEvents( 'bodyresize', 'titlechange', 'collapse', 'expand', 'beforecollapse', 'beforeexpand', 'beforeclose', 'close', 'activate', 'deactivate' ); if(this.tbar){ this.elements += ',tbar'; if(typeof this.tbar == 'object'){ this.topToolbar = this.tbar; } delete this.tbar; } if(this.bbar){ this.elements += ',bbar'; if(typeof this.bbar == 'object'){ this.bottomToolbar = this.bbar; } delete this.bbar; } if(this.header === true){ this.elements += ',header'; delete this.header; }else if(this.title && this.header !== false){ this.elements += ',header'; } if(this.footer === true){ this.elements += ',footer'; delete this.footer; } if(this.buttons){ var btns = this.buttons; this.buttons = []; for(var i = 0, len = btns.length; i < len; i++) { if(btns[i].render){ this.buttons.push(btns[i]); }else{ this.addButton(btns[i]); } } } if(this.autoLoad){ this.on('render', this.doAutoLoad, this, {delay:10}); } }, createElement : function(name, pnode){ if(this[name]){ pnode.appendChild(this[name].dom); return; } if(name === 'bwrap' || this.elements.indexOf(name) != -1){ if(this[name+'Cfg']){ this[name] = Ext.fly(pnode).createChild(this[name+'Cfg']); }else{ var el = document.createElement('div'); el.className = this[name+'Cls']; this[name] = Ext.get(pnode.appendChild(el)); } } }, onRender : function(ct, position){ Ext.Panel.superclass.onRender.call(this, ct, position); this.createClasses(); if(this.el){ this.el.addClass(this.baseCls); this.header = this.el.down('.'+this.headerCls); this.bwrap = this.el.down('.'+this.bwrapCls); var cp = this.bwrap ? this.bwrap : this.el; this.tbar = cp.down('.'+this.tbarCls); this.body = cp.down('.'+this.bodyCls); this.bbar = cp.down('.'+this.bbarCls); this.footer = cp.down('.'+this.footerCls); this.fromMarkup = true; }else{ this.el = ct.createChild({ id: this.id, cls: this.baseCls }, position); } var el = this.el, d = el.dom; if(this.cls){ this.el.addClass(this.cls); } if(this.buttons){ this.elements += ',footer'; } if(this.frame){ el.insertHtml('afterBegin', String.format(Ext.Element.boxMarkup, this.baseCls)); this.createElement('header', d.firstChild.firstChild.firstChild); this.createElement('bwrap', d); var bw = this.bwrap.dom; var ml = d.childNodes[1], bl = d.childNodes[2]; bw.appendChild(ml); bw.appendChild(bl); var mc = bw.firstChild.firstChild.firstChild; this.createElement('tbar', mc); this.createElement('body', mc); this.createElement('bbar', mc); this.createElement('footer', bw.lastChild.firstChild.firstChild); if(!this.footer){ this.bwrap.dom.lastChild.className += ' x-panel-nofooter'; } }else{ this.createElement('header', d); this.createElement('bwrap', d); var bw = this.bwrap.dom; this.createElement('tbar', bw); this.createElement('body', bw); this.createElement('bbar', bw); this.createElement('footer', bw); if(!this.header){ this.body.addClass(this.bodyCls + '-noheader'); if(this.tbar){ this.tbar.addClass(this.tbarCls + '-noheader'); } } } if(this.border === false){ this.el.addClass(this.baseCls + '-noborder'); this.body.addClass(this.bodyCls + '-noborder'); if(this.header){ this.header.addClass(this.headerCls + '-noborder'); } if(this.footer){ this.footer.addClass(this.footerCls + '-noborder'); } if(this.tbar){ this.tbar.addClass(this.tbarCls + '-noborder'); } if(this.bbar){ this.bbar.addClass(this.bbarCls + '-noborder'); } } if(this.bodyBorder === false){ this.body.addClass(this.bodyCls + '-noborder'); } if(this.bodyStyle){ this.body.applyStyles(this.bodyStyle); } this.bwrap.enableDisplayMode('block'); if(this.header){ this.header.unselectable(); if(this.headerAsText){ this.header.dom.innerHTML = '<span class="' + this.headerTextCls + '">'+this.header.dom.innerHTML+'</span>'; if(this.iconCls){ this.setIconClass(this.iconCls); } } } if(this.floating){ this.makeFloating(this.floating); } if(this.collapsible){ this.tools = this.tools ? this.tools.slice(0) : []; if(!this.hideCollapseTool){ this.tools[this.collapseFirst?'unshift':'push']({ id: 'toggle', handler : this.toggleCollapse, scope: this }); } if(this.titleCollapse && this.header){ this.header.on('click', this.toggleCollapse, this); this.header.setStyle('cursor', 'pointer'); } } if(this.tools){ var ts = this.tools; this.tools = {}; this.addTool.apply(this, ts); }else{ this.tools = {}; } if(this.buttons && this.buttons.length > 0){ var tb = this.footer.createChild({cls:'x-panel-btns-ct', cn: { cls:"x-panel-btns x-panel-btns-"+this.buttonAlign, html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>' }}, null, true); var tr = tb.getElementsByTagName('tr')[0]; for(var i = 0, len = this.buttons.length; i < len; i++) { var b = this.buttons[i]; var td = document.createElement('td'); td.className = 'x-panel-btn-td'; b.render(tr.appendChild(td)); } } if(this.tbar && this.topToolbar){ if(Ext.isArray(this.topToolbar)){ this.topToolbar = new Ext.Toolbar(this.topToolbar); } this.topToolbar.render(this.tbar); } if(this.bbar && this.bottomToolbar){ if(Ext.isArray(this.bottomToolbar)){ this.bottomToolbar = new Ext.Toolbar(this.bottomToolbar); } this.bottomToolbar.render(this.bbar); } }, setIconClass : function(cls){ var old = this.iconCls; this.iconCls = cls; if(this.rendered && this.header){ if(this.frame){ this.header.addClass('x-panel-icon'); this.header.replaceClass(old, this.iconCls); }else{ var hd = this.header.dom; var img = hd.firstChild && String(hd.firstChild.tagName).toLowerCase() == 'img' ? hd.firstChild : null; if(img){ Ext.fly(img).replaceClass(old, this.iconCls); }else{ Ext.DomHelper.insertBefore(hd.firstChild, { tag:'img', src: Ext.BLANK_IMAGE_URL, cls:'x-panel-inline-icon '+this.iconCls }); } } } }, makeFloating : function(cfg){ this.floating = true; this.el = new Ext.Layer( typeof cfg == 'object' ? cfg : { shadow: this.shadow !== undefined ? this.shadow : 'sides', shadowOffset: this.shadowOffset, constrain:false, shim: this.shim === false ? false : undefined }, this.el ); }, getTopToolbar : function(){ return this.topToolbar; }, getBottomToolbar : function(){ return this.bottomToolbar; }, addButton : function(config, handler, scope){ var bc = { handler: handler, scope: scope, minWidth: this.minButtonWidth, hideParent:true }; if(typeof config == "string"){ bc.text = config; }else{ Ext.apply(bc, config); } var btn = new Ext.Button(bc); btn.ownerCt = this; if(!this.buttons){ this.buttons = []; } this.buttons.push(btn); return btn; }, addTool : function(){ if(!this[this.toolTarget]) { return; } if(!this.toolTemplate){ var tt = new Ext.Template( '<div class="x-tool x-tool-{id}">&#160;</div>' ); tt.disableFormats = true; tt.compile(); Ext.Panel.prototype.toolTemplate = tt; } for(var i = 0, a = arguments, len = a.length; i < len; i++) { var tc = a[i], overCls = 'x-tool-'+tc.id+'-over'; var t = this.toolTemplate.insertFirst(this[this.toolTarget], tc, true); this.tools[tc.id] = t; t.enableDisplayMode('block'); t.on('click', this.createToolHandler(t, tc, overCls, this)); if(tc.on){ t.on(tc.on); } if(tc.hidden){ t.hide(); } if(tc.qtip){ if(typeof tc.qtip == 'object'){ Ext.QuickTips.register(Ext.apply({ target: t.id }, tc.qtip)); } else { t.dom.qtip = tc.qtip; } } t.addClassOnOver(overCls); } }, onShow : function(){ if(this.floating){ return this.el.show(); } Ext.Panel.superclass.onShow.call(this); }, onHide : function(){ if(this.floating){ return this.el.hide(); } Ext.Panel.superclass.onHide.call(this); }, createToolHandler : function(t, tc, overCls, panel){ return function(e){ t.removeClass(overCls); e.stopEvent(); if(tc.handler){ tc.handler.call(tc.scope || t, e, t, panel); } }; }, afterRender : function(){ if(this.fromMarkup && this.height === undefined && !this.autoHeight){ this.height = this.el.getHeight(); } if(this.floating && !this.hidden && !this.initHidden){ this.el.show(); } if(this.title){ this.setTitle(this.title); } this.setAutoScroll(); if(this.html){ this.body.update(typeof this.html == 'object' ? Ext.DomHelper.markup(this.html) : this.html); delete this.html; } if(this.contentEl){ var ce = Ext.getDom(this.contentEl); Ext.fly(ce).removeClass(['x-hidden', 'x-hide-display']); this.body.dom.appendChild(ce); } if(this.collapsed){ this.collapsed = false; this.collapse(false); } Ext.Panel.superclass.afterRender.call(this); this.initEvents(); }, setAutoScroll : function(){ if(this.rendered && this.autoScroll){ this.body.setOverflow('auto'); } }, getKeyMap : function(){ if(!this.keyMap){ this.keyMap = new Ext.KeyMap(this.el, this.keys); } return this.keyMap; }, initEvents : function(){ if(this.keys){ this.getKeyMap(); } if(this.draggable){ this.initDraggable(); } }, initDraggable : function(){ this.dd = new Ext.Panel.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable); }, beforeEffect : function(){ if(this.floating){ this.el.beforeAction(); } this.el.addClass('x-panel-animated'); }, afterEffect : function(){ this.syncShadow(); this.el.removeClass('x-panel-animated'); }, createEffect : function(a, cb, scope){ var o = { scope:scope, block:true }; if(a === true){ o.callback = cb; return o; }else if(!a.callback){ o.callback = cb; }else { o.callback = function(){ cb.call(scope); Ext.callback(a.callback, a.scope); }; } return Ext.applyIf(o, a); }, collapse : function(animate){ if(this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforecollapse', this, animate) === false){ return; } var doAnim = animate === true || (animate !== false && this.animCollapse); this.beforeEffect(); this.onCollapse(doAnim, animate); return this; }, onCollapse : function(doAnim, animArg){ if(doAnim){ this[this.collapseEl].slideOut(this.slideAnchor, Ext.apply(this.createEffect(animArg||true, this.afterCollapse, this), this.collapseDefaults)); }else{ this[this.collapseEl].hide(); this.afterCollapse(); } }, afterCollapse : function(){ this.collapsed = true; this.el.addClass(this.collapsedCls); this.afterEffect(); this.fireEvent('collapse', this); }, expand : function(animate){ if(!this.collapsed || this.el.hasFxBlock() || this.fireEvent('beforeexpand', this, animate) === false){ return; } var doAnim = animate === true || (animate !== false && this.animCollapse); this.el.removeClass(this.collapsedCls); this.beforeEffect(); this.onExpand(doAnim, animate); return this; }, onExpand : function(doAnim, animArg){ if(doAnim){ this[this.collapseEl].slideIn(this.slideAnchor, Ext.apply(this.createEffect(animArg||true, this.afterExpand, this), this.expandDefaults)); }else{ this[this.collapseEl].show(); this.afterExpand(); } }, afterExpand : function(){ this.collapsed = false; this.afterEffect(); this.fireEvent('expand', this); }, toggleCollapse : function(animate){ this[this.collapsed ? 'expand' : 'collapse'](animate); return this; }, onDisable : function(){ if(this.rendered && this.maskDisabled){ this.el.mask(); } Ext.Panel.superclass.onDisable.call(this); }, onEnable : function(){ if(this.rendered && this.maskDisabled){ this.el.unmask(); } Ext.Panel.superclass.onEnable.call(this); }, onResize : function(w, h){ if(w !== undefined || h !== undefined){ if(!this.collapsed){ if(typeof w == 'number'){ this.body.setWidth( this.adjustBodyWidth(w - this.getFrameWidth())); }else if(w == 'auto'){ this.body.setWidth(w); } if(typeof h == 'number'){ this.body.setHeight( this.adjustBodyHeight(h - this.getFrameHeight())); }else if(h == 'auto'){ this.body.setHeight(h); } }else{ this.queuedBodySize = {width: w, height: h}; if(!this.queuedExpand && this.allowQueuedExpand !== false){ this.queuedExpand = true; this.on('expand', function(){ delete this.queuedExpand; this.onResize(this.queuedBodySize.width, this.queuedBodySize.height); this.doLayout(); }, this, {single:true}); } } this.fireEvent('bodyresize', this, w, h); } this.syncShadow(); }, adjustBodyHeight : function(h){ return h; }, adjustBodyWidth : function(w){ return w; }, onPosition : function(){ this.syncShadow(); }, onDestroy : function(){ if(this.tools){ for(var k in this.tools){ Ext.destroy(this.tools[k]); } } if(this.buttons){ for(var b in this.buttons){ Ext.destroy(this.buttons[b]); } } Ext.destroy( this.topToolbar, this.bottomToolbar ); Ext.Panel.superclass.onDestroy.call(this); }, getFrameWidth : function(){ var w = this.el.getFrameWidth('lr'); if(this.frame){ var l = this.bwrap.dom.firstChild; w += (Ext.fly(l).getFrameWidth('l') + Ext.fly(l.firstChild).getFrameWidth('r')); var mc = this.bwrap.dom.firstChild.firstChild.firstChild; w += Ext.fly(mc).getFrameWidth('lr'); } return w; }, getFrameHeight : function(){ var h = this.el.getFrameWidth('tb'); h += (this.tbar ? this.tbar.getHeight() : 0) + (this.bbar ? this.bbar.getHeight() : 0); if(this.frame){ var hd = this.el.dom.firstChild; var ft = this.bwrap.dom.lastChild; h += (hd.offsetHeight + ft.offsetHeight); var mc = this.bwrap.dom.firstChild.firstChild.firstChild; h += Ext.fly(mc).getFrameWidth('tb'); }else{ h += (this.header ? this.header.getHeight() : 0) + (this.footer ? this.footer.getHeight() : 0); } return h; }, getInnerWidth : function(){ return this.getSize().width - this.getFrameWidth(); }, getInnerHeight : function(){ return this.getSize().height - this.getFrameHeight(); }, syncShadow : function(){ if(this.floating){ this.el.sync(true); } }, getLayoutTarget : function(){ return this.body; }, setTitle : function(title, iconCls){ this.title = title; if(this.header && this.headerAsText){ this.header.child('span').update(title); } if(iconCls){ this.setIconClass(iconCls); } this.fireEvent('titlechange', this, title); return this; }, getUpdater : function(){ return this.body.getUpdater(); }, load : function(){ var um = this.body.getUpdater(); um.update.apply(um, arguments); return this; }, beforeDestroy : function(){ Ext.Element.uncache( this.header, this.tbar, this.bbar, this.footer, this.body ); }, createClasses : function(){ this.headerCls = this.baseCls + '-header'; this.headerTextCls = this.baseCls + '-header-text'; this.bwrapCls = this.baseCls + '-bwrap'; this.tbarCls = this.baseCls + '-tbar'; this.bodyCls = this.baseCls + '-body'; this.bbarCls = this.baseCls + '-bbar'; this.footerCls = this.baseCls + '-footer'; }, createGhost : function(cls, useShim, appendTo){ var el = document.createElement('div'); el.className = 'x-panel-ghost ' + (cls ? cls : ''); if(this.header){ el.appendChild(this.el.dom.firstChild.cloneNode(true)); } Ext.fly(el.appendChild(document.createElement('ul'))).setHeight(this.bwrap.getHeight()); el.style.width = this.el.dom.offsetWidth + 'px';; if(!appendTo){ this.container.dom.appendChild(el); }else{ Ext.getDom(appendTo).appendChild(el); } if(useShim !== false && this.el.useShim !== false){ var layer = new Ext.Layer({shadow:false, useDisplay:true, constrain:false}, el); layer.show(); return layer; }else{ return new Ext.Element(el); } }, doAutoLoad : function(){ this.body.load( typeof this.autoLoad == 'object' ? this.autoLoad : {url: this.autoLoad}); } }); Ext.reg('panel', Ext.Panel); Ext.Window = Ext.extend(Ext.Panel, { baseCls : 'x-window', resizable:true, draggable:true, closable : true, constrain:false, constrainHeader:false, plain:false, minimizable : false, maximizable : false, minHeight: 100, minWidth: 200, expandOnShow: true, closeAction: 'close', collapsible:false, initHidden : true, monitorResize : true, elements: 'header,body', frame:true, floating:true, initComponent : function(){ Ext.Window.superclass.initComponent.call(this); this.addEvents( 'resize', 'maximize', 'minimize', 'restore' ); }, getState : function(){ return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox()); }, onRender : function(ct, position){ Ext.Window.superclass.onRender.call(this, ct, position); if(this.plain){ this.el.addClass('x-window-plain'); } this.focusEl = this.el.createChild({ tag: "a", href:"#", cls:"x-dlg-focus", tabIndex:"-1", html: "&#160;"}); this.focusEl.swallowEvent('click', true); this.proxy = this.el.createProxy("x-window-proxy"); this.proxy.enableDisplayMode('block'); if(this.modal){ this.mask = this.container.createChild({cls:"ext-el-mask"}, this.el.dom); this.mask.enableDisplayMode("block"); this.mask.hide(); } }, initEvents : function(){ Ext.Window.superclass.initEvents.call(this); if(this.animateTarget){ this.setAnimateTarget(this.animateTarget); } if(this.resizable){ this.resizer = new Ext.Resizable(this.el, { minWidth: this.minWidth, minHeight:this.minHeight, handles: this.resizeHandles || "all", pinned: true, resizeElement : this.resizerAction }); this.resizer.window = this; this.resizer.on("beforeresize", this.beforeResize, this); } if(this.draggable){ this.header.addClass("x-window-draggable"); } this.initTools(); this.el.on("mousedown", this.toFront, this); this.manager = this.manager || Ext.WindowMgr; this.manager.register(this); this.hidden = true; if(this.maximized){ this.maximized = false; this.maximize(); } if(this.closable){ var km = this.getKeyMap(); km.on(27, this.onEsc, this); km.disable(); } }, initDraggable : function(){ this.dd = new Ext.Window.DD(this); }, onEsc : function(){ this[this.closeAction](); }, beforeDestroy : function(){ Ext.destroy( this.resizer, this.dd, this.proxy, this.mask ); Ext.Window.superclass.beforeDestroy.call(this); }, onDestroy : function(){ if(this.manager){ this.manager.unregister(this); } Ext.Window.superclass.onDestroy.call(this); }, initTools : function(){ if(this.minimizable){ this.addTool({ id: 'minimize', handler: this.minimize.createDelegate(this, []) }); } if(this.maximizable){ this.addTool({ id: 'maximize', handler: this.maximize.createDelegate(this, []) }); this.addTool({ id: 'restore', handler: this.restore.createDelegate(this, []), hidden:true }); this.header.on('dblclick', this.toggleMaximize, this); } if(this.closable){ this.addTool({ id: 'close', handler: this[this.closeAction].createDelegate(this, []) }); } }, resizerAction : function(){ var box = this.proxy.getBox(); this.proxy.hide(); this.window.handleResize(box); return box; }, beforeResize : function(){ this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40); this.resizeBox = this.el.getBox(); }, updateHandles : function(){ if(Ext.isIE && this.resizer){ this.resizer.syncHandleHeight(); this.el.repaint(); } }, handleResize : function(box){ var rz = this.resizeBox; if(rz.x != box.x || rz.y != box.y){ this.updateBox(box); }else{ this.setSize(box); } this.focus(); this.updateHandles(); this.saveState(); this.fireEvent("resize", this, box.width, box.height); }, focus : function(){ var f = this.focusEl, db = this.defaultButton, t = typeof db; if(t != 'undefined'){ if(t == 'number'){ f = this.buttons[db]; }else if(t == 'string'){ f = Ext.getCmp(db); }else{ f = db; } } f.focus.defer(10, f); }, setAnimateTarget : function(el){ el = Ext.get(el); this.animateTarget = el; }, beforeShow : function(){ delete this.el.lastXY; delete this.el.lastLT; if(this.x === undefined || this.y === undefined){ var xy = this.el.getAlignToXY(this.container, 'c-c'); var pos = this.el.translatePoints(xy[0], xy[1]); this.x = this.x === undefined? pos.left : this.x; this.y = this.y === undefined? pos.top : this.y; } this.el.setLeftTop(this.x, this.y); if(this.expandOnShow){ this.expand(false); } if(this.modal){ Ext.getBody().addClass("x-body-masked"); this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.mask.show(); } }, show : function(animateTarget, cb, scope){ if(!this.rendered){ this.render(Ext.getBody()); } if(this.hidden === false){ this.toFront(); return; } if(this.fireEvent("beforeshow", this) === false){ return; } if(cb){ this.on('show', cb, scope, {single:true}); } this.hidden = false; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } this.beforeShow(); if(this.animateTarget){ this.animShow(); }else{ this.afterShow(); } }, afterShow : function(){ this.proxy.hide(); this.el.setStyle('display', 'block'); this.el.show(); if(this.maximized){ this.fitContainer(); } if(Ext.isMac && Ext.isGecko){ this.cascade(this.setAutoScroll); } if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.onWindowResize(this.onWindowResize, this); } this.doConstrain(); if(this.layout){ this.doLayout(); } if(this.keyMap){ this.keyMap.enable(); } this.toFront(); this.updateHandles(); this.fireEvent("show", this); }, animShow : function(){ this.proxy.show(); this.proxy.setBox(this.animateTarget.getBox()); this.proxy.setOpacity(0); var b = this.getBox(false); b.callback = this.afterShow; b.scope = this; b.duration = .25; b.easing = 'easeNone'; b.opacity = .5; b.block = true; this.el.setStyle('display', 'none'); this.proxy.shift(b); }, hide : function(animateTarget, cb, scope){ if(this.hidden || this.fireEvent("beforehide", this) === false){ return; } if(cb){ this.on('hide', cb, scope, {single:true}); } this.hidden = true; if(animateTarget !== undefined){ this.setAnimateTarget(animateTarget); } if(this.animateTarget){ this.animHide(); }else{ this.el.hide(); this.afterHide(); } }, afterHide : function(){ this.proxy.hide(); if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){ Ext.EventManager.removeResizeListener(this.onWindowResize, this); } if(this.modal){ this.mask.hide(); Ext.getBody().removeClass("x-body-masked"); } if(this.keyMap){ this.keyMap.disable(); } this.fireEvent("hide", this); }, animHide : function(){ this.proxy.setOpacity(.5); this.proxy.show(); var tb = this.getBox(false); this.proxy.setBox(tb); this.el.hide(); var b = this.animateTarget.getBox(); b.callback = this.afterHide; b.scope = this; b.duration = .25; b.easing = 'easeNone'; b.block = true; b.opacity = 0; this.proxy.shift(b); }, onWindowResize : function(){ if(this.maximized){ this.fitContainer(); } if(this.modal){ this.mask.setSize('100%', '100%'); var force = this.mask.dom.offsetHeight; this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); } this.doConstrain(); }, doConstrain : function(){ if(this.constrain || this.constrainHeader){ var offsets; if(this.constrain){ offsets = { right:this.el.shadowOffset, left:this.el.shadowOffset, bottom:this.el.shadowOffset }; }else { var s = this.getSize(); offsets = { right:-(s.width - 100), bottom:-(s.height - 25) }; } var xy = this.el.getConstrainToXY(this.container, true, offsets); if(xy){ this.setPosition(xy[0], xy[1]); } } }, ghost : function(cls){ var ghost = this.createGhost(cls); var box = this.getBox(true); ghost.setLeftTop(box.x, box.y); ghost.setWidth(box.width); this.el.hide(); this.activeGhost = ghost; return ghost; }, unghost : function(show, matchPosition){ if(show !== false){ this.el.show(); this.focus(); if(Ext.isMac && Ext.isGecko){ this.cascade(this.setAutoScroll); } } if(matchPosition !== false){ this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true)); } this.activeGhost.hide(); this.activeGhost.remove(); delete this.activeGhost; }, minimize : function(){ this.fireEvent('minimize', this); }, close : function(){ if(this.fireEvent("beforeclose", this) !== false){ this.hide(null, function(){ this.fireEvent('close', this); this.destroy(); }, this); } }, maximize : function(){ if(!this.maximized){ this.expand(false); this.restoreSize = this.getSize(); this.restorePos = this.getPosition(true); this.tools.maximize.hide(); this.tools.restore.show(); this.maximized = true; this.el.disableShadow(); if(this.dd){ this.dd.lock(); } if(this.collapsible){ this.tools.toggle.hide(); } this.el.addClass('x-window-maximized'); this.container.addClass('x-window-maximized-ct'); this.setPosition(0, 0); this.fitContainer(); this.fireEvent('maximize', this); } }, restore : function(){ if(this.maximized){ this.el.removeClass('x-window-maximized'); this.tools.restore.hide(); this.tools.maximize.show(); this.setPosition(this.restorePos[0], this.restorePos[1]); this.setSize(this.restoreSize.width, this.restoreSize.height); delete this.restorePos; delete this.restoreSize; this.maximized = false; this.el.enableShadow(true); if(this.dd){ this.dd.unlock(); } if(this.collapsible){ this.tools.toggle.show(); } this.container.removeClass('x-window-maximized-ct'); this.doConstrain(); this.fireEvent('restore', this); } }, toggleMaximize : function(){ this[this.maximized ? 'restore' : 'maximize'](); }, fitContainer : function(){ var vs = this.container.getViewSize(); this.setSize(vs.width, vs.height); }, setZIndex : function(index){ if(this.modal){ this.mask.setStyle("z-index", index); } this.el.setZIndex(++index); index += 5; if(this.resizer){ this.resizer.proxy.setStyle("z-index", ++index); } this.lastZIndex = index; }, alignTo : function(element, position, offsets){ var xy = this.el.getAlignToXY(element, position, offsets); this.setPagePosition(xy[0], xy[1]); return this; }, anchorTo : function(el, alignment, offsets, monitorScroll, _pname){ var action = function(){ this.alignTo(el, alignment, offsets); }; Ext.EventManager.onWindowResize(action, this); var tm = typeof monitorScroll; if(tm != 'undefined'){ Ext.EventManager.on(window, 'scroll', action, this, {buffer: tm == 'number' ? monitorScroll : 50}); } action.call(this); this[_pname] = action; return this; }, toFront : function(){ if(this.manager.bringToFront(this)){ this.focus(); } return this; }, setActive : function(active){ if(active){ if(!this.maximized){ this.el.enableShadow(true); } this.fireEvent('activate', this); }else{ this.el.disableShadow(); this.fireEvent('deactivate', this); } }, toBack : function(){ this.manager.sendToBack(this); return this; }, center : function(){ var xy = this.el.getAlignToXY(this.container, 'c-c'); this.setPagePosition(xy[0], xy[1]); return this; } }); Ext.reg('window', Ext.Window); Ext.Window.DD = function(win){ this.win = win; Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-'+win.id); this.setHandleElId(win.header.id); this.scroll = false; }; Ext.extend(Ext.Window.DD, Ext.dd.DD, { moveOnly:true, headerOffsets:[100, 25], startDrag : function(){ var w = this.win; this.proxy = w.ghost(); if(w.constrain !== false){ var so = w.el.shadowOffset; this.constrainTo(w.container, {right: so, left: so, bottom: so}); }else if(w.constrainHeader !== false){ var s = this.proxy.getSize(); this.constrainTo(w.container, {right: -(s.width-this.headerOffsets[0]), bottom: -(s.height-this.headerOffsets[1])}); } }, b4Drag : Ext.emptyFn, onDrag : function(e){ this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY()); }, endDrag : function(e){ this.win.unghost(); this.win.saveState(); } }); Ext.WindowGroup = function(){ var list = {}; var accessList = []; var front = null; var sortWindows = function(d1, d2){ return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1; }; var orderWindows = function(){ var a = accessList, len = a.length; if(len > 0){ a.sort(sortWindows); var seed = a[0].manager.zseed; for(var i = 0; i < len; i++){ var win = a[i]; if(win && !win.hidden){ win.setZIndex(seed + (i*10)); } } } activateLast(); }; var setActiveWin = function(win){ if(win != front){ if(front){ front.setActive(false); } front = win; if(win){ win.setActive(true); } } }; var activateLast = function(){ for(var i = accessList.length-1; i >=0; --i) { if(!accessList[i].hidden){ setActiveWin(accessList[i]); return; } } setActiveWin(null); }; return { zseed : 9000, register : function(win){ list[win.id] = win; accessList.push(win); win.on('hide', activateLast); }, unregister : function(win){ delete list[win.id]; win.un('hide', activateLast); accessList.remove(win); }, get : function(id){ return typeof id == "object" ? id : list[id]; }, bringToFront : function(win){ win = this.get(win); if(win != front){ win._lastAccess = new Date().getTime(); orderWindows(); return true; } return false; }, sendToBack : function(win){ win = this.get(win); win._lastAccess = -(new Date().getTime()); orderWindows(); return win; }, hideAll : function(){ for(var id in list){ if(list[id] && typeof list[id] != "function" && list[id].isVisible()){ list[id].hide(); } } }, getActive : function(){ return front; }, getBy : function(fn, scope){ var r = []; for(var i = accessList.length-1; i >=0; --i) { var win = accessList[i]; if(fn.call(scope||win, win) !== false){ r.push(win); } } return r; }, each : function(fn, scope){ for(var id in list){ if(list[id] && typeof list[id] != "function"){ if(fn.call(scope || list[id], list[id]) === false){ return; } } } } }; }; Ext.WindowMgr = new Ext.WindowGroup(); Ext.dd.PanelProxy = function(panel, config){ this.panel = panel; this.id = this.panel.id +'-ddproxy'; Ext.apply(this, config); }; Ext.dd.PanelProxy.prototype = { insertProxy : true, setStatus : Ext.emptyFn, reset : Ext.emptyFn, update : Ext.emptyFn, stop : Ext.emptyFn, sync: Ext.emptyFn, getEl : function(){ return this.ghost; }, getGhost : function(){ return this.ghost; }, getProxy : function(){ return this.proxy; }, hide : function(){ if(this.ghost){ if(this.proxy){ this.proxy.remove(); delete this.proxy; } this.panel.el.dom.style.display = ''; this.ghost.remove(); delete this.ghost; } }, show : function(){ if(!this.ghost){ this.ghost = this.panel.createGhost(undefined, undefined, Ext.getBody()); this.ghost.setXY(this.panel.el.getXY()) if(this.insertProxy){ this.proxy = this.panel.el.insertSibling({cls:'x-panel-dd-spacer'}); this.proxy.setSize(this.panel.getSize()); } this.panel.el.dom.style.display = 'none'; } }, repair : function(xy, callback, scope){ this.hide(); if(typeof callback == "function"){ callback.call(scope || this); } }, moveProxy : function(parentNode, before){ if(this.proxy){ parentNode.insertBefore(this.proxy.dom, before); } } }; Ext.Panel.DD = function(panel, cfg){ this.panel = panel; this.dragData = {panel: panel}; this.proxy = new Ext.dd.PanelProxy(panel, cfg); Ext.Panel.DD.superclass.constructor.call(this, panel.el, cfg); this.setHandleElId(panel.header.id); panel.header.setStyle('cursor', 'move'); this.scroll = false; }; Ext.extend(Ext.Panel.DD, Ext.dd.DragSource, { showFrame: Ext.emptyFn, startDrag: Ext.emptyFn, b4StartDrag: function(x, y) { this.proxy.show(); }, b4MouseDown: function(e) { var x = e.getPageX(); var y = e.getPageY(); this.autoOffset(x, y); }, onInitDrag : function(x, y){ this.onStartDrag(x, y); return true; }, createFrame : Ext.emptyFn, getDragEl : function(e){ return this.proxy.ghost.dom; }, endDrag : function(e){ this.proxy.hide(); this.panel.saveState(); }, autoOffset : function(x, y) { x -= this.startPageX; y -= this.startPageY; this.setDelta(x, y); } }); Ext.state.Provider = function(){ this.addEvents("statechange"); this.state = {}; Ext.state.Provider.superclass.constructor.call(this); }; Ext.extend(Ext.state.Provider, Ext.util.Observable, { get : function(name, defaultValue){ return typeof this.state[name] == "undefined" ? defaultValue : this.state[name]; }, clear : function(name){ delete this.state[name]; this.fireEvent("statechange", this, name, null); }, set : function(name, value){ this.state[name] = value; this.fireEvent("statechange", this, name, value); }, decodeValue : function(cookie){ var re = /^(a|n|d|b|s|o)\:(.*)$/; var matches = re.exec(unescape(cookie)); if(!matches || !matches[1]) return; var type = matches[1]; var v = matches[2]; switch(type){ case "n": return parseFloat(v); case "d": return new Date(Date.parse(v)); case "b": return (v == "1"); case "a": var all = []; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ all.push(this.decodeValue(values[i])); } return all; case "o": var all = {}; var values = v.split("^"); for(var i = 0, len = values.length; i < len; i++){ var kv = values[i].split("="); all[kv[0]] = this.decodeValue(kv[1]); } return all; default: return v; } }, encodeValue : function(v){ var enc; if(typeof v == "number"){ enc = "n:" + v; }else if(typeof v == "boolean"){ enc = "b:" + (v ? "1" : "0"); }else if(Ext.isDate(v)){ enc = "d:" + v.toGMTString(); }else if(Ext.isArray(v)){ var flat = ""; for(var i = 0, len = v.length; i < len; i++){ flat += this.encodeValue(v[i]); if(i != len-1) flat += "^"; } enc = "a:" + flat; }else if(typeof v == "object"){ var flat = ""; for(var key in v){ if(typeof v[key] != "function" && v[key] !== undefined){ flat += key + "=" + this.encodeValue(v[key]) + "^"; } } enc = "o:" + flat.substring(0, flat.length-1); }else{ enc = "s:" + v; } return escape(enc); } }); Ext.state.Manager = function(){ var provider = new Ext.state.Provider(); return { setProvider : function(stateProvider){ provider = stateProvider; }, get : function(key, defaultValue){ return provider.get(key, defaultValue); }, set : function(key, value){ provider.set(key, value); }, clear : function(key){ provider.clear(key); }, getProvider : function(){ return provider; } }; }(); Ext.state.CookieProvider = function(config){ Ext.state.CookieProvider.superclass.constructor.call(this); this.path = "/"; this.expires = new Date(new Date().getTime()+(1000*60*60*24*7)); this.domain = null; this.secure = false; Ext.apply(this, config); this.state = this.readCookies(); }; Ext.extend(Ext.state.CookieProvider, Ext.state.Provider, { set : function(name, value){ if(typeof value == "undefined" || value === null){ this.clear(name); return; } this.setCookie(name, value); Ext.state.CookieProvider.superclass.set.call(this, name, value); }, clear : function(name){ this.clearCookie(name); Ext.state.CookieProvider.superclass.clear.call(this, name); }, readCookies : function(){ var cookies = {}; var c = document.cookie + ";"; var re = /\s?(.*?)=(.*?);/g; var matches; while((matches = re.exec(c)) != null){ var name = matches[1]; var value = matches[2]; if(name && name.substring(0,3) == "ys-"){ cookies[name.substr(3)] = this.decodeValue(value); } } return cookies; }, setCookie : function(name, value){ document.cookie = "ys-"+ name + "=" + this.encodeValue(value) + ((this.expires == null) ? "" : ("; expires=" + this.expires.toGMTString())) + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : ""); }, clearCookie : function(name){ document.cookie = "ys-" + name + "=null; expires=Thu, 01-Jan-70 00:00:01 GMT" + ((this.path == null) ? "" : ("; path=" + this.path)) + ((this.domain == null) ? "" : ("; domain=" + this.domain)) + ((this.secure == true) ? "; secure" : ""); } }); Ext.DataView = Ext.extend(Ext.BoxComponent, { selectedClass : "x-view-selected", emptyText : "", last: false, initComponent : function(){ Ext.DataView.superclass.initComponent.call(this); if(typeof this.tpl == "string"){ this.tpl = new Ext.XTemplate(this.tpl); } this.addEvents( "beforeclick", "click", "containerclick", "dblclick", "contextmenu", "selectionchange", "beforeselect" ); this.all = new Ext.CompositeElementLite(); this.selected = new Ext.CompositeElementLite(); }, onRender : function(){ if(!this.el){ this.el = document.createElement('div'); } Ext.DataView.superclass.onRender.apply(this, arguments); }, afterRender : function(){ Ext.DataView.superclass.afterRender.call(this); this.el.on({ "click": this.onClick, "dblclick": this.onDblClick, "contextmenu": this.onContextMenu, scope:this }); if(this.overClass){ this.el.on({ "mouseover": this.onMouseOver, "mouseout": this.onMouseOut, scope:this }); } if(this.store){ this.setStore(this.store, true); } }, refresh : function(){ this.clearSelections(false, true); this.el.update(""); var html = []; var records = this.store.getRange(); if(records.length < 1){ this.el.update(this.emptyText); this.all.clear(); return; } this.tpl.overwrite(this.el, this.collectData(records, 0)); this.all.fill(Ext.query(this.itemSelector, this.el.dom)); this.updateIndexes(0); }, prepareData : function(data){ return data; }, collectData : function(records, startIndex){ var r = []; for(var i = 0, len = records.length; i < len; i++){ r[r.length] = this.prepareData(records[i].data, startIndex+i, records[i]); } return r; }, bufferRender : function(records){ var div = document.createElement('div'); this.tpl.overwrite(div, this.collectData(records)); return Ext.query(this.itemSelector, div); }, onUpdate : function(ds, record){ var index = this.store.indexOf(record); var sel = this.isSelected(index); var original = this.all.elements[index]; var node = this.bufferRender([record], index)[0]; this.all.replaceElement(index, node, true); if(sel){ this.selected.replaceElement(original, node); this.all.item(index).addClass(this.selectedClass); } this.updateIndexes(index, index); }, onAdd : function(ds, records, index){ if(this.all.getCount() == 0){ this.refresh(); return; } var nodes = this.bufferRender(records, index), n; if(index < this.all.getCount()){ n = this.all.item(index).insertSibling(nodes, 'before', true); this.all.elements.splice(index, 0, n); }else{ n = this.all.last().insertSibling(nodes, 'after', true); this.all.elements.push(n); } this.updateIndexes(index); }, onRemove : function(ds, record, index){ this.deselect(index); this.all.removeElement(index, true); this.updateIndexes(index); }, refreshNode : function(index){ this.onUpdate(this.store, this.store.getAt(index)); }, updateIndexes : function(startIndex, endIndex){ var ns = this.all.elements; startIndex = startIndex || 0; endIndex = endIndex || ((endIndex === 0) ? 0 : (ns.length - 1)); for(var i = startIndex; i <= endIndex; i++){ ns[i].viewIndex = i; } }, setStore : function(store, initial){ if(!initial && this.store){ this.store.un("beforeload", this.onBeforeLoad, this); this.store.un("datachanged", this.refresh, this); this.store.un("add", this.onAdd, this); this.store.un("remove", this.onRemove, this); this.store.un("update", this.onUpdate, this); this.store.un("clear", this.refresh, this); } if(store){ store = Ext.StoreMgr.lookup(store); store.on("beforeload", this.onBeforeLoad, this); store.on("datachanged", this.refresh, this); store.on("add", this.onAdd, this); store.on("remove", this.onRemove, this); store.on("update", this.onUpdate, this); store.on("clear", this.refresh, this); } this.store = store; if(store){ this.refresh(); } }, findItemFromChild : function(node){ return Ext.fly(node).findParent(this.itemSelector, this.el); }, onClick : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ var index = this.indexOf(item); if(this.onItemClick(item, index, e) !== false){ this.fireEvent("click", this, index, item, e); } }else{ if(this.fireEvent("containerclick", this, e) !== false){ this.clearSelections(); } } }, onContextMenu : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ this.fireEvent("contextmenu", this, this.indexOf(item), item, e); } }, onDblClick : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item){ this.fireEvent("dblclick", this, this.indexOf(item), item, e); } }, onMouseOver : function(e){ var item = e.getTarget(this.itemSelector, this.el); if(item && item !== this.lastItem){ this.lastItem = item; Ext.fly(item).addClass(this.overClass); } }, onMouseOut : function(e){ if(this.lastItem){ if(!e.within(this.lastItem, true)){ Ext.fly(this.lastItem).removeClass(this.overClass); delete this.lastItem; } } }, onItemClick : function(item, index, e){ if(this.fireEvent("beforeclick", this, index, item, e) === false){ return false; } if(this.multiSelect){ this.doMultiSelection(item, index, e); e.preventDefault(); }else if(this.singleSelect){ this.doSingleSelection(item, index, e); e.preventDefault(); } return true; }, doSingleSelection : function(item, index, e){ if(e.ctrlKey && this.isSelected(index)){ this.deselect(index); }else{ this.select(index, false); } }, doMultiSelection : function(item, index, e){ if(e.shiftKey && this.last !== false){ var last = this.last; this.selectRange(last, index, e.ctrlKey); this.last = last; }else{ if((e.ctrlKey||this.simpleSelect) && this.isSelected(index)){ this.deselect(index); }else{ this.select(index, e.ctrlKey || e.shiftKey || this.simpleSelect); } } }, getSelectionCount : function(){ return this.selected.getCount() }, getSelectedNodes : function(){ return this.selected.elements; }, getSelectedIndexes : function(){ var indexes = [], s = this.selected.elements; for(var i = 0, len = s.length; i < len; i++){ indexes.push(s[i].viewIndex); } return indexes; }, getSelectedRecords : function(){ var r = [], s = this.selected.elements; for(var i = 0, len = s.length; i < len; i++){ r[r.length] = this.store.getAt(s[i].viewIndex); } return r; }, getRecords : function(nodes){ var r = [], s = nodes; for(var i = 0, len = s.length; i < len; i++){ r[r.length] = this.store.getAt(s[i].viewIndex); } return r; }, getRecord : function(node){ return this.store.getAt(node.viewIndex); }, clearSelections : function(suppressEvent, skipUpdate){ if(this.multiSelect || this.singleSelect){ if(!skipUpdate){ this.selected.removeClass(this.selectedClass); } this.selected.clear(); this.last = false; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selected.elements); } } }, isSelected : function(node){ return this.selected.contains(this.getNode(node)); }, deselect : function(node){ if(this.isSelected(node)){ var node = this.getNode(node); this.selected.removeElement(node); if(this.last == node.viewIndex){ this.last = false; } Ext.fly(node).removeClass(this.selectedClass); this.fireEvent("selectionchange", this, this.selected.elements); } }, select : function(nodeInfo, keepExisting, suppressEvent){ if(Ext.isArray(nodeInfo)){ if(!keepExisting){ this.clearSelections(true); } for(var i = 0, len = nodeInfo.length; i < len; i++){ this.select(nodeInfo[i], true, true); } } else{ var node = this.getNode(nodeInfo); if(!keepExisting){ this.clearSelections(true); } if(node && !this.isSelected(node)){ if(this.fireEvent("beforeselect", this, node, this.selected.elements) !== false){ Ext.fly(node).addClass(this.selectedClass); this.selected.add(node); this.last = node.viewIndex; if(!suppressEvent){ this.fireEvent("selectionchange", this, this.selected.elements); } } } } }, selectRange : function(start, end, keepExisting){ if(!keepExisting){ this.clearSelections(true); } this.select(this.getNodes(start, end), true); }, getNode : function(nodeInfo){ if(typeof nodeInfo == "string"){ return document.getElementById(nodeInfo); }else if(typeof nodeInfo == "number"){ return this.all.elements[nodeInfo]; } return nodeInfo; }, getNodes : function(start, end){ var ns = this.all.elements; start = start || 0; end = typeof end == "undefined" ? ns.length - 1 : end; var nodes = [], i; if(start <= end){ for(i = start; i <= end; i++){ nodes.push(ns[i]); } } else{ for(i = start; i >= end; i--){ nodes.push(ns[i]); } } return nodes; }, indexOf : function(node){ node = this.getNode(node); if(typeof node.viewIndex == "number"){ return node.viewIndex; } return this.all.indexOf(node); }, onBeforeLoad : function(){ if(this.loadingText){ this.clearSelections(false, true); this.el.update('<div class="loading-indicator">'+this.loadingText+'</div>'); this.all.clear(); } } }); Ext.reg('dataview', Ext.DataView); Ext.ColorPalette = function(config){ Ext.ColorPalette.superclass.constructor.call(this, config); this.addEvents( 'select' ); if(this.handler){ this.on("select", this.handler, this.scope, true); } }; Ext.extend(Ext.ColorPalette, Ext.Component, { itemCls : "x-color-palette", value : null, clickEvent:'click', ctype: "Ext.ColorPalette", allowReselect : false, colors : [ "000000", "993300", "333300", "003300", "003366", "000080", "333399", "333333", "800000", "FF6600", "808000", "008000", "008080", "0000FF", "666699", "808080", "FF0000", "FF9900", "99CC00", "339966", "33CCCC", "3366FF", "800080", "969696", "FF00FF", "FFCC00", "FFFF00", "00FF00", "00FFFF", "00CCFF", "993366", "C0C0C0", "FF99CC", "FFCC99", "FFFFCC", "CCFFCC", "CCFFFF", "99CCFF", "CC99FF", "FFFFFF" ], onRender : function(container, position){ var t = this.tpl || new Ext.XTemplate( '<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on">&#160;</span></em></a></tpl>' ); var el = document.createElement("div"); el.className = this.itemCls; t.overwrite(el, this.colors); container.dom.insertBefore(el, position); this.el = Ext.get(el); this.el.on(this.clickEvent, this.handleClick, this, {delegate: "a"}); if(this.clickEvent != 'click'){ this.el.on('click', Ext.emptyFn, this, {delegate: "a", preventDefault:true}); } }, afterRender : function(){ Ext.ColorPalette.superclass.afterRender.call(this); if(this.value){ var s = this.value; this.value = null; this.select(s); } }, handleClick : function(e, t){ e.preventDefault(); if(!this.disabled){ var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1]; this.select(c.toUpperCase()); } }, select : function(color){ color = color.replace("#", ""); if(color != this.value || this.allowReselect){ var el = this.el; if(this.value){ el.child("a.color-"+this.value).removeClass("x-color-palette-sel"); } el.child("a.color-"+color).addClass("x-color-palette-sel"); this.value = color; this.fireEvent("select", this, color); } } }); Ext.reg('colorpalette', Ext.ColorPalette); Ext.DatePicker = Ext.extend(Ext.Component, { todayText : "Today", okText : "&#160;OK&#160;", cancelText : "Cancel", todayTip : "{0} (Spacebar)", minDate : null, maxDate : null, minText : "This date is before the minimum date", maxText : "This date is after the maximum date", format : "m/d/y", disabledDays : null, disabledDaysText : "", disabledDatesRE : null, disabledDatesText : "", constrainToViewport : true, monthNames : Date.monthNames, dayNames : Date.dayNames, nextText: 'Next Month (Control+Right)', prevText: 'Previous Month (Control+Left)', monthYearText: 'Choose a month (Control+Up/Down to move years)', startDay : 0, initComponent : function(){ Ext.DatePicker.superclass.initComponent.call(this); this.value = this.value ? this.value.clearTime() : new Date().clearTime(); this.addEvents( 'select' ); if(this.handler){ this.on("select", this.handler, this.scope || this); } this.initDisabledDays(); }, initDisabledDays : function(){ if(!this.disabledDatesRE && this.disabledDates){ var dd = this.disabledDates; var re = "(?:"; for(var i = 0; i < dd.length; i++){ re += dd[i]; if(i != dd.length-1) re += "|"; } this.disabledDatesRE = new RegExp(re + ")"); } }, setValue : function(value){ var old = this.value; this.value = value.clearTime(true); if(this.el){ this.update(this.value); } }, getValue : function(){ return this.value; }, focus : function(){ if(this.el){ this.update(this.activeDate); } }, onRender : function(container, position){ var m = [ '<table cellspacing="0">', '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>', '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>']; var dn = this.dayNames; for(var i = 0; i < 7; i++){ var d = this.startDay+i; if(d > 6){ d = d-7; } m.push("<th><span>", dn[d].substr(0,1), "</span></th>"); } m[m.length] = "</tr></thead><tbody><tr>"; for(var i = 0; i < 42; i++) { if(i % 7 == 0 && i != 0){ m[m.length] = "</tr><tr>"; } m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>'; } m[m.length] = '</tr></tbody></table></td></tr><tr><td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>'; var el = document.createElement("div"); el.className = "x-date-picker"; el.innerHTML = m.join(""); container.dom.insertBefore(el, position); this.el = Ext.get(el); this.eventEl = Ext.get(el.firstChild); new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), { handler: this.showPrevMonth, scope: this, preventDefault:true, stopDefault:true }); new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), { handler: this.showNextMonth, scope: this, preventDefault:true, stopDefault:true }); this.eventEl.on("mousewheel", this.handleMouseWheel, this); this.monthPicker = this.el.down('div.x-date-mp'); this.monthPicker.enableDisplayMode('block'); var kn = new Ext.KeyNav(this.eventEl, { "left" : function(e){ e.ctrlKey ? this.showPrevMonth() : this.update(this.activeDate.add("d", -1)); }, "right" : function(e){ e.ctrlKey ? this.showNextMonth() : this.update(this.activeDate.add("d", 1)); }, "up" : function(e){ e.ctrlKey ? this.showNextYear() : this.update(this.activeDate.add("d", -7)); }, "down" : function(e){ e.ctrlKey ? this.showPrevYear() : this.update(this.activeDate.add("d", 7)); }, "pageUp" : function(e){ this.showNextMonth(); }, "pageDown" : function(e){ this.showPrevMonth(); }, "enter" : function(e){ e.stopPropagation(); return true; }, scope : this }); this.eventEl.on("click", this.handleDateClick, this, {delegate: "a.x-date-date"}); this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this); this.el.unselectable(); this.cells = this.el.select("table.x-date-inner tbody td"); this.textNodes = this.el.query("table.x-date-inner tbody span"); this.mbtn = new Ext.Button({ text: "&#160;", tooltip: this.monthYearText, renderTo: this.el.child("td.x-date-middle", true) }); this.mbtn.on('click', this.showMonthPicker, this); this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu"); var today = (new Date()).dateFormat(this.format); this.todayBtn = new Ext.Button({ renderTo: this.el.child("td.x-date-bottom", true), text: String.format(this.todayText, today), tooltip: String.format(this.todayTip, today), handler: this.selectToday, scope: this }); if(Ext.isIE){ this.el.repaint(); } this.update(this.value); }, createMonthPicker : function(){ if(!this.monthPicker.dom.firstChild){ var buf = ['<table border="0" cellspacing="0">']; for(var i = 0; i < 6; i++){ buf.push( '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>', '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>', i == 0 ? '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' : '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>' ); } buf.push( '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">', this.okText, '</button><button type="button" class="x-date-mp-cancel">', this.cancelText, '</button></td></tr>', '</table>' ); this.monthPicker.update(buf.join('')); this.monthPicker.on('click', this.onMonthClick, this); this.monthPicker.on('dblclick', this.onMonthDblClick, this); this.mpMonths = this.monthPicker.select('td.x-date-mp-month'); this.mpYears = this.monthPicker.select('td.x-date-mp-year'); this.mpMonths.each(function(m, a, i){ i += 1; if((i%2) == 0){ m.dom.xmonth = 5 + Math.round(i * .5); }else{ m.dom.xmonth = Math.round((i-1) * .5); } }); } }, showMonthPicker : function(){ this.createMonthPicker(); var size = this.el.getSize(); this.monthPicker.setSize(size); this.monthPicker.child('table').setSize(size); this.mpSelMonth = (this.activeDate || this.value).getMonth(); this.updateMPMonth(this.mpSelMonth); this.mpSelYear = (this.activeDate || this.value).getFullYear(); this.updateMPYear(this.mpSelYear); this.monthPicker.slideIn('t', {duration:.2}); }, updateMPYear : function(y){ this.mpyear = y; var ys = this.mpYears.elements; for(var i = 1; i <= 10; i++){ var td = ys[i-1], y2; if((i%2) == 0){ y2 = y + Math.round(i * .5); td.firstChild.innerHTML = y2; td.xyear = y2; }else{ y2 = y - (5-Math.round(i * .5)); td.firstChild.innerHTML = y2; td.xyear = y2; } this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel'); } }, updateMPMonth : function(sm){ this.mpMonths.each(function(m, a, i){ m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel'); }); }, selectMPMonth: function(m){ }, onMonthClick : function(e, t){ e.stopEvent(); var el = new Ext.Element(t), pn; if(el.is('button.x-date-mp-cancel')){ this.hideMonthPicker(); } else if(el.is('button.x-date-mp-ok')){ this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } else if(pn = el.up('td.x-date-mp-month', 2)){ this.mpMonths.removeClass('x-date-mp-sel'); pn.addClass('x-date-mp-sel'); this.mpSelMonth = pn.dom.xmonth; } else if(pn = el.up('td.x-date-mp-year', 2)){ this.mpYears.removeClass('x-date-mp-sel'); pn.addClass('x-date-mp-sel'); this.mpSelYear = pn.dom.xyear; } else if(el.is('a.x-date-mp-prev')){ this.updateMPYear(this.mpyear-10); } else if(el.is('a.x-date-mp-next')){ this.updateMPYear(this.mpyear+10); } }, onMonthDblClick : function(e, t){ e.stopEvent(); var el = new Ext.Element(t), pn; if(pn = el.up('td.x-date-mp-month', 2)){ this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } else if(pn = el.up('td.x-date-mp-year', 2)){ this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate())); this.hideMonthPicker(); } }, hideMonthPicker : function(disableAnim){ if(this.monthPicker){ if(disableAnim === true){ this.monthPicker.hide(); }else{ this.monthPicker.slideOut('t', {duration:.2}); } } }, showPrevMonth : function(e){ this.update(this.activeDate.add("mo", -1)); }, showNextMonth : function(e){ this.update(this.activeDate.add("mo", 1)); }, showPrevYear : function(){ this.update(this.activeDate.add("y", -1)); }, showNextYear : function(){ this.update(this.activeDate.add("y", 1)); }, handleMouseWheel : function(e){ var delta = e.getWheelDelta(); if(delta > 0){ this.showPrevMonth(); e.stopEvent(); } else if(delta < 0){ this.showNextMonth(); e.stopEvent(); } }, handleDateClick : function(e, t){ e.stopEvent(); if(t.dateValue && !Ext.fly(t.parentNode).hasClass("x-date-disabled")){ this.setValue(new Date(t.dateValue)); this.fireEvent("select", this, this.value); } }, selectToday : function(){ this.setValue(new Date().clearTime()); this.fireEvent("select", this, this.value); }, update : function(date){ var vd = this.activeDate; this.activeDate = date; if(vd && this.el){ var t = date.getTime(); if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){ this.cells.removeClass("x-date-selected"); this.cells.each(function(c){ if(c.dom.firstChild.dateValue == t){ c.addClass("x-date-selected"); setTimeout(function(){ try{c.dom.firstChild.focus();}catch(e){} }, 50); return false; } }); return; } } var days = date.getDaysInMonth(); var firstOfMonth = date.getFirstDateOfMonth(); var startingPos = firstOfMonth.getDay()-this.startDay; if(startingPos <= this.startDay){ startingPos += 7; } var pm = date.add("mo", -1); var prevStart = pm.getDaysInMonth()-startingPos; var cells = this.cells.elements; var textEls = this.textNodes; days += startingPos; var day = 86400000; var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime(); var today = new Date().clearTime().getTime(); var sel = date.clearTime().getTime(); var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY; var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY; var ddMatch = this.disabledDatesRE; var ddText = this.disabledDatesText; var ddays = this.disabledDays ? this.disabledDays.join("") : false; var ddaysText = this.disabledDaysText; var format = this.format; var setCellClass = function(cal, cell){ cell.title = ""; var t = d.getTime(); cell.firstChild.dateValue = t; if(t == today){ cell.className += " x-date-today"; cell.title = cal.todayText; } if(t == sel){ cell.className += " x-date-selected"; setTimeout(function(){ try{cell.firstChild.focus();}catch(e){} }, 50); } if(t < min) { cell.className = " x-date-disabled"; cell.title = cal.minText; return; } if(t > max) { cell.className = " x-date-disabled"; cell.title = cal.maxText; return; } if(ddays){ if(ddays.indexOf(d.getDay()) != -1){ cell.title = ddaysText; cell.className = " x-date-disabled"; } } if(ddMatch && format){ var fvalue = d.dateFormat(format); if(ddMatch.test(fvalue)){ cell.title = ddText.replace("%0", fvalue); cell.className = " x-date-disabled"; } } }; var i = 0; for(; i < startingPos; i++) { textEls[i].innerHTML = (++prevStart); d.setDate(d.getDate()+1); cells[i].className = "x-date-prevday"; setCellClass(this, cells[i]); } for(; i < days; i++){ intDay = i - startingPos + 1; textEls[i].innerHTML = (intDay); d.setDate(d.getDate()+1); cells[i].className = "x-date-active"; setCellClass(this, cells[i]); } var extraDays = 0; for(; i < 42; i++) { textEls[i].innerHTML = (++extraDays); d.setDate(d.getDate()+1); cells[i].className = "x-date-nextday"; setCellClass(this, cells[i]); } this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear()); if(!this.internalRender){ var main = this.el.dom.firstChild; var w = main.offsetWidth; this.el.setWidth(w + this.el.getBorderWidth("lr")); Ext.fly(main).setWidth(w); this.internalRender = true; if(Ext.isOpera && !this.secondPass){ main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px"; this.secondPass = true; this.update.defer(10, this, [date]); } } }, beforeDestroy : function() { this.mbtn.destroy(); this.todayBtn.destroy(); } }); Ext.reg('datepicker', Ext.DatePicker); Ext.TabPanel = Ext.extend(Ext.Panel, { monitorResize : true, deferredRender : true, tabWidth: 120, minTabWidth: 30, resizeTabs:false, enableTabScroll: false, scrollIncrement : 0, scrollRepeatInterval : 400, scrollDuration : .35, animScroll : true, tabPosition: 'top', baseCls: 'x-tab-panel', autoTabs : false, autoTabSelector:'div.x-tab', activeTab : null, tabMargin : 2, plain: false, wheelIncrement : 20, idDelimiter : '__', itemCls : 'x-tab-item', elements: 'body', headerAsText: false, frame: false, hideBorders:true, initComponent : function(){ this.frame = false; Ext.TabPanel.superclass.initComponent.call(this); this.addEvents( 'beforetabchange', 'tabchange', 'contextmenu' ); this.setLayout(new Ext.layout.CardLayout({ deferredRender: this.deferredRender })); if(this.tabPosition == 'top'){ this.elements += ',header'; this.stripTarget = 'header'; }else { this.elements += ',footer'; this.stripTarget = 'footer'; } if(!this.stack){ this.stack = Ext.TabPanel.AccessStack(); } this.initItems(); }, render : function(){ Ext.TabPanel.superclass.render.apply(this, arguments); if(this.activeTab !== undefined){ var item = this.activeTab; delete this.activeTab; this.setActiveTab(item); } }, onRender : function(ct, position){ Ext.TabPanel.superclass.onRender.call(this, ct, position); if(this.plain){ var pos = this.tabPosition == 'top' ? 'header' : 'footer'; this[pos].addClass('x-tab-panel-'+pos+'-plain'); } var st = this[this.stripTarget]; this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{ tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}}); this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'}); this.strip = new Ext.Element(this.stripWrap.dom.firstChild); this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'}); this.strip.createChild({cls:'x-clear'}); this.body.addClass('x-tab-panel-body-'+this.tabPosition); if(!this.itemTpl){ var tt = new Ext.Template( '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>', '<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">', '<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>', '</em></a></li>' ); tt.disableFormats = true; tt.compile(); Ext.TabPanel.prototype.itemTpl = tt; } this.items.each(this.initTab, this); }, afterRender : function(){ Ext.TabPanel.superclass.afterRender.call(this); if(this.autoTabs){ this.readTabs(false); } }, initEvents : function(){ Ext.TabPanel.superclass.initEvents.call(this); this.on('add', this.onAdd, this); this.on('remove', this.onRemove, this); this.strip.on('mousedown', this.onStripMouseDown, this); this.strip.on('click', this.onStripClick, this); this.strip.on('contextmenu', this.onStripContextMenu, this); if(this.enableTabScroll){ this.strip.on('mousewheel', this.onWheel, this); } }, findTargets : function(e){ var item = null; var itemEl = e.getTarget('li', this.strip); if(itemEl){ item = this.getComponent(itemEl.id.split(this.idDelimiter)[1]); if(item.disabled){ return { close : null, item : null, el : null }; } } return { close : e.getTarget('.x-tab-strip-close', this.strip), item : item, el : itemEl }; }, onStripMouseDown : function(e){ e.preventDefault(); if(e.button != 0){ return; } var t = this.findTargets(e); if(t.close){ this.remove(t.item); return; } if(t.item && t.item != this.activeTab){ this.setActiveTab(t.item); } }, onStripClick : function(e){ var t = this.findTargets(e); if(!t.close && t.item && t.item != this.activeTab){ this.setActiveTab(t.item); } }, onStripContextMenu : function(e){ e.preventDefault(); var t = this.findTargets(e); if(t.item){ this.fireEvent('contextmenu', this, t.item, e); } }, readTabs : function(removeExisting){ if(removeExisting === true){ this.items.each(function(item){ this.remove(item); }, this); } var tabs = this.el.query(this.autoTabSelector); for(var i = 0, len = tabs.length; i < len; i++){ var tab = tabs[i]; var title = tab.getAttribute('title'); tab.removeAttribute('title'); this.add({ title: title, el: tab }); } }, initTab : function(item, index){ var before = this.strip.dom.childNodes[index]; var cls = item.closable ? 'x-tab-strip-closable' : ''; if(item.disabled){ cls += ' x-item-disabled'; } if(item.iconCls){ cls += ' x-tab-with-icon'; } if(item.tabCls){ cls += ' ' + item.tabCls; } var p = { id: this.id + this.idDelimiter + item.getItemId(), text: item.title, cls: cls, iconCls: item.iconCls || '' }; var el = before ? this.itemTpl.insertBefore(before, p) : this.itemTpl.append(this.strip, p); Ext.fly(el).addClassOnOver('x-tab-strip-over'); if(item.tabTip){ Ext.fly(el).child('span.x-tab-strip-text', true).qtip = item.tabTip; } item.on('disable', this.onItemDisabled, this); item.on('enable', this.onItemEnabled, this); item.on('titlechange', this.onItemTitleChanged, this); item.on('beforeshow', this.onBeforeShowItem, this); }, onAdd : function(tp, item, index){ this.initTab(item, index); if(this.items.getCount() == 1){ this.syncSize(); } this.delegateUpdates(); }, onBeforeAdd : function(item){ var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item); if(existing){ this.setActiveTab(item); return false; } Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments); var es = item.elements; item.elements = es ? es.replace(',header', '') : es; item.border = (item.border === true); }, onRemove : function(tp, item){ Ext.removeNode(this.getTabEl(item)); this.stack.remove(item); if(item == this.activeTab){ var next = this.stack.next(); if(next){ this.setActiveTab(next); }else{ this.setActiveTab(0); } } this.delegateUpdates(); }, onBeforeShowItem : function(item){ if(item != this.activeTab){ this.setActiveTab(item); return false; } }, onItemDisabled : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).addClass('x-item-disabled'); } this.stack.remove(item); }, onItemEnabled : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).removeClass('x-item-disabled'); } }, onItemTitleChanged : function(item){ var el = this.getTabEl(item); if(el){ Ext.fly(el).child('span.x-tab-strip-text', true).innerHTML = item.title; } }, getTabEl : function(item){ var itemId = (typeof item === 'number')?this.items.items[item].getItemId() : item.getItemId(); return document.getElementById(this.id+this.idDelimiter+itemId); }, onResize : function(){ Ext.TabPanel.superclass.onResize.apply(this, arguments); this.delegateUpdates(); }, beginUpdate : function(){ this.suspendUpdates = true; }, endUpdate : function(){ this.suspendUpdates = false; this.delegateUpdates(); }, hideTabStripItem : function(item){ item = this.getComponent(item); var el = this.getTabEl(item); if(el){ el.style.display = 'none'; this.delegateUpdates(); } }, unhideTabStripItem : function(item){ item = this.getComponent(item); var el = this.getTabEl(item); if(el){ el.style.display = ''; this.delegateUpdates(); } }, delegateUpdates : function(){ if(this.suspendUpdates){ return; } if(this.resizeTabs && this.rendered){ this.autoSizeTabs(); } if(this.enableTabScroll && this.rendered){ this.autoScrollTabs(); } }, autoSizeTabs : function(){ var count = this.items.length; var ce = this.tabPosition != 'bottom' ? 'header' : 'footer'; var ow = this[ce].dom.offsetWidth; var aw = this[ce].dom.clientWidth; if(!this.resizeTabs || count < 1 || !aw){ return; } var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.tabMargin, this.tabWidth), this.minTabWidth); this.lastTabWidth = each; var lis = this.stripWrap.dom.getElementsByTagName('li'); for(var i = 0, len = lis.length-1; i < len; i++) { var li = lis[i]; var inner = li.childNodes[1].firstChild.firstChild; var tw = li.offsetWidth; var iw = inner.offsetWidth; inner.style.width = (each - (tw-iw)) + 'px'; } }, adjustBodyWidth : function(w){ if(this.header){ this.header.setWidth(w); } if(this.footer){ this.footer.setWidth(w); } return w; }, setActiveTab : function(item){ item = this.getComponent(item); if(!item || this.fireEvent('beforetabchange', this, item, this.activeTab) === false){ return; } if(!this.rendered){ this.activeTab = item; return; } if(this.activeTab != item){ if(this.activeTab){ var oldEl = this.getTabEl(this.activeTab); if(oldEl){ Ext.fly(oldEl).removeClass('x-tab-strip-active'); } this.activeTab.fireEvent('deactivate', this.activeTab); } var el = this.getTabEl(item); Ext.fly(el).addClass('x-tab-strip-active'); this.activeTab = item; this.stack.add(item); this.layout.setActiveItem(item); if(this.layoutOnTabChange && item.doLayout){ item.doLayout(); } if(this.scrolling){ this.scrollToTab(item, this.animScroll); } item.fireEvent('activate', item); this.fireEvent('tabchange', this, item); } }, getActiveTab : function(){ return this.activeTab || null; }, getItem : function(item){ return this.getComponent(item); }, autoScrollTabs : function(){ var count = this.items.length; var ow = this.header.dom.offsetWidth; var tw = this.header.dom.clientWidth; var wrap = this.stripWrap; var wd = wrap.dom; var cw = wd.offsetWidth; var pos = this.getScrollPos(); var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos; if(!this.enableTabScroll || count < 1 || cw < 20){ return; } if(l <= tw){ wd.scrollLeft = 0; wrap.setWidth(tw); if(this.scrolling){ this.scrolling = false; this.header.removeClass('x-tab-scrolling'); this.scrollLeft.hide(); this.scrollRight.hide(); if(Ext.isAir){ wd.style.marginLeft = ''; wd.style.marginRight = ''; } } }else{ if(!this.scrolling){ this.header.addClass('x-tab-scrolling'); if(Ext.isAir){ wd.style.marginLeft = '18px'; wd.style.marginRight = '18px'; } } tw -= wrap.getMargins('lr'); wrap.setWidth(tw > 20 ? tw : 20); if(!this.scrolling){ if(!this.scrollLeft){ this.createScrollers(); }else{ this.scrollLeft.show(); this.scrollRight.show(); } } this.scrolling = true; if(pos > (l-tw)){ wd.scrollLeft = l-tw; }else{ this.scrollToTab(this.activeTab, false); } this.updateScrollButtons(); } }, createScrollers : function(){ var h = this.stripWrap.dom.offsetHeight; var sl = this.header.insertFirst({ cls:'x-tab-scroller-left' }); sl.setHeight(h); sl.addClassOnOver('x-tab-scroller-left-over'); this.leftRepeater = new Ext.util.ClickRepeater(sl, { interval : this.scrollRepeatInterval, handler: this.onScrollLeft, scope: this }); this.scrollLeft = sl; var sr = this.header.insertFirst({ cls:'x-tab-scroller-right' }); sr.setHeight(h); sr.addClassOnOver('x-tab-scroller-right-over'); this.rightRepeater = new Ext.util.ClickRepeater(sr, { interval : this.scrollRepeatInterval, handler: this.onScrollRight, scope: this }); this.scrollRight = sr; }, getScrollWidth : function(){ return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos(); }, getScrollPos : function(){ return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0; }, getScrollArea : function(){ return parseInt(this.stripWrap.dom.clientWidth, 10) || 0; }, getScrollAnim : function(){ return {duration:this.scrollDuration, callback: this.updateScrollButtons, scope: this}; }, getScrollIncrement : function(){ return this.scrollIncrement || (this.resizeTabs ? this.lastTabWidth+2 : 100); }, scrollToTab : function(item, animate){ if(!item){ return; } var el = this.getTabEl(item); var pos = this.getScrollPos(), area = this.getScrollArea(); var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos; var right = left + el.offsetWidth; if(left < pos){ this.scrollTo(left, animate); }else if(right > (pos + area)){ this.scrollTo(right - area, animate); } }, scrollTo : function(pos, animate){ this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false); if(!animate){ this.updateScrollButtons(); } }, onWheel : function(e){ var d = e.getWheelDelta()*this.wheelIncrement*-1; e.stopEvent(); var pos = this.getScrollPos(); var newpos = pos + d; var sw = this.getScrollWidth()-this.getScrollArea(); var s = Math.max(0, Math.min(sw, newpos)); if(s != pos){ this.scrollTo(s, false); } }, onScrollRight : function(){ var sw = this.getScrollWidth()-this.getScrollArea(); var pos = this.getScrollPos(); var s = Math.min(sw, pos + this.getScrollIncrement()); if(s != pos){ this.scrollTo(s, this.animScroll); } }, onScrollLeft : function(){ var pos = this.getScrollPos(); var s = Math.max(0, pos - this.getScrollIncrement()); if(s != pos){ this.scrollTo(s, this.animScroll); } }, updateScrollButtons : function(){ var pos = this.getScrollPos(); this.scrollLeft[pos == 0 ? 'addClass' : 'removeClass']('x-tab-scroller-left-disabled'); this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('x-tab-scroller-right-disabled'); } }); Ext.reg('tabpanel', Ext.TabPanel); Ext.TabPanel.prototype.activate = Ext.TabPanel.prototype.setActiveTab; Ext.TabPanel.AccessStack = function(){ var items = []; return { add : function(item){ items.push(item); if(items.length > 10){ items.shift(); } }, remove : function(item){ var s = []; for(var i = 0, len = items.length; i < len; i++) { if(items[i] != item){ s.push(items[i]); } } items = s; }, next : function(){ return items.pop(); } }; }; Ext.Button = Ext.extend(Ext.Component, { hidden : false, disabled : false, pressed : false, enableToggle: false, menuAlign : "tl-bl?", type : 'button', menuClassTarget: 'tr', clickEvent : 'click', handleMouseEvents : true, tooltipType : 'qtip', buttonSelector : "button:first", initComponent : function(){ Ext.Button.superclass.initComponent.call(this); this.addEvents( "click", "toggle", 'mouseover', 'mouseout', 'menushow', 'menuhide', 'menutriggerover', 'menutriggerout' ); if(this.menu){ this.menu = Ext.menu.MenuMgr.get(this.menu); } if(typeof this.toggleGroup === 'string'){ this.enableToggle = true; } }, onRender : function(ct, position){ if(!this.template){ if(!Ext.Button.buttonTemplate){ Ext.Button.buttonTemplate = new Ext.Template( '<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap"><tbody><tr>', '<td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td><td class="x-btn-right"><i>&#160;</i></td>', "</tr></tbody></table>"); } this.template = Ext.Button.buttonTemplate; } var btn, targs = [this.text || '&#160;', this.type]; if(position){ btn = this.template.insertBefore(position, targs, true); }else{ btn = this.template.append(ct, targs, true); } var btnEl = btn.child(this.buttonSelector); btnEl.on('focus', this.onFocus, this); btnEl.on('blur', this.onBlur, this); this.initButtonEl(btn, btnEl); if(this.menu){ this.el.child(this.menuClassTarget).addClass("x-btn-with-menu"); } Ext.ButtonToggleMgr.register(this); }, initButtonEl : function(btn, btnEl){ this.el = btn; btn.addClass("x-btn"); if(this.icon){ btnEl.setStyle('background-image', 'url(' +this.icon +')'); } if(this.iconCls){ btnEl.addClass(this.iconCls); if(!this.cls){ btn.addClass(this.text ? 'x-btn-text-icon' : 'x-btn-icon'); } } if(this.tabIndex !== undefined){ btnEl.dom.tabIndex = this.tabIndex; } if(this.tooltip){ if(typeof this.tooltip == 'object'){ Ext.QuickTips.register(Ext.apply({ target: btnEl.id }, this.tooltip)); } else { btnEl.dom[this.tooltipType] = this.tooltip; } } if(this.pressed){ this.el.addClass("x-btn-pressed"); } if(this.handleMouseEvents){ btn.on("mouseover", this.onMouseOver, this); btn.on("mousedown", this.onMouseDown, this); } if(this.menu){ this.menu.on("show", this.onMenuShow, this); this.menu.on("hide", this.onMenuHide, this); } if(this.id){ this.el.dom.id = this.el.id = this.id; } if(this.repeat){ var repeater = new Ext.util.ClickRepeater(btn, typeof this.repeat == "object" ? this.repeat : {} ); repeater.on("click", this.onClick, this); } btn.on(this.clickEvent, this.onClick, this); }, afterRender : function(){ Ext.Button.superclass.afterRender.call(this); if(Ext.isIE6){ this.autoWidth.defer(1, this); }else{ this.autoWidth(); } }, setIconClass : function(cls){ if(this.el){ this.el.child(this.buttonSelector).replaceClass(this.iconCls, cls); } this.iconCls = cls; }, beforeDestroy: function(){ if(this.rendered){ var btn = this.el.child(this.buttonSelector); if(btn){ btn.removeAllListeners(); } } if(this.menu){ Ext.destroy(this.menu); } }, onDestroy : function(){ if(this.rendered){ Ext.ButtonToggleMgr.unregister(this); } }, autoWidth : function(){ if(this.el){ this.el.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child(this.buttonSelector); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if(this.el.getWidth() < this.minWidth){ this.el.setWidth(this.minWidth); } } } }, setHandler : function(handler, scope){ this.handler = handler; this.scope = scope; }, setText : function(text){ this.text = text; if(this.el){ this.el.child("td.x-btn-center " + this.buttonSelector).update(text); } this.autoWidth(); }, getText : function(){ return this.text; }, toggle : function(state){ state = state === undefined ? !this.pressed : state; if(state != this.pressed){ if(state){ this.el.addClass("x-btn-pressed"); this.pressed = true; this.fireEvent("toggle", this, true); }else{ this.el.removeClass("x-btn-pressed"); this.pressed = false; this.fireEvent("toggle", this, false); } if(this.toggleHandler){ this.toggleHandler.call(this.scope || this, this, state); } } }, focus : function(){ this.el.child(this.buttonSelector).focus(); }, onDisable : function(){ if(this.el){ if(!Ext.isIE6 || !this.text){ this.el.addClass(this.disabledClass); } this.el.dom.disabled = true; } this.disabled = true; }, onEnable : function(){ if(this.el){ if(!Ext.isIE6 || !this.text){ this.el.removeClass(this.disabledClass); } this.el.dom.disabled = false; } this.disabled = false; }, showMenu : function(){ if(this.menu){ this.menu.show(this.el, this.menuAlign); } return this; }, hideMenu : function(){ if(this.menu){ this.menu.hide(); } return this; }, hasVisibleMenu : function(){ return this.menu && this.menu.isVisible(); }, onClick : function(e){ if(e){ e.preventDefault(); } if(e.button != 0){ return; } if(!this.disabled){ if(this.enableToggle && (this.allowDepress !== false || !this.pressed)){ this.toggle(); } if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){ this.showMenu(); } this.fireEvent("click", this, e); if(this.handler){ this.handler.call(this.scope || this, this, e); } } }, isMenuTriggerOver : function(e, internal){ return this.menu && !internal; }, isMenuTriggerOut : function(e, internal){ return this.menu && !internal; }, onMouseOver : function(e){ if(!this.disabled){ var internal = e.within(this.el, true); if(!internal){ this.el.addClass("x-btn-over"); Ext.getDoc().on('mouseover', this.monitorMouseOver, this); this.fireEvent('mouseover', this, e); } if(this.isMenuTriggerOver(e, internal)){ this.fireEvent('menutriggerover', this, this.menu, e); } } }, monitorMouseOver : function(e){ if(e.target != this.el.dom && !e.within(this.el)){ Ext.getDoc().un('mouseover', this.monitorMouseOver, this); this.onMouseOut(e); } }, onMouseOut : function(e){ var internal = e.within(this.el) && e.target != this.el.dom; this.el.removeClass("x-btn-over"); this.fireEvent('mouseout', this, e); if(this.isMenuTriggerOut(e, internal)){ this.fireEvent('menutriggerout', this, this.menu, e); } }, onFocus : function(e){ if(!this.disabled){ this.el.addClass("x-btn-focus"); } }, onBlur : function(e){ this.el.removeClass("x-btn-focus"); }, getClickEl : function(e, isUp){ return this.el; }, onMouseDown : function(e){ if(!this.disabled && e.button == 0){ this.getClickEl(e).addClass("x-btn-click"); Ext.getDoc().on('mouseup', this.onMouseUp, this); } }, onMouseUp : function(e){ if(e.button == 0){ this.getClickEl(e, true).removeClass("x-btn-click"); Ext.getDoc().un('mouseup', this.onMouseUp, this); } }, onMenuShow : function(e){ this.ignoreNextClick = 0; this.el.addClass("x-btn-menu-active"); this.fireEvent('menushow', this, this.menu); }, onMenuHide : function(e){ this.el.removeClass("x-btn-menu-active"); this.ignoreNextClick = this.restoreClick.defer(250, this); this.fireEvent('menuhide', this, this.menu); }, restoreClick : function(){ this.ignoreNextClick = 0; } }); Ext.reg('button', Ext.Button); Ext.ButtonToggleMgr = function(){ var groups = {}; function toggleGroup(btn, state){ if(state){ var g = groups[btn.toggleGroup]; for(var i = 0, l = g.length; i < l; i++){ if(g[i] != btn){ g[i].toggle(false); } } } } return { register : function(btn){ if(!btn.toggleGroup){ return; } var g = groups[btn.toggleGroup]; if(!g){ g = groups[btn.toggleGroup] = []; } g.push(btn); btn.on("toggle", toggleGroup); }, unregister : function(btn){ if(!btn.toggleGroup){ return; } var g = groups[btn.toggleGroup]; if(g){ g.remove(btn); btn.un("toggle", toggleGroup); } } }; }(); Ext.SplitButton = Ext.extend(Ext.Button, { arrowSelector : 'button:last', initComponent : function(){ Ext.SplitButton.superclass.initComponent.call(this); this.addEvents("arrowclick"); }, onRender : function(ct, position){ var tpl = new Ext.Template( '<table cellspacing="0" class="x-btn-menu-wrap x-btn"><tr><td>', '<table cellspacing="0" class="x-btn-wrap x-btn-menu-text-wrap"><tbody>', '<tr><td class="x-btn-left"><i>&#160;</i></td><td class="x-btn-center"><button class="x-btn-text" type="{1}">{0}</button></td></tr>', "</tbody></table></td><td>", '<table cellspacing="0" class="x-btn-wrap x-btn-menu-arrow-wrap"><tbody>', '<tr><td class="x-btn-center"><button class="x-btn-menu-arrow-el" type="button">&#160;</button></td><td class="x-btn-right"><i>&#160;</i></td></tr>', "</tbody></table></td></tr></table>" ); var btn, targs = [this.text || '&#160;', this.type]; if(position){ btn = tpl.insertBefore(position, targs, true); }else{ btn = tpl.append(ct, targs, true); } var btnEl = btn.child(this.buttonSelector); this.initButtonEl(btn, btnEl); this.arrowBtnTable = btn.child("table:last"); if(this.arrowTooltip){ btn.child(this.arrowSelector).dom[this.tooltipType] = this.arrowTooltip; } }, autoWidth : function(){ if(this.el){ var tbl = this.el.child("table:first"); var tbl2 = this.el.child("table:last"); this.el.setWidth("auto"); tbl.setWidth("auto"); if(Ext.isIE7 && Ext.isStrict){ var ib = this.el.child(this.buttonSelector); if(ib && ib.getWidth() > 20){ ib.clip(); ib.setWidth(Ext.util.TextMetrics.measure(ib, this.text).width+ib.getFrameWidth('lr')); } } if(this.minWidth){ if((tbl.getWidth()+tbl2.getWidth()) < this.minWidth){ tbl.setWidth(this.minWidth-tbl2.getWidth()); } } this.el.setWidth(tbl.getWidth()+tbl2.getWidth()); } }, setArrowHandler : function(handler, scope){ this.arrowHandler = handler; this.scope = scope; }, onClick : function(e){ e.preventDefault(); if(!this.disabled){ if(e.getTarget(".x-btn-menu-arrow-wrap")){ if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){ this.showMenu(); } this.fireEvent("arrowclick", this, e); if(this.arrowHandler){ this.arrowHandler.call(this.scope || this, this, e); } }else{ if(this.enableToggle){ this.toggle(); } this.fireEvent("click", this, e); if(this.handler){ this.handler.call(this.scope || this, this, e); } } } }, getClickEl : function(e, isUp){ if(!isUp){ return (this.lastClickEl = e.getTarget("table", 10, true)); } return this.lastClickEl; }, onDisable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.addClass("x-item-disabled"); } this.el.child(this.buttonSelector).dom.disabled = true; this.el.child(this.arrowSelector).dom.disabled = true; } this.disabled = true; }, onEnable : function(){ if(this.el){ if(!Ext.isIE6){ this.el.removeClass("x-item-disabled"); } this.el.child(this.buttonSelector).dom.disabled = false; this.el.child(this.arrowSelector).dom.disabled = false; } this.disabled = false; }, isMenuTriggerOver : function(e){ return this.menu && e.within(this.arrowBtnTable) && !e.within(this.arrowBtnTable, true); }, isMenuTriggerOut : function(e, internal){ return this.menu && !e.within(this.arrowBtnTable); }, onDestroy : function(){ Ext.destroy(this.arrowBtnTable); Ext.SplitButton.superclass.onDestroy.call(this); } }); Ext.MenuButton = Ext.SplitButton; Ext.reg('splitbutton', Ext.SplitButton); Ext.CycleButton = Ext.extend(Ext.SplitButton, { getItemText : function(item){ if(item && this.showText === true){ var text = ''; if(this.prependText){ text += this.prependText; } text += item.text; return text; } return undefined; }, setActiveItem : function(item, suppressEvent){ if(typeof item != 'object'){ item = this.menu.items.get(item); } if(item){ if(!this.rendered){ this.text = this.getItemText(item); this.iconCls = item.iconCls; }else{ var t = this.getItemText(item); if(t){ this.setText(t); } this.setIconClass(item.iconCls); } this.activeItem = item; if(!item.checked){ item.setChecked(true, true); } if(this.forceIcon){ this.setIconClass(this.forceIcon); } if(!suppressEvent){ this.fireEvent('change', this, item); } } }, getActiveItem : function(){ return this.activeItem; }, initComponent : function(){ this.addEvents( "change" ); if(this.changeHandler){ this.on('change', this.changeHandler, this.scope||this); delete this.changeHandler; } this.itemCount = this.items.length; this.menu = {cls:'x-cycle-menu', items:[]}; var checked; for(var i = 0, len = this.itemCount; i < len; i++){ var item = this.items[i]; item.group = item.group || this.id; item.itemIndex = i; item.checkHandler = this.checkHandler; item.scope = this; item.checked = item.checked || false; this.menu.items.push(item); if(item.checked){ checked = item; } } this.setActiveItem(checked, true); Ext.CycleButton.superclass.initComponent.call(this); this.on('click', this.toggleSelected, this); }, checkHandler : function(item, pressed){ if(pressed){ this.setActiveItem(item); } }, toggleSelected : function(){ this.menu.render(); var nextIdx, checkItem; for (var i = 1; i < this.itemCount; i++) { nextIdx = (this.activeItem.itemIndex + i) % this.itemCount; checkItem = this.menu.items.itemAt(nextIdx); if (!checkItem.disabled) { checkItem.setChecked(true); break; } } } }); Ext.reg('cycle', Ext.CycleButton); Ext.Toolbar = function(config){ if(Ext.isArray(config)){ config = {buttons:config}; } Ext.Toolbar.superclass.constructor.call(this, config); }; (function(){ var T = Ext.Toolbar; Ext.extend(T, Ext.BoxComponent, { trackMenus : true, initComponent : function(){ T.superclass.initComponent.call(this); if(this.items){ this.buttons = this.items; } this.items = new Ext.util.MixedCollection(false, function(o){ return o.itemId || o.id || Ext.id(); }); }, autoCreate: { cls:'x-toolbar x-small-editor', html:'<table cellspacing="0"><tr></tr></table>' }, onRender : function(ct, position){ this.el = ct.createChild(Ext.apply({ id: this.id },this.autoCreate), position); this.tr = this.el.child("tr", true); }, afterRender : function(){ T.superclass.afterRender.call(this); if(this.buttons){ this.add.apply(this, this.buttons); delete this.buttons; } }, add : function(){ var a = arguments, l = a.length; for(var i = 0; i < l; i++){ var el = a[i]; if(el.isFormField){ this.addField(el); }else if(el.render){ this.addItem(el); }else if(typeof el == "string"){ if(el == "separator" || el == "-"){ this.addSeparator(); }else if(el == " "){ this.addSpacer(); }else if(el == "->"){ this.addFill(); }else{ this.addText(el); } }else if(el.tagName){ this.addElement(el); }else if(typeof el == "object"){ if(el.xtype){ this.addField(Ext.ComponentMgr.create(el, 'button')); }else{ this.addButton(el); } } } }, addSeparator : function(){ return this.addItem(new T.Separator()); }, addSpacer : function(){ return this.addItem(new T.Spacer()); }, addFill : function(){ return this.addItem(new T.Fill()); }, addElement : function(el){ return this.addItem(new T.Item(el)); }, addItem : function(item){ var td = this.nextBlock(); this.initMenuTracking(item); item.render(td); this.items.add(item); return item; }, addButton : function(config){ if(Ext.isArray(config)){ var buttons = []; for(var i = 0, len = config.length; i < len; i++) { buttons.push(this.addButton(config[i])); } return buttons; } var b = config; if(!(config instanceof T.Button)){ b = config.split ? new T.SplitButton(config) : new T.Button(config); } var td = this.nextBlock(); this.initMenuTracking(b); b.render(td); this.items.add(b); return b; }, initMenuTracking : function(item){ if(this.trackMenus && item.menu){ item.on({ 'menutriggerover' : this.onButtonTriggerOver, 'menushow' : this.onButtonMenuShow, 'menuhide' : this.onButtonMenuHide, scope: this }) } }, addText : function(text){ return this.addItem(new T.TextItem(text)); }, insertButton : function(index, item){ if(Ext.isArray(item)){ var buttons = []; for(var i = 0, len = item.length; i < len; i++) { buttons.push(this.insertButton(index + i, item[i])); } return buttons; } if (!(item instanceof T.Button)){ item = new T.Button(item); } var td = document.createElement("td"); this.tr.insertBefore(td, this.tr.childNodes[index]); this.initMenuTracking(item); item.render(td); this.items.insert(index, item); return item; }, addDom : function(config, returnEl){ var td = this.nextBlock(); Ext.DomHelper.overwrite(td, config); var ti = new T.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, addField : function(field){ var td = this.nextBlock(); field.render(td); var ti = new T.Item(td.firstChild); ti.render(td); this.items.add(ti); return ti; }, nextBlock : function(){ var td = document.createElement("td"); this.tr.appendChild(td); return td; }, onDestroy : function(){ Ext.Toolbar.superclass.onDestroy.call(this); if(this.rendered){ if(this.items){ Ext.destroy.apply(Ext, this.items.items); } Ext.Element.uncache(this.tr); } }, onDisable : function(){ this.items.each(function(item){ if(item.disable){ item.disable(); } }); }, onEnable : function(){ this.items.each(function(item){ if(item.enable){ item.enable(); } }); }, onButtonTriggerOver : function(btn){ if(this.activeMenuBtn && this.activeMenuBtn != btn){ this.activeMenuBtn.hideMenu(); btn.showMenu(); this.activeMenuBtn = btn; } }, onButtonMenuShow : function(btn){ this.activeMenuBtn = btn; }, onButtonMenuHide : function(btn){ delete this.activeMenuBtn; } }); Ext.reg('toolbar', Ext.Toolbar); T.Item = function(el){ this.el = Ext.getDom(el); this.id = Ext.id(this.el); this.hidden = false; }; T.Item.prototype = { getEl : function(){ return this.el; }, render : function(td){ this.td = td; td.appendChild(this.el); }, destroy : function(){ if(this.td && this.td.parentNode){ this.td.parentNode.removeChild(this.td); } }, show: function(){ this.hidden = false; this.td.style.display = ""; }, hide: function(){ this.hidden = true; this.td.style.display = "none"; }, setVisible: function(visible){ if(visible) { this.show(); }else{ this.hide(); } }, focus : function(){ Ext.fly(this.el).focus(); }, disable : function(){ Ext.fly(this.td).addClass("x-item-disabled"); this.disabled = true; this.el.disabled = true; }, enable : function(){ Ext.fly(this.td).removeClass("x-item-disabled"); this.disabled = false; this.el.disabled = false; } }; Ext.reg('tbitem', T.Item); T.Separator = function(){ var s = document.createElement("span"); s.className = "ytb-sep"; T.Separator.superclass.constructor.call(this, s); }; Ext.extend(T.Separator, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbseparator', T.Separator); T.Spacer = function(){ var s = document.createElement("div"); s.className = "ytb-spacer"; T.Spacer.superclass.constructor.call(this, s); }; Ext.extend(T.Spacer, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbspacer', T.Spacer); T.Fill = Ext.extend(T.Spacer, { render : function(td){ td.style.width = '100%'; T.Fill.superclass.render.call(this, td); } }); Ext.reg('tbfill', T.Fill); T.TextItem = function(t){ var s = document.createElement("span"); s.className = "ytb-text"; s.innerHTML = t.text ? t.text : t; T.TextItem.superclass.constructor.call(this, s); }; Ext.extend(T.TextItem, T.Item, { enable:Ext.emptyFn, disable:Ext.emptyFn, focus:Ext.emptyFn }); Ext.reg('tbtext', T.TextItem); T.Button = Ext.extend(Ext.Button, { hideParent : true, onDestroy : function(){ T.Button.superclass.onDestroy.call(this); if(this.container){ this.container.remove(); } } }); Ext.reg('tbbutton', T.Button); T.SplitButton = Ext.extend(Ext.SplitButton, { hideParent : true, onDestroy : function(){ T.SplitButton.superclass.onDestroy.call(this); if(this.container){ this.container.remove(); } } }); Ext.reg('tbsplit', T.SplitButton); T.MenuButton = T.SplitButton; })(); Ext.PagingToolbar = Ext.extend(Ext.Toolbar, { pageSize: 20, displayMsg : 'Displaying {0} - {1} of {2}', emptyMsg : 'No data to display', beforePageText : "Page", afterPageText : "of {0}", firstText : "First Page", prevText : "Previous Page", nextText : "Next Page", lastText : "Last Page", refreshText : "Refresh", paramNames : {start: 'start', limit: 'limit'}, initComponent : function(){ Ext.PagingToolbar.superclass.initComponent.call(this); this.cursor = 0; this.bind(this.store); }, onRender : function(ct, position){ Ext.PagingToolbar.superclass.onRender.call(this, ct, position); this.first = this.addButton({ tooltip: this.firstText, iconCls: "x-tbar-page-first", disabled: true, handler: this.onClick.createDelegate(this, ["first"]) }); this.prev = this.addButton({ tooltip: this.prevText, iconCls: "x-tbar-page-prev", disabled: true, handler: this.onClick.createDelegate(this, ["prev"]) }); this.addSeparator(); this.add(this.beforePageText); this.field = Ext.get(this.addDom({ tag: "input", type: "text", size: "3", value: "1", cls: "x-tbar-page-number" }).el); this.field.on("keydown", this.onPagingKeydown, this); this.field.on("focus", function(){this.dom.select();}); this.afterTextEl = this.addText(String.format(this.afterPageText, 1)); this.field.setHeight(18); this.addSeparator(); this.next = this.addButton({ tooltip: this.nextText, iconCls: "x-tbar-page-next", disabled: true, handler: this.onClick.createDelegate(this, ["next"]) }); this.last = this.addButton({ tooltip: this.lastText, iconCls: "x-tbar-page-last", disabled: true, handler: this.onClick.createDelegate(this, ["last"]) }); this.addSeparator(); this.loading = this.addButton({ tooltip: this.refreshText, iconCls: "x-tbar-loading", handler: this.onClick.createDelegate(this, ["refresh"]) }); if(this.displayInfo){ this.displayEl = Ext.fly(this.el.dom).createChild({cls:'x-paging-info'}); } if(this.dsLoaded){ this.onLoad.apply(this, this.dsLoaded); } }, updateInfo : function(){ if(this.displayEl){ var count = this.store.getCount(); var msg = count == 0 ? this.emptyMsg : String.format( this.displayMsg, this.cursor+1, this.cursor+count, this.store.getTotalCount() ); this.displayEl.update(msg); } }, onLoad : function(store, r, o){ if(!this.rendered){ this.dsLoaded = [store, r, o]; return; } this.cursor = o.params ? o.params[this.paramNames.start] : 0; var d = this.getPageData(), ap = d.activePage, ps = d.pages; this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages); this.field.dom.value = ap; this.first.setDisabled(ap == 1); this.prev.setDisabled(ap == 1); this.next.setDisabled(ap == ps); this.last.setDisabled(ap == ps); this.loading.enable(); this.updateInfo(); }, getPageData : function(){ var total = this.store.getTotalCount(); return { total : total, activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize), pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize) }; }, onLoadError : function(){ if(!this.rendered){ return; } this.loading.enable(); }, readPage : function(d){ var v = this.field.dom.value, pageNum; if (!v || isNaN(pageNum = parseInt(v, 10))) { this.field.dom.value = d.activePage; return false; } return pageNum; }, onPagingKeydown : function(e){ var k = e.getKey(), d = this.getPageData(), pageNum; if (k == e.RETURN) { e.stopEvent(); if(pageNum = this.readPage(d)){ pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1; this.doLoad(pageNum * this.pageSize); } }else if (k == e.HOME || k == e.END){ e.stopEvent(); pageNum = k == e.HOME ? 1 : d.pages; this.field.dom.value = pageNum; }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){ e.stopEvent(); if(pageNum = this.readPage(d)){ var increment = e.shiftKey ? 10 : 1; if(k == e.DOWN || k == e.PAGEDOWN){ increment *= -1; } pageNum += increment; if(pageNum >= 1 & pageNum <= d.pages){ this.field.dom.value = pageNum; } } } }, beforeLoad : function(){ if(this.rendered && this.loading){ this.loading.disable(); } }, doLoad : function(start){ var o = {}, pn = this.paramNames; o[pn.start] = start; o[pn.limit] = this.pageSize; this.store.load({params:o}); }, onClick : function(which){ var store = this.store; switch(which){ case "first": this.doLoad(0); break; case "prev": this.doLoad(Math.max(0, this.cursor-this.pageSize)); break; case "next": this.doLoad(this.cursor+this.pageSize); break; case "last": var total = store.getTotalCount(); var extra = total % this.pageSize; var lastStart = extra ? (total - extra) : total-this.pageSize; this.doLoad(lastStart); break; case "refresh": this.doLoad(this.cursor); break; } }, unbind : function(store){ store = Ext.StoreMgr.lookup(store); store.un("beforeload", this.beforeLoad, this); store.un("load", this.onLoad, this); store.un("loadexception", this.onLoadError, this); this.store = undefined; }, bind : function(store){ store = Ext.StoreMgr.lookup(store); store.on("beforeload", this.beforeLoad, this); store.on("load", this.onLoad, this); store.on("loadexception", this.onLoadError, this); this.store = store; } }); Ext.reg('paging', Ext.PagingToolbar); Ext.Resizable = function(el, config){ this.el = Ext.get(el); if(config && config.wrap){ config.resizeChild = this.el; this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"}); this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap"; this.el.setStyle("overflow", "hidden"); this.el.setPositioning(config.resizeChild.getPositioning()); config.resizeChild.clearPositioning(); if(!config.width || !config.height){ var csize = config.resizeChild.getSize(); this.el.setSize(csize.width, csize.height); } if(config.pinned && !config.adjustments){ config.adjustments = "auto"; } } this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"}); this.proxy.unselectable(); this.proxy.enableDisplayMode('block'); Ext.apply(this, config); if(this.pinned){ this.disableTrackOver = true; this.el.addClass("x-resizable-pinned"); } var position = this.el.getStyle("position"); if(position != "absolute" && position != "fixed"){ this.el.setStyle("position", "relative"); } if(!this.handles){ this.handles = 's,e,se'; if(this.multiDirectional){ this.handles += ',n,w'; } } if(this.handles == "all"){ this.handles = "n s e w ne nw se sw"; } var hs = this.handles.split(/\s*?[,;]\s*?| /); var ps = Ext.Resizable.positions; for(var i = 0, len = hs.length; i < len; i++){ if(hs[i] && ps[hs[i]]){ var pos = ps[hs[i]]; this[pos] = new Ext.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent); } } this.corner = this.southeast; if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1){ this.updateBox = true; } this.activeHandle = null; if(this.resizeChild){ if(typeof this.resizeChild == "boolean"){ this.resizeChild = Ext.get(this.el.dom.firstChild, true); }else{ this.resizeChild = Ext.get(this.resizeChild, true); } } if(this.adjustments == "auto"){ var rc = this.resizeChild; var hw = this.west, he = this.east, hn = this.north, hs = this.south; if(rc && (hw || hn)){ rc.position("relative"); rc.setLeft(hw ? hw.el.getWidth() : 0); rc.setTop(hn ? hn.el.getHeight() : 0); } this.adjustments = [ (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0), (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1 ]; } if(this.draggable){ this.dd = this.dynamic ? this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id}); this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id); } this.addEvents( "beforeresize", "resize" ); if(this.width !== null && this.height !== null){ this.resizeTo(this.width, this.height); }else{ this.updateChildSize(); } if(Ext.isIE){ this.el.dom.style.zoom = 1; } Ext.Resizable.superclass.constructor.call(this); }; Ext.extend(Ext.Resizable, Ext.util.Observable, { resizeChild : false, adjustments : [0, 0], minWidth : 5, minHeight : 5, maxWidth : 10000, maxHeight : 10000, enabled : true, animate : false, duration : .35, dynamic : false, handles : false, multiDirectional : false, disableTrackOver : false, easing : 'easeOutStrong', widthIncrement : 0, heightIncrement : 0, pinned : false, width : null, height : null, preserveRatio : false, transparent: false, minX: 0, minY: 0, draggable: false, resizeTo : function(width, height){ this.el.setSize(width, height); this.updateChildSize(); this.fireEvent("resize", this, width, height, null); }, startSizing : function(e, handle){ this.fireEvent("beforeresize", this, e); if(this.enabled){ if(!this.overlay){ this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"}, Ext.getBody()); this.overlay.unselectable(); this.overlay.enableDisplayMode("block"); this.overlay.on("mousemove", this.onMouseMove, this); this.overlay.on("mouseup", this.onMouseUp, this); } this.overlay.setStyle("cursor", handle.el.getStyle("cursor")); this.resizing = true; this.startBox = this.el.getBox(); this.startPoint = e.getXY(); this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0], (this.startBox.y + this.startBox.height) - this.startPoint[1]]; this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)); this.overlay.show(); if(this.constrainTo) { var ct = Ext.get(this.constrainTo); this.resizeRegion = ct.getRegion().adjust( ct.getFrameWidth('t'), ct.getFrameWidth('l'), -ct.getFrameWidth('b'), -ct.getFrameWidth('r') ); } this.proxy.setStyle('visibility', 'hidden'); this.proxy.show(); this.proxy.setBox(this.startBox); if(!this.dynamic){ this.proxy.setStyle('visibility', 'visible'); } } }, onMouseDown : function(handle, e){ if(this.enabled){ e.stopEvent(); this.activeHandle = handle; this.startSizing(e, handle); } }, onMouseUp : function(e){ var size = this.resizeElement(); this.resizing = false; this.handleOut(); this.overlay.hide(); this.proxy.hide(); this.fireEvent("resize", this, size.width, size.height, e); }, updateChildSize : function(){ if(this.resizeChild){ var el = this.el; var child = this.resizeChild; var adj = this.adjustments; if(el.dom.offsetWidth){ var b = el.getSize(true); child.setSize(b.width+adj[0], b.height+adj[1]); } if(Ext.isIE){ setTimeout(function(){ if(el.dom.offsetWidth){ var b = el.getSize(true); child.setSize(b.width+adj[0], b.height+adj[1]); } }, 10); } } }, snap : function(value, inc, min){ if(!inc || !value) return value; var newValue = value; var m = value % inc; if(m > 0){ if(m > (inc/2)){ newValue = value + (inc-m); }else{ newValue = value - m; } } return Math.max(min, newValue); }, resizeElement : function(){ var box = this.proxy.getBox(); if(this.updateBox){ this.el.setBox(box, false, this.animate, this.duration, null, this.easing); }else{ this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing); } this.updateChildSize(); if(!this.dynamic){ this.proxy.hide(); } return box; }, constrain : function(v, diff, m, mx){ if(v - diff < m){ diff = v - m; }else if(v - diff > mx){ diff = mx - v; } return diff; }, onMouseMove : function(e){ if(this.enabled){ try{ if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) { return; } var curSize = this.curSize || this.startBox; var x = this.startBox.x, y = this.startBox.y; var ox = x, oy = y; var w = curSize.width, h = curSize.height; var ow = w, oh = h; var mw = this.minWidth, mh = this.minHeight; var mxw = this.maxWidth, mxh = this.maxHeight; var wi = this.widthIncrement; var hi = this.heightIncrement; var eventXY = e.getXY(); var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0])); var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1])); var pos = this.activeHandle.position; switch(pos){ case "east": w += diffX; w = Math.min(Math.max(mw, w), mxw); break; case "south": h += diffY; h = Math.min(Math.max(mh, h), mxh); break; case "southeast": w += diffX; h += diffY; w = Math.min(Math.max(mw, w), mxw); h = Math.min(Math.max(mh, h), mxh); break; case "north": diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; break; case "west": diffX = this.constrain(w, diffX, mw, mxw); x += diffX; w -= diffX; break; case "northeast": w += diffX; w = Math.min(Math.max(mw, w), mxw); diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; break; case "northwest": diffX = this.constrain(w, diffX, mw, mxw); diffY = this.constrain(h, diffY, mh, mxh); y += diffY; h -= diffY; x += diffX; w -= diffX; break; case "southwest": diffX = this.constrain(w, diffX, mw, mxw); h += diffY; h = Math.min(Math.max(mh, h), mxh); x += diffX; w -= diffX; break; } var sw = this.snap(w, wi, mw); var sh = this.snap(h, hi, mh); if(sw != w || sh != h){ switch(pos){ case "northeast": y -= sh - h; break; case "north": y -= sh - h; break; case "southwest": x -= sw - w; break; case "west": x -= sw - w; break; case "northwest": x -= sw - w; y -= sh - h; break; } w = sw; h = sh; } if(this.preserveRatio){ switch(pos){ case "southeast": case "east": h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); w = ow * (h/oh); break; case "south": w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); break; case "northeast": w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); break; case "north": var tw = w; w = ow * (h/oh); w = Math.min(Math.max(mw, w), mxw); h = oh * (w/ow); x += (tw - w) / 2; break; case "southwest": h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); var tw = w; w = ow * (h/oh); x += tw - w; break; case "west": var th = h; h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); y += (th - h) / 2; var tw = w; w = ow * (h/oh); x += tw - w; break; case "northwest": var tw = w; var th = h; h = oh * (w/ow); h = Math.min(Math.max(mh, h), mxh); w = ow * (h/oh); y += th - h; x += tw - w; break; } } this.proxy.setBounds(x, y, w, h); if(this.dynamic){ this.resizeElement(); } }catch(e){} } }, handleOver : function(){ if(this.enabled){ this.el.addClass("x-resizable-over"); } }, handleOut : function(){ if(!this.resizing){ this.el.removeClass("x-resizable-over"); } }, getEl : function(){ return this.el; }, getResizeChild : function(){ return this.resizeChild; }, destroy : function(removeEl){ this.proxy.remove(); if(this.overlay){ this.overlay.removeAllListeners(); this.overlay.remove(); } var ps = Ext.Resizable.positions; for(var k in ps){ if(typeof ps[k] != "function" && this[ps[k]]){ var h = this[ps[k]]; h.el.removeAllListeners(); h.el.remove(); } } if(removeEl){ this.el.update(""); this.el.remove(); } }, syncHandleHeight : function(){ var h = this.el.getHeight(true); if(this.west){ this.west.el.setHeight(h); } if(this.east){ this.east.el.setHeight(h); } } }); Ext.Resizable.positions = { n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast" }; Ext.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){ if(!this.tpl){ var tpl = Ext.DomHelper.createTemplate( {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"} ); tpl.compile(); Ext.Resizable.Handle.prototype.tpl = tpl; } this.position = pos; this.rz = rz; this.el = this.tpl.append(rz.el.dom, [this.position], true); this.el.unselectable(); if(transparent){ this.el.setOpacity(0); } this.el.on("mousedown", this.onMouseDown, this); if(!disableTrackOver){ this.el.on("mouseover", this.onMouseOver, this); this.el.on("mouseout", this.onMouseOut, this); } }; Ext.Resizable.Handle.prototype = { afterResize : function(rz){ }, onMouseDown : function(e){ this.rz.onMouseDown(this, e); }, onMouseOver : function(e){ this.rz.handleOver(this, e); }, onMouseOut : function(e){ this.rz.handleOut(this, e); } }; Ext.Editor = function(field, config){ this.field = field; Ext.Editor.superclass.constructor.call(this, config); }; Ext.extend(Ext.Editor, Ext.Component, { value : "", alignment: "c-c?", shadow : "frame", constrain : false, swallowKeys : true, completeOnEnter : false, cancelOnEsc : false, updateEl : false, initComponent : function(){ Ext.Editor.superclass.initComponent.call(this); this.addEvents( "beforestartedit", "startedit", "beforecomplete", "complete", "specialkey" ); }, onRender : function(ct, position){ this.el = new Ext.Layer({ shadow: this.shadow, cls: "x-editor", parentEl : ct, shim : this.shim, shadowOffset:4, id: this.id, constrain: this.constrain }); this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden"); if(this.field.msgTarget != 'title'){ this.field.msgTarget = 'qtip'; } this.field.inEditor = true; this.field.render(this.el); if(Ext.isGecko){ this.field.el.dom.setAttribute('autocomplete', 'off'); } this.field.on("specialkey", this.onSpecialKey, this); if(this.swallowKeys){ this.field.el.swallowEvent(['keydown','keypress']); } this.field.show(); this.field.on("blur", this.onBlur, this); if(this.field.grow){ this.field.on("autosize", this.el.sync, this.el, {delay:1}); } }, onSpecialKey : function(field, e){ if(this.completeOnEnter && e.getKey() == e.ENTER){ e.stopEvent(); this.completeEdit(); }else if(this.cancelOnEsc && e.getKey() == e.ESC){ this.cancelEdit(); }else{ this.fireEvent('specialkey', field, e); } }, startEdit : function(el, value){ if(this.editing){ this.completeEdit(); } this.boundEl = Ext.get(el); var v = value !== undefined ? value : this.boundEl.dom.innerHTML; if(!this.rendered){ this.render(this.parentEl || document.body); } if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){ return; } this.startValue = v; this.field.setValue(v); this.doAutoSize(); this.el.alignTo(this.boundEl, this.alignment); this.editing = true; this.show(); }, doAutoSize : function(){ if(this.autoSize){ var sz = this.boundEl.getSize(); switch(this.autoSize){ case "width": this.setSize(sz.width, ""); break; case "height": this.setSize("", sz.height); break; default: this.setSize(sz.width, sz.height); } } }, setSize : function(w, h){ delete this.field.lastSize; this.field.setSize(w, h); if(this.el){ this.el.sync(); } }, realign : function(){ this.el.alignTo(this.boundEl, this.alignment); }, completeEdit : function(remainVisible){ if(!this.editing){ return; } var v = this.getValue(); if(this.revertInvalid !== false && !this.field.isValid()){ v = this.startValue; this.cancelEdit(true); } if(String(v) === String(this.startValue) && this.ignoreNoChange){ this.editing = false; this.hide(); return; } if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){ this.editing = false; if(this.updateEl && this.boundEl){ this.boundEl.update(v); } if(remainVisible !== true){ this.hide(); } this.fireEvent("complete", this, v, this.startValue); } }, onShow : function(){ this.el.show(); if(this.hideEl !== false){ this.boundEl.hide(); } this.field.show(); if(Ext.isIE && !this.fixIEFocus){ this.fixIEFocus = true; this.deferredFocus.defer(50, this); }else{ this.field.focus(); } this.fireEvent("startedit", this.boundEl, this.startValue); }, deferredFocus : function(){ if(this.editing){ this.field.focus(); } }, cancelEdit : function(remainVisible){ if(this.editing){ this.setValue(this.startValue); if(remainVisible !== true){ this.hide(); } } }, onBlur : function(){ if(this.allowBlur !== true && this.editing){ this.completeEdit(); } }, onHide : function(){ if(this.editing){ this.completeEdit(); return; } this.field.blur(); if(this.field.collapse){ this.field.collapse(); } this.el.hide(); if(this.hideEl !== false){ this.boundEl.show(); } }, setValue : function(v){ this.field.setValue(v); }, getValue : function(){ return this.field.getValue(); }, beforeDestroy : function(){ this.field.destroy(); this.field = null; } }); Ext.reg('editor', Ext.Editor); Ext.MessageBox = function(){ var dlg, opt, mask, waitTimer; var bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl; var buttons, activeTextEl, bwidth, iconCls = ''; var handleButton = function(button){ dlg.hide(); Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1); }; var handleHide = function(){ if(opt && opt.cls){ dlg.el.removeClass(opt.cls); } progressBar.reset(); }; var handleEsc = function(d, k, e){ if(opt && opt.closable !== false){ dlg.hide(); } if(e){ e.stopEvent(); } }; var updateButtons = function(b){ var width = 0; if(!b){ buttons["ok"].hide(); buttons["cancel"].hide(); buttons["yes"].hide(); buttons["no"].hide(); return width; } dlg.footer.dom.style.display = ''; for(var k in buttons){ if(typeof buttons[k] != "function"){ if(b[k]){ buttons[k].show(); buttons[k].setText(typeof b[k] == "string" ? b[k] : Ext.MessageBox.buttonText[k]); width += buttons[k].el.getWidth()+15; }else{ buttons[k].hide(); } } } return width; }; return { getDialog : function(titleText){ if(!dlg){ dlg = new Ext.Window({ autoCreate : true, title:titleText, resizable:false, constrain:true, constrainHeader:true, minimizable : false, maximizable : false, stateful: false, modal: true, shim:true, buttonAlign:"center", width:400, height:100, minHeight: 80, plain:true, footer:true, closable:true, close : function(){ if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){ handleButton("no"); }else{ handleButton("cancel"); } } }); buttons = {}; var bt = this.buttonText; buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok")); buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes")); buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no")); buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel")); buttons["ok"].hideMode = buttons["yes"].hideMode = buttons["no"].hideMode = buttons["cancel"].hideMode = 'offsets'; dlg.render(document.body); dlg.getEl().addClass('x-window-dlg'); mask = dlg.mask; bodyEl = dlg.body.createChild({ html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div>' }); iconEl = Ext.get(bodyEl.dom.firstChild); var contentEl = bodyEl.dom.childNodes[1]; msgEl = Ext.get(contentEl.firstChild); textboxEl = Ext.get(contentEl.childNodes[2]); textboxEl.enableDisplayMode(); textboxEl.addKeyListener([10,13], function(){ if(dlg.isVisible() && opt && opt.buttons){ if(opt.buttons.ok){ handleButton("ok"); }else if(opt.buttons.yes){ handleButton("yes"); } } }); textareaEl = Ext.get(contentEl.childNodes[3]); textareaEl.enableDisplayMode(); progressBar = new Ext.ProgressBar({ renderTo:bodyEl }); bodyEl.createChild({cls:'x-clear'}); } return dlg; }, updateText : function(text){ if(!dlg.isVisible() && !opt.width){ dlg.setSize(this.maxWidth, 100); } msgEl.update(text || '&#160;'); var iw = iconCls != '' ? (iconEl.getWidth() + iconEl.getMargins('lr')) : 0; var mw = msgEl.getWidth() + msgEl.getMargins('lr'); var fw = dlg.getFrameWidth('lr'); var bw = dlg.body.getFrameWidth('lr'); if (Ext.isIE && iw > 0){ iw += 3; } var w = Math.max(Math.min(opt.width || iw+mw+fw+bw, this.maxWidth), Math.max(opt.minWidth || this.minWidth, bwidth || 0)); if(opt.prompt === true){ activeTextEl.setWidth(w-iw-fw-bw); } if(opt.progress === true || opt.wait === true){ progressBar.setSize(w-iw-fw-bw); } dlg.setSize(w, 'auto').center(); return this; }, updateProgress : function(value, progressText, msg){ progressBar.updateProgress(value, progressText); if(msg){ this.updateText(msg); } return this; }, isVisible : function(){ return dlg && dlg.isVisible(); }, hide : function(){ if(this.isVisible()){ dlg.hide(); handleHide(); } return this; }, show : function(options){ if(this.isVisible()){ this.hide(); } opt = options; var d = this.getDialog(opt.title || "&#160;"); d.setTitle(opt.title || "&#160;"); var allowClose = (opt.closable !== false && opt.progress !== true && opt.wait !== true); d.tools.close.setDisplayed(allowClose); activeTextEl = textboxEl; opt.prompt = opt.prompt || (opt.multiline ? true : false); if(opt.prompt){ if(opt.multiline){ textboxEl.hide(); textareaEl.show(); textareaEl.setHeight(typeof opt.multiline == "number" ? opt.multiline : this.defaultTextHeight); activeTextEl = textareaEl; }else{ textboxEl.show(); textareaEl.hide(); } }else{ textboxEl.hide(); textareaEl.hide(); } activeTextEl.dom.value = opt.value || ""; if(opt.prompt){ d.focusEl = activeTextEl; }else{ var bs = opt.buttons; var db = null; if(bs && bs.ok){ db = buttons["ok"]; }else if(bs && bs.yes){ db = buttons["yes"]; } if (db){ d.focusEl = db; } } this.setIcon(opt.icon); bwidth = updateButtons(opt.buttons); progressBar.setVisible(opt.progress === true || opt.wait === true); this.updateProgress(0, opt.progressText); this.updateText(opt.msg); if(opt.cls){ d.el.addClass(opt.cls); } d.proxyDrag = opt.proxyDrag === true; d.modal = opt.modal !== false; d.mask = opt.modal !== false ? mask : false; if(!d.isVisible()){ document.body.appendChild(dlg.el.dom); d.setAnimateTarget(opt.animEl); d.show(opt.animEl); } d.on('show', function(){ if(allowClose === true){ d.keyMap.enable(); }else{ d.keyMap.disable(); } }, this, {single:true}); if(opt.wait === true){ progressBar.wait(opt.waitConfig); } return this; }, setIcon : function(icon){ if(icon && icon != ''){ iconEl.removeClass('x-hidden'); iconEl.replaceClass(iconCls, icon); iconCls = icon; }else{ iconEl.replaceClass(iconCls, 'x-hidden'); iconCls = ''; } return this; }, progress : function(title, msg, progressText){ this.show({ title : title, msg : msg, buttons: false, progress:true, closable:false, minWidth: this.minProgressWidth, progressText: progressText }); return this; }, wait : function(msg, title, config){ this.show({ title : title, msg : msg, buttons: false, closable:false, wait:true, modal:true, minWidth: this.minProgressWidth, waitConfig: config }); return this; }, alert : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.OK, fn: fn, scope : scope }); return this; }, confirm : function(title, msg, fn, scope){ this.show({ title : title, msg : msg, buttons: this.YESNO, fn: fn, scope : scope, icon: this.QUESTION }); return this; }, prompt : function(title, msg, fn, scope, multiline){ this.show({ title : title, msg : msg, buttons: this.OKCANCEL, fn: fn, minWidth:250, scope : scope, prompt:true, multiline: multiline }); return this; }, OK : {ok:true}, CANCEL : {cancel:true}, OKCANCEL : {ok:true, cancel:true}, YESNO : {yes:true, no:true}, YESNOCANCEL : {yes:true, no:true, cancel:true}, INFO : 'ext-mb-info', WARNING : 'ext-mb-warning', QUESTION : 'ext-mb-question', ERROR : 'ext-mb-error', defaultTextHeight : 75, maxWidth : 600, minWidth : 100, minProgressWidth : 250, buttonText : { ok : "OK", cancel : "Cancel", yes : "Yes", no : "No" } }; }(); Ext.Msg = Ext.MessageBox; Ext.Tip = Ext.extend(Ext.Panel, { minWidth : 40, maxWidth : 300, shadow : "sides", defaultAlign : "tl-bl?", autoRender: true, quickShowInterval : 250, frame:true, hidden:true, baseCls: 'x-tip', floating:{shadow:true,shim:true,useDisplay:true,constrain:false}, autoHeight:true, initComponent : function(){ Ext.Tip.superclass.initComponent.call(this); if(this.closable && !this.title){ this.elements += ',header'; } }, afterRender : function(){ Ext.Tip.superclass.afterRender.call(this); if(this.closable){ this.addTool({ id: 'close', handler: this.hide, scope: this }); } }, showAt : function(xy){ Ext.Tip.superclass.show.call(this); if(this.measureWidth !== false && (!this.initialConfig || typeof this.initialConfig.width != 'number')){ var bw = this.body.getTextWidth(); if(this.title){ bw = Math.max(bw, this.header.child('span').getTextWidth(this.title)); } bw += this.getFrameWidth() + (this.closable ? 20 : 0) + this.body.getPadding("lr"); this.setWidth(bw.constrain(this.minWidth, this.maxWidth)); } if(this.constrainPosition){ xy = this.el.adjustForConstraints(xy); } this.setPagePosition(xy[0], xy[1]); }, showBy : function(el, pos){ if(!this.rendered){ this.render(Ext.getBody()); } this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign)); }, initDraggable : function(){ this.dd = new Ext.Tip.DD(this, typeof this.draggable == 'boolean' ? null : this.draggable); this.header.addClass('x-tip-draggable'); } }); Ext.Tip.DD = function(tip, config){ Ext.apply(this, config); this.tip = tip; Ext.Tip.DD.superclass.constructor.call(this, tip.el.id, 'WindowDD-'+tip.id); this.setHandleElId(tip.header.id); this.scroll = false; }; Ext.extend(Ext.Tip.DD, Ext.dd.DD, { moveOnly:true, scroll:false, headerOffsets:[100, 25], startDrag : function(){ this.tip.el.disableShadow(); }, endDrag : function(e){ this.tip.el.enableShadow(true); } }); Ext.ToolTip = Ext.extend(Ext.Tip, { showDelay: 500, hideDelay: 200, dismissDelay: 5000, mouseOffset: [15,18], trackMouse : false, constrainPosition: true, initComponent: function(){ Ext.ToolTip.superclass.initComponent.call(this); this.lastActive = new Date(); this.initTarget(); }, initTarget : function(){ if(this.target){ this.target = Ext.get(this.target); this.target.on('mouseover', this.onTargetOver, this); this.target.on('mouseout', this.onTargetOut, this); this.target.on('mousemove', this.onMouseMove, this); } }, onMouseMove : function(e){ this.targetXY = e.getXY(); if(!this.hidden && this.trackMouse){ this.setPagePosition(this.getTargetXY()); } }, getTargetXY : function(){ return [this.targetXY[0]+this.mouseOffset[0], this.targetXY[1]+this.mouseOffset[1]]; }, onTargetOver : function(e){ if(this.disabled || e.within(this.target.dom, true)){ return; } this.clearTimer('hide'); this.targetXY = e.getXY(); this.delayShow(); }, delayShow : function(){ if(this.hidden && !this.showTimer){ if(this.lastActive.getElapsed() < this.quickShowInterval){ this.show(); }else{ this.showTimer = this.show.defer(this.showDelay, this); } }else if(!this.hidden && this.autoHide !== false){ this.show(); } }, onTargetOut : function(e){ if(this.disabled || e.within(this.target.dom, true)){ return; } this.clearTimer('show'); if(this.autoHide !== false){ this.delayHide(); } }, delayHide : function(){ if(!this.hidden && !this.hideTimer){ this.hideTimer = this.hide.defer(this.hideDelay, this); } }, hide: function(){ this.clearTimer('dismiss'); this.lastActive = new Date(); Ext.ToolTip.superclass.hide.call(this); }, show : function(){ this.showAt(this.getTargetXY()); }, showAt : function(xy){ this.lastActive = new Date(); this.clearTimers(); Ext.ToolTip.superclass.showAt.call(this, xy); if(this.dismissDelay && this.autoHide !== false){ this.dismissTimer = this.hide.defer(this.dismissDelay, this); } }, clearTimer : function(name){ name = name + 'Timer'; clearTimeout(this[name]); delete this[name]; }, clearTimers : function(){ this.clearTimer('show'); this.clearTimer('dismiss'); this.clearTimer('hide'); }, onShow : function(){ Ext.ToolTip.superclass.onShow.call(this); Ext.getDoc().on('mousedown', this.onDocMouseDown, this); }, onHide : function(){ Ext.ToolTip.superclass.onHide.call(this); Ext.getDoc().un('mousedown', this.onDocMouseDown, this); }, onDocMouseDown : function(e){ if(this.autoHide !== false && !e.within(this.el.dom)){ this.disable(); this.enable.defer(100, this); } }, onDisable : function(){ this.clearTimers(); this.hide(); }, adjustPosition : function(x, y){ var ay = this.targetXY[1], h = this.getSize().height; if(this.constrainPosition && y <= ay && (y+h) >= ay){ y = ay-h-5; } return {x : x, y: y}; }, onDestroy : function(){ Ext.ToolTip.superclass.onDestroy.call(this); if(this.target){ this.target.un('mouseover', this.onTargetOver, this); this.target.un('mouseout', this.onTargetOut, this); this.target.un('mousemove', this.onMouseMove, this); } } }); Ext.QuickTip = Ext.extend(Ext.ToolTip, { interceptTitles : false, tagConfig : { namespace : "ext", attribute : "qtip", width : "qwidth", target : "target", title : "qtitle", hide : "hide", cls : "qclass", align : "qalign" }, initComponent : function(){ this.target = this.target || Ext.getDoc(); this.targets = this.targets || {}; Ext.QuickTip.superclass.initComponent.call(this); }, register : function(config){ var cs = Ext.isArray(config) ? config : arguments; for(var i = 0, len = cs.length; i < len; i++){ var c = cs[i]; var target = c.target; if(target){ if(Ext.isArray(target)){ for(var j = 0, jlen = target.length; j < jlen; j++){ this.targets[Ext.id(target[j])] = c; } } else{ this.targets[Ext.id(target)] = c; } } } }, unregister : function(el){ delete this.targets[Ext.id(el)]; }, onTargetOver : function(e){ if(this.disabled){ return; } this.targetXY = e.getXY(); var t = e.getTarget(); if(!t || t.nodeType !== 1 || t == document || t == document.body){ return; } if(this.activeTarget && t == this.activeTarget.el){ this.clearTimer('hide'); this.show(); return; } if(t && this.targets[t.id]){ this.activeTarget = this.targets[t.id]; this.activeTarget.el = t; this.delayShow(); return; } var ttp, et = Ext.fly(t), cfg = this.tagConfig; var ns = cfg.namespace; if(this.interceptTitles && t.title){ ttp = t.title; t.qtip = ttp; t.removeAttribute("title"); e.preventDefault(); } else{ ttp = t.qtip || et.getAttributeNS(ns, cfg.attribute); } if(ttp){ var autoHide = et.getAttributeNS(ns, cfg.hide); this.activeTarget = { el: t, text: ttp, width: et.getAttributeNS(ns, cfg.width), autoHide: autoHide != "user" && autoHide !== 'false', title: et.getAttributeNS(ns, cfg.title), cls: et.getAttributeNS(ns, cfg.cls), align: et.getAttributeNS(ns, cfg.align) }; this.delayShow(); } }, onTargetOut : function(e){ this.clearTimer('show'); if(this.autoHide !== false){ this.delayHide(); } }, showAt : function(xy){ var t = this.activeTarget; if(t){ if(!this.rendered){ this.render(Ext.getBody()); this.activeTarget = t; } if(t.width){ this.setWidth(t.width); this.body.setWidth(this.adjustBodyWidth(t.width - this.getFrameWidth())); this.measureWidth = false; } else{ this.measureWidth = true; } this.setTitle(t.title || ''); this.body.update(t.text); this.autoHide = t.autoHide; this.dismissDelay = t.dismissDelay || this.dismissDelay; if(this.lastCls){ this.el.removeClass(this.lastCls); delete this.lastCls; } if(t.cls){ this.el.addClass(t.cls); this.lastCls = t.cls; } if(t.align){ xy = this.el.getAlignToXY(t.el, t.align); this.constrainPosition = false; } else{ this.constrainPosition = true; } } Ext.QuickTip.superclass.showAt.call(this, xy); }, hide: function(){ delete this.activeTarget; Ext.QuickTip.superclass.hide.call(this); } }); Ext.QuickTips = function(){ var tip, locks = []; return { init : function(){ if(!tip){ tip = new Ext.QuickTip({elements:'header,body'}); } }, enable : function(){ if(tip){ locks.pop(); if(locks.length < 1){ tip.enable(); } } }, disable : function(){ if(tip){ tip.disable(); } locks.push(1); }, isEnabled : function(){ return tip && !tip.disabled; }, getQuickTip : function(){ return tip; }, register : function(){ tip.register.apply(tip, arguments); }, unregister : function(){ tip.unregister.apply(tip, arguments); }, tips :function(){ tip.register.apply(tip, arguments); } } }(); Ext.tree.TreePanel = Ext.extend(Ext.Panel, { rootVisible : true, animate: Ext.enableFx, lines : true, enableDD : false, hlDrop : Ext.enableFx, pathSeparator: "/", initComponent : function(){ Ext.tree.TreePanel.superclass.initComponent.call(this); if(!this.eventModel){ this.eventModel = new Ext.tree.TreeEventModel(this); } this.nodeHash = {}; if(this.root){ this.setRootNode(this.root); } this.addEvents( "append", "remove", "movenode", "insert", "beforeappend", "beforeremove", "beforemovenode", "beforeinsert", "beforeload", "load", "textchange", "beforeexpandnode", "beforecollapsenode", "expandnode", "disabledchange", "collapsenode", "beforeclick", "click", "checkchange", "dblclick", "contextmenu", "beforechildrenrendered", "startdrag", "enddrag", "dragdrop", "beforenodedrop", "nodedrop", "nodedragover" ); if(this.singleExpand){ this.on("beforeexpandnode", this.restrictExpand, this); } }, proxyNodeEvent : function(ename, a1, a2, a3, a4, a5, a6){ if(ename == 'collapse' || ename == 'expand' || ename == 'beforecollapse' || ename == 'beforeexpand' || ename == 'move' || ename == 'beforemove'){ ename = ename+'node'; } return this.fireEvent(ename, a1, a2, a3, a4, a5, a6); }, getRootNode : function(){ return this.root; }, setRootNode : function(node){ this.root = node; node.ownerTree = this; node.isRoot = true; this.registerNode(node); if(!this.rootVisible){ var uiP = node.attributes.uiProvider; node.ui = uiP ? new uiP(node) : new Ext.tree.RootTreeNodeUI(node); } return node; }, getNodeById : function(id){ return this.nodeHash[id]; }, registerNode : function(node){ this.nodeHash[node.id] = node; }, unregisterNode : function(node){ delete this.nodeHash[node.id]; }, toString : function(){ return "[Tree"+(this.id?" "+this.id:"")+"]"; }, restrictExpand : function(node){ var p = node.parentNode; if(p){ if(p.expandedChild && p.expandedChild.parentNode == p){ p.expandedChild.collapse(); } p.expandedChild = node; } }, getChecked : function(a, startNode){ startNode = startNode || this.root; var r = []; var f = function(){ if(this.attributes.checked){ r.push(!a ? this : (a == 'id' ? this.id : this.attributes[a])); } } startNode.cascade(f); return r; }, getEl : function(){ return this.el; }, getLoader : function(){ return this.loader; }, expandAll : function(){ this.root.expand(true); }, collapseAll : function(){ this.root.collapse(true); }, getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.tree.DefaultSelectionModel(); } return this.selModel; }, expandPath : function(path, attr, callback){ attr = attr || "id"; var keys = path.split(this.pathSeparator); var curNode = this.root; if(curNode.attributes[attr] != keys[1]){ if(callback){ callback(false, null); } return; } var index = 1; var f = function(){ if(++index == keys.length){ if(callback){ callback(true, curNode); } return; } var c = curNode.findChild(attr, keys[index]); if(!c){ if(callback){ callback(false, curNode); } return; } curNode = c; c.expand(false, false, f); }; curNode.expand(false, false, f); }, selectPath : function(path, attr, callback){ attr = attr || "id"; var keys = path.split(this.pathSeparator); var v = keys.pop(); if(keys.length > 0){ var f = function(success, node){ if(success && node){ var n = node.findChild(attr, v); if(n){ n.select(); if(callback){ callback(true, n); } }else if(callback){ callback(false, n); } }else{ if(callback){ callback(false, n); } } }; this.expandPath(keys.join(this.pathSeparator), attr, f); }else{ this.root.select(); if(callback){ callback(true, this.root); } } }, getTreeEl : function(){ return this.body; }, onRender : function(ct, position){ Ext.tree.TreePanel.superclass.onRender.call(this, ct, position); this.el.addClass('x-tree'); this.innerCt = this.body.createChild({tag:"ul", cls:"x-tree-root-ct " + (this.useArrows ? 'x-tree-arrows' : this.lines ? "x-tree-lines" : "x-tree-no-lines")}); }, initEvents : function(){ Ext.tree.TreePanel.superclass.initEvents.call(this); if(this.containerScroll){ Ext.dd.ScrollManager.register(this.body); } if((this.enableDD || this.enableDrop) && !this.dropZone){ this.dropZone = new Ext.tree.TreeDropZone(this, this.dropConfig || { ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true }); } if((this.enableDD || this.enableDrag) && !this.dragZone){ this.dragZone = new Ext.tree.TreeDragZone(this, this.dragConfig || { ddGroup: this.ddGroup || "TreeDD", scroll: this.ddScroll }); } this.getSelectionModel().init(this); }, afterRender : function(){ Ext.tree.TreePanel.superclass.afterRender.call(this); this.root.render(); if(!this.rootVisible){ this.root.renderChildren(); } }, onDestroy : function(){ if(this.rendered){ this.body.removeAllListeners(); Ext.dd.ScrollManager.unregister(this.body); if(this.dropZone){ this.dropZone.unreg(); } if(this.dragZone){ this.dragZone.unreg(); } } this.root.destroy(); this.nodeHash = null; Ext.tree.TreePanel.superclass.onDestroy.call(this); } }); Ext.reg('treepanel', Ext.tree.TreePanel); Ext.tree.TreeEventModel = function(tree){ this.tree = tree; this.tree.on('render', this.initEvents, this); } Ext.tree.TreeEventModel.prototype = { initEvents : function(){ var el = this.tree.getTreeEl(); el.on('click', this.delegateClick, this); if(this.tree.trackMouseOver !== false){ el.on('mouseover', this.delegateOver, this); el.on('mouseout', this.delegateOut, this); } el.on('dblclick', this.delegateDblClick, this); el.on('contextmenu', this.delegateContextMenu, this); }, getNode : function(e){ var t; if(t = e.getTarget('.x-tree-node-el', 10)){ var id = Ext.fly(t, '_treeEvents').getAttributeNS('ext', 'tree-node-id'); if(id){ return this.tree.getNodeById(id); } } return null; }, getNodeTarget : function(e){ var t = e.getTarget('.x-tree-node-icon', 1); if(!t){ t = e.getTarget('.x-tree-node-el', 6); } return t; }, delegateOut : function(e, t){ if(!this.beforeEvent(e)){ return; } if(e.getTarget('.x-tree-ec-icon', 1)){ var n = this.getNode(e); this.onIconOut(e, n); if(n == this.lastEcOver){ delete this.lastEcOver; } } if((t = this.getNodeTarget(e)) && !e.within(t, true)){ this.onNodeOut(e, this.getNode(e)); } }, delegateOver : function(e, t){ if(!this.beforeEvent(e)){ return; } if(this.lastEcOver){ this.onIconOut(e, this.lastEcOver); delete this.lastEcOver; } if(e.getTarget('.x-tree-ec-icon', 1)){ this.lastEcOver = this.getNode(e); this.onIconOver(e, this.lastEcOver); } if(t = this.getNodeTarget(e)){ this.onNodeOver(e, this.getNode(e)); } }, delegateClick : function(e, t){ if(!this.beforeEvent(e)){ return; } if(e.getTarget('input[type=checkbox]', 1)){ this.onCheckboxClick(e, this.getNode(e)); } else if(e.getTarget('.x-tree-ec-icon', 1)){ this.onIconClick(e, this.getNode(e)); } else if(this.getNodeTarget(e)){ this.onNodeClick(e, this.getNode(e)); } }, delegateDblClick : function(e, t){ if(this.beforeEvent(e) && this.getNodeTarget(e)){ this.onNodeDblClick(e, this.getNode(e)); } }, delegateContextMenu : function(e, t){ if(this.beforeEvent(e) && this.getNodeTarget(e)){ this.onNodeContextMenu(e, this.getNode(e)); } }, onNodeClick : function(e, node){ node.ui.onClick(e); }, onNodeOver : function(e, node){ node.ui.onOver(e); }, onNodeOut : function(e, node){ node.ui.onOut(e); }, onIconOver : function(e, node){ node.ui.addClass('x-tree-ec-over'); }, onIconOut : function(e, node){ node.ui.removeClass('x-tree-ec-over'); }, onIconClick : function(e, node){ node.ui.ecClick(e); }, onCheckboxClick : function(e, node){ node.ui.onCheckChange(e); }, onNodeDblClick : function(e, node){ node.ui.onDblClick(e); }, onNodeContextMenu : function(e, node){ node.ui.onContextMenu(e); }, beforeEvent : function(e){ if(this.disabled){ e.stopEvent(); return false; } return true; }, disable: function(){ this.disabled = true; }, enable: function(){ this.disabled = false; } }; Ext.tree.DefaultSelectionModel = function(config){ this.selNode = null; this.addEvents( "selectionchange", "beforeselect" ); Ext.apply(this, config); Ext.tree.DefaultSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.tree.DefaultSelectionModel, Ext.util.Observable, { init : function(tree){ this.tree = tree; tree.getTreeEl().on("keydown", this.onKeyDown, this); tree.on("click", this.onNodeClick, this); }, onNodeClick : function(node, e){ this.select(node); }, select : function(node){ var last = this.selNode; if(last != node && this.fireEvent('beforeselect', this, node, last) !== false){ if(last){ last.ui.onSelectedChange(false); } this.selNode = node; node.ui.onSelectedChange(true); this.fireEvent("selectionchange", this, node, last); } return node; }, unselect : function(node){ if(this.selNode == node){ this.clearSelections(); } }, clearSelections : function(){ var n = this.selNode; if(n){ n.ui.onSelectedChange(false); this.selNode = null; this.fireEvent("selectionchange", this, null); } return n; }, getSelectedNode : function(){ return this.selNode; }, isSelected : function(node){ return this.selNode == node; }, selectPrevious : function(){ var s = this.selNode || this.lastSelNode; if(!s){ return null; } var ps = s.previousSibling; if(ps){ if(!ps.isExpanded() || ps.childNodes.length < 1){ return this.select(ps); } else{ var lc = ps.lastChild; while(lc && lc.isExpanded() && lc.childNodes.length > 0){ lc = lc.lastChild; } return this.select(lc); } } else if(s.parentNode && (this.tree.rootVisible || !s.parentNode.isRoot)){ return this.select(s.parentNode); } return null; }, selectNext : function(){ var s = this.selNode || this.lastSelNode; if(!s){ return null; } if(s.firstChild && s.isExpanded()){ return this.select(s.firstChild); }else if(s.nextSibling){ return this.select(s.nextSibling); }else if(s.parentNode){ var newS = null; s.parentNode.bubble(function(){ if(this.nextSibling){ newS = this.getOwnerTree().selModel.select(this.nextSibling); return false; } }); return newS; } return null; }, onKeyDown : function(e){ var s = this.selNode || this.lastSelNode; var sm = this; if(!s){ return; } var k = e.getKey(); switch(k){ case e.DOWN: e.stopEvent(); this.selectNext(); break; case e.UP: e.stopEvent(); this.selectPrevious(); break; case e.RIGHT: e.preventDefault(); if(s.hasChildNodes()){ if(!s.isExpanded()){ s.expand(); }else if(s.firstChild){ this.select(s.firstChild, e); } } break; case e.LEFT: e.preventDefault(); if(s.hasChildNodes() && s.isExpanded()){ s.collapse(); }else if(s.parentNode && (this.tree.rootVisible || s.parentNode != this.tree.getRootNode())){ this.select(s.parentNode, e); } break; }; } }); Ext.tree.MultiSelectionModel = function(config){ this.selNodes = []; this.selMap = {}; this.addEvents( "selectionchange" ); Ext.apply(this, config); Ext.tree.MultiSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.tree.MultiSelectionModel, Ext.util.Observable, { init : function(tree){ this.tree = tree; tree.getTreeEl().on("keydown", this.onKeyDown, this); tree.on("click", this.onNodeClick, this); }, onNodeClick : function(node, e){ this.select(node, e, e.ctrlKey); }, select : function(node, e, keepExisting){ if(keepExisting !== true){ this.clearSelections(true); } if(this.isSelected(node)){ this.lastSelNode = node; return node; } this.selNodes.push(node); this.selMap[node.id] = node; this.lastSelNode = node; node.ui.onSelectedChange(true); this.fireEvent("selectionchange", this, this.selNodes); return node; }, unselect : function(node){ if(this.selMap[node.id]){ node.ui.onSelectedChange(false); var sn = this.selNodes; var index = sn.indexOf(node); if(index != -1){ this.selNodes.splice(index, 1); } delete this.selMap[node.id]; this.fireEvent("selectionchange", this, this.selNodes); } }, clearSelections : function(suppressEvent){ var sn = this.selNodes; if(sn.length > 0){ for(var i = 0, len = sn.length; i < len; i++){ sn[i].ui.onSelectedChange(false); } this.selNodes = []; this.selMap = {}; if(suppressEvent !== true){ this.fireEvent("selectionchange", this, this.selNodes); } } }, isSelected : function(node){ return this.selMap[node.id] ? true : false; }, getSelectedNodes : function(){ return this.selNodes; }, onKeyDown : Ext.tree.DefaultSelectionModel.prototype.onKeyDown, selectNext : Ext.tree.DefaultSelectionModel.prototype.selectNext, selectPrevious : Ext.tree.DefaultSelectionModel.prototype.selectPrevious }); Ext.tree.TreeNode = function(attributes){ attributes = attributes || {}; if(typeof attributes == "string"){ attributes = {text: attributes}; } this.childrenRendered = false; this.rendered = false; Ext.tree.TreeNode.superclass.constructor.call(this, attributes); this.expanded = attributes.expanded === true; this.isTarget = attributes.isTarget !== false; this.draggable = attributes.draggable !== false && attributes.allowDrag !== false; this.allowChildren = attributes.allowChildren !== false && attributes.allowDrop !== false; this.text = attributes.text; this.disabled = attributes.disabled === true; this.addEvents( "textchange", "beforeexpand", "beforecollapse", "expand", "disabledchange", "collapse", "beforeclick", "click", "checkchange", "dblclick", "contextmenu", "beforechildrenrendered" ); var uiClass = this.attributes.uiProvider || this.defaultUI || Ext.tree.TreeNodeUI; this.ui = new uiClass(this); }; Ext.extend(Ext.tree.TreeNode, Ext.data.Node, { preventHScroll: true, isExpanded : function(){ return this.expanded; }, getUI : function(){ return this.ui; }, setFirstChild : function(node){ var of = this.firstChild; Ext.tree.TreeNode.superclass.setFirstChild.call(this, node); if(this.childrenRendered && of && node != of){ of.renderIndent(true, true); } if(this.rendered){ this.renderIndent(true, true); } }, setLastChild : function(node){ var ol = this.lastChild; Ext.tree.TreeNode.superclass.setLastChild.call(this, node); if(this.childrenRendered && ol && node != ol){ ol.renderIndent(true, true); } if(this.rendered){ this.renderIndent(true, true); } }, appendChild : function(){ var node = Ext.tree.TreeNode.superclass.appendChild.apply(this, arguments); if(node && this.childrenRendered){ node.render(); } this.ui.updateExpandIcon(); return node; }, removeChild : function(node){ this.ownerTree.getSelectionModel().unselect(node); Ext.tree.TreeNode.superclass.removeChild.apply(this, arguments); if(this.childrenRendered){ node.ui.remove(); } if(this.childNodes.length < 1){ this.collapse(false, false); }else{ this.ui.updateExpandIcon(); } if(!this.firstChild && !this.isHiddenRoot()) { this.childrenRendered = false; } return node; }, insertBefore : function(node, refNode){ var newNode = Ext.tree.TreeNode.superclass.insertBefore.apply(this, arguments); if(newNode && refNode && this.childrenRendered){ node.render(); } this.ui.updateExpandIcon(); return newNode; }, setText : function(text){ var oldText = this.text; this.text = text; this.attributes.text = text; if(this.rendered){ this.ui.onTextChange(this, text, oldText); } this.fireEvent("textchange", this, text, oldText); }, select : function(){ this.getOwnerTree().getSelectionModel().select(this); }, unselect : function(){ this.getOwnerTree().getSelectionModel().unselect(this); }, isSelected : function(){ return this.getOwnerTree().getSelectionModel().isSelected(this); }, expand : function(deep, anim, callback){ if(!this.expanded){ if(this.fireEvent("beforeexpand", this, deep, anim) === false){ return; } if(!this.childrenRendered){ this.renderChildren(); } this.expanded = true; if(!this.isHiddenRoot() && (this.getOwnerTree().animate && anim !== false) || anim){ this.ui.animExpand(function(){ this.fireEvent("expand", this); if(typeof callback == "function"){ callback(this); } if(deep === true){ this.expandChildNodes(true); } }.createDelegate(this)); return; }else{ this.ui.expand(); this.fireEvent("expand", this); if(typeof callback == "function"){ callback(this); } } }else{ if(typeof callback == "function"){ callback(this); } } if(deep === true){ this.expandChildNodes(true); } }, isHiddenRoot : function(){ return this.isRoot && !this.getOwnerTree().rootVisible; }, collapse : function(deep, anim){ if(this.expanded && !this.isHiddenRoot()){ if(this.fireEvent("beforecollapse", this, deep, anim) === false){ return; } this.expanded = false; if((this.getOwnerTree().animate && anim !== false) || anim){ this.ui.animCollapse(function(){ this.fireEvent("collapse", this); if(deep === true){ this.collapseChildNodes(true); } }.createDelegate(this)); return; }else{ this.ui.collapse(); this.fireEvent("collapse", this); } } if(deep === true){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].collapse(true, false); } } }, delayedExpand : function(delay){ if(!this.expandProcId){ this.expandProcId = this.expand.defer(delay, this); } }, cancelExpand : function(){ if(this.expandProcId){ clearTimeout(this.expandProcId); } this.expandProcId = false; }, toggle : function(){ if(this.expanded){ this.collapse(); }else{ this.expand(); } }, ensureVisible : function(callback){ var tree = this.getOwnerTree(); tree.expandPath(this.parentNode.getPath(), false, function(){ var node = tree.getNodeById(this.id); tree.getTreeEl().scrollChildIntoView(node.ui.anchor); Ext.callback(callback); }.createDelegate(this)); }, expandChildNodes : function(deep){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].expand(deep); } }, collapseChildNodes : function(deep){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++) { cs[i].collapse(deep); } }, disable : function(){ this.disabled = true; this.unselect(); if(this.rendered && this.ui.onDisableChange){ this.ui.onDisableChange(this, true); } this.fireEvent("disabledchange", this, true); }, enable : function(){ this.disabled = false; if(this.rendered && this.ui.onDisableChange){ this.ui.onDisableChange(this, false); } this.fireEvent("disabledchange", this, false); }, renderChildren : function(suppressEvent){ if(suppressEvent !== false){ this.fireEvent("beforechildrenrendered", this); } var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].render(true); } this.childrenRendered = true; }, sort : function(fn, scope){ Ext.tree.TreeNode.superclass.sort.apply(this, arguments); if(this.childrenRendered){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].render(true); } } }, render : function(bulkRender){ this.ui.render(bulkRender); if(!this.rendered){ this.getOwnerTree().registerNode(this); this.rendered = true; if(this.expanded){ this.expanded = false; this.expand(false, false); } } }, renderIndent : function(deep, refresh){ if(refresh){ this.ui.childIndent = null; } this.ui.renderIndent(); if(deep === true && this.childrenRendered){ var cs = this.childNodes; for(var i = 0, len = cs.length; i < len; i++){ cs[i].renderIndent(true, refresh); } } }, beginUpdate : function(){ this.childrenRendered = false; }, endUpdate : function(){ if(this.expanded){ this.renderChildren(); } }, destroy : function(){ for(var i = 0,l = this.childNodes.length; i < l; i++){ this.childNodes[i].destroy(); } this.childNodes = null; if(this.ui.destroy){ this.ui.destroy(); } } }); Ext.tree.AsyncTreeNode = function(config){ this.loaded = false; this.loading = false; Ext.tree.AsyncTreeNode.superclass.constructor.apply(this, arguments); this.addEvents('beforeload', 'load'); }; Ext.extend(Ext.tree.AsyncTreeNode, Ext.tree.TreeNode, { expand : function(deep, anim, callback){ if(this.loading){ var timer; var f = function(){ if(!this.loading){ clearInterval(timer); this.expand(deep, anim, callback); } }.createDelegate(this); timer = setInterval(f, 200); return; } if(!this.loaded){ if(this.fireEvent("beforeload", this) === false){ return; } this.loading = true; this.ui.beforeLoad(this); var loader = this.loader || this.attributes.loader || this.getOwnerTree().getLoader(); if(loader){ loader.load(this, this.loadComplete.createDelegate(this, [deep, anim, callback])); return; } } Ext.tree.AsyncTreeNode.superclass.expand.call(this, deep, anim, callback); }, isLoading : function(){ return this.loading; }, loadComplete : function(deep, anim, callback){ this.loading = false; this.loaded = true; this.ui.afterLoad(this); this.fireEvent("load", this); this.expand(deep, anim, callback); }, isLoaded : function(){ return this.loaded; }, hasChildNodes : function(){ if(!this.isLeaf() && !this.loaded){ return true; }else{ return Ext.tree.AsyncTreeNode.superclass.hasChildNodes.call(this); } }, reload : function(callback){ this.collapse(false, false); while(this.firstChild){ this.removeChild(this.firstChild); } this.childrenRendered = false; this.loaded = false; if(this.isHiddenRoot()){ this.expanded = false; } this.expand(false, false, callback); } }); Ext.tree.TreeNodeUI = function(node){ this.node = node; this.rendered = false; this.animating = false; this.wasLeaf = true; this.ecc = 'x-tree-ec-icon x-tree-elbow'; this.emptyIcon = Ext.BLANK_IMAGE_URL; }; Ext.tree.TreeNodeUI.prototype = { removeChild : function(node){ if(this.rendered){ this.ctNode.removeChild(node.ui.getEl()); } }, beforeLoad : function(){ this.addClass("x-tree-node-loading"); }, afterLoad : function(){ this.removeClass("x-tree-node-loading"); }, onTextChange : function(node, text, oldText){ if(this.rendered){ this.textNode.innerHTML = text; } }, onDisableChange : function(node, state){ this.disabled = state; if (this.checkbox) { this.checkbox.disabled = state; } if(state){ this.addClass("x-tree-node-disabled"); }else{ this.removeClass("x-tree-node-disabled"); } }, onSelectedChange : function(state){ if(state){ this.focus(); this.addClass("x-tree-selected"); }else{ this.removeClass("x-tree-selected"); } }, onMove : function(tree, node, oldParent, newParent, index, refNode){ this.childIndent = null; if(this.rendered){ var targetNode = newParent.ui.getContainer(); if(!targetNode){ this.holder = document.createElement("div"); this.holder.appendChild(this.wrap); return; } var insertBefore = refNode ? refNode.ui.getEl() : null; if(insertBefore){ targetNode.insertBefore(this.wrap, insertBefore); }else{ targetNode.appendChild(this.wrap); } this.node.renderIndent(true); } }, addClass : function(cls){ if(this.elNode){ Ext.fly(this.elNode).addClass(cls); } }, removeClass : function(cls){ if(this.elNode){ Ext.fly(this.elNode).removeClass(cls); } }, remove : function(){ if(this.rendered){ this.holder = document.createElement("div"); this.holder.appendChild(this.wrap); } }, fireEvent : function(){ return this.node.fireEvent.apply(this.node, arguments); }, initEvents : function(){ this.node.on("move", this.onMove, this); if(this.node.disabled){ this.addClass("x-tree-node-disabled"); if (this.checkbox) { this.checkbox.disabled = true; } } if(this.node.hidden){ this.hide(); } var ot = this.node.getOwnerTree(); var dd = ot.enableDD || ot.enableDrag || ot.enableDrop; if(dd && (!this.node.isRoot || ot.rootVisible)){ Ext.dd.Registry.register(this.elNode, { node: this.node, handles: this.getDDHandles(), isHandle: false }); } }, getDDHandles : function(){ return [this.iconNode, this.textNode, this.elNode]; }, hide : function(){ this.node.hidden = true; if(this.wrap){ this.wrap.style.display = "none"; } }, show : function(){ this.node.hidden = false; if(this.wrap){ this.wrap.style.display = ""; } }, onContextMenu : function(e){ if (this.node.hasListener("contextmenu") || this.node.getOwnerTree().hasListener("contextmenu")) { e.preventDefault(); this.focus(); this.fireEvent("contextmenu", this.node, e); } }, onClick : function(e){ if(this.dropping){ e.stopEvent(); return; } if(this.fireEvent("beforeclick", this.node, e) !== false){ var a = e.getTarget('a'); if(!this.disabled && this.node.attributes.href && a){ this.fireEvent("click", this.node, e); return; }else if(a && e.ctrlKey){ e.stopEvent(); } e.preventDefault(); if(this.disabled){ return; } if(this.node.attributes.singleClickExpand && !this.animating && this.node.hasChildNodes()){ this.node.toggle(); } this.fireEvent("click", this.node, e); }else{ e.stopEvent(); } }, onDblClick : function(e){ e.preventDefault(); if(this.disabled){ return; } if(this.checkbox){ this.toggleCheck(); } if(!this.animating && this.node.hasChildNodes()){ this.node.toggle(); } this.fireEvent("dblclick", this.node, e); }, onOver : function(e){ this.addClass('x-tree-node-over'); }, onOut : function(e){ this.removeClass('x-tree-node-over'); }, onCheckChange : function(){ var checked = this.checkbox.checked; this.node.attributes.checked = checked; this.fireEvent('checkchange', this.node, checked); }, ecClick : function(e){ if(!this.animating && (this.node.hasChildNodes() || this.node.attributes.expandable)){ this.node.toggle(); } }, startDrop : function(){ this.dropping = true; }, endDrop : function(){ setTimeout(function(){ this.dropping = false; }.createDelegate(this), 50); }, expand : function(){ this.updateExpandIcon(); this.ctNode.style.display = ""; }, focus : function(){ if(!this.node.preventHScroll){ try{this.anchor.focus(); }catch(e){} }else if(!Ext.isIE){ try{ var noscroll = this.node.getOwnerTree().getTreeEl().dom; var l = noscroll.scrollLeft; this.anchor.focus(); noscroll.scrollLeft = l; }catch(e){} } }, toggleCheck : function(value){ var cb = this.checkbox; if(cb){ cb.checked = (value === undefined ? !cb.checked : value); } }, blur : function(){ try{ this.anchor.blur(); }catch(e){} }, animExpand : function(callback){ var ct = Ext.get(this.ctNode); ct.stopFx(); if(!this.node.hasChildNodes()){ this.updateExpandIcon(); this.ctNode.style.display = ""; Ext.callback(callback); return; } this.animating = true; this.updateExpandIcon(); ct.slideIn('t', { callback : function(){ this.animating = false; Ext.callback(callback); }, scope: this, duration: this.node.ownerTree.duration || .25 }); }, highlight : function(){ var tree = this.node.getOwnerTree(); Ext.fly(this.wrap).highlight( tree.hlColor || "C3DAF9", {endColor: tree.hlBaseColor} ); }, collapse : function(){ this.updateExpandIcon(); this.ctNode.style.display = "none"; }, animCollapse : function(callback){ var ct = Ext.get(this.ctNode); ct.enableDisplayMode('block'); ct.stopFx(); this.animating = true; this.updateExpandIcon(); ct.slideOut('t', { callback : function(){ this.animating = false; Ext.callback(callback); }, scope: this, duration: this.node.ownerTree.duration || .25 }); }, getContainer : function(){ return this.ctNode; }, getEl : function(){ return this.wrap; }, appendDDGhost : function(ghostNode){ ghostNode.appendChild(this.elNode.cloneNode(true)); }, getDDRepairXY : function(){ return Ext.lib.Dom.getXY(this.iconNode); }, onRender : function(){ this.render(); }, render : function(bulkRender){ var n = this.node, a = n.attributes; var targetNode = n.parentNode ? n.parentNode.ui.getContainer() : n.ownerTree.innerCt.dom; if(!this.rendered){ this.rendered = true; this.renderElements(n, a, targetNode, bulkRender); if(a.qtip){ if(this.textNode.setAttributeNS){ this.textNode.setAttributeNS("ext", "qtip", a.qtip); if(a.qtipTitle){ this.textNode.setAttributeNS("ext", "qtitle", a.qtipTitle); } }else{ this.textNode.setAttribute("ext:qtip", a.qtip); if(a.qtipTitle){ this.textNode.setAttribute("ext:qtitle", a.qtipTitle); } } }else if(a.qtipCfg){ a.qtipCfg.target = Ext.id(this.textNode); Ext.QuickTips.register(a.qtipCfg); } this.initEvents(); if(!this.node.expanded){ this.updateExpandIcon(true); } }else{ if(bulkRender === true) { targetNode.appendChild(this.wrap); } } }, renderElements : function(n, a, targetNode, bulkRender){ this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : ''; var cb = typeof a.checked == 'boolean'; var href = a.href ? a.href : Ext.isGecko ? "" : "#"; var buf = ['<li class="x-tree-node"><div tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on">', '<span class="x-tree-node-indent">',this.indentMarkup,"</span>", '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />', '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />', cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '', '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ', a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,"</span></a></div>", '<ul class="x-tree-node-ct" style="display:none;"></ul>', "</li>"].join(''); var nel; if(bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())){ this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf); }else{ this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf); } this.elNode = this.wrap.childNodes[0]; this.ctNode = this.wrap.childNodes[1]; var cs = this.elNode.childNodes; this.indentNode = cs[0]; this.ecNode = cs[1]; this.iconNode = cs[2]; var index = 3; if(cb){ this.checkbox = cs[3]; index++; } this.anchor = cs[index]; this.textNode = cs[index].firstChild; }, getAnchor : function(){ return this.anchor; }, getTextEl : function(){ return this.textNode; }, getIconEl : function(){ return this.iconNode; }, isChecked : function(){ return this.checkbox ? this.checkbox.checked : false; }, updateExpandIcon : function(){ if(this.rendered){ var n = this.node, c1, c2; var cls = n.isLast() ? "x-tree-elbow-end" : "x-tree-elbow"; var hasChild = n.hasChildNodes(); if(hasChild || n.attributes.expandable){ if(n.expanded){ cls += "-minus"; c1 = "x-tree-node-collapsed"; c2 = "x-tree-node-expanded"; }else{ cls += "-plus"; c1 = "x-tree-node-expanded"; c2 = "x-tree-node-collapsed"; } if(this.wasLeaf){ this.removeClass("x-tree-node-leaf"); this.wasLeaf = false; } if(this.c1 != c1 || this.c2 != c2){ Ext.fly(this.elNode).replaceClass(c1, c2); this.c1 = c1; this.c2 = c2; } }else{ if(!this.wasLeaf){ Ext.fly(this.elNode).replaceClass("x-tree-node-expanded", "x-tree-node-leaf"); delete this.c1; delete this.c2; this.wasLeaf = true; } } var ecc = "x-tree-ec-icon "+cls; if(this.ecc != ecc){ this.ecNode.className = ecc; this.ecc = ecc; } } }, getChildIndent : function(){ if(!this.childIndent){ var buf = []; var p = this.node; while(p){ if(!p.isRoot || (p.isRoot && p.ownerTree.rootVisible)){ if(!p.isLast()) { buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-elbow-line" />'); } else { buf.unshift('<img src="'+this.emptyIcon+'" class="x-tree-icon" />'); } } p = p.parentNode; } this.childIndent = buf.join(""); } return this.childIndent; }, renderIndent : function(){ if(this.rendered){ var indent = ""; var p = this.node.parentNode; if(p){ indent = p.ui.getChildIndent(); } if(this.indentMarkup != indent){ this.indentNode.innerHTML = indent; this.indentMarkup = indent; } this.updateExpandIcon(); } }, destroy : function(){ if(this.elNode){ Ext.dd.Registry.unregister(this.elNode.id); } delete this.elNode; delete this.ctNode; delete this.indentNode; delete this.ecNode; delete this.iconNode; delete this.checkbox; delete this.anchor; delete this.textNode; Ext.removeNode(this.ctNode); } }; Ext.tree.RootTreeNodeUI = Ext.extend(Ext.tree.TreeNodeUI, { render : function(){ if(!this.rendered){ var targetNode = this.node.ownerTree.innerCt.dom; this.node.expanded = true; targetNode.innerHTML = '<div class="x-tree-root-node"></div>'; this.wrap = this.ctNode = targetNode.firstChild; } }, collapse : Ext.emptyFn, expand : Ext.emptyFn }); Ext.tree.TreeLoader = function(config){ this.baseParams = {}; this.requestMethod = "POST"; Ext.apply(this, config); this.addEvents( "beforeload", "load", "loadexception" ); Ext.tree.TreeLoader.superclass.constructor.call(this); }; Ext.extend(Ext.tree.TreeLoader, Ext.util.Observable, { uiProviders : {}, clearOnLoad : true, load : function(node, callback){ if(this.clearOnLoad){ while(node.firstChild){ node.removeChild(node.firstChild); } } if(this.doPreload(node)){ if(typeof callback == "function"){ callback(); } }else if(this.dataUrl||this.url){ this.requestData(node, callback); } }, doPreload : function(node){ if(node.attributes.children){ if(node.childNodes.length < 1){ var cs = node.attributes.children; node.beginUpdate(); for(var i = 0, len = cs.length; i < len; i++){ var cn = node.appendChild(this.createNode(cs[i])); if(this.preloadChildren){ this.doPreload(cn); } } node.endUpdate(); } return true; }else { return false; } }, getParams: function(node){ var buf = [], bp = this.baseParams; for(var key in bp){ if(typeof bp[key] != "function"){ buf.push(encodeURIComponent(key), "=", encodeURIComponent(bp[key]), "&"); } } buf.push("node=", encodeURIComponent(node.id)); return buf.join(""); }, requestData : function(node, callback){ if(this.fireEvent("beforeload", this, node, callback) !== false){ this.transId = Ext.Ajax.request({ method:this.requestMethod, url: this.dataUrl||this.url, success: this.handleResponse, failure: this.handleFailure, scope: this, argument: {callback: callback, node: node}, params: this.getParams(node) }); }else{ if(typeof callback == "function"){ callback(); } } }, isLoading : function(){ return this.transId ? true : false; }, abort : function(){ if(this.isLoading()){ Ext.Ajax.abort(this.transId); } }, createNode : function(attr){ if(this.baseAttrs){ Ext.applyIf(attr, this.baseAttrs); } if(this.applyLoader !== false){ attr.loader = this; } if(typeof attr.uiProvider == 'string'){ attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider); } return(attr.leaf ? new Ext.tree.TreeNode(attr) : new Ext.tree.AsyncTreeNode(attr)); }, processResponse : function(response, node, callback){ var json = response.responseText; try { var o = eval("("+json+")"); node.beginUpdate(); for(var i = 0, len = o.length; i < len; i++){ var n = this.createNode(o[i]); if(n){ node.appendChild(n); } } node.endUpdate(); if(typeof callback == "function"){ callback(this, node); } }catch(e){ this.handleFailure(response); } }, handleResponse : function(response){ this.transId = false; var a = response.argument; this.processResponse(response, a.node, a.callback); this.fireEvent("load", this, a.node, response); }, handleFailure : function(response){ this.transId = false; var a = response.argument; this.fireEvent("loadexception", this, a.node, response); if(typeof a.callback == "function"){ a.callback(this, a.node); } } }); Ext.tree.TreeFilter = function(tree, config){ this.tree = tree; this.filtered = {}; Ext.apply(this, config); }; Ext.tree.TreeFilter.prototype = { clearBlank:false, reverse:false, autoClear:false, remove:false, filter : function(value, attr, startNode){ attr = attr || "text"; var f; if(typeof value == "string"){ var vlen = value.length; if(vlen == 0 && this.clearBlank){ this.clear(); return; } value = value.toLowerCase(); f = function(n){ return n.attributes[attr].substr(0, vlen).toLowerCase() == value; }; }else if(value.exec){ f = function(n){ return value.test(n.attributes[attr]); }; }else{ throw 'Illegal filter type, must be string or regex'; } this.filterBy(f, null, startNode); }, filterBy : function(fn, scope, startNode){ startNode = startNode || this.tree.root; if(this.autoClear){ this.clear(); } var af = this.filtered, rv = this.reverse; var f = function(n){ if(n == startNode){ return true; } if(af[n.id]){ return false; } var m = fn.call(scope || n, n); if(!m || rv){ af[n.id] = n; n.ui.hide(); return false; } return true; }; startNode.cascade(f); if(this.remove){ for(var id in af){ if(typeof id != "function"){ var n = af[id]; if(n && n.parentNode){ n.parentNode.removeChild(n); } } } } }, clear : function(){ var t = this.tree; var af = this.filtered; for(var id in af){ if(typeof id != "function"){ var n = af[id]; if(n){ n.ui.show(); } } } this.filtered = {}; } }; Ext.tree.TreeSorter = function(tree, config){ Ext.apply(this, config); tree.on("beforechildrenrendered", this.doSort, this); tree.on("append", this.updateSort, this); tree.on("insert", this.updateSort, this); tree.on("textchange", this.updateSortParent, this); var dsc = this.dir && this.dir.toLowerCase() == "desc"; var p = this.property || "text"; var sortType = this.sortType; var fs = this.folderSort; var cs = this.caseSensitive === true; var leafAttr = this.leafAttr || 'leaf'; this.sortFn = function(n1, n2){ if(fs){ if(n1.attributes[leafAttr] && !n2.attributes[leafAttr]){ return 1; } if(!n1.attributes[leafAttr] && n2.attributes[leafAttr]){ return -1; } } var v1 = sortType ? sortType(n1) : (cs ? n1.attributes[p] : n1.attributes[p].toUpperCase()); var v2 = sortType ? sortType(n2) : (cs ? n2.attributes[p] : n2.attributes[p].toUpperCase()); if(v1 < v2){ return dsc ? +1 : -1; }else if(v1 > v2){ return dsc ? -1 : +1; }else{ return 0; } }; }; Ext.tree.TreeSorter.prototype = { doSort : function(node){ node.sort(this.sortFn); }, compareNodes : function(n1, n2){ return (n1.text.toUpperCase() > n2.text.toUpperCase() ? 1 : -1); }, updateSort : function(tree, node){ if(node.childrenRendered){ this.doSort.defer(1, this, [node]); } }, updateSortParent : function(node){ var p = node.parentNode; if(p && p.childrenRendered){ this.doSort.defer(1, this, [p]); } } }; if(Ext.dd.DropZone){ Ext.tree.TreeDropZone = function(tree, config){ this.allowParentInsert = false; this.allowContainerDrop = false; this.appendOnly = false; Ext.tree.TreeDropZone.superclass.constructor.call(this, tree.innerCt, config); this.tree = tree; this.dragOverData = {}; this.lastInsertClass = "x-tree-no-status"; }; Ext.extend(Ext.tree.TreeDropZone, Ext.dd.DropZone, { ddGroup : "TreeDD", expandDelay : 1000, expandNode : function(node){ if(node.hasChildNodes() && !node.isExpanded()){ node.expand(false, null, this.triggerCacheRefresh.createDelegate(this)); } }, queueExpand : function(node){ this.expandProcId = this.expandNode.defer(this.expandDelay, this, [node]); }, cancelExpand : function(){ if(this.expandProcId){ clearTimeout(this.expandProcId); this.expandProcId = false; } }, isValidDropPoint : function(n, pt, dd, e, data){ if(!n || !data){ return false; } var targetNode = n.node; var dropNode = data.node; if(!(targetNode && targetNode.isTarget && pt)){ return false; } if(pt == "append" && targetNode.allowChildren === false){ return false; } if((pt == "above" || pt == "below") && (targetNode.parentNode && targetNode.parentNode.allowChildren === false)){ return false; } if(dropNode && (targetNode == dropNode || dropNode.contains(targetNode))){ return false; } var overEvent = this.dragOverData; overEvent.tree = this.tree; overEvent.target = targetNode; overEvent.data = data; overEvent.point = pt; overEvent.source = dd; overEvent.rawEvent = e; overEvent.dropNode = dropNode; overEvent.cancel = false; var result = this.tree.fireEvent("nodedragover", overEvent); return overEvent.cancel === false && result !== false; }, getDropPoint : function(e, n, dd){ var tn = n.node; if(tn.isRoot){ return tn.allowChildren !== false ? "append" : false; } var dragEl = n.ddel; var t = Ext.lib.Dom.getY(dragEl), b = t + dragEl.offsetHeight; var y = Ext.lib.Event.getPageY(e); var noAppend = tn.allowChildren === false || tn.isLeaf(); if(this.appendOnly || tn.parentNode.allowChildren === false){ return noAppend ? false : "append"; } var noBelow = false; if(!this.allowParentInsert){ noBelow = tn.hasChildNodes() && tn.isExpanded(); } var q = (b - t) / (noAppend ? 2 : 3); if(y >= t && y < (t + q)){ return "above"; }else if(!noBelow && (noAppend || y >= b-q && y <= b)){ return "below"; }else{ return "append"; } }, onNodeEnter : function(n, dd, e, data){ this.cancelExpand(); }, onNodeOver : function(n, dd, e, data){ var pt = this.getDropPoint(e, n, dd); var node = n.node; if(!this.expandProcId && pt == "append" && node.hasChildNodes() && !n.node.isExpanded()){ this.queueExpand(node); }else if(pt != "append"){ this.cancelExpand(); } var returnCls = this.dropNotAllowed; if(this.isValidDropPoint(n, pt, dd, e, data)){ if(pt){ var el = n.ddel; var cls; if(pt == "above"){ returnCls = n.node.isFirst() ? "x-tree-drop-ok-above" : "x-tree-drop-ok-between"; cls = "x-tree-drag-insert-above"; }else if(pt == "below"){ returnCls = n.node.isLast() ? "x-tree-drop-ok-below" : "x-tree-drop-ok-between"; cls = "x-tree-drag-insert-below"; }else{ returnCls = "x-tree-drop-ok-append"; cls = "x-tree-drag-append"; } if(this.lastInsertClass != cls){ Ext.fly(el).replaceClass(this.lastInsertClass, cls); this.lastInsertClass = cls; } } } return returnCls; }, onNodeOut : function(n, dd, e, data){ this.cancelExpand(); this.removeDropIndicators(n); }, onNodeDrop : function(n, dd, e, data){ var point = this.getDropPoint(e, n, dd); var targetNode = n.node; targetNode.ui.startDrop(); if(!this.isValidDropPoint(n, point, dd, e, data)){ targetNode.ui.endDrop(); return false; } var dropNode = data.node || (dd.getTreeNode ? dd.getTreeNode(data, targetNode, point, e) : null); var dropEvent = { tree : this.tree, target: targetNode, data: data, point: point, source: dd, rawEvent: e, dropNode: dropNode, cancel: !dropNode, dropStatus: false }; var retval = this.tree.fireEvent("beforenodedrop", dropEvent); if(retval === false || dropEvent.cancel === true || !dropEvent.dropNode){ targetNode.ui.endDrop(); return dropEvent.dropStatus; } targetNode = dropEvent.target; if(point == "append" && !targetNode.isExpanded()){ targetNode.expand(false, null, function(){ this.completeDrop(dropEvent); }.createDelegate(this)); }else{ this.completeDrop(dropEvent); } return true; }, completeDrop : function(de){ var ns = de.dropNode, p = de.point, t = de.target; if(!Ext.isArray(ns)){ ns = [ns]; } var n; for(var i = 0, len = ns.length; i < len; i++){ n = ns[i]; if(p == "above"){ t.parentNode.insertBefore(n, t); }else if(p == "below"){ t.parentNode.insertBefore(n, t.nextSibling); }else{ t.appendChild(n); } } n.ui.focus(); if(this.tree.hlDrop){ n.ui.highlight(); } t.ui.endDrop(); this.tree.fireEvent("nodedrop", de); }, afterNodeMoved : function(dd, data, e, targetNode, dropNode){ if(this.tree.hlDrop){ dropNode.ui.focus(); dropNode.ui.highlight(); } this.tree.fireEvent("nodedrop", this.tree, targetNode, data, dd, e); }, getTree : function(){ return this.tree; }, removeDropIndicators : function(n){ if(n && n.ddel){ var el = n.ddel; Ext.fly(el).removeClass([ "x-tree-drag-insert-above", "x-tree-drag-insert-below", "x-tree-drag-append"]); this.lastInsertClass = "_noclass"; } }, beforeDragDrop : function(target, e, id){ this.cancelExpand(); return true; }, afterRepair : function(data){ if(data && Ext.enableFx){ data.node.ui.highlight(); } this.hideProxy(); } }); } if(Ext.dd.DragZone){ Ext.tree.TreeDragZone = function(tree, config){ Ext.tree.TreeDragZone.superclass.constructor.call(this, tree.getTreeEl(), config); this.tree = tree; }; Ext.extend(Ext.tree.TreeDragZone, Ext.dd.DragZone, { ddGroup : "TreeDD", onBeforeDrag : function(data, e){ var n = data.node; return n && n.draggable && !n.disabled; }, onInitDrag : function(e){ var data = this.dragData; this.tree.getSelectionModel().select(data.node); this.tree.eventModel.disable(); this.proxy.update(""); data.node.ui.appendDDGhost(this.proxy.ghost.dom); this.tree.fireEvent("startdrag", this.tree, data.node, e); }, getRepairXY : function(e, data){ return data.node.ui.getDDRepairXY(); }, onEndDrag : function(data, e){ this.tree.eventModel.enable.defer(100, this.tree.eventModel); this.tree.fireEvent("enddrag", this.tree, data.node, e); }, onValidDrop : function(dd, e, id){ this.tree.fireEvent("dragdrop", this.tree, this.dragData.node, dd, e); this.hideProxy(); }, beforeInvalidDrop : function(e, id){ var sm = this.tree.getSelectionModel(); sm.clearSelections(); sm.select(this.dragData.node); } }); } Ext.tree.TreeEditor = function(tree, config){ config = config || {}; var field = config.events ? config : new Ext.form.TextField(config); Ext.tree.TreeEditor.superclass.constructor.call(this, field); this.tree = tree; if(!tree.rendered){ tree.on('render', this.initEditor, this); }else{ this.initEditor(tree); } }; Ext.extend(Ext.tree.TreeEditor, Ext.Editor, { alignment: "l-l", autoSize: false, hideEl : false, cls: "x-small-editor x-tree-editor", shim:false, shadow:"frame", maxWidth: 250, editDelay : 350, initEditor : function(tree){ tree.on('beforeclick', this.beforeNodeClick, this); tree.on('dblclick', this.onNodeDblClick, this); this.on('complete', this.updateNode, this); this.on('beforestartedit', this.fitToTree, this); this.on('startedit', this.bindScroll, this, {delay:10}); this.on('specialkey', this.onSpecialKey, this); }, fitToTree : function(ed, el){ var td = this.tree.getTreeEl().dom, nd = el.dom; if(td.scrollLeft > nd.offsetLeft){ td.scrollLeft = nd.offsetLeft; } var w = Math.min( this.maxWidth, (td.clientWidth > 20 ? td.clientWidth : td.offsetWidth) - Math.max(0, nd.offsetLeft-td.scrollLeft) - 5); this.setSize(w, ''); }, triggerEdit : function(node, defer){ this.completeEdit(); if(node.attributes.editable !== false){ this.editNode = node; this.autoEditTimer = this.startEdit.defer(this.editDelay, this, [node.ui.textNode, node.text]); return false; } }, bindScroll : function(){ this.tree.getTreeEl().on('scroll', this.cancelEdit, this); }, beforeNodeClick : function(node, e){ clearTimeout(this.autoEditTimer); if(this.tree.getSelectionModel().isSelected(node)){ e.stopEvent(); return this.triggerEdit(node); } }, onNodeDblClick : function(node, e){ clearTimeout(this.autoEditTimer); }, updateNode : function(ed, value){ this.tree.getTreeEl().un('scroll', this.cancelEdit, this); this.editNode.setText(value); }, onHide : function(){ Ext.tree.TreeEditor.superclass.onHide.call(this); if(this.editNode){ this.editNode.ui.focus.defer(50, this.editNode.ui); } }, onSpecialKey : function(field, e){ var k = e.getKey(); if(k == e.ESC){ e.stopEvent(); this.cancelEdit(); }else if(k == e.ENTER && !e.hasModifier()){ e.stopEvent(); this.completeEdit(); } } }); Ext.menu.Menu = function(config){ if(Ext.isArray(config)){ config = {items:config}; } Ext.apply(this, config); this.id = this.id || Ext.id(); this.addEvents( 'beforeshow', 'beforehide', 'show', 'hide', 'click', 'mouseover', 'mouseout', 'itemclick' ); Ext.menu.MenuMgr.register(this); Ext.menu.Menu.superclass.constructor.call(this); var mis = this.items; this.items = new Ext.util.MixedCollection(); if(mis){ this.add.apply(this, mis); } }; Ext.extend(Ext.menu.Menu, Ext.util.Observable, { minWidth : 120, shadow : "sides", subMenuAlign : "tl-tr?", defaultAlign : "tl-bl?", allowOtherMenus : false, hidden:true, createEl : function(){ return new Ext.Layer({ cls: "x-menu", shadow:this.shadow, constrain: false, parentEl: this.parentEl || document.body, zindex:15000 }); }, render : function(){ if(this.el){ return; } var el = this.el = this.createEl(); if(!this.keyNav){ this.keyNav = new Ext.menu.MenuNav(this); } if(this.plain){ el.addClass("x-menu-plain"); } if(this.cls){ el.addClass(this.cls); } this.focusEl = el.createChild({ tag: "a", cls: "x-menu-focus", href: "#", onclick: "return false;", tabIndex:"-1" }); var ul = el.createChild({tag: "ul", cls: "x-menu-list"}); ul.on("click", this.onClick, this); ul.on("mouseover", this.onMouseOver, this); ul.on("mouseout", this.onMouseOut, this); this.items.each(function(item){ var li = document.createElement("li"); li.className = "x-menu-list-item"; ul.dom.appendChild(li); item.render(li, this); }, this); this.ul = ul; this.autoWidth(); }, autoWidth : function(){ var el = this.el, ul = this.ul; if(!el){ return; } var w = this.width; if(w){ el.setWidth(w); }else if(Ext.isIE){ el.setWidth(this.minWidth); var t = el.dom.offsetWidth; el.setWidth(ul.getWidth()+el.getFrameWidth("lr")); } }, delayAutoWidth : function(){ if(this.el){ if(!this.awTask){ this.awTask = new Ext.util.DelayedTask(this.autoWidth, this); } this.awTask.delay(20); } }, findTargetItem : function(e){ var t = e.getTarget(".x-menu-list-item", this.ul, true); if(t && t.menuItemId){ return this.items.get(t.menuItemId); } }, onClick : function(e){ var t; if(t = this.findTargetItem(e)){ t.onClick(e); this.fireEvent("click", this, t, e); } }, setActiveItem : function(item, autoExpand){ if(item != this.activeItem){ if(this.activeItem){ this.activeItem.deactivate(); } this.activeItem = item; item.activate(autoExpand); }else if(autoExpand){ item.expandMenu(); } }, tryActivate : function(start, step){ var items = this.items; for(var i = start, len = items.length; i >= 0 && i < len; i+= step){ var item = items.get(i); if(!item.disabled && item.canActivate){ this.setActiveItem(item, false); return item; } } return false; }, onMouseOver : function(e){ var t; if(t = this.findTargetItem(e)){ if(t.canActivate && !t.disabled){ this.setActiveItem(t, true); } } this.fireEvent("mouseover", this, e, t); }, onMouseOut : function(e){ var t; if(t = this.findTargetItem(e)){ if(t == this.activeItem && t.shouldDeactivate(e)){ this.activeItem.deactivate(); delete this.activeItem; } } this.fireEvent("mouseout", this, e, t); }, isVisible : function(){ return this.el && !this.hidden; }, show : function(el, pos, parentMenu){ this.parentMenu = parentMenu; if(!this.el){ this.render(); } this.fireEvent("beforeshow", this); this.showAt(this.el.getAlignToXY(el, pos || this.defaultAlign), parentMenu, false); }, showAt : function(xy, parentMenu, _e){ this.parentMenu = parentMenu; if(!this.el){ this.render(); } if(_e !== false){ this.fireEvent("beforeshow", this); xy = this.el.adjustForConstraints(xy); } this.el.setXY(xy); this.el.show(); this.hidden = false; this.focus(); this.fireEvent("show", this); }, focus : function(){ if(!this.hidden){ this.doFocus.defer(50, this); } }, doFocus : function(){ if(!this.hidden){ this.focusEl.focus(); } }, hide : function(deep){ if(this.el && this.isVisible()){ this.fireEvent("beforehide", this); if(this.activeItem){ this.activeItem.deactivate(); this.activeItem = null; } this.el.hide(); this.hidden = true; this.fireEvent("hide", this); } if(deep === true && this.parentMenu){ this.parentMenu.hide(true); } }, add : function(){ var a = arguments, l = a.length, item; for(var i = 0; i < l; i++){ var el = a[i]; if(el.render){ item = this.addItem(el); }else if(typeof el == "string"){ if(el == "separator" || el == "-"){ item = this.addSeparator(); }else{ item = this.addText(el); } }else if(el.tagName || el.el){ item = this.addElement(el); }else if(typeof el == "object"){ Ext.applyIf(el, this.defaults); item = this.addMenuItem(el); } } return item; }, getEl : function(){ if(!this.el){ this.render(); } return this.el; }, addSeparator : function(){ return this.addItem(new Ext.menu.Separator()); }, addElement : function(el){ return this.addItem(new Ext.menu.BaseItem(el)); }, addItem : function(item){ this.items.add(item); if(this.ul){ var li = document.createElement("li"); li.className = "x-menu-list-item"; this.ul.dom.appendChild(li); item.render(li, this); this.delayAutoWidth(); } return item; }, addMenuItem : function(config){ if(!(config instanceof Ext.menu.Item)){ if(typeof config.checked == "boolean"){ config = new Ext.menu.CheckItem(config); }else{ config = new Ext.menu.Item(config); } } return this.addItem(config); }, addText : function(text){ return this.addItem(new Ext.menu.TextItem(text)); }, insert : function(index, item){ this.items.insert(index, item); if(this.ul){ var li = document.createElement("li"); li.className = "x-menu-list-item"; this.ul.dom.insertBefore(li, this.ul.dom.childNodes[index]); item.render(li, this); this.delayAutoWidth(); } return item; }, remove : function(item){ this.items.removeKey(item.id); item.destroy(); }, removeAll : function(){ var f; while(f = this.items.first()){ this.remove(f); } }, destroy : function(){ this.beforeDestroy(); Ext.menu.MenuMgr.unregister(this); if (this.keyNav) { this.keyNav.disable(); } this.removeAll(); if (this.ul) { this.ul.removeAllListeners(); } if (this.el) { this.el.destroy(); } }, beforeDestroy : Ext.emptyFn }); Ext.menu.MenuNav = function(menu){ Ext.menu.MenuNav.superclass.constructor.call(this, menu.el); this.scope = this.menu = menu; }; Ext.extend(Ext.menu.MenuNav, Ext.KeyNav, { doRelay : function(e, h){ var k = e.getKey(); if(!this.menu.activeItem && e.isNavKeyPress() && k != e.SPACE && k != e.RETURN){ this.menu.tryActivate(0, 1); return false; } return h.call(this.scope || this, e, this.menu); }, up : function(e, m){ if(!m.tryActivate(m.items.indexOf(m.activeItem)-1, -1)){ m.tryActivate(m.items.length-1, -1); } }, down : function(e, m){ if(!m.tryActivate(m.items.indexOf(m.activeItem)+1, 1)){ m.tryActivate(0, 1); } }, right : function(e, m){ if(m.activeItem){ m.activeItem.expandMenu(true); } }, left : function(e, m){ m.hide(); if(m.parentMenu && m.parentMenu.activeItem){ m.parentMenu.activeItem.activate(); } }, enter : function(e, m){ if(m.activeItem){ e.stopPropagation(); m.activeItem.onClick(e); m.fireEvent("click", this, m.activeItem); return true; } } }); Ext.menu.MenuMgr = function(){ var menus, active, groups = {}, attached = false, lastShow = new Date(); function init(){ menus = {}; active = new Ext.util.MixedCollection(); Ext.getDoc().addKeyListener(27, function(){ if(active.length > 0){ hideAll(); } }); } function hideAll(){ if(active && active.length > 0){ var c = active.clone(); c.each(function(m){ m.hide(); }); } } function onHide(m){ active.remove(m); if(active.length < 1){ Ext.getDoc().un("mousedown", onMouseDown); attached = false; } } function onShow(m){ var last = active.last(); lastShow = new Date(); active.add(m); if(!attached){ Ext.getDoc().on("mousedown", onMouseDown); attached = true; } if(m.parentMenu){ m.getEl().setZIndex(parseInt(m.parentMenu.getEl().getStyle("z-index"), 10) + 3); m.parentMenu.activeChild = m; }else if(last && last.isVisible()){ m.getEl().setZIndex(parseInt(last.getEl().getStyle("z-index"), 10) + 3); } } function onBeforeHide(m){ if(m.activeChild){ m.activeChild.hide(); } if(m.autoHideTimer){ clearTimeout(m.autoHideTimer); delete m.autoHideTimer; } } function onBeforeShow(m){ var pm = m.parentMenu; if(!pm && !m.allowOtherMenus){ hideAll(); }else if(pm && pm.activeChild){ pm.activeChild.hide(); } } function onMouseDown(e){ if(lastShow.getElapsed() > 50 && active.length > 0 && !e.getTarget(".x-menu")){ hideAll(); } } function onBeforeCheck(mi, state){ if(state){ var g = groups[mi.group]; for(var i = 0, l = g.length; i < l; i++){ if(g[i] != mi){ g[i].setChecked(false); } } } } return { hideAll : function(){ hideAll(); }, register : function(menu){ if(!menus){ init(); } menus[menu.id] = menu; menu.on("beforehide", onBeforeHide); menu.on("hide", onHide); menu.on("beforeshow", onBeforeShow); menu.on("show", onShow); var g = menu.group; if(g && menu.events["checkchange"]){ if(!groups[g]){ groups[g] = []; } groups[g].push(menu); menu.on("checkchange", onCheck); } }, get : function(menu){ if(typeof menu == "string"){ if(!menus){ return null; } return menus[menu]; }else if(menu.events){ return menu; }else if(typeof menu.length == 'number'){ return new Ext.menu.Menu({items:menu}); }else{ return new Ext.menu.Menu(menu); } }, unregister : function(menu){ delete menus[menu.id]; menu.un("beforehide", onBeforeHide); menu.un("hide", onHide); menu.un("beforeshow", onBeforeShow); menu.un("show", onShow); var g = menu.group; if(g && menu.events["checkchange"]){ groups[g].remove(menu); menu.un("checkchange", onCheck); } }, registerCheckable : function(menuItem){ var g = menuItem.group; if(g){ if(!groups[g]){ groups[g] = []; } groups[g].push(menuItem); menuItem.on("beforecheckchange", onBeforeCheck); } }, unregisterCheckable : function(menuItem){ var g = menuItem.group; if(g){ groups[g].remove(menuItem); menuItem.un("beforecheckchange", onBeforeCheck); } }, getCheckedItem : function(groupId){ var g = groups[groupId]; if(g){ for(var i = 0, l = g.length; i < l; i++){ if(g[i].checked){ return g[i]; } } } return null; }, setCheckedItem : function(groupId, itemId){ var g = groups[groupId]; if(g){ for(var i = 0, l = g.length; i < l; i++){ if(g[i].id == itemId){ g[i].setChecked(true); } } } return null; } }; }(); Ext.menu.BaseItem = function(config){ Ext.menu.BaseItem.superclass.constructor.call(this, config); this.addEvents( 'click', 'activate', 'deactivate' ); if(this.handler){ this.on("click", this.handler, this.scope); } }; Ext.extend(Ext.menu.BaseItem, Ext.Component, { canActivate : false, activeClass : "x-menu-item-active", hideOnClick : true, hideDelay : 100, ctype: "Ext.menu.BaseItem", actionMode : "container", render : function(container, parentMenu){ this.parentMenu = parentMenu; Ext.menu.BaseItem.superclass.render.call(this, container); this.container.menuItemId = this.id; }, onRender : function(container, position){ this.el = Ext.get(this.el); container.dom.appendChild(this.el.dom); }, setHandler : function(handler, scope){ if(this.handler){ this.un("click", this.handler, this.scope); } this.on("click", this.handler = handler, this.scope = scope); }, onClick : function(e){ if(!this.disabled && this.fireEvent("click", this, e) !== false && this.parentMenu.fireEvent("itemclick", this, e) !== false){ this.handleClick(e); }else{ e.stopEvent(); } }, activate : function(){ if(this.disabled){ return false; } var li = this.container; li.addClass(this.activeClass); this.region = li.getRegion().adjust(2, 2, -2, -2); this.fireEvent("activate", this); return true; }, deactivate : function(){ this.container.removeClass(this.activeClass); this.fireEvent("deactivate", this); }, shouldDeactivate : function(e){ return !this.region || !this.region.contains(e.getPoint()); }, handleClick : function(e){ if(this.hideOnClick){ this.parentMenu.hide.defer(this.hideDelay, this.parentMenu, [true]); } }, expandMenu : function(autoActivate){ }, hideMenu : function(){ } }); Ext.menu.TextItem = function(text){ this.text = text; Ext.menu.TextItem.superclass.constructor.call(this); }; Ext.extend(Ext.menu.TextItem, Ext.menu.BaseItem, { hideOnClick : false, itemCls : "x-menu-text", onRender : function(){ var s = document.createElement("span"); s.className = this.itemCls; s.innerHTML = this.text; this.el = s; Ext.menu.TextItem.superclass.onRender.apply(this, arguments); } }); Ext.menu.Separator = function(config){ Ext.menu.Separator.superclass.constructor.call(this, config); }; Ext.extend(Ext.menu.Separator, Ext.menu.BaseItem, { itemCls : "x-menu-sep", hideOnClick : false, onRender : function(li){ var s = document.createElement("span"); s.className = this.itemCls; s.innerHTML = "&#160;"; this.el = s; li.addClass("x-menu-sep-li"); Ext.menu.Separator.superclass.onRender.apply(this, arguments); } }); Ext.menu.Item = function(config){ Ext.menu.Item.superclass.constructor.call(this, config); if(this.menu){ this.menu = Ext.menu.MenuMgr.get(this.menu); } }; Ext.extend(Ext.menu.Item, Ext.menu.BaseItem, { itemCls : "x-menu-item", canActivate : true, showDelay: 200, hideDelay: 200, ctype: "Ext.menu.Item", onRender : function(container, position){ var el = document.createElement("a"); el.hideFocus = true; el.unselectable = "on"; el.href = this.href || "#"; if(this.hrefTarget){ el.target = this.hrefTarget; } el.className = this.itemCls + (this.menu ? " x-menu-item-arrow" : "") + (this.cls ? " " + this.cls : ""); el.innerHTML = String.format( '<img src="{0}" class="x-menu-item-icon {2}" />{1}', this.icon || Ext.BLANK_IMAGE_URL, this.itemText||this.text, this.iconCls || ''); this.el = el; Ext.menu.Item.superclass.onRender.call(this, container, position); }, setText : function(text){ this.text = text; if(this.rendered){ this.el.update(String.format( '<img src="{0}" class="x-menu-item-icon {2}">{1}', this.icon || Ext.BLANK_IMAGE_URL, this.text, this.iconCls || '')); this.parentMenu.autoWidth(); } }, setIconClass : function(cls){ var oldCls = this.iconCls; this.iconCls = cls; if(this.rendered){ this.el.child('img.x-menu-item-icon').replaceClass(oldCls, this.iconCls); } }, handleClick : function(e){ if(!this.href){ e.stopEvent(); } Ext.menu.Item.superclass.handleClick.apply(this, arguments); }, activate : function(autoExpand){ if(Ext.menu.Item.superclass.activate.apply(this, arguments)){ this.focus(); if(autoExpand){ this.expandMenu(); } } return true; }, shouldDeactivate : function(e){ if(Ext.menu.Item.superclass.shouldDeactivate.call(this, e)){ if(this.menu && this.menu.isVisible()){ return !this.menu.getEl().getRegion().contains(e.getPoint()); } return true; } return false; }, deactivate : function(){ Ext.menu.Item.superclass.deactivate.apply(this, arguments); this.hideMenu(); }, expandMenu : function(autoActivate){ if(!this.disabled && this.menu){ clearTimeout(this.hideTimer); delete this.hideTimer; if(!this.menu.isVisible() && !this.showTimer){ this.showTimer = this.deferExpand.defer(this.showDelay, this, [autoActivate]); }else if (this.menu.isVisible() && autoActivate){ this.menu.tryActivate(0, 1); } } }, deferExpand : function(autoActivate){ delete this.showTimer; this.menu.show(this.container, this.parentMenu.subMenuAlign || "tl-tr?", this.parentMenu); if(autoActivate){ this.menu.tryActivate(0, 1); } }, hideMenu : function(){ clearTimeout(this.showTimer); delete this.showTimer; if(!this.hideTimer && this.menu && this.menu.isVisible()){ this.hideTimer = this.deferHide.defer(this.hideDelay, this); } }, deferHide : function(){ delete this.hideTimer; this.menu.hide(); } }); Ext.menu.CheckItem = function(config){ Ext.menu.CheckItem.superclass.constructor.call(this, config); this.addEvents( "beforecheckchange" , "checkchange" ); if(this.checkHandler){ this.on('checkchange', this.checkHandler, this.scope); } Ext.menu.MenuMgr.registerCheckable(this); }; Ext.extend(Ext.menu.CheckItem, Ext.menu.Item, { itemCls : "x-menu-item x-menu-check-item", groupClass : "x-menu-group-item", checked: false, ctype: "Ext.menu.CheckItem", onRender : function(c){ Ext.menu.CheckItem.superclass.onRender.apply(this, arguments); if(this.group){ this.el.addClass(this.groupClass); } if(this.checked){ this.checked = false; this.setChecked(true, true); } }, destroy : function(){ Ext.menu.MenuMgr.unregisterCheckable(this); Ext.menu.CheckItem.superclass.destroy.apply(this, arguments); }, setChecked : function(state, suppressEvent){ if(this.checked != state && this.fireEvent("beforecheckchange", this, state) !== false){ if(this.container){ this.container[state ? "addClass" : "removeClass"]("x-menu-item-checked"); } this.checked = state; if(suppressEvent !== true){ this.fireEvent("checkchange", this, state); } } }, handleClick : function(e){ if(!this.disabled && !(this.checked && this.group)){ this.setChecked(!this.checked); } Ext.menu.CheckItem.superclass.handleClick.apply(this, arguments); } }); Ext.menu.Adapter = function(component, config){ Ext.menu.Adapter.superclass.constructor.call(this, config); this.component = component; }; Ext.extend(Ext.menu.Adapter, Ext.menu.BaseItem, { canActivate : true, onRender : function(container, position){ this.component.render(container); this.el = this.component.getEl(); }, activate : function(){ if(this.disabled){ return false; } this.component.focus(); this.fireEvent("activate", this); return true; }, deactivate : function(){ this.fireEvent("deactivate", this); }, disable : function(){ this.component.disable(); Ext.menu.Adapter.superclass.disable.call(this); }, enable : function(){ this.component.enable(); Ext.menu.Adapter.superclass.enable.call(this); } }); Ext.menu.DateItem = function(config){ Ext.menu.DateItem.superclass.constructor.call(this, new Ext.DatePicker(config), config); this.picker = this.component; this.addEvents('select'); this.picker.on("render", function(picker){ picker.getEl().swallowEvent("click"); picker.container.addClass("x-menu-date-item"); }); this.picker.on("select", this.onSelect, this); }; Ext.extend(Ext.menu.DateItem, Ext.menu.Adapter, { onSelect : function(picker, date){ this.fireEvent("select", this, date, picker); Ext.menu.DateItem.superclass.handleClick.call(this); } }); Ext.menu.ColorItem = function(config){ Ext.menu.ColorItem.superclass.constructor.call(this, new Ext.ColorPalette(config), config); this.palette = this.component; this.relayEvents(this.palette, ["select"]); if(this.selectHandler){ this.on('select', this.selectHandler, this.scope); } }; Ext.extend(Ext.menu.ColorItem, Ext.menu.Adapter); Ext.menu.DateMenu = function(config){ Ext.menu.DateMenu.superclass.constructor.call(this, config); this.plain = true; var di = new Ext.menu.DateItem(config); this.add(di); this.picker = di.picker; this.relayEvents(di, ["select"]); this.on('beforeshow', function(){ if(this.picker){ this.picker.hideMonthPicker(true); } }, this); }; Ext.extend(Ext.menu.DateMenu, Ext.menu.Menu, { cls:'x-date-menu', beforeDestroy : function() { this.picker.destroy(); } }); Ext.menu.ColorMenu = function(config){ Ext.menu.ColorMenu.superclass.constructor.call(this, config); this.plain = true; var ci = new Ext.menu.ColorItem(config); this.add(ci); this.palette = ci.palette; this.relayEvents(ci, ["select"]); }; Ext.extend(Ext.menu.ColorMenu, Ext.menu.Menu); Ext.form.Field = Ext.extend(Ext.BoxComponent, { invalidClass : "x-form-invalid", invalidText : "The value in this field is invalid", focusClass : "x-form-focus", validationEvent : "keyup", validateOnBlur : true, validationDelay : 250, defaultAutoCreate : {tag: "input", type: "text", size: "20", autocomplete: "off"}, fieldClass : "x-form-field", msgTarget : 'qtip', msgFx : 'normal', readOnly : false, disabled : false, isFormField : true, hasFocus : false, initComponent : function(){ Ext.form.Field.superclass.initComponent.call(this); this.addEvents( 'focus', 'blur', 'specialkey', 'change', 'invalid', 'valid' ); }, getName: function(){ return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || ''); }, onRender : function(ct, position){ Ext.form.Field.superclass.onRender.call(this, ct, position); if(!this.el){ var cfg = this.getAutoCreate(); if(!cfg.name){ cfg.name = this.name || this.id; } if(this.inputType){ cfg.type = this.inputType; } this.el = ct.createChild(cfg, position); } var type = this.el.dom.type; if(type){ if(type == 'password'){ type = 'text'; } this.el.addClass('x-form-'+type); } if(this.readOnly){ this.el.dom.readOnly = true; } if(this.tabIndex !== undefined){ this.el.dom.setAttribute('tabIndex', this.tabIndex); } this.el.addClass([this.fieldClass, this.cls]); this.initValue(); }, initValue : function(){ if(this.value !== undefined){ this.setValue(this.value); }else if(this.el.dom.value.length > 0){ this.setValue(this.el.dom.value); } }, isDirty : function() { if(this.disabled) { return false; } return String(this.getValue()) !== String(this.originalValue); }, afterRender : function(){ Ext.form.Field.superclass.afterRender.call(this); this.initEvents(); }, fireKey : function(e){ if(e.isSpecialKey()){ this.fireEvent("specialkey", this, e); } }, reset : function(){ this.setValue(this.originalValue); this.clearInvalid(); }, initEvents : function(){ this.el.on(Ext.isIE ? "keydown" : "keypress", this.fireKey, this); this.el.on("focus", this.onFocus, this); this.el.on("blur", this.onBlur, this); this.originalValue = this.getValue(); }, onFocus : function(){ if(!Ext.isOpera && this.focusClass){ this.el.addClass(this.focusClass); } if(!this.hasFocus){ this.hasFocus = true; this.startValue = this.getValue(); this.fireEvent("focus", this); } }, beforeBlur : Ext.emptyFn, onBlur : function(){ this.beforeBlur(); if(!Ext.isOpera && this.focusClass){ this.el.removeClass(this.focusClass); } this.hasFocus = false; if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){ this.validate(); } var v = this.getValue(); if(String(v) !== String(this.startValue)){ this.fireEvent('change', this, v, this.startValue); } this.fireEvent("blur", this); }, isValid : function(preventMark){ if(this.disabled){ return true; } var restore = this.preventMark; this.preventMark = preventMark === true; var v = this.validateValue(this.processValue(this.getRawValue())); this.preventMark = restore; return v; }, validate : function(){ if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){ this.clearInvalid(); return true; } return false; }, processValue : function(value){ return value; }, validateValue : function(value){ return true; }, markInvalid : function(msg){ if(!this.rendered || this.preventMark){ return; } this.el.addClass(this.invalidClass); msg = msg || this.invalidText; switch(this.msgTarget){ case 'qtip': this.el.dom.qtip = msg; this.el.dom.qclass = 'x-form-invalid-tip'; if(Ext.QuickTips){ Ext.QuickTips.enable(); } break; case 'title': this.el.dom.title = msg; break; case 'under': if(!this.errorEl){ var elp = this.el.findParent('.x-form-element', 5, true); this.errorEl = elp.createChild({cls:'x-form-invalid-msg'}); this.errorEl.setWidth(elp.getWidth(true)-20); } this.errorEl.update(msg); Ext.form.Field.msgFx[this.msgFx].show(this.errorEl, this); break; case 'side': if(!this.errorIcon){ var elp = this.el.findParent('.x-form-element', 5, true); this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'}); } this.alignErrorIcon(); this.errorIcon.dom.qtip = msg; this.errorIcon.dom.qclass = 'x-form-invalid-tip'; this.errorIcon.show(); this.on('resize', this.alignErrorIcon, this); break; default: var t = Ext.getDom(this.msgTarget); t.innerHTML = msg; t.style.display = this.msgDisplay; break; } this.fireEvent('invalid', this, msg); }, alignErrorIcon : function(){ this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]); }, clearInvalid : function(){ if(!this.rendered || this.preventMark){ return; } this.el.removeClass(this.invalidClass); switch(this.msgTarget){ case 'qtip': this.el.dom.qtip = ''; break; case 'title': this.el.dom.title = ''; break; case 'under': if(this.errorEl){ Ext.form.Field.msgFx[this.msgFx].hide(this.errorEl, this); } break; case 'side': if(this.errorIcon){ this.errorIcon.dom.qtip = ''; this.errorIcon.hide(); this.un('resize', this.alignErrorIcon, this); } break; default: var t = Ext.getDom(this.msgTarget); t.innerHTML = ''; t.style.display = 'none'; break; } this.fireEvent('valid', this); }, getRawValue : function(){ var v = this.rendered ? this.el.getValue() : Ext.value(this.value, ''); if(v === this.emptyText){ v = ''; } return v; }, getValue : function(){ if(!this.rendered) { return this.value; } var v = this.el.getValue(); if(v === this.emptyText || v === undefined){ v = ''; } return v; }, setRawValue : function(v){ return this.el.dom.value = (v === null || v === undefined ? '' : v); }, setValue : function(v){ this.value = v; if(this.rendered){ this.el.dom.value = (v === null || v === undefined ? '' : v); this.validate(); } }, adjustSize : function(w, h){ var s = Ext.form.Field.superclass.adjustSize.call(this, w, h); s.width = this.adjustWidth(this.el.dom.tagName, s.width); return s; }, adjustWidth : function(tag, w){ tag = tag.toLowerCase(); if(typeof w == 'number' && !Ext.isSafari){ if(Ext.isIE && (tag == 'input' || tag == 'textarea')){ if(tag == 'input' && !Ext.isStrict){ return this.inEditor ? w : w - 3; } if(tag == 'input' && Ext.isStrict){ return w - (Ext.isIE6 ? 4 : 1); } if(tag = 'textarea' && Ext.isStrict){ return w-2; } }else if(Ext.isOpera && Ext.isStrict){ if(tag == 'input'){ return w + 2; } if(tag = 'textarea'){ return w-2; } } } return w; } }); Ext.form.Field.msgFx = { normal : { show: function(msgEl, f){ msgEl.setDisplayed('block'); }, hide : function(msgEl, f){ msgEl.setDisplayed(false).update(''); } }, slide : { show: function(msgEl, f){ msgEl.slideIn('t', {stopFx:true}); }, hide : function(msgEl, f){ msgEl.slideOut('t', {stopFx:true,useDisplay:true}); } }, slideRight : { show: function(msgEl, f){ msgEl.fixDisplay(); msgEl.alignTo(f.el, 'tl-tr'); msgEl.slideIn('l', {stopFx:true}); }, hide : function(msgEl, f){ msgEl.slideOut('l', {stopFx:true,useDisplay:true}); } } }; Ext.reg('field', Ext.form.Field); Ext.form.TextField = Ext.extend(Ext.form.Field, { grow : false, growMin : 30, growMax : 800, vtype : null, maskRe : null, disableKeyFilter : false, allowBlank : true, minLength : 0, maxLength : Number.MAX_VALUE, minLengthText : "The minimum length for this field is {0}", maxLengthText : "The maximum length for this field is {0}", selectOnFocus : false, blankText : "This field is required", validator : null, regex : null, regexText : "", emptyText : null, emptyClass : 'x-form-empty-field', initComponent : function(){ Ext.form.TextField.superclass.initComponent.call(this); this.addEvents( 'autosize' ); }, initEvents : function(){ Ext.form.TextField.superclass.initEvents.call(this); if(this.validationEvent == 'keyup'){ this.validationTask = new Ext.util.DelayedTask(this.validate, this); this.el.on('keyup', this.filterValidation, this); } else if(this.validationEvent !== false){ this.el.on(this.validationEvent, this.validate, this, {buffer: this.validationDelay}); } if(this.selectOnFocus || this.emptyText){ this.on("focus", this.preFocus, this); if(this.emptyText){ this.on('blur', this.postBlur, this); this.applyEmptyText(); } } if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){ this.el.on("keypress", this.filterKeys, this); } if(this.grow){ this.el.on("keyup", this.onKeyUp, this, {buffer:50}); this.el.on("click", this.autoSize, this); } }, processValue : function(value){ if(this.stripCharsRe){ var newValue = value.replace(this.stripCharsRe, ''); if(newValue !== value){ this.setRawValue(newValue); return newValue; } } return value; }, filterValidation : function(e){ if(!e.isNavKeyPress()){ this.validationTask.delay(this.validationDelay); } }, onKeyUp : function(e){ if(!e.isNavKeyPress()){ this.autoSize(); } }, reset : function(){ Ext.form.TextField.superclass.reset.call(this); this.applyEmptyText(); }, applyEmptyText : function(){ if(this.rendered && this.emptyText && this.getRawValue().length < 1){ this.setRawValue(this.emptyText); this.el.addClass(this.emptyClass); } }, preFocus : function(){ if(this.emptyText){ if(this.el.dom.value == this.emptyText){ this.setRawValue(''); } this.el.removeClass(this.emptyClass); } if(this.selectOnFocus){ this.el.dom.select(); } }, postBlur : function(){ this.applyEmptyText(); }, filterKeys : function(e){ var k = e.getKey(); if(!Ext.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){ return; } var c = e.getCharCode(), cc = String.fromCharCode(c); if(Ext.isIE && (e.isSpecialKey() || !cc)){ return; } if(!this.maskRe.test(cc)){ e.stopEvent(); } }, setValue : function(v){ if(this.emptyText && this.el && v !== undefined && v !== null && v !== ''){ this.el.removeClass(this.emptyClass); } Ext.form.TextField.superclass.setValue.apply(this, arguments); this.applyEmptyText(); this.autoSize(); }, validateValue : function(value){ if(value.length < 1 || value === this.emptyText){ if(this.allowBlank){ this.clearInvalid(); return true; }else{ this.markInvalid(this.blankText); return false; } } if(value.length < this.minLength){ this.markInvalid(String.format(this.minLengthText, this.minLength)); return false; } if(value.length > this.maxLength){ this.markInvalid(String.format(this.maxLengthText, this.maxLength)); return false; } if(this.vtype){ var vt = Ext.form.VTypes; if(!vt[this.vtype](value, this)){ this.markInvalid(this.vtypeText || vt[this.vtype +'Text']); return false; } } if(typeof this.validator == "function"){ var msg = this.validator(value); if(msg !== true){ this.markInvalid(msg); return false; } } if(this.regex && !this.regex.test(value)){ this.markInvalid(this.regexText); return false; } return true; }, selectText : function(start, end){ var v = this.getRawValue(); if(v.length > 0){ start = start === undefined ? 0 : start; end = end === undefined ? v.length : end; var d = this.el.dom; if(d.setSelectionRange){ d.setSelectionRange(start, end); }else if(d.createTextRange){ var range = d.createTextRange(); range.moveStart("character", start); range.moveEnd("character", end-v.length); range.select(); } } }, autoSize : function(){ if(!this.grow || !this.rendered){ return; } if(!this.metrics){ this.metrics = Ext.util.TextMetrics.createInstance(this.el); } var el = this.el; var v = el.dom.value; var d = document.createElement('div'); d.appendChild(document.createTextNode(v)); v = d.innerHTML; d = null; v += "&#160;"; var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + 10, this.growMin)); this.el.setWidth(w); this.fireEvent("autosize", this, w); } }); Ext.reg('textfield', Ext.form.TextField); Ext.form.TriggerField = Ext.extend(Ext.form.TextField, { defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"}, hideTrigger:false, autoSize: Ext.emptyFn, monitorTab : true, deferHeight : true, mimicing : false, onResize : function(w, h){ Ext.form.TriggerField.superclass.onResize.call(this, w, h); if(typeof w == 'number'){ this.el.setWidth(this.adjustWidth('input', w - this.trigger.getWidth())); } this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()); }, adjustSize : Ext.BoxComponent.prototype.adjustSize, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, alignErrorIcon : function(){ this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]); }, onRender : function(ct, position){ Ext.form.TriggerField.superclass.onRender.call(this, ct, position); this.wrap = this.el.wrap({cls: "x-form-field-wrap"}); this.trigger = this.wrap.createChild(this.triggerConfig || {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}); if(this.hideTrigger){ this.trigger.setDisplayed(false); } this.initTrigger(); if(!this.width){ this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()); } }, initTrigger : function(){ this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true}); this.trigger.addClassOnOver('x-form-trigger-over'); this.trigger.addClassOnClick('x-form-trigger-click'); }, onDestroy : function(){ if(this.trigger){ this.trigger.removeAllListeners(); this.trigger.remove(); } if(this.wrap){ this.wrap.remove(); } Ext.form.TriggerField.superclass.onDestroy.call(this); }, onFocus : function(){ Ext.form.TriggerField.superclass.onFocus.call(this); if(!this.mimicing){ this.wrap.addClass('x-trigger-wrap-focus'); this.mimicing = true; Ext.get(Ext.isIE ? document.body : document).on("mousedown", this.mimicBlur, this, {delay: 10}); if(this.monitorTab){ this.el.on("keydown", this.checkTab, this); } } }, checkTab : function(e){ if(e.getKey() == e.TAB){ this.triggerBlur(); } }, onBlur : function(){ }, mimicBlur : function(e){ if(!this.wrap.contains(e.target) && this.validateBlur(e)){ this.triggerBlur(); } }, triggerBlur : function(){ this.mimicing = false; Ext.get(Ext.isIE ? document.body : document).un("mousedown", this.mimicBlur); if(this.monitorTab){ this.el.un("keydown", this.checkTab, this); } this.beforeBlur(); this.wrap.removeClass('x-trigger-wrap-focus'); Ext.form.TriggerField.superclass.onBlur.call(this); }, beforeBlur : Ext.emptyFn, validateBlur : function(e){ return true; }, onDisable : function(){ Ext.form.TriggerField.superclass.onDisable.call(this); if(this.wrap){ this.wrap.addClass('x-item-disabled'); } }, onEnable : function(){ Ext.form.TriggerField.superclass.onEnable.call(this); if(this.wrap){ this.wrap.removeClass('x-item-disabled'); } }, onShow : function(){ if(this.wrap){ this.wrap.dom.style.display = ''; this.wrap.dom.style.visibility = 'visible'; } }, onHide : function(){ this.wrap.dom.style.display = 'none'; }, onTriggerClick : Ext.emptyFn }); Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, { initComponent : function(){ Ext.form.TwinTriggerField.superclass.initComponent.call(this); this.triggerConfig = { tag:'span', cls:'x-form-twin-triggers', cn:[ {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class}, {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class} ]}; }, getTrigger : function(index){ return this.triggers[index]; }, initTrigger : function(){ var ts = this.trigger.select('.x-form-trigger', true); this.wrap.setStyle('overflow', 'hidden'); var triggerField = this; ts.each(function(t, all, index){ t.hide = function(){ var w = triggerField.wrap.getWidth(); this.dom.style.display = 'none'; triggerField.el.setWidth(w-triggerField.trigger.getWidth()); }; t.show = function(){ var w = triggerField.wrap.getWidth(); this.dom.style.display = ''; triggerField.el.setWidth(w-triggerField.trigger.getWidth()); }; var triggerIndex = 'Trigger'+(index+1); if(this['hide'+triggerIndex]){ t.dom.style.display = 'none'; } t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true}); t.addClassOnOver('x-form-trigger-over'); t.addClassOnClick('x-form-trigger-click'); }, this); this.triggers = ts.elements; }, onTrigger1Click : Ext.emptyFn, onTrigger2Click : Ext.emptyFn }); Ext.reg('trigger', Ext.form.TriggerField); Ext.form.TextArea = Ext.extend(Ext.form.TextField, { growMin : 60, growMax: 1000, growAppend : '&#160;\n&#160;', growPad : 0, enterIsSpecial : false, preventScrollbars: false, onRender : function(ct, position){ if(!this.el){ this.defaultAutoCreate = { tag: "textarea", style:"width:100px;height:60px;", autocomplete: "off" }; } Ext.form.TextArea.superclass.onRender.call(this, ct, position); if(this.grow){ this.textSizeEl = Ext.DomHelper.append(document.body, { tag: "pre", cls: "x-form-grow-sizer" }); if(this.preventScrollbars){ this.el.setStyle("overflow", "hidden"); } this.el.setHeight(this.growMin); } }, onDestroy : function(){ if(this.textSizeEl){ Ext.removeNode(this.textSizeEl); } Ext.form.TextArea.superclass.onDestroy.call(this); }, fireKey : function(e){ if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){ this.fireEvent("specialkey", this, e); } }, onKeyUp : function(e){ if(!e.isNavKeyPress() || e.getKey() == e.ENTER){ this.autoSize(); } }, autoSize : function(){ if(!this.grow || !this.textSizeEl){ return; } var el = this.el; var v = el.dom.value; var ts = this.textSizeEl; ts.innerHTML = ''; ts.appendChild(document.createTextNode(v)); v = ts.innerHTML; Ext.fly(ts).setWidth(this.el.getWidth()); if(v.length < 1){ v = "&#160;&#160;"; }else{ if(Ext.isIE){ v = v.replace(/\n/g, '<p>&#160;</p>'); } v += this.growAppend; } ts.innerHTML = v; var h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin)+this.growPad); if(h != this.lastHeight){ this.lastHeight = h; this.el.setHeight(h); this.fireEvent("autosize", this, h); } } }); Ext.reg('textarea', Ext.form.TextArea); Ext.form.NumberField = Ext.extend(Ext.form.TextField, { fieldClass: "x-form-field x-form-num-field", allowDecimals : true, decimalSeparator : ".", decimalPrecision : 2, allowNegative : true, minValue : Number.NEGATIVE_INFINITY, maxValue : Number.MAX_VALUE, minText : "The minimum value for this field is {0}", maxText : "The maximum value for this field is {0}", nanText : "{0} is not a valid number", baseChars : "0123456789", initEvents : function(){ Ext.form.NumberField.superclass.initEvents.call(this); var allowed = this.baseChars+''; if(this.allowDecimals){ allowed += this.decimalSeparator; } if(this.allowNegative){ allowed += "-"; } this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi'); var keyPress = function(e){ var k = e.getKey(); if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){ return; } var c = e.getCharCode(); if(allowed.indexOf(String.fromCharCode(c)) === -1){ e.stopEvent(); } }; this.el.on("keypress", keyPress, this); }, validateValue : function(value){ if(!Ext.form.NumberField.superclass.validateValue.call(this, value)){ return false; } if(value.length < 1){ return true; } value = String(value).replace(this.decimalSeparator, "."); if(isNaN(value)){ this.markInvalid(String.format(this.nanText, value)); return false; } var num = this.parseValue(value); if(num < this.minValue){ this.markInvalid(String.format(this.minText, this.minValue)); return false; } if(num > this.maxValue){ this.markInvalid(String.format(this.maxText, this.maxValue)); return false; } return true; }, getValue : function(){ return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this))); }, setValue : function(v){ v = parseFloat(v); v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator); Ext.form.NumberField.superclass.setValue.call(this, v); }, parseValue : function(value){ value = parseFloat(String(value).replace(this.decimalSeparator, ".")); return isNaN(value) ? '' : value; }, fixPrecision : function(value){ var nan = isNaN(value); if(!this.allowDecimals || this.decimalPrecision == -1 || nan || !value){ return nan ? '' : value; } return parseFloat(parseFloat(value).toFixed(this.decimalPrecision)); }, beforeBlur : function(){ var v = this.parseValue(this.getRawValue()); if(v){ this.setValue(this.fixPrecision(v)); } } }); Ext.reg('numberfield', Ext.form.NumberField); Ext.form.DateField = Ext.extend(Ext.form.TriggerField, { format : "m/d/y", altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d", disabledDays : null, disabledDaysText : "Disabled", disabledDates : null, disabledDatesText : "Disabled", minValue : null, maxValue : null, minText : "The date in this field must be equal to or after {0}", maxText : "The date in this field must be equal to or before {0}", invalidText : "{0} is not a valid date - it must be in the format {1}", triggerClass : 'x-form-date-trigger', defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"}, initComponent : function(){ Ext.form.DateField.superclass.initComponent.call(this); if(typeof this.minValue == "string"){ this.minValue = this.parseDate(this.minValue); } if(typeof this.maxValue == "string"){ this.maxValue = this.parseDate(this.maxValue); } this.ddMatch = null; if(this.disabledDates){ var dd = this.disabledDates; var re = "(?:"; for(var i = 0; i < dd.length; i++){ re += dd[i]; if(i != dd.length-1) re += "|"; } this.ddMatch = new RegExp(re + ")"); } }, validateValue : function(value){ value = this.formatDate(value); if(!Ext.form.DateField.superclass.validateValue.call(this, value)){ return false; } if(value.length < 1){ return true; } var svalue = value; value = this.parseDate(value); if(!value){ this.markInvalid(String.format(this.invalidText, svalue, this.format)); return false; } var time = value.getTime(); if(this.minValue && time < this.minValue.getTime()){ this.markInvalid(String.format(this.minText, this.formatDate(this.minValue))); return false; } if(this.maxValue && time > this.maxValue.getTime()){ this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue))); return false; } if(this.disabledDays){ var day = value.getDay(); for(var i = 0; i < this.disabledDays.length; i++) { if(day === this.disabledDays[i]){ this.markInvalid(this.disabledDaysText); return false; } } } var fvalue = this.formatDate(value); if(this.ddMatch && this.ddMatch.test(fvalue)){ this.markInvalid(String.format(this.disabledDatesText, fvalue)); return false; } return true; }, validateBlur : function(){ return !this.menu || !this.menu.isVisible(); }, getValue : function(){ return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || ""; }, setValue : function(date){ Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date))); }, parseDate : function(value){ if(!value || Ext.isDate(value)){ return value; } var v = Date.parseDate(value, this.format); if(!v && this.altFormats){ if(!this.altFormatsArray){ this.altFormatsArray = this.altFormats.split("|"); } for(var i = 0, len = this.altFormatsArray.length; i < len && !v; i++){ v = Date.parseDate(value, this.altFormatsArray[i]); } } return v; }, onDestroy : function(){ if(this.menu) { this.menu.destroy(); } if(this.wrap){ this.wrap.remove(); } Ext.form.DateField.superclass.onDestroy.call(this); }, formatDate : function(date){ return Ext.isDate(date) ? date.dateFormat(this.format) : date; }, menuListeners : { select: function(m, d){ this.setValue(d); }, show : function(){ this.onFocus(); }, hide : function(){ this.focus.defer(10, this); var ml = this.menuListeners; this.menu.un("select", ml.select, this); this.menu.un("show", ml.show, this); this.menu.un("hide", ml.hide, this); } }, onTriggerClick : function(){ if(this.disabled){ return; } if(this.menu == null){ this.menu = new Ext.menu.DateMenu(); } Ext.apply(this.menu.picker, { minDate : this.minValue, maxDate : this.maxValue, disabledDatesRE : this.ddMatch, disabledDatesText : this.disabledDatesText, disabledDays : this.disabledDays, disabledDaysText : this.disabledDaysText, format : this.format, minText : String.format(this.minText, this.formatDate(this.minValue)), maxText : String.format(this.maxText, this.formatDate(this.maxValue)) }); this.menu.on(Ext.apply({}, this.menuListeners, { scope:this })); this.menu.picker.setValue(this.getValue() || new Date()); this.menu.show(this.el, "tl-bl?"); }, beforeBlur : function(){ var v = this.parseDate(this.getRawValue()); if(v){ this.setValue(v); } } }); Ext.reg('datefield', Ext.form.DateField); Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, { defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"}, listClass: '', selectedClass: 'x-combo-selected', triggerClass : 'x-form-arrow-trigger', shadow:'sides', listAlign: 'tl-bl?', maxHeight: 300, minHeight: 90, triggerAction: 'query', minChars : 4, typeAhead: false, queryDelay: 500, pageSize: 0, selectOnFocus:false, queryParam: 'query', loadingText: 'Loading...', resizable: false, handleHeight : 8, editable: true, allQuery: '', mode: 'remote', minListWidth : 70, forceSelection:false, typeAheadDelay : 250, lazyInit : true, initComponent : function(){ Ext.form.ComboBox.superclass.initComponent.call(this); this.addEvents( 'expand', 'collapse', 'beforeselect', 'select', 'beforequery' ); if(this.transform){ this.allowDomMove = false; var s = Ext.getDom(this.transform); if(!this.hiddenName){ this.hiddenName = s.name; } if(!this.store){ this.mode = 'local'; var d = [], opts = s.options; for(var i = 0, len = opts.length;i < len; i++){ var o = opts[i]; var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text; if(o.selected) { this.value = value; } d.push([value, o.text]); } this.store = new Ext.data.SimpleStore({ 'id': 0, fields: ['value', 'text'], data : d }); this.valueField = 'value'; this.displayField = 'text'; } s.name = Ext.id(); if(!this.lazyRender){ this.target = true; this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate); Ext.removeNode(s); this.render(this.el.parentNode); }else{ Ext.removeNode(s); } } this.selectedIndex = -1; if(this.mode == 'local'){ if(this.initialConfig.queryDelay === undefined){ this.queryDelay = 10; } if(this.initialConfig.minChars === undefined){ this.minChars = 0; } } }, onRender : function(ct, position){ Ext.form.ComboBox.superclass.onRender.call(this, ct, position); if(this.hiddenName){ this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName, id: (this.hiddenId||this.hiddenName)}, 'before', true); this.hiddenField.value = this.hiddenValue !== undefined ? this.hiddenValue : this.value !== undefined ? this.value : ''; this.el.dom.removeAttribute('name'); } if(Ext.isGecko){ this.el.dom.setAttribute('autocomplete', 'off'); } if(!this.lazyInit){ this.initList(); }else{ this.on('focus', this.initList, this, {single: true}); } if(!this.editable){ this.editable = true; this.setEditable(false); } }, initList : function(){ if(!this.list){ var cls = 'x-combo-list'; this.list = new Ext.Layer({ shadow: this.shadow, cls: [cls, this.listClass].join(' '), constrain:false }); var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth); this.list.setWidth(lw); this.list.swallowEvent('mousewheel'); this.assetHeight = 0; if(this.title){ this.header = this.list.createChild({cls:cls+'-hd', html: this.title}); this.assetHeight += this.header.getHeight(); } this.innerList = this.list.createChild({cls:cls+'-inner'}); this.innerList.on('mouseover', this.onViewOver, this); this.innerList.on('mousemove', this.onViewMove, this); this.innerList.setWidth(lw - this.list.getFrameWidth('lr')); if(this.pageSize){ this.footer = this.list.createChild({cls:cls+'-ft'}); this.pageTb = new Ext.PagingToolbar({ store:this.store, pageSize: this.pageSize, renderTo:this.footer }); this.assetHeight += this.footer.getHeight(); } if(!this.tpl){ this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>'; } this.view = new Ext.DataView({ applyTo: this.innerList, tpl: this.tpl, singleSelect: true, selectedClass: this.selectedClass, itemSelector: this.itemSelector || '.' + cls + '-item' }); this.view.on('click', this.onViewClick, this); this.bindStore(this.store, true); if(this.resizable){ this.resizer = new Ext.Resizable(this.list, { pinned:true, handles:'se' }); this.resizer.on('resize', function(r, w, h){ this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight; this.listWidth = w; this.innerList.setWidth(w - this.list.getFrameWidth('lr')); this.restrictHeight(); }, this); this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px'); } } }, bindStore : function(store, initial){ if(this.store && !initial){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.collapse, this); if(!store){ this.store = null; if(this.view){ this.view.setStore(null); } } } if(store){ this.store = Ext.StoreMgr.lookup(store); this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.collapse, this); if(this.view){ this.view.setStore(store); } } }, initEvents : function(){ Ext.form.ComboBox.superclass.initEvents.call(this); this.keyNav = new Ext.KeyNav(this.el, { "up" : function(e){ this.inKeyMode = true; this.selectPrev(); }, "down" : function(e){ if(!this.isExpanded()){ this.onTriggerClick(); }else{ this.inKeyMode = true; this.selectNext(); } }, "enter" : function(e){ this.onViewClick(); this.delayedCheck = true; this.unsetDelayCheck.defer(10, this); }, "esc" : function(e){ this.collapse(); }, "tab" : function(e){ this.onViewClick(false); return true; }, scope : this, doRelay : function(foo, bar, hname){ if(hname == 'down' || this.scope.isExpanded()){ return Ext.KeyNav.prototype.doRelay.apply(this, arguments); } return true; }, forceKeyDown : true }); this.queryDelay = Math.max(this.queryDelay || 10, this.mode == 'local' ? 10 : 250); this.dqTask = new Ext.util.DelayedTask(this.initQuery, this); if(this.typeAhead){ this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this); } if(this.editable !== false){ this.el.on("keyup", this.onKeyUp, this); } if(this.forceSelection){ this.on('blur', this.doForce, this); } }, onDestroy : function(){ if(this.view){ this.view.el.removeAllListeners(); this.view.el.remove(); this.view.purgeListeners(); } if(this.list){ this.list.destroy(); } this.bindStore(null); Ext.form.ComboBox.superclass.onDestroy.call(this); }, unsetDelayCheck : function(){ delete this.delayedCheck; }, fireKey : function(e){ if(e.isNavKeyPress() && !this.isExpanded() && !this.delayedCheck){ this.fireEvent("specialkey", this, e); } }, onResize: function(w, h){ Ext.form.ComboBox.superclass.onResize.apply(this, arguments); if(this.list && this.listWidth === undefined){ var lw = Math.max(w, this.minListWidth); this.list.setWidth(lw); this.innerList.setWidth(lw - this.list.getFrameWidth('lr')); } }, onEnable: function(){ Ext.form.ComboBox.superclass.onEnable.apply(this, arguments); if(this.hiddenField){ this.hiddenField.disabled = false; } }, onDisable: function(){ Ext.form.ComboBox.superclass.onDisable.apply(this, arguments); if(this.hiddenField){ this.hiddenField.disabled = true; } }, setEditable : function(value){ if(value == this.editable){ return; } this.editable = value; if(!value){ this.el.dom.setAttribute('readOnly', true); this.el.on('mousedown', this.onTriggerClick, this); this.el.addClass('x-combo-noedit'); }else{ this.el.dom.setAttribute('readOnly', false); this.el.un('mousedown', this.onTriggerClick, this); this.el.removeClass('x-combo-noedit'); } }, onBeforeLoad : function(){ if(!this.hasFocus){ return; } this.innerList.update(this.loadingText ? '<div class="loading-indicator">'+this.loadingText+'</div>' : ''); this.restrictHeight(); this.selectedIndex = -1; }, onLoad : function(){ if(!this.hasFocus){ return; } if(this.store.getCount() > 0){ this.expand(); this.restrictHeight(); if(this.lastQuery == this.allQuery){ if(this.editable){ this.el.dom.select(); } if(!this.selectByValue(this.value, true)){ this.select(0, true); } }else{ this.selectNext(); if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){ this.taTask.delay(this.typeAheadDelay); } } }else{ this.onEmptyResults(); } }, onTypeAhead : function(){ if(this.store.getCount() > 0){ var r = this.store.getAt(0); var newValue = r.data[this.displayField]; var len = newValue.length; var selStart = this.getRawValue().length; if(selStart != len){ this.setRawValue(newValue); this.selectText(selStart, newValue.length); } } }, onSelect : function(record, index){ if(this.fireEvent('beforeselect', this, record, index) !== false){ this.setValue(record.data[this.valueField || this.displayField]); this.collapse(); this.fireEvent('select', this, record, index); } }, getValue : function(){ if(this.valueField){ return typeof this.value != 'undefined' ? this.value : ''; }else{ return Ext.form.ComboBox.superclass.getValue.call(this); } }, clearValue : function(){ if(this.hiddenField){ this.hiddenField.value = ''; } this.setRawValue(''); this.lastSelectionText = ''; this.applyEmptyText(); this.value = ''; }, setValue : function(v){ var text = v; if(this.valueField){ var r = this.findRecord(this.valueField, v); if(r){ text = r.data[this.displayField]; }else if(this.valueNotFoundText !== undefined){ text = this.valueNotFoundText; } } this.lastSelectionText = text; if(this.hiddenField){ this.hiddenField.value = v; } Ext.form.ComboBox.superclass.setValue.call(this, text); this.value = v; }, findRecord : function(prop, value){ var record; if(this.store.getCount() > 0){ this.store.each(function(r){ if(r.data[prop] == value){ record = r; return false; } }); } return record; }, onViewMove : function(e, t){ this.inKeyMode = false; }, onViewOver : function(e, t){ if(this.inKeyMode){ return; } var item = this.view.findItemFromChild(t); if(item){ var index = this.view.indexOf(item); this.select(index, false); } }, onViewClick : function(doFocus){ var index = this.view.getSelectedIndexes()[0]; var r = this.store.getAt(index); if(r){ this.onSelect(r, index); } if(doFocus !== false){ this.el.focus(); } }, restrictHeight : function(){ this.innerList.dom.style.height = ''; var inner = this.innerList.dom; var pad = this.list.getFrameWidth('tb')+(this.resizable?this.handleHeight:0)+this.assetHeight; var h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight); var ha = this.getPosition()[1]-Ext.getBody().getScroll().top; var hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height; var space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadow.offset-pad-2; h = Math.min(h, space, this.maxHeight); this.innerList.setHeight(h); this.list.beginUpdate(); this.list.setHeight(h+pad); this.list.alignTo(this.el, this.listAlign); this.list.endUpdate(); }, onEmptyResults : function(){ this.collapse(); }, isExpanded : function(){ return this.list && this.list.isVisible(); }, selectByValue : function(v, scrollIntoView){ if(v !== undefined && v !== null){ var r = this.findRecord(this.valueField || this.displayField, v); if(r){ this.select(this.store.indexOf(r), scrollIntoView); return true; } } return false; }, select : function(index, scrollIntoView){ this.selectedIndex = index; this.view.select(index); if(scrollIntoView !== false){ var el = this.view.getNode(index); if(el){ this.innerList.scrollChildIntoView(el, false); } } }, selectNext : function(){ var ct = this.store.getCount(); if(ct > 0){ if(this.selectedIndex == -1){ this.select(0); }else if(this.selectedIndex < ct-1){ this.select(this.selectedIndex+1); } } }, selectPrev : function(){ var ct = this.store.getCount(); if(ct > 0){ if(this.selectedIndex == -1){ this.select(0); }else if(this.selectedIndex != 0){ this.select(this.selectedIndex-1); } } }, onKeyUp : function(e){ if(this.editable !== false && !e.isSpecialKey()){ this.lastKey = e.getKey(); this.dqTask.delay(this.queryDelay); } }, validateBlur : function(){ return !this.list || !this.list.isVisible(); }, initQuery : function(){ this.doQuery(this.getRawValue()); }, doForce : function(){ if(this.el.dom.value.length > 0){ this.el.dom.value = this.lastSelectionText === undefined ? '' : this.lastSelectionText; this.applyEmptyText(); } }, doQuery : function(q, forceAll){ if(q === undefined || q === null){ q = ''; } var qe = { query: q, forceAll: forceAll, combo: this, cancel:false }; if(this.fireEvent('beforequery', qe)===false || qe.cancel){ return false; } q = qe.query; forceAll = qe.forceAll; if(forceAll === true || (q.length >= this.minChars)){ if(this.lastQuery !== q){ this.lastQuery = q; if(this.mode == 'local'){ this.selectedIndex = -1; if(forceAll){ this.store.clearFilter(); }else{ this.store.filter(this.displayField, q); } this.onLoad(); }else{ this.store.baseParams[this.queryParam] = q; this.store.load({ params: this.getParams(q) }); this.expand(); } }else{ this.selectedIndex = -1; this.onLoad(); } } }, getParams : function(q){ var p = {}; if(this.pageSize){ p.start = 0; p.limit = this.pageSize; } return p; }, collapse : function(){ if(!this.isExpanded()){ return; } this.list.hide(); Ext.getDoc().un('mousewheel', this.collapseIf, this); Ext.getDoc().un('mousedown', this.collapseIf, this); this.fireEvent('collapse', this); }, collapseIf : function(e){ if(!e.within(this.wrap) && !e.within(this.list)){ this.collapse(); } }, expand : function(){ if(this.isExpanded() || !this.hasFocus){ return; } this.list.alignTo(this.wrap, this.listAlign); this.list.show(); this.innerList.setOverflow('auto'); Ext.getDoc().on('mousewheel', this.collapseIf, this); Ext.getDoc().on('mousedown', this.collapseIf, this); this.fireEvent('expand', this); }, onTriggerClick : function(){ if(this.disabled){ return; } if(this.isExpanded()){ this.collapse(); this.el.focus(); }else { this.onFocus({}); if(this.triggerAction == 'all') { this.doQuery(this.allQuery, true); } else { this.doQuery(this.getRawValue()); } this.el.focus(); } } }); Ext.reg('combo', Ext.form.ComboBox); Ext.form.Checkbox = Ext.extend(Ext.form.Field, { focusClass : undefined, fieldClass: "x-form-field", checked: false, defaultAutoCreate : { tag: "input", type: 'checkbox', autocomplete: "off"}, initComponent : function(){ Ext.form.Checkbox.superclass.initComponent.call(this); this.addEvents( 'check' ); }, onResize : function(){ Ext.form.Checkbox.superclass.onResize.apply(this, arguments); if(!this.boxLabel){ this.el.alignTo(this.wrap, 'c-c'); } }, initEvents : function(){ Ext.form.Checkbox.superclass.initEvents.call(this); this.el.on("click", this.onClick, this); this.el.on("change", this.onClick, this); }, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn, onRender : function(ct, position){ Ext.form.Checkbox.superclass.onRender.call(this, ct, position); if(this.inputValue !== undefined){ this.el.dom.value = this.inputValue; } this.wrap = this.el.wrap({cls: "x-form-check-wrap"}); if(this.boxLabel){ this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel}); } if(this.checked){ this.setValue(true); }else{ this.checked = this.el.dom.checked; } }, onDestroy : function(){ if(this.wrap){ this.wrap.remove(); } Ext.form.Checkbox.superclass.onDestroy.call(this); }, initValue : Ext.emptyFn, getValue : function(){ if(this.rendered){ return this.el.dom.checked; } return false; }, onClick : function(){ if(this.el.dom.checked != this.checked){ this.setValue(this.el.dom.checked); } }, setValue : function(v){ this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on'); if(this.el && this.el.dom){ this.el.dom.checked = this.checked; this.el.dom.defaultChecked = this.checked; } this.fireEvent("check", this, this.checked); } }); Ext.reg('checkbox', Ext.form.Checkbox); Ext.form.Radio = Ext.extend(Ext.form.Checkbox, { inputType: 'radio', markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn, getGroupValue : function(){ var p = this.el.up('form') || Ext.getBody(); var c = p.child('input[name='+this.el.dom.name+']:checked', true); return c ? c.value : null; }, onClick : function(){ if(this.el.dom.checked != this.checked){ var p = this.el.up('form') || Ext.getBody(); var els = p.select('input[name='+this.el.dom.name+']'); els.each(function(el){ if(el.dom.id == this.id){ this.setValue(true); }else{ Ext.getCmp(el.dom.id).setValue(false); } }, this); } }, setValue : function(v){ if (typeof v == 'boolean') { Ext.form.Radio.superclass.setValue.call(this, v); } else { var r = this.el.up('form').child('input[name='+this.el.dom.name+'][value='+v+']', true); if (r){ r.checked = true; }; } } }); Ext.reg('radio', Ext.form.Radio); Ext.form.Hidden = Ext.extend(Ext.form.Field, { inputType : 'hidden', onRender : function(){ Ext.form.Hidden.superclass.onRender.apply(this, arguments); }, initEvents : function(){ this.originalValue = this.getValue(); }, setSize : Ext.emptyFn, setWidth : Ext.emptyFn, setHeight : Ext.emptyFn, setPosition : Ext.emptyFn, setPagePosition : Ext.emptyFn, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn }); Ext.reg('hidden', Ext.form.Hidden); Ext.form.BasicForm = function(el, config){ Ext.apply(this, config); this.items = new Ext.util.MixedCollection(false, function(o){ return o.id || (o.id = Ext.id()); }); this.addEvents( 'beforeaction', 'actionfailed', 'actioncomplete' ); if(el){ this.initEl(el); } Ext.form.BasicForm.superclass.constructor.call(this); }; Ext.extend(Ext.form.BasicForm, Ext.util.Observable, { timeout: 30, activeAction : null, trackResetOnLoad : false, initEl : function(el){ this.el = Ext.get(el); this.id = this.el.id || Ext.id(); if(!this.standardSubmit){ this.el.on('submit', this.onSubmit, this); } this.el.addClass('x-form'); }, getEl: function(){ return this.el; }, onSubmit : function(e){ e.stopEvent(); }, destroy: function() { this.items.each(function(f){ Ext.destroy(f); }); if(this.el){ this.el.removeAllListeners(); this.el.remove(); } this.purgeListeners(); }, isValid : function(){ var valid = true; this.items.each(function(f){ if(!f.validate()){ valid = false; } }); return valid; }, isDirty : function(){ var dirty = false; this.items.each(function(f){ if(f.isDirty()){ dirty = true; return false; } }); return dirty; }, doAction : function(action, options){ if(typeof action == 'string'){ action = new Ext.form.Action.ACTION_TYPES[action](this, options); } if(this.fireEvent('beforeaction', this, action) !== false){ this.beforeAction(action); action.run.defer(100, action); } return this; }, submit : function(options){ if(this.standardSubmit){ var v = this.isValid(); if(v){ this.el.dom.submit(); } return v; } this.doAction('submit', options); return this; }, load : function(options){ this.doAction('load', options); return this; }, updateRecord : function(record){ record.beginEdit(); var fs = record.fields; fs.each(function(f){ var field = this.findField(f.name); if(field){ record.set(f.name, field.getValue()); } }, this); record.endEdit(); return this; }, loadRecord : function(record){ this.setValues(record.data); return this; }, beforeAction : function(action){ var o = action.options; if(o.waitMsg){ if(this.waitMsgTarget === true){ this.el.mask(o.waitMsg, 'x-mask-loading'); }else if(this.waitMsgTarget){ this.waitMsgTarget = Ext.get(this.waitMsgTarget); this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading'); }else{ Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle || 'Please Wait...'); } } }, afterAction : function(action, success){ this.activeAction = null; var o = action.options; if(o.waitMsg){ if(this.waitMsgTarget === true){ this.el.unmask(); }else if(this.waitMsgTarget){ this.waitMsgTarget.unmask(); }else{ Ext.MessageBox.updateProgress(1); Ext.MessageBox.hide(); } } if(success){ if(o.reset){ this.reset(); } Ext.callback(o.success, o.scope, [this, action]); this.fireEvent('actioncomplete', this, action); }else{ Ext.callback(o.failure, o.scope, [this, action]); this.fireEvent('actionfailed', this, action); } }, findField : function(id){ var field = this.items.get(id); if(!field){ this.items.each(function(f){ if(f.isFormField && (f.dataIndex == id || f.id == id || f.getName() == id)){ field = f; return false; } }); } return field || null; }, markInvalid : function(errors){ if(Ext.isArray(errors)){ for(var i = 0, len = errors.length; i < len; i++){ var fieldError = errors[i]; var f = this.findField(fieldError.id); if(f){ f.markInvalid(fieldError.msg); } } }else{ var field, id; for(id in errors){ if(typeof errors[id] != 'function' && (field = this.findField(id))){ field.markInvalid(errors[id]); } } } return this; }, setValues : function(values){ if(Ext.isArray(values)){ for(var i = 0, len = values.length; i < len; i++){ var v = values[i]; var f = this.findField(v.id); if(f){ f.setValue(v.value); if(this.trackResetOnLoad){ f.originalValue = f.getValue(); } } } }else{ var field, id; for(id in values){ if(typeof values[id] != 'function' && (field = this.findField(id))){ field.setValue(values[id]); if(this.trackResetOnLoad){ field.originalValue = field.getValue(); } } } } return this; }, getValues : function(asString){ var fs = Ext.lib.Ajax.serializeForm(this.el.dom); if(asString === true){ return fs; } return Ext.urlDecode(fs); }, clearInvalid : function(){ this.items.each(function(f){ f.clearInvalid(); }); return this; }, reset : function(){ this.items.each(function(f){ f.reset(); }); return this; }, add : function(){ this.items.addAll(Array.prototype.slice.call(arguments, 0)); return this; }, remove : function(field){ this.items.remove(field); return this; }, render : function(){ this.items.each(function(f){ if(f.isFormField && !f.rendered && document.getElementById(f.id)){ f.applyToMarkup(f.id); } }); return this; }, applyToFields : function(o){ this.items.each(function(f){ Ext.apply(f, o); }); return this; }, applyIfToFields : function(o){ this.items.each(function(f){ Ext.applyIf(f, o); }); return this; } }); Ext.BasicForm = Ext.form.BasicForm; Ext.FormPanel = Ext.extend(Ext.Panel, { buttonAlign:'center', minButtonWidth:75, labelAlign:'left', monitorValid : false, monitorPoll : 200, layout: 'form', initComponent :function(){ this.form = this.createForm(); Ext.FormPanel.superclass.initComponent.call(this); this.addEvents( 'clientvalidation' ); this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']); }, createForm: function(){ delete this.initialConfig.listeners; return new Ext.form.BasicForm(null, this.initialConfig); }, initFields : function(){ var f = this.form; var formPanel = this; var fn = function(c){ if(c.doLayout && c != formPanel){ Ext.applyIf(c, { labelAlign: c.ownerCt.labelAlign, labelWidth: c.ownerCt.labelWidth, itemCls: c.ownerCt.itemCls }); if(c.items){ c.items.each(fn); } }else if(c.isFormField){ f.add(c); } } this.items.each(fn); }, getLayoutTarget : function(){ return this.form.el; }, getForm : function(){ return this.form; }, onRender : function(ct, position){ this.initFields(); Ext.FormPanel.superclass.onRender.call(this, ct, position); var o = { tag: 'form', method : this.method || 'POST', id : this.formId || Ext.id() }; if(this.fileUpload) { o.enctype = 'multipart/form-data'; } this.form.initEl(this.body.createChild(o)); }, beforeDestroy: function(){ Ext.FormPanel.superclass.beforeDestroy.call(this); Ext.destroy(this.form); }, initEvents : function(){ Ext.FormPanel.superclass.initEvents.call(this); this.items.on('remove', this.onRemove, this); this.items.on('add', this.onAdd, this); if(this.monitorValid){ this.startMonitoring(); } }, onAdd : function(ct, c) { if (c.isFormField) { this.form.add(c); } }, onRemove : function(c) { if (c.isFormField) { Ext.destroy(c.container.up('.x-form-item')); this.form.remove(c); } }, startMonitoring : function(){ if(!this.bound){ this.bound = true; Ext.TaskMgr.start({ run : this.bindHandler, interval : this.monitorPoll || 200, scope: this }); } }, stopMonitoring : function(){ this.bound = false; }, load : function(){ this.form.load.apply(this.form, arguments); }, onDisable : function(){ Ext.FormPanel.superclass.onDisable.call(this); if(this.form){ this.form.items.each(function(){ this.disable(); }); } }, onEnable : function(){ Ext.FormPanel.superclass.onEnable.call(this); if(this.form){ this.form.items.each(function(){ this.enable(); }); } }, bindHandler : function(){ if(!this.bound){ return false; } var valid = true; this.form.items.each(function(f){ if(!f.isValid(true)){ valid = false; return false; } }); if(this.buttons){ for(var i = 0, len = this.buttons.length; i < len; i++){ var btn = this.buttons[i]; if(btn.formBind === true && btn.disabled === valid){ btn.setDisabled(!valid); } } } this.fireEvent('clientvalidation', this, valid); } }); Ext.reg('form', Ext.FormPanel); Ext.form.FormPanel = Ext.FormPanel; Ext.form.FieldSet = Ext.extend(Ext.Panel, { baseCls:'x-fieldset', layout: 'form', onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('fieldset'); this.el.id = this.id; if (this.title || this.header || this.checkboxToggle) { this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header'; } } Ext.form.FieldSet.superclass.onRender.call(this, ct, position); if(this.checkboxToggle){ var o = typeof this.checkboxToggle == 'object' ? this.checkboxToggle : {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}; this.checkbox = this.header.insertFirst(o); this.checkbox.dom.checked = !this.collapsed; this.checkbox.on('click', this.onCheckClick, this); } }, onCollapse : function(doAnim, animArg){ if(this.checkbox){ this.checkbox.dom.checked = false; } this.afterCollapse(); }, onExpand : function(doAnim, animArg){ if(this.checkbox){ this.checkbox.dom.checked = true; } this.afterExpand(); }, onCheckClick : function(){ this[this.checkbox.dom.checked ? 'expand' : 'collapse'](); } }); Ext.reg('fieldset', Ext.form.FieldSet); Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, { enableFormat : true, enableFontSize : true, enableColors : true, enableAlignments : true, enableLists : true, enableSourceEdit : true, enableLinks : true, enableFont : true, createLinkText : 'Please enter the URL for the link:', defaultLinkValue : 'http:/'+'/', fontFamilies : [ 'Arial', 'Courier New', 'Tahoma', 'Times New Roman', 'Verdana' ], defaultFont: 'tahoma', validationEvent : false, deferHeight: true, initialized : false, activated : false, sourceEditMode : false, onFocus : Ext.emptyFn, iframePad:3, hideMode:'offsets', defaultAutoCreate : { tag: "textarea", style:"width:500px;height:300px;", autocomplete: "off" }, initComponent : function(){ this.addEvents( 'initialize', 'activate', 'beforesync', 'beforepush', 'sync', 'push', 'editmodechange' ) }, createFontOptions : function(){ var buf = [], fs = this.fontFamilies, ff, lc; for(var i = 0, len = fs.length; i< len; i++){ ff = fs[i]; lc = ff.toLowerCase(); buf.push( '<option value="',lc,'" style="font-family:',ff,';"', (this.defaultFont == lc ? ' selected="true">' : '>'), ff, '</option>' ); } return buf.join(''); }, createToolbar : function(editor){ function btn(id, toggle, handler){ return { itemId : id, cls : 'x-btn-icon x-edit-'+id, enableToggle:toggle !== false, scope: editor, handler:handler||editor.relayBtnCmd, clickEvent:'mousedown', tooltip: editor.buttonTips[id] || undefined, tabIndex:-1 }; } var tb = new Ext.Toolbar({ renderTo:this.wrap.dom.firstChild }); tb.el.on('click', function(e){ e.preventDefault(); }); if(this.enableFont && !Ext.isSafari){ this.fontSelect = tb.el.createChild({ tag:'select', cls:'x-font-select', html: this.createFontOptions() }); this.fontSelect.on('change', function(){ var font = this.fontSelect.dom.value; this.relayCmd('fontname', font); this.deferFocus(); }, this); tb.add( this.fontSelect.dom, '-' ); }; if(this.enableFormat){ tb.add( btn('bold'), btn('italic'), btn('underline') ); }; if(this.enableFontSize){ tb.add( '-', btn('increasefontsize', false, this.adjustFont), btn('decreasefontsize', false, this.adjustFont) ); }; if(this.enableColors){ tb.add( '-', { itemId:'forecolor', cls:'x-btn-icon x-edit-forecolor', clickEvent:'mousedown', tooltip: editor.buttonTips['forecolor'] || undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ allowReselect: true, focus: Ext.emptyFn, value:'000000', plain:true, selectHandler: function(cp, color){ this.execCmd('forecolor', Ext.isSafari || Ext.isIE ? '#'+color : color); this.deferFocus(); }, scope: this, clickEvent:'mousedown' }) }, { itemId:'backcolor', cls:'x-btn-icon x-edit-backcolor', clickEvent:'mousedown', tooltip: editor.buttonTips['backcolor'] || undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ focus: Ext.emptyFn, value:'FFFFFF', plain:true, allowReselect: true, selectHandler: function(cp, color){ if(Ext.isGecko){ this.execCmd('useCSS', false); this.execCmd('hilitecolor', color); this.execCmd('useCSS', true); this.deferFocus(); }else{ this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isSafari || Ext.isIE ? '#'+color : color); this.deferFocus(); } }, scope:this, clickEvent:'mousedown' }) } ); }; if(this.enableAlignments){ tb.add( '-', btn('justifyleft'), btn('justifycenter'), btn('justifyright') ); }; if(!Ext.isSafari){ if(this.enableLinks){ tb.add( '-', btn('createlink', false, this.createLink) ); }; if(this.enableLists){ tb.add( '-', btn('insertorderedlist'), btn('insertunorderedlist') ); } if(this.enableSourceEdit){ tb.add( '-', btn('sourceedit', true, function(btn){ this.toggleSourceEdit(btn.pressed); }) ); } } this.tb = tb; }, getDocMarkup : function(){ return '<html><head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>'; }, getEditorBody : function(){ return this.doc.body || this.doc.documentElement; }, onRender : function(ct, position){ Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position); this.el.dom.style.border = '0 none'; this.el.dom.setAttribute('tabIndex', -1); this.el.addClass('x-hidden'); if(Ext.isIE){ this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;') } this.wrap = this.el.wrap({ cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'} }); this.createToolbar(this); this.tb.items.each(function(item){ if(item.itemId != 'sourceedit'){ item.disable(); } }); var iframe = document.createElement('iframe'); iframe.name = Ext.id(); iframe.frameBorder = 'no'; iframe.src=(Ext.SSL_SECURE_URL || "javascript:false"); this.wrap.dom.appendChild(iframe); this.iframe = iframe; if(Ext.isIE){ iframe.contentWindow.document.designMode = 'on'; this.doc = iframe.contentWindow.document; this.win = iframe.contentWindow; } else { this.doc = (iframe.contentDocument || window.frames[iframe.name].document); this.win = window.frames[iframe.name]; this.doc.designMode = 'on'; } this.doc.open(); this.doc.write(this.getDocMarkup()) this.doc.close(); var task = { run : function(){ if(this.doc.body || this.doc.readyState == 'complete'){ Ext.TaskMgr.stop(task); this.doc.designMode="on"; this.initEditor.defer(10, this); } }, interval : 10, duration:10000, scope: this }; Ext.TaskMgr.start(task); if(!this.width){ this.setSize(this.el.getSize()); } }, onResize : function(w, h){ Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments); if(this.el && this.iframe){ if(typeof w == 'number'){ var aw = w - this.wrap.getFrameWidth('lr'); this.el.setWidth(this.adjustWidth('textarea', aw)); this.iframe.style.width = aw + 'px'; } if(typeof h == 'number'){ var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight(); this.el.setHeight(this.adjustWidth('textarea', ah)); this.iframe.style.height = ah + 'px'; if(this.doc){ this.getEditorBody().style.height = (ah - (this.iframePad*2)) + 'px'; } } } }, toggleSourceEdit : function(sourceEditMode){ if(sourceEditMode === undefined){ sourceEditMode = !this.sourceEditMode; } this.sourceEditMode = sourceEditMode === true; var btn = this.tb.items.get('sourceedit'); if(btn.pressed !== this.sourceEditMode){ btn.toggle(this.sourceEditMode); return; } if(this.sourceEditMode){ this.tb.items.each(function(item){ if(item.itemId != 'sourceedit'){ item.disable(); } }); this.syncValue(); this.iframe.className = 'x-hidden'; this.el.removeClass('x-hidden'); this.el.dom.removeAttribute('tabIndex'); this.el.focus(); }else{ if(this.initialized){ this.tb.items.each(function(item){ item.enable(); }); } this.pushValue(); this.iframe.className = ''; this.el.addClass('x-hidden'); this.el.dom.setAttribute('tabIndex', -1); this.deferFocus(); } var lastSize = this.lastSize; if(lastSize){ delete this.lastSize; this.setSize(lastSize); } this.fireEvent('editmodechange', this, this.sourceEditMode); }, createLink : function(){ var url = prompt(this.createLinkText, this.defaultLinkValue); if(url && url != 'http:/'+'/'){ this.relayCmd('createlink', url); } }, adjustSize : Ext.BoxComponent.prototype.adjustSize, getResizeEl : function(){ return this.wrap; }, getPositionEl : function(){ return this.wrap; }, initEvents : function(){ this.originalValue = this.getValue(); }, markInvalid : Ext.emptyFn, clearInvalid : Ext.emptyFn, setValue : function(v){ Ext.form.HtmlEditor.superclass.setValue.call(this, v); this.pushValue(); }, cleanHtml : function(html){ html = String(html); if(html.length > 5){ if(Ext.isSafari){ html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, ''); } } if(html == '&nbsp;'){ html = ''; } return html; }, syncValue : function(){ if(this.initialized){ var bd = this.getEditorBody(); var html = bd.innerHTML; if(Ext.isSafari){ var bs = bd.getAttribute('style'); var m = bs.match(/text-align:(.*?);/i); if(m && m[1]){ html = '<div style="'+m[0]+'">' + html + '</div>'; } } html = this.cleanHtml(html); if(this.fireEvent('beforesync', this, html) !== false){ this.el.dom.value = html; this.fireEvent('sync', this, html); } } }, pushValue : function(){ if(this.initialized){ var v = this.el.dom.value; if(!this.activated && v.length < 1){ v = '&nbsp;'; } if(this.fireEvent('beforepush', this, v) !== false){ this.getEditorBody().innerHTML = v; this.fireEvent('push', this, v); } } }, deferFocus : function(){ this.focus.defer(10, this); }, focus : function(){ if(this.win && !this.sourceEditMode){ this.win.focus(); }else{ this.el.focus(); } }, initEditor : function(){ var dbody = this.getEditorBody(); var ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat'); ss['background-attachment'] = 'fixed'; dbody.bgProperties = 'fixed'; Ext.DomHelper.applyStyles(dbody, ss); Ext.EventManager.on(this.doc, { 'mousedown': this.onEditorEvent, 'dblclick': this.onEditorEvent, 'click': this.onEditorEvent, 'keyup': this.onEditorEvent, buffer:100, scope: this }); if(Ext.isGecko){ Ext.EventManager.on(this.doc, 'keypress', this.applyCommand, this); } if(Ext.isIE || Ext.isSafari || Ext.isOpera){ Ext.EventManager.on(this.doc, 'keydown', this.fixKeys, this); } this.initialized = true; this.fireEvent('initialize', this); this.pushValue(); }, onDestroy : function(){ if(this.rendered){ this.tb.items.each(function(item){ if(item.menu){ item.menu.removeAll(); if(item.menu.el){ item.menu.el.destroy(); } } item.destroy(); }); this.wrap.dom.innerHTML = ''; this.wrap.remove(); } }, onFirstFocus : function(){ this.activated = true; this.tb.items.each(function(item){ item.enable(); }); if(Ext.isGecko){ this.win.focus(); var s = this.win.getSelection(); if(!s.focusNode || s.focusNode.nodeType != 3){ var r = s.getRangeAt(0); r.selectNodeContents(this.getEditorBody()); r.collapse(true); this.deferFocus(); } try{ this.execCmd('useCSS', true); this.execCmd('styleWithCSS', false); }catch(e){} } this.fireEvent('activate', this); }, adjustFont: function(btn){ var adjust = btn.itemId == 'increasefontsize' ? 1 : -1; var v = parseInt(this.doc.queryCommandValue('FontSize') || 2, 10); if(Ext.isSafari3 || Ext.isAir){ if(v <= 10){ v = 1 + adjust; }else if(v <= 13){ v = 2 + adjust; }else if(v <= 16){ v = 3 + adjust; }else if(v <= 18){ v = 4 + adjust; }else if(v <= 24){ v = 5 + adjust; }else { v = 6 + adjust; } v = v.constrain(1, 6); }else{ if(Ext.isSafari){ adjust *= 2; } v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0); } this.execCmd('FontSize', v); }, onEditorEvent : function(e){ this.updateToolbar(); }, updateToolbar: function(){ if(!this.activated){ this.onFirstFocus(); return; } var btns = this.tb.items.map, doc = this.doc; if(this.enableFont && !Ext.isSafari){ var name = (this.doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase(); if(name != this.fontSelect.dom.value){ this.fontSelect.dom.value = name; } } if(this.enableFormat){ btns.bold.toggle(doc.queryCommandState('bold')); btns.italic.toggle(doc.queryCommandState('italic')); btns.underline.toggle(doc.queryCommandState('underline')); } if(this.enableAlignments){ btns.justifyleft.toggle(doc.queryCommandState('justifyleft')); btns.justifycenter.toggle(doc.queryCommandState('justifycenter')); btns.justifyright.toggle(doc.queryCommandState('justifyright')); } if(!Ext.isSafari && this.enableLists){ btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist')); btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist')); } Ext.menu.MenuMgr.hideAll(); this.syncValue(); }, relayBtnCmd : function(btn){ this.relayCmd(btn.itemId); }, relayCmd : function(cmd, value){ this.win.focus(); this.execCmd(cmd, value); this.updateToolbar(); this.deferFocus(); }, execCmd : function(cmd, value){ this.doc.execCommand(cmd, false, value === undefined ? null : value); this.syncValue(); }, applyCommand : function(e){ if(e.ctrlKey){ var c = e.getCharCode(), cmd; if(c > 0){ c = String.fromCharCode(c); switch(c){ case 'b': cmd = 'bold'; break; case 'i': cmd = 'italic'; break; case 'u': cmd = 'underline'; break; } if(cmd){ this.win.focus(); this.execCmd(cmd); this.deferFocus(); e.preventDefault(); } } } }, insertAtCursor : function(text){ if(!this.activated){ return; } if(Ext.isIE){ this.win.focus(); var r = this.doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML(text); this.syncValue(); this.deferFocus(); } }else if(Ext.isGecko || Ext.isOpera){ this.win.focus(); this.execCmd('InsertHTML', text); this.deferFocus(); }else if(Ext.isSafari){ this.execCmd('InsertText', text); this.deferFocus(); } }, fixKeys : function(){ if(Ext.isIE){ return function(e){ var k = e.getKey(), r; if(k == e.TAB){ e.stopEvent(); r = this.doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }else if(k == e.ENTER){ r = this.doc.selection.createRange(); if(r){ var target = r.parentElement(); if(!target || target.tagName.toLowerCase() != 'li'){ e.stopEvent(); r.pasteHTML('<br />'); r.collapse(false); r.select(); } } } }; }else if(Ext.isOpera){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.win.focus(); this.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }; }else if(Ext.isSafari){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.execCmd('InsertText','\t'); this.deferFocus(); } }; } }(), getToolbar : function(){ return this.tb; }, buttonTips : { bold : { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: 'x-html-editor-tip' }, italic : { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: 'x-html-editor-tip' }, underline : { title: 'Underline (Ctrl+U)', text: 'Underline the selected text.', cls: 'x-html-editor-tip' }, increasefontsize : { title: 'Grow Text', text: 'Increase the font size.', cls: 'x-html-editor-tip' }, decreasefontsize : { title: 'Shrink Text', text: 'Decrease the font size.', cls: 'x-html-editor-tip' }, backcolor : { title: 'Text Highlight Color', text: 'Change the background color of the selected text.', cls: 'x-html-editor-tip' }, forecolor : { title: 'Font Color', text: 'Change the color of the selected text.', cls: 'x-html-editor-tip' }, justifyleft : { title: 'Align Text Left', text: 'Align text to the left.', cls: 'x-html-editor-tip' }, justifycenter : { title: 'Center Text', text: 'Center text in the editor.', cls: 'x-html-editor-tip' }, justifyright : { title: 'Align Text Right', text: 'Align text to the right.', cls: 'x-html-editor-tip' }, insertunorderedlist : { title: 'Bullet List', text: 'Start a bulleted list.', cls: 'x-html-editor-tip' }, insertorderedlist : { title: 'Numbered List', text: 'Start a numbered list.', cls: 'x-html-editor-tip' }, createlink : { title: 'Hyperlink', text: 'Make the selected text a hyperlink.', cls: 'x-html-editor-tip' }, sourceedit : { title: 'Source Edit', text: 'Switch to source editing mode.', cls: 'x-html-editor-tip' } } }); Ext.reg('htmleditor', Ext.form.HtmlEditor); Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, { minValue : null, maxValue : null, minText : "The time in this field must be equal to or after {0}", maxText : "The time in this field must be equal to or before {0}", invalidText : "{0} is not a valid time", format : "g:i A", altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H", increment: 15, mode: 'local', triggerAction: 'all', typeAhead: false, initComponent : function(){ Ext.form.TimeField.superclass.initComponent.call(this); if(typeof this.minValue == "string"){ this.minValue = this.parseDate(this.minValue); } if(typeof this.maxValue == "string"){ this.maxValue = this.parseDate(this.maxValue); } if(!this.store){ var min = this.parseDate(this.minValue); if(!min){ min = new Date().clearTime(); } var max = this.parseDate(this.maxValue); if(!max){ max = new Date().clearTime().add('mi', (24 * 60) - 1); } var times = []; while(min <= max){ times.push([min.dateFormat(this.format)]); min = min.add('mi', this.increment); } this.store = new Ext.data.SimpleStore({ fields: ['text'], data : times }); this.displayField = 'text'; } }, getValue : function(){ var v = Ext.form.TimeField.superclass.getValue.call(this); return this.formatDate(this.parseDate(v)) || ''; }, setValue : function(value){ Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value))); }, validateValue : Ext.form.DateField.prototype.validateValue, parseDate : Ext.form.DateField.prototype.parseDate, formatDate : Ext.form.DateField.prototype.formatDate, beforeBlur : function(){ var v = this.parseDate(this.getRawValue()); if(v){ this.setValue(v.dateFormat(this.format)); } } }); Ext.reg('timefield', Ext.form.TimeField); Ext.form.Label = Ext.extend(Ext.BoxComponent, { onRender : function(ct, position){ if(!this.el){ this.el = document.createElement('label'); this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || ''); if(this.forId){ this.el.setAttribute('htmlFor', this.forId); } } Ext.form.Label.superclass.onRender.call(this, ct, position); } }); Ext.reg('label', Ext.form.Label); Ext.form.Action = function(form, options){ this.form = form; this.options = options || {}; }; Ext.form.Action.CLIENT_INVALID = 'client'; Ext.form.Action.SERVER_INVALID = 'server'; Ext.form.Action.CONNECT_FAILURE = 'connect'; Ext.form.Action.LOAD_FAILURE = 'load'; Ext.form.Action.prototype = { type : 'default', run : function(options){ }, success : function(response){ }, handleResponse : function(response){ }, failure : function(response){ this.response = response; this.failureType = Ext.form.Action.CONNECT_FAILURE; this.form.afterAction(this, false); }, processResponse : function(response){ this.response = response; if(!response.responseText){ return true; } this.result = this.handleResponse(response); return this.result; }, getUrl : function(appendParams){ var url = this.options.url || this.form.url || this.form.el.dom.action; if(appendParams){ var p = this.getParams(); if(p){ url += (url.indexOf('?') != -1 ? '&' : '?') + p; } } return url; }, getMethod : function(){ return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase(); }, getParams : function(){ var bp = this.form.baseParams; var p = this.options.params; if(p){ if(typeof p == "object"){ p = Ext.urlEncode(Ext.applyIf(p, bp)); }else if(typeof p == 'string' && bp){ p += '&' + Ext.urlEncode(bp); } }else if(bp){ p = Ext.urlEncode(bp); } return p; }, createCallback : function(opts){ var opts = opts || {}; return { success: this.success, failure: this.failure, scope: this, timeout: (opts.timeout*1000) || (this.form.timeout*1000), upload: this.form.fileUpload ? this.success : undefined }; } }; Ext.form.Action.Submit = function(form, options){ Ext.form.Action.Submit.superclass.constructor.call(this, form, options); }; Ext.extend(Ext.form.Action.Submit, Ext.form.Action, { type : 'submit', run : function(){ var o = this.options; var method = this.getMethod(); var isPost = method == 'POST'; if(o.clientValidation === false || this.form.isValid()){ Ext.Ajax.request(Ext.apply(this.createCallback(o), { form:this.form.el.dom, url:this.getUrl(!isPost), method: method, params:isPost ? this.getParams() : null, isUpload: this.form.fileUpload })); }else if (o.clientValidation !== false){ this.failureType = Ext.form.Action.CLIENT_INVALID; this.form.afterAction(this, false); } }, success : function(response){ var result = this.processResponse(response); if(result === true || result.success){ this.form.afterAction(this, true); return; } if(result.errors){ this.form.markInvalid(result.errors); this.failureType = Ext.form.Action.SERVER_INVALID; } this.form.afterAction(this, false); }, handleResponse : function(response){ if(this.form.errorReader){ var rs = this.form.errorReader.read(response); var errors = []; if(rs.records){ for(var i = 0, len = rs.records.length; i < len; i++) { var r = rs.records[i]; errors[i] = r.data; } } if(errors.length < 1){ errors = null; } return { success : rs.success, errors : errors }; } return Ext.decode(response.responseText); } }); Ext.form.Action.Load = function(form, options){ Ext.form.Action.Load.superclass.constructor.call(this, form, options); this.reader = this.form.reader; }; Ext.extend(Ext.form.Action.Load, Ext.form.Action, { type : 'load', run : function(){ Ext.Ajax.request(Ext.apply( this.createCallback(this.options), { method:this.getMethod(), url:this.getUrl(false), params:this.getParams() })); }, success : function(response){ var result = this.processResponse(response); if(result === true || !result.success || !result.data){ this.failureType = Ext.form.Action.LOAD_FAILURE; this.form.afterAction(this, false); return; } this.form.clearInvalid(); this.form.setValues(result.data); this.form.afterAction(this, true); }, handleResponse : function(response){ if(this.form.reader){ var rs = this.form.reader.read(response); var data = rs.records && rs.records[0] ? rs.records[0].data : null; return { success : rs.success, data : data }; } return Ext.decode(response.responseText); } }); Ext.form.Action.ACTION_TYPES = { 'load' : Ext.form.Action.Load, 'submit' : Ext.form.Action.Submit }; Ext.form.VTypes = function(){ var alpha = /^[a-zA-Z_]+$/; var alphanum = /^[a-zA-Z0-9_]+$/; var email = /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/; var url = /(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i; return { 'email' : function(v){ return email.test(v); }, 'emailText' : 'This field should be an e-mail address in the format "user@domain.com"', 'emailMask' : /[a-z0-9_\.\-@]/i, 'url' : function(v){ return url.test(v); }, 'urlText' : 'This field should be a URL in the format "http:/'+'/www.domain.com"', 'alpha' : function(v){ return alpha.test(v); }, 'alphaText' : 'This field should only contain letters and _', 'alphaMask' : /[a-z_]/i, 'alphanum' : function(v){ return alphanum.test(v); }, 'alphanumText' : 'This field should only contain letters, numbers and _', 'alphanumMask' : /[a-z0-9_]/i }; }(); Ext.grid.GridPanel = Ext.extend(Ext.Panel, { ddText : "{0} selected row{1}", minColumnWidth : 25, trackMouseOver : true, enableDragDrop : false, enableColumnMove : true, enableColumnHide : true, enableHdMenu : true, stripeRows : false, autoExpandColumn : false, autoExpandMin : 50, autoExpandMax : 1000, view : null, loadMask : false, rendered : false, viewReady: false, stateEvents: ["columnmove", "columnresize", "sortchange"], initComponent : function(){ Ext.grid.GridPanel.superclass.initComponent.call(this); this.autoScroll = false; this.autoWidth = false; if(Ext.isArray(this.columns)){ this.colModel = new Ext.grid.ColumnModel(this.columns); delete this.columns; } if(this.ds){ this.store = this.ds; delete this.ds; } if(this.cm){ this.colModel = this.cm; delete this.cm; } if(this.sm){ this.selModel = this.sm; delete this.sm; } this.store = Ext.StoreMgr.lookup(this.store); this.addEvents( "click", "dblclick", "contextmenu", "mousedown", "mouseup", "mouseover", "mouseout", "keypress", "keydown", "cellmousedown", "rowmousedown", "headermousedown", "cellclick", "celldblclick", "rowclick", "rowdblclick", "headerclick", "headerdblclick", "rowcontextmenu", "cellcontextmenu", "headercontextmenu", "bodyscroll", "columnresize", "columnmove", "sortchange" ); }, onRender : function(ct, position){ Ext.grid.GridPanel.superclass.onRender.apply(this, arguments); var c = this.body; this.el.addClass('x-grid-panel'); var view = this.getView(); view.init(this); c.on("mousedown", this.onMouseDown, this); c.on("click", this.onClick, this); c.on("dblclick", this.onDblClick, this); c.on("contextmenu", this.onContextMenu, this); c.on("keydown", this.onKeyDown, this); this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]); this.getSelectionModel().init(this); this.view.render(); }, initEvents : function(){ Ext.grid.GridPanel.superclass.initEvents.call(this); if(this.loadMask){ this.loadMask = new Ext.LoadMask(this.bwrap, Ext.apply({store:this.store}, this.loadMask)); } }, initStateEvents : function(){ Ext.grid.GridPanel.superclass.initStateEvents.call(this); this.colModel.on('hiddenchange', this.saveState, this, {delay: 100}); }, applyState : function(state){ var cm = this.colModel; var cs = state.columns; if(cs){ for(var i = 0, len = cs.length; i < len; i++){ var s = cs[i]; var c = cm.getColumnById(s.id); if(c){ c.hidden = s.hidden; c.width = s.width; var oldIndex = cm.getIndexById(s.id); if(oldIndex != i){ cm.moveColumn(oldIndex, i); } } } } if(state.sort){ this.store[this.store.remoteSort ? 'setDefaultSort' : 'sort'](state.sort.field, state.sort.direction); } }, getState : function(){ var o = {columns: []}; for(var i = 0, c; c = this.colModel.config[i]; i++){ o.columns[i] = { id: c.id, width: c.width }; if(c.hidden){ o.columns[i].hidden = true; } } var ss = this.store.getSortState(); if(ss){ o.sort = ss; } return o; }, afterRender : function(){ Ext.grid.GridPanel.superclass.afterRender.call(this); this.view.layout(); this.viewReady = true; }, reconfigure : function(store, colModel){ if(this.loadMask){ this.loadMask.destroy(); this.loadMask = new Ext.LoadMask(this.bwrap, Ext.apply({store:store}, this.initialConfig.loadMask)); } this.view.bind(store, colModel); this.store = store; this.colModel = colModel; if(this.rendered){ this.view.refresh(true); } }, onKeyDown : function(e){ this.fireEvent("keydown", e); }, onDestroy : function(){ if(this.rendered){ if(this.loadMask){ this.loadMask.destroy(); } var c = this.body; c.removeAllListeners(); this.view.destroy(); c.update(""); } this.colModel.purgeListeners(); Ext.grid.GridPanel.superclass.onDestroy.call(this); }, processEvent : function(name, e){ this.fireEvent(name, e); var t = e.getTarget(); var v = this.view; var header = v.findHeaderIndex(t); if(header !== false){ this.fireEvent("header" + name, this, header, e); }else{ var row = v.findRowIndex(t); var cell = v.findCellIndex(t); if(row !== false){ this.fireEvent("row" + name, this, row, e); if(cell !== false){ this.fireEvent("cell" + name, this, row, cell, e); } } } }, onClick : function(e){ this.processEvent("click", e); }, onMouseDown : function(e){ this.processEvent("mousedown", e); }, onContextMenu : function(e, t){ this.processEvent("contextmenu", e); }, onDblClick : function(e){ this.processEvent("dblclick", e); }, walkCells : function(row, col, step, fn, scope){ var cm = this.colModel, clen = cm.getColumnCount(); var ds = this.store, rlen = ds.getCount(), first = true; if(step < 0){ if(col < 0){ row--; first = false; } while(row >= 0){ if(!first){ col = clen-1; } first = false; while(col >= 0){ if(fn.call(scope || this, row, col, cm) === true){ return [row, col]; } col--; } row--; } } else { if(col >= clen){ row++; first = false; } while(row < rlen){ if(!first){ col = 0; } first = false; while(col < clen){ if(fn.call(scope || this, row, col, cm) === true){ return [row, col]; } col++; } row++; } } return null; }, getSelections : function(){ return this.selModel.getSelections(); }, onResize : function(){ Ext.grid.GridPanel.superclass.onResize.apply(this, arguments); if(this.viewReady){ this.view.layout(); } }, getGridEl : function(){ return this.body; }, stopEditing : function(){}, getSelectionModel : function(){ if(!this.selModel){ this.selModel = new Ext.grid.RowSelectionModel( this.disableSelection ? {selectRow: Ext.emptyFn} : null); } return this.selModel; }, getStore : function(){ return this.store; }, getColumnModel : function(){ return this.colModel; }, getView : function(){ if(!this.view){ this.view = new Ext.grid.GridView(this.viewConfig); } return this.view; }, getDragDropText : function(){ var count = this.selModel.getCount(); return String.format(this.ddText, count, count == 1 ? '' : 's'); } }); Ext.reg('grid', Ext.grid.GridPanel); Ext.grid.GridView = function(config){ Ext.apply(this, config); this.addEvents( "beforerowremoved", "beforerowsinserted", "beforerefresh", "rowremoved", "rowsinserted", "rowupdated", "refresh" ); Ext.grid.GridView.superclass.constructor.call(this); }; Ext.extend(Ext.grid.GridView, Ext.util.Observable, { scrollOffset: 19, autoFill: false, forceFit: false, sortClasses : ["sort-asc", "sort-desc"], sortAscText : "Sort Ascending", sortDescText : "Sort Descending", columnsText : "Columns", borderWidth: 2, initTemplates : function(){ var ts = this.templates || {}; if(!ts.master){ ts.master = new Ext.Template( '<div class="x-grid3" hidefocus="true">', '<div class="x-grid3-viewport">', '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>', '<div class="x-grid3-scroller"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>', "</div>", '<div class="x-grid3-resize-marker">&#160;</div>', '<div class="x-grid3-resize-proxy">&#160;</div>', "</div>" ); } if(!ts.header){ ts.header = new Ext.Template( '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>', "</table>" ); } if(!ts.hcell){ ts.hcell = new Ext.Template( '<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id}" style="{style}"><div {tooltip} {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '', '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />', "</div></td>" ); } if(!ts.body){ ts.body = new Ext.Template('{rows}'); } if(!ts.row){ ts.row = new Ext.Template( '<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<tbody><tr>{cells}</tr>', (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''), '</tbody></table></div>' ); } if(!ts.cell){ ts.cell = new Ext.Template( '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>', '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>', "</td>" ); } for(var k in ts){ var t = ts[k]; if(t && typeof t.compile == 'function' && !t.compiled){ t.disableFormats = true; t.compile(); } } this.templates = ts; this.tdClass = 'x-grid3-cell'; this.cellSelector = 'td.x-grid3-cell'; this.hdCls = 'x-grid3-hd'; this.rowSelector = 'div.x-grid3-row'; this.colRe = new RegExp("x-grid3-td-([^\\s]+)", ""); }, fly : function(el){ if(!this._flyweight){ this._flyweight = new Ext.Element.Flyweight(document.body); } this._flyweight.dom = el; return this._flyweight; }, getEditorParent : function(ed){ return this.scroller.dom; }, initElements : function(){ var E = Ext.Element; var el = this.grid.getGridEl().dom.firstChild; var cs = el.childNodes; this.el = new E(el); this.mainWrap = new E(cs[0]); this.mainHd = new E(this.mainWrap.dom.firstChild); if(this.grid.hideHeaders){ this.mainHd.setDisplayed(false); } this.innerHd = this.mainHd.dom.firstChild; this.scroller = new E(this.mainWrap.dom.childNodes[1]); if(this.forceFit){ this.scroller.setStyle('overflow-x', 'hidden'); } this.mainBody = new E(this.scroller.dom.firstChild); this.focusEl = new E(this.scroller.dom.childNodes[1]); this.focusEl.swallowEvent("click", true); this.resizeMarker = new E(cs[1]); this.resizeProxy = new E(cs[2]); }, getRows : function(){ return this.hasRows() ? this.mainBody.dom.childNodes : []; }, findCell : function(el){ if(!el){ return false; } return this.fly(el).findParent(this.cellSelector, 3); }, findCellIndex : function(el, requiredCls){ var cell = this.findCell(el); if(cell && (!requiredCls || this.fly(cell).hasClass(requiredCls))){ return this.getCellIndex(cell); } return false; }, getCellIndex : function(el){ if(el){ var m = el.className.match(this.colRe); if(m && m[1]){ return this.cm.getIndexById(m[1]); } } return false; }, findHeaderCell : function(el){ var cell = this.findCell(el); return cell && this.fly(cell).hasClass(this.hdCls) ? cell : null; }, findHeaderIndex : function(el){ return this.findCellIndex(el, this.hdCls); }, findRow : function(el){ if(!el){ return false; } return this.fly(el).findParent(this.rowSelector, 10); }, findRowIndex : function(el){ var r = this.findRow(el); return r ? r.rowIndex : false; }, getRow : function(row){ return this.getRows()[row]; }, getCell : function(row, col){ return this.getRow(row).getElementsByTagName('td')[col]; }, getHeaderCell : function(index){ return this.mainHd.dom.getElementsByTagName('td')[index]; }, addRowClass : function(row, cls){ var r = this.getRow(row); if(r){ this.fly(r).addClass(cls); } }, removeRowClass : function(row, cls){ var r = this.getRow(row); if(r){ this.fly(r).removeClass(cls); } }, removeRow : function(row){ Ext.removeNode(this.getRow(row)); }, removeRows : function(firstRow, lastRow){ var bd = this.mainBody.dom; for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){ Ext.removeNode(bd.childNodes[firstRow]); } }, getScrollState : function(){ var sb = this.scroller.dom; return {left: sb.scrollLeft, top: sb.scrollTop}; }, restoreScroll : function(state){ var sb = this.scroller.dom; sb.scrollLeft = state.left; sb.scrollTop = state.top; }, scrollToTop : function(){ this.scroller.dom.scrollTop = 0; this.scroller.dom.scrollLeft = 0; }, syncScroll : function(){ this.syncHeaderScroll(); var mb = this.scroller.dom; this.grid.fireEvent("bodyscroll", mb.scrollLeft, mb.scrollTop); }, syncHeaderScroll : function(){ var mb = this.scroller.dom; this.innerHd.scrollLeft = mb.scrollLeft; this.innerHd.scrollLeft = mb.scrollLeft; }, updateSortIcon : function(col, dir){ var sc = this.sortClasses; var hds = this.mainHd.select('td').removeClass(sc); hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]); }, updateAllColumnWidths : function(){ var tw = this.getTotalWidth(); var clen = this.cm.getColumnCount(); var ws = []; for(var i = 0; i < clen; i++){ ws[i] = this.getColumnWidth(i); } this.innerHd.firstChild.firstChild.style.width = tw; for(var i = 0; i < clen; i++){ var hd = this.getHeaderCell(i); hd.style.width = ws[i]; } var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; var row = ns[i].firstChild.rows[0]; for(var j = 0; j < clen; j++){ row.childNodes[j].style.width = ws[j]; } } this.onAllColumnWidthsUpdated(ws, tw); }, updateColumnWidth : function(col, width){ var w = this.getColumnWidth(col); var tw = this.getTotalWidth(); this.innerHd.firstChild.firstChild.style.width = tw; var hd = this.getHeaderCell(col); hd.style.width = w; var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; ns[i].firstChild.rows[0].childNodes[col].style.width = w; } this.onColumnWidthUpdated(col, w, tw); }, updateColumnHidden : function(col, hidden){ var tw = this.getTotalWidth(); this.innerHd.firstChild.firstChild.style.width = tw; var display = hidden ? 'none' : ''; var hd = this.getHeaderCell(col); hd.style.display = display; var ns = this.getRows(); for(var i = 0, len = ns.length; i < len; i++){ ns[i].style.width = tw; ns[i].firstChild.style.width = tw; ns[i].firstChild.rows[0].childNodes[col].style.display = display; } this.onColumnHiddenUpdated(col, hidden, tw); delete this.lastViewWidth; this.layout(); }, doRender : function(cs, rs, ds, startRow, colCount, stripe){ var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1; var tstyle = 'width:'+this.getTotalWidth()+';'; var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r; for(var j = 0, len = rs.length; j < len; j++){ r = rs[j]; cb = []; var rowIndex = (j+startRow); for(var i = 0; i < colCount; i++){ c = cs[i]; p.id = c.id; p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); p.attr = p.cellAttr = ""; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); p.style = c.style; if(p.value == undefined || p.value === "") p.value = "&#160;"; if(r.dirty && typeof r.modified[c.name] !== 'undefined'){ p.css += ' x-grid3-dirty-cell'; } cb[cb.length] = ct.apply(p); } var alt = []; if(stripe && ((rowIndex+1) % 2 == 0)){ alt[0] = "x-grid3-row-alt"; } if(r.dirty){ alt[1] = " x-grid3-dirty-row"; } rp.cols = colCount; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex, rp, ds); } rp.alt = alt.join(" "); rp.cells = cb.join(""); buf[buf.length] = rt.apply(rp); } return buf.join(""); }, processRows : function(startRow, skipStripe){ if(this.ds.getCount() < 1){ return; } skipStripe = skipStripe || !this.grid.stripeRows; startRow = startRow || 0; var rows = this.getRows(); var cls = ' x-grid3-row-alt '; for(var i = startRow, len = rows.length; i < len; i++){ var row = rows[i]; row.rowIndex = i; if(!skipStripe){ var isAlt = ((i+1) % 2 == 0); var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1; if(isAlt == hasAlt){ continue; } if(isAlt){ row.className += " x-grid3-row-alt"; }else{ row.className = row.className.replace("x-grid3-row-alt", ""); } } } }, renderUI : function(){ var header = this.renderHeaders(); var body = this.templates.body.apply({rows:''}); var html = this.templates.master.apply({ body: body, header: header }); var g = this.grid; g.getGridEl().dom.innerHTML = html; this.initElements(); this.mainBody.dom.innerHTML = this.renderRows(); this.processRows(0, true); Ext.fly(this.innerHd).on("click", this.handleHdDown, this); this.mainHd.on("mouseover", this.handleHdOver, this); this.mainHd.on("mouseout", this.handleHdOut, this); this.mainHd.on("mousemove", this.handleHdMove, this); this.scroller.on('scroll', this.syncScroll, this); if(g.enableColumnResize !== false){ this.splitone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom); } if(g.enableColumnMove){ this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd); this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom); } if(g.enableHdMenu !== false){ if(g.enableColumnHide !== false){ this.colMenu = new Ext.menu.Menu({id:g.id + "-hcols-menu"}); this.colMenu.on("beforeshow", this.beforeColMenuShow, this); this.colMenu.on("itemclick", this.handleHdMenuClick, this); } this.hmenu = new Ext.menu.Menu({id: g.id + "-hctx"}); this.hmenu.add( {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"}, {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"} ); if(g.enableColumnHide !== false){ this.hmenu.add('-', {id:"columns", text: this.columnsText, menu: this.colMenu, iconCls: 'x-cols-icon'} ); } this.hmenu.on("itemclick", this.handleHdMenuClick, this); } if(g.enableDragDrop || g.enableDrag){ var dd = new Ext.grid.GridDragZone(g, { ddGroup : g.ddGroup || 'GridDD' }); } this.updateHeaderSortState(); }, layout : function(){ if(!this.mainBody){ return; } var g = this.grid; var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this; var csize = c.getSize(true); var vw = csize.width; if(vw < 20 || csize.height < 20){ return; } if(g.autoHeight){ this.scroller.dom.style.overflow = 'visible'; }else{ this.el.setSize(csize.width, csize.height); var hdHeight = this.mainHd.getHeight(); var vh = csize.height - (hdHeight); this.scroller.setSize(vw, vh); if(this.innerHd){ this.innerHd.style.width = (vw)+'px'; } } if(this.forceFit){ if(this.lastViewWidth != vw){ this.fitColumns(false, false); this.lastViewWidth = vw; } }else { this.autoExpand(); this.syncHeaderScroll(); } this.onLayout(vw, vh); }, onLayout : function(vw, vh){ }, onColumnWidthUpdated : function(col, w, tw){ }, onAllColumnWidthsUpdated : function(ws, tw){ }, onColumnHiddenUpdated : function(col, hidden, tw){ }, updateColumnText : function(col, text){ }, afterMove : function(colIndex){ }, init: function(grid){ this.grid = grid; this.initTemplates(); this.initData(grid.store, grid.colModel); this.initUI(grid); }, getColumnId : function(index){ return this.cm.getColumnId(index); }, renderHeaders : function(){ var cm = this.cm, ts = this.templates; var ct = ts.hcell; var cb = [], sb = [], p = {}; for(var i = 0, len = cm.getColumnCount(); i < len; i++){ p.id = cm.getColumnId(i); p.value = cm.getColumnHeader(i) || ""; p.style = this.getColumnStyle(i, true); p.tooltip = this.getColumnTooltip(i); if(cm.config[i].align == 'right'){ p.istyle = 'padding-right:16px'; } else { delete p.istyle; } cb[cb.length] = ct.apply(p); } return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'}); }, getColumnTooltip : function(i){ var tt = this.cm.getColumnTooltip(i); if(tt){ if(Ext.QuickTips.isEnabled()){ return 'ext:qtip="'+tt+'"'; }else{ return 'title="'+tt+'"'; } } return ""; }, beforeUpdate : function(){ this.grid.stopEditing(true); }, updateHeaders : function(){ this.innerHd.firstChild.innerHTML = this.renderHeaders(); }, focusRow : function(row){ this.focusCell(row, 0, false); }, focusCell : function(row, col, hscroll){ var xy = this.ensureVisible(row, col, hscroll); this.focusEl.setXY(xy); if(Ext.isGecko){ this.focusEl.focus(); }else{ this.focusEl.focus.defer(1, this.focusEl); } }, ensureVisible : function(row, col, hscroll){ if(typeof row != "number"){ row = row.rowIndex; } if(!this.ds){ return; } if(row < 0 || row >= this.ds.getCount()){ return; } col = (col !== undefined ? col : 0); var rowEl = this.getRow(row), cellEl; if(!(hscroll === false && col === 0)){ while(this.cm.isHidden(col)){ col++; } cellEl = this.getCell(row, col); } if(!rowEl){ return; } var c = this.scroller.dom; var ctop = 0; var p = rowEl, stop = this.el.dom; while(p && p != stop){ ctop += p.offsetTop; p = p.offsetParent; } ctop -= this.mainHd.dom.offsetHeight; var cbot = ctop + rowEl.offsetHeight; var ch = c.clientHeight; var stop = parseInt(c.scrollTop, 10); var sbot = stop + ch; if(ctop < stop){ c.scrollTop = ctop; }else if(cbot > sbot){ c.scrollTop = cbot-ch; } if(hscroll !== false){ var cleft = parseInt(cellEl.offsetLeft, 10); var cright = cleft + cellEl.offsetWidth; var sleft = parseInt(c.scrollLeft, 10); var sright = sleft + c.clientWidth; if(cleft < sleft){ c.scrollLeft = cleft; }else if(cright > sright){ c.scrollLeft = cright-c.clientWidth; } } return cellEl ? Ext.fly(cellEl).getXY() : [c.scrollLeft, Ext.fly(rowEl).getY()]; }, insertRows : function(dm, firstRow, lastRow, isUpdate){ if(!isUpdate && firstRow === 0 && lastRow == dm.getCount()-1){ this.refresh(); }else{ if(!isUpdate){ this.fireEvent("beforerowsinserted", this, firstRow, lastRow); } var html = this.renderRows(firstRow, lastRow); var before = this.getRow(firstRow); if(before){ Ext.DomHelper.insertHtml('beforeBegin', before, html); }else{ Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html); } if(!isUpdate){ this.fireEvent("rowsinserted", this, firstRow, lastRow); this.processRows(firstRow); } } }, deleteRows : function(dm, firstRow, lastRow){ if(dm.getRowCount()<1){ this.refresh(); }else{ this.fireEvent("beforerowsdeleted", this, firstRow, lastRow); this.removeRows(firstRow, lastRow); this.processRows(firstRow); this.fireEvent("rowsdeleted", this, firstRow, lastRow); } }, getColumnStyle : function(col, isHeader){ var style = !isHeader ? (this.cm.config[col].css || '') : ''; style += 'width:'+this.getColumnWidth(col)+';'; if(this.cm.isHidden(col)){ style += 'display:none;'; } var align = this.cm.config[col].align; if(align){ style += 'text-align:'+align+';'; } return style; }, getColumnWidth : function(col){ var w = this.cm.getColumnWidth(col); if(typeof w == 'number'){ return (Ext.isBorderBox ? w : (w-this.borderWidth > 0 ? w-this.borderWidth:0)) + 'px'; } return w; }, getTotalWidth : function(){ return this.cm.getTotalWidth()+'px'; }, fitColumns : function(preventRefresh, onlyExpand, omitColumn){ var cm = this.cm, leftOver, dist, i; var tw = cm.getTotalWidth(false); var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset; if(aw < 20){ return; } var extra = aw - tw; if(extra === 0){ return false; } var vc = cm.getColumnCount(true); var ac = vc-(typeof omitColumn == 'number' ? 1 : 0); if(ac === 0){ ac = 1; omitColumn = undefined; } var colCount = cm.getColumnCount(); var cols = []; var extraCol = 0; var width = 0; var w; for (i = 0; i < colCount; i++){ if(!cm.isHidden(i) && !cm.isFixed(i) && i !== omitColumn){ w = cm.getColumnWidth(i); cols.push(i); extraCol = i; cols.push(w); width += w; } } var frac = (aw - cm.getTotalWidth())/width; while (cols.length){ w = cols.pop(); i = cols.pop(); cm.setColumnWidth(i, Math.max(this.grid.minColumnWidth, Math.floor(w + w*frac)), true); } if((tw = cm.getTotalWidth(false)) > aw){ var adjustCol = ac != vc ? omitColumn : extraCol; cm.setColumnWidth(adjustCol, Math.max(1, cm.getColumnWidth(adjustCol)- (tw-aw)), true); } if(preventRefresh !== true){ this.updateAllColumnWidths(); } return true; }, autoExpand : function(preventUpdate){ var g = this.grid, cm = this.cm; if(!this.userResized && g.autoExpandColumn){ var tw = cm.getTotalWidth(false); var aw = this.grid.getGridEl().getWidth(true)-this.scrollOffset; if(tw != aw){ var ci = cm.getIndexById(g.autoExpandColumn); var currentWidth = cm.getColumnWidth(ci); var cw = Math.min(Math.max(((aw-tw)+currentWidth), g.autoExpandMin), g.autoExpandMax); if(cw != currentWidth){ cm.setColumnWidth(ci, cw, true); if(preventUpdate !== true){ this.updateColumnWidth(ci, cw); } } } } }, getColumnData : function(){ var cs = [], cm = this.cm, colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ var name = cm.getDataIndex(i); cs[i] = { name : (typeof name == 'undefined' ? this.ds.fields.get(i).name : name), renderer : cm.getRenderer(i), id : cm.getColumnId(i), style : this.getColumnStyle(i) }; } return cs; }, renderRows : function(startRow, endRow){ var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows; var colCount = cm.getColumnCount(); if(ds.getCount() < 1){ return ""; } var cs = this.getColumnData(); startRow = startRow || 0; endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow; var rs = ds.getRange(startRow, endRow); return this.doRender(cs, rs, ds, startRow, colCount, stripe); }, renderBody : function(){ var markup = this.renderRows(); return this.templates.body.apply({rows: markup}); }, refreshRow : function(record){ var ds = this.ds, index; if(typeof record == 'number'){ index = record; record = ds.getAt(index); }else{ index = ds.indexOf(record); } var cls = []; this.insertRows(ds, index, index, true); this.getRow(index).rowIndex = index; this.onRemove(ds, record, index+1, true); this.fireEvent("rowupdated", this, index, record); }, refresh : function(headersToo){ this.fireEvent("beforerefresh", this); this.grid.stopEditing(true); var result = this.renderBody(); this.mainBody.update(result); if(headersToo === true){ this.updateHeaders(); this.updateHeaderSortState(); } this.processRows(0, true); this.layout(); this.applyEmptyText(); this.fireEvent("refresh", this); }, applyEmptyText : function(){ if(this.emptyText && !this.hasRows()){ this.mainBody.update('<div class="x-grid-empty">' + this.emptyText + '</div>'); } }, updateHeaderSortState : function(){ var state = this.ds.getSortState(); if(!state){ return; } if(!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)){ this.grid.fireEvent('sortchange', this.grid, state); } this.sortState = state; var sortColumn = this.cm.findColumnIndex(state.field); if(sortColumn != -1){ var sortDir = state.direction; this.updateSortIcon(sortColumn, sortDir); } }, destroy : function(){ if(this.colMenu){ this.colMenu.removeAll(); Ext.menu.MenuMgr.unregister(this.colMenu); this.colMenu.getEl().remove(); delete this.colMenu; } if(this.hmenu){ this.hmenu.removeAll(); Ext.menu.MenuMgr.unregister(this.hmenu); this.hmenu.getEl().remove(); delete this.hmenu; } if(this.grid.enableColumnMove){ var dds = Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id]; if(dds){ for(var dd in dds){ if(!dds[dd].config.isTarget && dds[dd].dragElId){ var elid = dds[dd].dragElId; dds[dd].unreg(); Ext.get(elid).remove(); } else if(dds[dd].config.isTarget){ dds[dd].proxyTop.remove(); dds[dd].proxyBottom.remove(); dds[dd].unreg(); } if(Ext.dd.DDM.locationCache[dd]){ delete Ext.dd.DDM.locationCache[dd]; } } delete Ext.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id]; } } Ext.destroy(this.resizeMarker, this.resizeProxy); this.initData(null, null); Ext.EventManager.removeResizeListener(this.onWindowResize, this); }, onDenyColumnHide : function(){ }, render : function(){ var cm = this.cm; var colCount = cm.getColumnCount(); if(this.autoFill){ this.fitColumns(true, true); }else if(this.forceFit){ this.fitColumns(true, false); }else if(this.grid.autoExpandColumn){ this.autoExpand(true); } this.renderUI(); }, initData : function(ds, cm){ if(this.ds){ this.ds.un("load", this.onLoad, this); this.ds.un("datachanged", this.onDataChange, this); this.ds.un("add", this.onAdd, this); this.ds.un("remove", this.onRemove, this); this.ds.un("update", this.onUpdate, this); this.ds.un("clear", this.onClear, this); } if(ds){ ds.on("load", this.onLoad, this); ds.on("datachanged", this.onDataChange, this); ds.on("add", this.onAdd, this); ds.on("remove", this.onRemove, this); ds.on("update", this.onUpdate, this); ds.on("clear", this.onClear, this); } this.ds = ds; if(this.cm){ this.cm.un("configchange", this.onColConfigChange, this); this.cm.un("widthchange", this.onColWidthChange, this); this.cm.un("headerchange", this.onHeaderChange, this); this.cm.un("hiddenchange", this.onHiddenChange, this); this.cm.un("columnmoved", this.onColumnMove, this); this.cm.un("columnlockchange", this.onColumnLock, this); } if(cm){ cm.on("configchange", this.onColConfigChange, this); cm.on("widthchange", this.onColWidthChange, this); cm.on("headerchange", this.onHeaderChange, this); cm.on("hiddenchange", this.onHiddenChange, this); cm.on("columnmoved", this.onColumnMove, this); cm.on("columnlockchange", this.onColumnLock, this); } this.cm = cm; }, onDataChange : function(){ this.refresh(); this.updateHeaderSortState(); }, onClear : function(){ this.refresh(); }, onUpdate : function(ds, record){ this.refreshRow(record); }, onAdd : function(ds, records, index){ this.insertRows(ds, index, index + (records.length-1)); }, onRemove : function(ds, record, index, isUpdate){ if(isUpdate !== true){ this.fireEvent("beforerowremoved", this, index, record); } this.removeRow(index); if(isUpdate !== true){ this.processRows(index); this.applyEmptyText(); this.fireEvent("rowremoved", this, index, record); } }, onLoad : function(){ this.scrollToTop(); }, onColWidthChange : function(cm, col, width){ this.updateColumnWidth(col, width); }, onHeaderChange : function(cm, col, text){ this.updateHeaders(); }, onHiddenChange : function(cm, col, hidden){ this.updateColumnHidden(col, hidden); }, onColumnMove : function(cm, oldIndex, newIndex){ this.indexMap = null; var s = this.getScrollState(); this.refresh(true); this.restoreScroll(s); this.afterMove(newIndex); }, onColConfigChange : function(){ delete this.lastViewWidth; this.indexMap = null; this.refresh(true); }, initUI : function(grid){ grid.on("headerclick", this.onHeaderClick, this); if(grid.trackMouseOver){ grid.on("mouseover", this.onRowOver, this); grid.on("mouseout", this.onRowOut, this); } }, initEvents : function(){ }, onHeaderClick : function(g, index){ if(this.headersDisabled || !this.cm.isSortable(index)){ return; } g.stopEditing(true); g.store.sort(this.cm.getDataIndex(index)); }, onRowOver : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false){ this.addRowClass(row, "x-grid3-row-over"); } }, onRowOut : function(e, t){ var row; if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){ this.removeRowClass(row, "x-grid3-row-over"); } }, handleWheel : function(e){ e.stopPropagation(); }, onRowSelect : function(row){ this.addRowClass(row, "x-grid3-row-selected"); }, onRowDeselect : function(row){ this.removeRowClass(row, "x-grid3-row-selected"); }, onCellSelect : function(row, col){ var cell = this.getCell(row, col); if(cell){ this.fly(cell).addClass("x-grid3-cell-selected"); } }, onCellDeselect : function(row, col){ var cell = this.getCell(row, col); if(cell){ this.fly(cell).removeClass("x-grid3-cell-selected"); } }, onColumnSplitterMoved : function(i, w){ this.userResized = true; var cm = this.grid.colModel; cm.setColumnWidth(i, w, true); if(this.forceFit){ this.fitColumns(true, false, i); this.updateAllColumnWidths(); }else{ this.updateColumnWidth(i, w); } this.grid.fireEvent("columnresize", i, w); }, handleHdMenuClick : function(item){ var index = this.hdCtxIndex; var cm = this.cm, ds = this.ds; switch(item.id){ case "asc": ds.sort(cm.getDataIndex(index), "ASC"); break; case "desc": ds.sort(cm.getDataIndex(index), "DESC"); break; default: index = cm.getIndexById(item.id.substr(4)); if(index != -1){ if(item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1){ this.onDenyColumnHide(); return false; } cm.setHidden(index, item.checked); } } return true; }, isHideableColumn : function(c){ return !c.hidden && !c.fixed; }, beforeColMenuShow : function(){ var cm = this.cm, colCount = cm.getColumnCount(); this.colMenu.removeAll(); for(var i = 0; i < colCount; i++){ if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){ this.colMenu.add(new Ext.menu.CheckItem({ id: "col-"+cm.getColumnId(i), text: cm.getColumnHeader(i), checked: !cm.isHidden(i), hideOnClick:false, disabled: cm.config[i].hideable === false })); } } }, handleHdDown : function(e, t){ if(Ext.fly(t).hasClass('x-grid3-hd-btn')){ e.stopEvent(); var hd = this.findHeaderCell(t); Ext.fly(hd).addClass('x-grid3-hd-menu-open'); var index = this.getCellIndex(hd); this.hdCtxIndex = index; var ms = this.hmenu.items, cm = this.cm; ms.get("asc").setDisabled(!cm.isSortable(index)); ms.get("desc").setDisabled(!cm.isSortable(index)); this.hmenu.on("hide", function(){ Ext.fly(hd).removeClass('x-grid3-hd-menu-open'); }, this, {single:true}); this.hmenu.show(t, "tl-bl?"); } }, handleHdOver : function(e, t){ var hd = this.findHeaderCell(t); if(hd && !this.headersDisabled){ this.activeHd = hd; this.activeHdIndex = this.getCellIndex(hd); var fly = this.fly(hd); this.activeHdRegion = fly.getRegion(); if(!this.cm.isMenuDisabled(this.activeHdIndex)){ fly.addClass("x-grid3-hd-over"); this.activeHdBtn = fly.child('.x-grid3-hd-btn'); if(this.activeHdBtn){ this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight-1)+'px'; } } } }, handleHdMove : function(e, t){ if(this.activeHd && !this.headersDisabled){ var hw = this.splitHandleWidth || 5; var r = this.activeHdRegion; var x = e.getPageX(); var ss = this.activeHd.style; if(x - r.left <= hw && this.cm.isResizable(this.activeHdIndex-1)){ ss.cursor = Ext.isAir ? 'move' : Ext.isSafari ? 'e-resize' : 'col-resize'; }else if(r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)){ ss.cursor = Ext.isAir ? 'move' : Ext.isSafari ? 'w-resize' : 'col-resize'; }else{ ss.cursor = ''; } } }, handleHdOut : function(e, t){ var hd = this.findHeaderCell(t); if(hd && (!Ext.isIE || !e.within(hd, true))){ this.activeHd = null; this.fly(hd).removeClass("x-grid3-hd-over"); hd.style.cursor = ''; } }, hasRows : function(){ var fc = this.mainBody.dom.firstChild; return fc && fc.className != 'x-grid-empty'; }, bind : function(d, c){ this.initData(d, c); } }); Ext.grid.GridView.SplitDragZone = function(grid, hd){ this.grid = grid; this.view = grid.getView(); this.marker = this.view.resizeMarker; this.proxy = this.view.resizeProxy; Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this, hd, "gridSplitters" + this.grid.getGridEl().id, { dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); this.scroll = false; this.hw = this.view.splitHandleWidth || 5; }; Ext.extend(Ext.grid.GridView.SplitDragZone, Ext.dd.DDProxy, { b4StartDrag : function(x, y){ this.view.headersDisabled = true; var h = this.view.mainWrap.getHeight(); this.marker.setHeight(h); this.marker.show(); this.marker.alignTo(this.view.getHeaderCell(this.cellIndex), 'tl-tl', [-2, 0]); this.proxy.setHeight(h); var w = this.cm.getColumnWidth(this.cellIndex); var minw = Math.max(w-this.grid.minColumnWidth, 0); this.resetConstraints(); this.setXConstraint(minw, 1000); this.setYConstraint(0, 0); this.minX = x - minw; this.maxX = x + 1000; this.startPos = x; Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, handleMouseDown : function(e){ var t = this.view.findHeaderCell(e.getTarget()); if(t){ var xy = this.view.fly(t).getXY(), x = xy[0], y = xy[1]; var exy = e.getXY(), ex = exy[0], ey = exy[1]; var w = t.offsetWidth, adjust = false; if((ex - x) <= this.hw){ adjust = -1; }else if((x+w) - ex <= this.hw){ adjust = 0; } if(adjust !== false){ this.cm = this.grid.colModel; var ci = this.view.getCellIndex(t); if(adjust == -1){ if (ci + adjust < 0) { return; } while(this.cm.isHidden(ci+adjust)){ --adjust; if(ci+adjust < 0){ return; } } } this.cellIndex = ci+adjust; this.split = t.dom; if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } }else if(this.view.columnDrag){ this.view.columnDrag.callHandleMouseDown(e); } } }, endDrag : function(e){ this.marker.hide(); var v = this.view; var endX = Math.max(this.minX, e.getPageX()); var diff = endX - this.startPos; v.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); setTimeout(function(){ v.headersDisabled = false; }, 50); }, autoOffset : function(){ this.setDelta(0,0); } }); Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, { hideGroupedColumn:false, showGroupName:true, startCollapsed:false, enableGrouping:true, enableGroupingMenu:true, enableNoGroups:true, emptyGroupText : '(None)', ignoreAdd: false, groupTextTpl : '{text}', gidSeed : 1000, initTemplates : function(){ Ext.grid.GroupingView.superclass.initTemplates.call(this); this.state = {}; var sm = this.grid.getSelectionModel(); sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect', this.onBeforeRowSelect, this); if(!this.startGroup){ this.startGroup = new Ext.XTemplate( '<div id="{groupId}" class="x-grid-group {cls}">', '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div>', this.groupTextTpl ,'</div></div>', '<div id="{groupId}-bd" class="x-grid-group-body">' ); } this.startGroup.compile(); this.endGroup = '</div></div>'; }, findGroup : function(el){ return Ext.fly(el).up('.x-grid-group', this.mainBody.dom); }, getGroups : function(){ return this.hasRows() ? this.mainBody.dom.childNodes : []; }, onAdd : function(){ if(this.enableGrouping && !this.ignoreAdd){ var ss = this.getScrollState(); this.refresh(); this.restoreScroll(ss); }else if(!this.enableGrouping){ Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments); } }, onRemove : function(ds, record, index, isUpdate){ Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments); var g = document.getElementById(record._groupId); if(g && g.childNodes[1].childNodes.length < 1){ Ext.removeNode(g); } this.applyEmptyText(); }, refreshRow : function(record){ if(this.ds.getCount()==1){ this.refresh(); }else{ this.isUpdating = true; Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments); this.isUpdating = false; } }, beforeMenuShow : function(){ var field = this.getGroupField(); var g = this.hmenu.items.get('groupBy'); if(g){ g.setDisabled(this.cm.config[this.hdCtxIndex].groupable === false); } var s = this.hmenu.items.get('showGroups'); if(s){ if (!!field){ s.setDisabled(this.cm.config[this.hdCtxIndex].groupable === false) } s.setChecked(!!field); } }, renderUI : function(){ Ext.grid.GroupingView.superclass.renderUI.call(this); this.mainBody.on('mousedown', this.interceptMouse, this); if(this.enableGroupingMenu && this.hmenu){ this.hmenu.add('-',{ id:'groupBy', text: this.groupByText, handler: this.onGroupByClick, scope: this, iconCls:'x-group-by-icon' }); if(this.enableNoGroups){ this.hmenu.add({ id:'showGroups', text: this.showGroupsText, checked: true, checkHandler: this.onShowGroupsClick, scope: this }); } this.hmenu.on('beforeshow', this.beforeMenuShow, this); } }, onGroupByClick : function(){ this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex)); this.beforeMenuShow(); }, onShowGroupsClick : function(mi, checked){ if(checked){ this.onGroupByClick(); }else{ this.grid.store.clearGrouping(); } }, toggleGroup : function(group, expanded){ this.grid.stopEditing(true); group = Ext.getDom(group); var gel = Ext.fly(group); expanded = expanded !== undefined ? expanded : gel.hasClass('x-grid-group-collapsed'); this.state[gel.dom.id] = expanded; gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed'); }, toggleAllGroups : function(expanded){ var groups = this.getGroups(); for(var i = 0, len = groups.length; i < len; i++){ this.toggleGroup(groups[i], expanded); } }, expandAllGroups : function(){ this.toggleAllGroups(true); }, collapseAllGroups : function(){ this.toggleAllGroups(false); }, interceptMouse : function(e){ var hd = e.getTarget('.x-grid-group-hd', this.mainBody); if(hd){ e.stopEvent(); this.toggleGroup(hd.parentNode); } }, getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){ var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v); if(g === ''){ g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText; } return g; }, getGroupField : function(){ return this.grid.store.getGroupState(); }, renderRows : function(){ var groupField = this.getGroupField(); var eg = !!groupField; if(this.hideGroupedColumn) { var colIndex = this.cm.findColumnIndex(groupField); if(!eg && this.lastGroupField !== undefined) { this.mainBody.update(''); this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false); delete this.lastGroupField; }else if (eg && this.lastGroupField === undefined) { this.lastGroupField = groupField; this.cm.setHidden(colIndex, true); }else if (eg && this.lastGroupField !== undefined && groupField !== this.lastGroupField) { this.mainBody.update(''); var oldIndex = this.cm.findColumnIndex(this.lastGroupField); this.cm.setHidden(oldIndex, false); this.lastGroupField = groupField; this.cm.setHidden(colIndex, true); } } return Ext.grid.GroupingView.superclass.renderRows.apply( this, arguments); }, doRender : function(cs, rs, ds, startRow, colCount, stripe){ if(rs.length < 1){ return ''; } var groupField = this.getGroupField(); var colIndex = this.cm.findColumnIndex(groupField); this.enableGrouping = !!groupField; if(!this.enableGrouping || this.isUpdating){ return Ext.grid.GroupingView.superclass.doRender.apply( this, arguments); } var gstyle = 'width:'+this.getTotalWidth()+';'; var gidPrefix = this.grid.getGridEl().id; var cfg = this.cm.config[colIndex]; var groupRenderer = cfg.groupRenderer || cfg.renderer; var prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : ''; var groups = [], curGroup, i, len, gid; for(i = 0, len = rs.length; i < len; i++){ var rowIndex = startRow + i; var r = rs[i], gvalue = r.data[groupField], g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds); if(!curGroup || curGroup.group != g){ gid = gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(g); var isCollapsed = typeof this.state[gid] !== 'undefined' ? !this.state[gid] : this.startCollapsed; var gcls = isCollapsed ? 'x-grid-group-collapsed' : ''; curGroup = { group: g, gvalue: gvalue, text: prefix + g, groupId: gid, startRow: rowIndex, rs: [r], cls: gcls, style: gstyle }; groups.push(curGroup); }else{ curGroup.rs.push(r); } r._groupId = gid; } var buf = []; for(i = 0, len = groups.length; i < len; i++){ var g = groups[i]; this.doGroupStart(buf, g, cs, ds, colCount); buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call( this, cs, g.rs, ds, g.startRow, colCount, stripe); this.doGroupEnd(buf, g, cs, ds, colCount); } return buf.join(''); }, getGroupId : function(value){ var gidPrefix = this.grid.getGridEl().id; var groupField = this.getGroupField(); var colIndex = this.cm.findColumnIndex(groupField); var cfg = this.cm.config[colIndex]; var groupRenderer = cfg.groupRenderer || cfg.renderer; var gtext = this.getGroup(value, {data:{}}, groupRenderer, 0, colIndex, this.ds); return gidPrefix + '-gp-' + groupField + '-' + Ext.util.Format.htmlEncode(value); }, doGroupStart : function(buf, g, cs, ds, colCount){ buf[buf.length] = this.startGroup.apply(g); }, doGroupEnd : function(buf, g, cs, ds, colCount){ buf[buf.length] = this.endGroup; }, getRows : function(){ if(!this.enableGrouping){ return Ext.grid.GroupingView.superclass.getRows.call(this); } var r = []; var g, gs = this.getGroups(); for(var i = 0, len = gs.length; i < len; i++){ g = gs[i].childNodes[1].childNodes; for(var j = 0, jlen = g.length; j < jlen; j++){ r[r.length] = g[j]; } } return r; }, updateGroupWidths : function(){ if(!this.enableGrouping || !this.hasRows()){ return; } var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.scrollOffset) +'px'; var gs = this.getGroups(); for(var i = 0, len = gs.length; i < len; i++){ gs[i].firstChild.style.width = tw; } }, onColumnWidthUpdated : function(col, w, tw){ this.updateGroupWidths(); }, onAllColumnWidthsUpdated : function(ws, tw){ this.updateGroupWidths(); }, onColumnHiddenUpdated : function(col, hidden, tw){ this.updateGroupWidths(); }, onLayout : function(){ this.updateGroupWidths(); }, onBeforeRowSelect : function(sm, rowIndex){ if(!this.enableGrouping){ return; } var row = this.getRow(rowIndex); if(row && !row.offsetParent){ var g = this.findGroup(row); this.toggleGroup(g, true); } }, groupByText: 'Group By This Field', showGroupsText: 'Show in Groups' }); Ext.grid.GroupingView.GROUP_ID = 1000; Ext.grid.HeaderDragZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.ddGroup = "gridHeader" + this.grid.getGridEl().id; Ext.grid.HeaderDragZone.superclass.constructor.call(this, hd); if(hd2){ this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); } this.scroll = false; }; Ext.extend(Ext.grid.HeaderDragZone, Ext.dd.DragZone, { maxDragWidth: 120, getDragData : function(e){ var t = Ext.lib.Event.getTarget(e); var h = this.view.findHeaderCell(t); if(h){ return {ddel: h.firstChild, header:h}; } return false; }, onInitDrag : function(e){ this.view.headersDisabled = true; var clone = this.dragData.ddel.cloneNode(true); clone.id = Ext.id(); clone.style.width = Math.min(this.dragData.header.offsetWidth,this.maxDragWidth) + "px"; this.proxy.update(clone); return true; }, afterValidDrop : function(){ var v = this.view; setTimeout(function(){ v.headersDisabled = false; }, 50); }, afterInvalidDrop : function(){ var v = this.view; setTimeout(function(){ v.headersDisabled = false; }, 50); } }); Ext.grid.HeaderDropZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.proxyTop = Ext.DomHelper.append(document.body, { cls:"col-move-top", html:"&#160;" }, true); this.proxyBottom = Ext.DomHelper.append(document.body, { cls:"col-move-bottom", html:"&#160;" }, true); this.proxyTop.hide = this.proxyBottom.hide = function(){ this.setLeftTop(-100,-100); this.setStyle("visibility", "hidden"); }; this.ddGroup = "gridHeader" + this.grid.getGridEl().id; Ext.grid.HeaderDropZone.superclass.constructor.call(this, grid.getGridEl().dom); }; Ext.extend(Ext.grid.HeaderDropZone, Ext.dd.DropZone, { proxyOffsets : [-4, -9], fly: Ext.Element.fly, getTargetFromEvent : function(e){ var t = Ext.lib.Event.getTarget(e); var cindex = this.view.findCellIndex(t); if(cindex !== false){ return this.view.getHeaderCell(cindex); } }, nextVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.nextSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.nextSibling; } return null; }, prevVisible : function(h){ var v = this.view, cm = this.grid.colModel; h = h.prevSibling; while(h){ if(!cm.isHidden(v.getCellIndex(h))){ return h; } h = h.prevSibling; } return null; }, positionIndicator : function(h, n, e){ var x = Ext.lib.Event.getPageX(e); var r = Ext.lib.Dom.getRegion(n.firstChild); var px, pt, py = r.top + this.proxyOffsets[1]; if((r.right - x) <= (r.right-r.left)/2){ px = r.right+this.view.borderWidth; pt = "after"; }else{ px = r.left; pt = "before"; } var oldIndex = this.view.getCellIndex(h); var newIndex = this.view.getCellIndex(n); if(this.grid.colModel.isFixed(newIndex)){ return false; } var locked = this.grid.colModel.isLocked(newIndex); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } if(oldIndex == newIndex && (locked == this.grid.colModel.isLocked(oldIndex))){ return false; } px += this.proxyOffsets[0]; this.proxyTop.setLeftTop(px, py); this.proxyTop.show(); if(!this.bottomOffset){ this.bottomOffset = this.view.mainHd.getHeight(); } this.proxyBottom.setLeftTop(px, py+this.proxyTop.dom.offsetHeight+this.bottomOffset); this.proxyBottom.show(); return pt; }, onNodeEnter : function(n, dd, e, data){ if(data.header != n){ this.positionIndicator(data.header, n, e); } }, onNodeOver : function(n, dd, e, data){ var result = false; if(data.header != n){ result = this.positionIndicator(data.header, n, e); } if(!result){ this.proxyTop.hide(); this.proxyBottom.hide(); } return result ? this.dropAllowed : this.dropNotAllowed; }, onNodeOut : function(n, dd, e, data){ this.proxyTop.hide(); this.proxyBottom.hide(); }, onNodeDrop : function(n, dd, e, data){ var h = data.header; if(h != n){ var cm = this.grid.colModel; var x = Ext.lib.Event.getPageX(e); var r = Ext.lib.Dom.getRegion(n.firstChild); var pt = (r.right - x) <= ((r.right-r.left)/2) ? "after" : "before"; var oldIndex = this.view.getCellIndex(h); var newIndex = this.view.getCellIndex(n); var locked = cm.isLocked(newIndex); if(pt == "after"){ newIndex++; } if(oldIndex < newIndex){ newIndex--; } if(oldIndex == newIndex && (locked == cm.isLocked(oldIndex))){ return false; } cm.setLocked(oldIndex, locked, true); cm.moveColumn(oldIndex, newIndex); this.grid.fireEvent("columnmove", oldIndex, newIndex); return true; } return false; } }); Ext.grid.GridView.ColumnDragZone = function(grid, hd){ Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null); this.proxy.el.addClass('x-grid3-col-dd'); }; Ext.extend(Ext.grid.GridView.ColumnDragZone, Ext.grid.HeaderDragZone, { handleMouseDown : function(e){ }, callHandleMouseDown : function(e){ Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e); } }); Ext.grid.SplitDragZone = function(grid, hd, hd2){ this.grid = grid; this.view = grid.getView(); this.proxy = this.view.resizeProxy; Ext.grid.SplitDragZone.superclass.constructor.call(this, hd, "gridSplitters" + this.grid.getGridEl().id, { dragElId : Ext.id(this.proxy.dom), resizeFrame:false }); this.setHandleElId(Ext.id(hd)); this.setOuterHandleElId(Ext.id(hd2)); this.scroll = false; }; Ext.extend(Ext.grid.SplitDragZone, Ext.dd.DDProxy, { fly: Ext.Element.fly, b4StartDrag : function(x, y){ this.view.headersDisabled = true; this.proxy.setHeight(this.view.mainWrap.getHeight()); var w = this.cm.getColumnWidth(this.cellIndex); var minw = Math.max(w-this.grid.minColumnWidth, 0); this.resetConstraints(); this.setXConstraint(minw, 1000); this.setYConstraint(0, 0); this.minX = x - minw; this.maxX = x + 1000; this.startPos = x; Ext.dd.DDProxy.prototype.b4StartDrag.call(this, x, y); }, handleMouseDown : function(e){ ev = Ext.EventObject.setEvent(e); var t = this.fly(ev.getTarget()); if(t.hasClass("x-grid-split")){ this.cellIndex = this.view.getCellIndex(t.dom); this.split = t.dom; this.cm = this.grid.colModel; if(this.cm.isResizable(this.cellIndex) && !this.cm.isFixed(this.cellIndex)){ Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this, arguments); } } }, endDrag : function(e){ this.view.headersDisabled = false; var endX = Math.max(this.minX, Ext.lib.Event.getPageX(e)); var diff = endX - this.startPos; this.view.onColumnSplitterMoved(this.cellIndex, this.cm.getColumnWidth(this.cellIndex)+diff); }, autoOffset : function(){ this.setDelta(0,0); } }); Ext.grid.GridDragZone = function(grid, config){ this.view = grid.getView(); Ext.grid.GridDragZone.superclass.constructor.call(this, this.view.mainBody.dom, config); if(this.view.lockedBody){ this.setHandleElId(Ext.id(this.view.mainBody.dom)); this.setOuterHandleElId(Ext.id(this.view.lockedBody.dom)); } this.scroll = false; this.grid = grid; this.ddel = document.createElement('div'); this.ddel.className = 'x-grid-dd-wrap'; }; Ext.extend(Ext.grid.GridDragZone, Ext.dd.DragZone, { ddGroup : "GridDD", getDragData : function(e){ var t = Ext.lib.Event.getTarget(e); var rowIndex = this.view.findRowIndex(t); if(rowIndex !== false){ var sm = this.grid.selModel; if(!sm.isSelected(rowIndex) || e.hasModifier()){ sm.handleMouseDown(this.grid, rowIndex, e); } return {grid: this.grid, ddel: this.ddel, rowIndex: rowIndex, selections:sm.getSelections()}; } return false; }, onInitDrag : function(e){ var data = this.dragData; this.ddel.innerHTML = this.grid.getDragDropText(); this.proxy.update(this.ddel); }, afterRepair : function(){ this.dragging = false; }, getRepairXY : function(e, data){ return false; }, onEndDrag : function(data, e){ }, onValidDrop : function(dd, e, id){ this.hideProxy(); }, beforeInvalidDrop : function(e, id){ } }); Ext.grid.ColumnModel = function(config){ this.defaultWidth = 100; this.defaultSortable = false; if(config.columns){ Ext.apply(this, config); this.setConfig(config.columns, true); }else{ this.setConfig(config, true); } this.addEvents( "widthchange", "headerchange", "hiddenchange", "columnmoved", "columnlockchange", "configchange" ); Ext.grid.ColumnModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.ColumnModel, Ext.util.Observable, { getColumnId : function(index){ return this.config[index].id; }, setConfig : function(config, initial){ if(!initial){ delete this.totalWidth; for(var i = 0, len = this.config.length; i < len; i++){ var c = this.config[i]; if(c.editor){ c.editor.destroy(); } } } this.config = config; this.lookup = {}; for(var i = 0, len = config.length; i < len; i++){ var c = config[i]; if(typeof c.renderer == "string"){ c.renderer = Ext.util.Format[c.renderer]; } if(typeof c.id == "undefined"){ c.id = i; } if(c.editor && c.editor.isFormField){ c.editor = new Ext.grid.GridEditor(c.editor); } this.lookup[c.id] = c; } if(!initial){ this.fireEvent('configchange', this); } }, getColumnById : function(id){ return this.lookup[id]; }, getIndexById : function(id){ for(var i = 0, len = this.config.length; i < len; i++){ if(this.config[i].id == id){ return i; } } return -1; }, moveColumn : function(oldIndex, newIndex){ var c = this.config[oldIndex]; this.config.splice(oldIndex, 1); this.config.splice(newIndex, 0, c); this.dataMap = null; this.fireEvent("columnmoved", this, oldIndex, newIndex); }, isLocked : function(colIndex){ return this.config[colIndex].locked === true; }, setLocked : function(colIndex, value, suppressEvent){ if(this.isLocked(colIndex) == value){ return; } this.config[colIndex].locked = value; if(!suppressEvent){ this.fireEvent("columnlockchange", this, colIndex, value); } }, getTotalLockedWidth : function(){ var totalWidth = 0; for(var i = 0; i < this.config.length; i++){ if(this.isLocked(i) && !this.isHidden(i)){ this.totalWidth += this.getColumnWidth(i); } } return totalWidth; }, getLockedCount : function(){ for(var i = 0, len = this.config.length; i < len; i++){ if(!this.isLocked(i)){ return i; } } }, getColumnCount : function(visibleOnly){ if(visibleOnly === true){ var c = 0; for(var i = 0, len = this.config.length; i < len; i++){ if(!this.isHidden(i)){ c++; } } return c; } return this.config.length; }, getColumnsBy : function(fn, scope){ var r = []; for(var i = 0, len = this.config.length; i < len; i++){ var c = this.config[i]; if(fn.call(scope||this, c, i) === true){ r[r.length] = c; } } return r; }, isSortable : function(col){ if(typeof this.config[col].sortable == "undefined"){ return this.defaultSortable; } return this.config[col].sortable; }, isMenuDisabled : function(col){ return !!this.config[col].menuDisabled; }, getRenderer : function(col){ if(!this.config[col].renderer){ return Ext.grid.ColumnModel.defaultRenderer; } return this.config[col].renderer; }, setRenderer : function(col, fn){ this.config[col].renderer = fn; }, getColumnWidth : function(col){ return this.config[col].width || this.defaultWidth; }, setColumnWidth : function(col, width, suppressEvent){ this.config[col].width = width; this.totalWidth = null; if(!suppressEvent){ this.fireEvent("widthchange", this, col, width); } }, getTotalWidth : function(includeHidden){ if(!this.totalWidth){ this.totalWidth = 0; for(var i = 0, len = this.config.length; i < len; i++){ if(includeHidden || !this.isHidden(i)){ this.totalWidth += this.getColumnWidth(i); } } } return this.totalWidth; }, getColumnHeader : function(col){ return this.config[col].header; }, setColumnHeader : function(col, header){ this.config[col].header = header; this.fireEvent("headerchange", this, col, header); }, getColumnTooltip : function(col){ return this.config[col].tooltip; }, setColumnTooltip : function(col, tooltip){ this.config[col].tooltip = tooltip; }, getDataIndex : function(col){ return this.config[col].dataIndex; }, setDataIndex : function(col, dataIndex){ this.config[col].dataIndex = dataIndex; }, findColumnIndex : function(dataIndex){ var c = this.config; for(var i = 0, len = c.length; i < len; i++){ if(c[i].dataIndex == dataIndex){ return i; } } return -1; }, isCellEditable : function(colIndex, rowIndex){ return (this.config[colIndex].editable || (typeof this.config[colIndex].editable == "undefined" && this.config[colIndex].editor)) ? true : false; }, getCellEditor : function(colIndex, rowIndex){ return this.config[colIndex].editor; }, setEditable : function(col, editable){ this.config[col].editable = editable; }, isHidden : function(colIndex){ return this.config[colIndex].hidden; }, isFixed : function(colIndex){ return this.config[colIndex].fixed; }, isResizable : function(colIndex){ return colIndex >= 0 && this.config[colIndex].resizable !== false && this.config[colIndex].fixed !== true; }, setHidden : function(colIndex, hidden){ var c = this.config[colIndex]; if(c.hidden !== hidden){ c.hidden = hidden; this.totalWidth = null; this.fireEvent("hiddenchange", this, colIndex, hidden); } }, setEditor : function(col, editor){ this.config[col].editor = editor; } }); Ext.grid.ColumnModel.defaultRenderer = function(value){ if(typeof value == "string" && value.length < 1){ return "&#160;"; } return value; }; Ext.grid.DefaultColumnModel = Ext.grid.ColumnModel; Ext.grid.AbstractSelectionModel = function(){ this.locked = false; Ext.grid.AbstractSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.AbstractSelectionModel, Ext.util.Observable, { init : function(grid){ this.grid = grid; this.initEvents(); }, lock : function(){ this.locked = true; }, unlock : function(){ this.locked = false; }, isLocked : function(){ return this.locked; } }); Ext.grid.RowSelectionModel = function(config){ Ext.apply(this, config); this.selections = new Ext.util.MixedCollection(false, function(o){ return o.id; }); this.last = false; this.lastActive = false; this.addEvents( "selectionchange", "beforerowselect", "rowselect", "rowdeselect" ); Ext.grid.RowSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.RowSelectionModel, Ext.grid.AbstractSelectionModel, { singleSelect : false, initEvents : function(){ if(!this.grid.enableDragDrop && !this.grid.enableDrag){ this.grid.on("rowmousedown", this.handleMouseDown, this); }else{ this.grid.on("rowclick", function(grid, rowIndex, e) { if(e.button === 0 && !e.shiftKey && !e.ctrlKey) { this.selectRow(rowIndex, false); grid.view.focusRow(rowIndex); } }, this); } this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), { "up" : function(e){ if(!e.shiftKey){ this.selectPrevious(e.shiftKey); }else if(this.last !== false && this.lastActive !== false){ var last = this.last; this.selectRange(this.last, this.lastActive-1); this.grid.getView().focusRow(this.lastActive); if(last !== false){ this.last = last; } }else{ this.selectFirstRow(); } }, "down" : function(e){ if(!e.shiftKey){ this.selectNext(e.shiftKey); }else if(this.last !== false && this.lastActive !== false){ var last = this.last; this.selectRange(this.last, this.lastActive+1); this.grid.getView().focusRow(this.lastActive); if(last !== false){ this.last = last; } }else{ this.selectFirstRow(); } }, scope: this }); var view = this.grid.view; view.on("refresh", this.onRefresh, this); view.on("rowupdated", this.onRowUpdated, this); view.on("rowremoved", this.onRemove, this); }, onRefresh : function(){ var ds = this.grid.store, index; var s = this.getSelections(); this.clearSelections(true); for(var i = 0, len = s.length; i < len; i++){ var r = s[i]; if((index = ds.indexOfId(r.id)) != -1){ this.selectRow(index, true); } } if(s.length != this.selections.getCount()){ this.fireEvent("selectionchange", this); } }, onRemove : function(v, index, r){ if(this.selections.remove(r) !== false){ this.fireEvent('selectionchange', this); } }, onRowUpdated : function(v, index, r){ if(this.isSelected(r)){ v.onRowSelect(index); } }, selectRecords : function(records, keepExisting){ if(!keepExisting){ this.clearSelections(); } var ds = this.grid.store; for(var i = 0, len = records.length; i < len; i++){ this.selectRow(ds.indexOf(records[i]), true); } }, getCount : function(){ return this.selections.length; }, selectFirstRow : function(){ this.selectRow(0); }, selectLastRow : function(keepExisting){ this.selectRow(this.grid.store.getCount() - 1, keepExisting); }, selectNext : function(keepExisting){ if(this.hasNext()){ this.selectRow(this.last+1, keepExisting); this.grid.getView().focusRow(this.last); return true; } return false; }, selectPrevious : function(keepExisting){ if(this.hasPrevious()){ this.selectRow(this.last-1, keepExisting); this.grid.getView().focusRow(this.last); return true; } return false; }, hasNext : function(){ return this.last !== false && (this.last+1) < this.grid.store.getCount(); }, hasPrevious : function(){ return !!this.last; }, getSelections : function(){ return [].concat(this.selections.items); }, getSelected : function(){ return this.selections.itemAt(0); }, each : function(fn, scope){ var s = this.getSelections(); for(var i = 0, len = s.length; i < len; i++){ if(fn.call(scope || this, s[i], i) === false){ return false; } } return true; }, clearSelections : function(fast){ if(this.locked) return; if(fast !== true){ var ds = this.grid.store; var s = this.selections; s.each(function(r){ this.deselectRow(ds.indexOfId(r.id)); }, this); s.clear(); }else{ this.selections.clear(); } this.last = false; }, selectAll : function(){ if(this.locked) return; this.selections.clear(); for(var i = 0, len = this.grid.store.getCount(); i < len; i++){ this.selectRow(i, true); } }, hasSelection : function(){ return this.selections.length > 0; }, isSelected : function(index){ var r = typeof index == "number" ? this.grid.store.getAt(index) : index; return (r && this.selections.key(r.id) ? true : false); }, isIdSelected : function(id){ return (this.selections.key(id) ? true : false); }, handleMouseDown : function(g, rowIndex, e){ if(e.button !== 0 || this.isLocked()){ return; }; var view = this.grid.getView(); if(e.shiftKey && this.last !== false){ var last = this.last; this.selectRange(last, rowIndex, e.ctrlKey); this.last = last; view.focusRow(rowIndex); }else{ var isSelected = this.isSelected(rowIndex); if(e.ctrlKey && isSelected){ this.deselectRow(rowIndex); }else if(!isSelected || this.getCount() > 1){ this.selectRow(rowIndex, e.ctrlKey || e.shiftKey); view.focusRow(rowIndex); } } }, selectRows : function(rows, keepExisting){ if(!keepExisting){ this.clearSelections(); } for(var i = 0, len = rows.length; i < len; i++){ this.selectRow(rows[i], true); } }, selectRange : function(startRow, endRow, keepExisting){ if(this.locked) return; if(!keepExisting){ this.clearSelections(); } if(startRow <= endRow){ for(var i = startRow; i <= endRow; i++){ this.selectRow(i, true); } }else{ for(var i = startRow; i >= endRow; i--){ this.selectRow(i, true); } } }, deselectRange : function(startRow, endRow, preventViewNotify){ if(this.locked) return; for(var i = startRow; i <= endRow; i++){ this.deselectRow(i, preventViewNotify); } }, selectRow : function(index, keepExisting, preventViewNotify){ if(this.locked || (index < 0 || index >= this.grid.store.getCount())) return; var r = this.grid.store.getAt(index); if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){ if(!keepExisting || this.singleSelect){ this.clearSelections(); } this.selections.add(r); this.last = this.lastActive = index; if(!preventViewNotify){ this.grid.getView().onRowSelect(index); } this.fireEvent("rowselect", this, index, r); this.fireEvent("selectionchange", this); } }, deselectRow : function(index, preventViewNotify){ if(this.locked) return; if(this.last == index){ this.last = false; } if(this.lastActive == index){ this.lastActive = false; } var r = this.grid.store.getAt(index); if(r){ this.selections.remove(r); if(!preventViewNotify){ this.grid.getView().onRowDeselect(index); } this.fireEvent("rowdeselect", this, index, r); this.fireEvent("selectionchange", this); } }, restoreLast : function(){ if(this._last){ this.last = this._last; } }, acceptsNav : function(row, col, cm){ return !cm.isHidden(col) && cm.isCellEditable(col, row); }, onEditorKey : function(field, e){ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor; var shift = e.shiftKey; if(k == e.TAB){ e.stopEvent(); ed.completeEdit(); if(shift){ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); } }else if(k == e.ENTER){ e.stopEvent(); ed.completeEdit(); if(this.moveEditorOnEnter !== false){ if(shift){ newCell = g.walkCells(ed.row - 1, ed.col, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row + 1, ed.col, 1, this.acceptsNav, this); } } }else if(k == e.ESC){ ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } }); Ext.grid.CellSelectionModel = function(config){ Ext.apply(this, config); this.selection = null; this.addEvents( "beforecellselect", "cellselect", "selectionchange" ); Ext.grid.CellSelectionModel.superclass.constructor.call(this); }; Ext.extend(Ext.grid.CellSelectionModel, Ext.grid.AbstractSelectionModel, { initEvents : function(){ this.grid.on("cellmousedown", this.handleMouseDown, this); this.grid.getGridEl().on(Ext.isIE ? "keydown" : "keypress", this.handleKeyDown, this); var view = this.grid.view; view.on("refresh", this.onViewChange, this); view.on("rowupdated", this.onRowUpdated, this); view.on("beforerowremoved", this.clearSelections, this); view.on("beforerowsinserted", this.clearSelections, this); if(this.grid.isEditor){ this.grid.on("beforeedit", this.beforeEdit, this); } }, beforeEdit : function(e){ this.select(e.row, e.column, false, true, e.record); }, onRowUpdated : function(v, index, r){ if(this.selection && this.selection.record == r){ v.onCellSelect(index, this.selection.cell[1]); } }, onViewChange : function(){ this.clearSelections(true); }, getSelectedCell : function(){ return this.selection ? this.selection.cell : null; }, clearSelections : function(preventNotify){ var s = this.selection; if(s){ if(preventNotify !== true){ this.grid.view.onCellDeselect(s.cell[0], s.cell[1]); } this.selection = null; this.fireEvent("selectionchange", this, null); } }, hasSelection : function(){ return this.selection ? true : false; }, handleMouseDown : function(g, row, cell, e){ if(e.button !== 0 || this.isLocked()){ return; }; this.select(row, cell); }, select : function(rowIndex, colIndex, preventViewNotify, preventFocus, r){ if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){ this.clearSelections(); r = r || this.grid.store.getAt(rowIndex); this.selection = { record : r, cell : [rowIndex, colIndex] }; if(!preventViewNotify){ var v = this.grid.getView(); v.onCellSelect(rowIndex, colIndex); if(preventFocus !== true){ v.focusCell(rowIndex, colIndex); } } this.fireEvent("cellselect", this, rowIndex, colIndex); this.fireEvent("selectionchange", this, this.selection); } }, isSelectable : function(rowIndex, colIndex, cm){ return !cm.isHidden(colIndex); }, handleKeyDown : function(e){ if(!e.isNavKeyPress()){ return; } var g = this.grid, s = this.selection; if(!s){ e.stopEvent(); var cell = g.walkCells(0, 0, 1, this.isSelectable, this); if(cell){ this.select(cell[0], cell[1]); } return; } var sm = this; var walk = function(row, col, step){ return g.walkCells(row, col, step, sm.isSelectable, sm); }; var k = e.getKey(), r = s.cell[0], c = s.cell[1]; var newCell; switch(k){ case e.TAB: if(e.shiftKey){ newCell = walk(r, c-1, -1); }else{ newCell = walk(r, c+1, 1); } break; case e.DOWN: newCell = walk(r+1, c, 1); break; case e.UP: newCell = walk(r-1, c, -1); break; case e.RIGHT: newCell = walk(r, c+1, 1); break; case e.LEFT: newCell = walk(r, c-1, -1); break; case e.ENTER: if(g.isEditor && !g.editing){ g.startEditing(r, c); e.stopEvent(); return; } break; }; if(newCell){ this.select(newCell[0], newCell[1]); e.stopEvent(); } }, acceptsNav : function(row, col, cm){ return !cm.isHidden(col) && cm.isCellEditable(col, row); }, onEditorKey : function(field, e){ var k = e.getKey(), newCell, g = this.grid, ed = g.activeEditor; if(k == e.TAB){ if(e.shiftKey){ newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this); }else{ newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this); } e.stopEvent(); }else if(k == e.ENTER){ ed.completeEdit(); e.stopEvent(); }else if(k == e.ESC){ e.stopEvent(); ed.cancelEdit(); } if(newCell){ g.startEditing(newCell[0], newCell[1]); } } }); Ext.grid.EditorGridPanel = Ext.extend(Ext.grid.GridPanel, { clicksToEdit: 2, isEditor : true, detectEdit: false, autoEncode : false, trackMouseOver: false, initComponent : function(){ Ext.grid.EditorGridPanel.superclass.initComponent.call(this); if(!this.selModel){ this.selModel = new Ext.grid.CellSelectionModel(); } this.activeEditor = null; this.addEvents( "beforeedit", "afteredit", "validateedit" ); }, initEvents : function(){ Ext.grid.EditorGridPanel.superclass.initEvents.call(this); this.on("bodyscroll", this.stopEditing, this, [true]); if(this.clicksToEdit == 1){ this.on("cellclick", this.onCellDblClick, this); }else { if(this.clicksToEdit == 'auto' && this.view.mainBody){ this.view.mainBody.on("mousedown", this.onAutoEditClick, this); } this.on("celldblclick", this.onCellDblClick, this); } this.getGridEl().addClass("xedit-grid"); }, onCellDblClick : function(g, row, col){ this.startEditing(row, col); }, onAutoEditClick : function(e, t){ if(e.button !== 0){ return; } var row = this.view.findRowIndex(t); var col = this.view.findCellIndex(t); if(row !== false && col !== false){ this.stopEditing(); if(this.selModel.getSelectedCell){ var sc = this.selModel.getSelectedCell(); if(sc && sc.cell[0] === row && sc.cell[1] === col){ this.startEditing(row, col); } }else{ if(this.selModel.isSelected(row)){ this.startEditing(row, col); } } } }, onEditComplete : function(ed, value, startValue){ this.editing = false; this.activeEditor = null; ed.un("specialkey", this.selModel.onEditorKey, this.selModel); var r = ed.record; var field = this.colModel.getDataIndex(ed.col); value = this.postEditValue(value, startValue, r, field); if(String(value) !== String(startValue)){ var e = { grid: this, record: r, field: field, originalValue: startValue, value: value, row: ed.row, column: ed.col, cancel:false }; if(this.fireEvent("validateedit", e) !== false && !e.cancel){ r.set(field, e.value); delete e.cancel; this.fireEvent("afteredit", e); } } this.view.focusCell(ed.row, ed.col); }, startEditing : function(row, col){ this.stopEditing(); if(this.colModel.isCellEditable(col, row)){ this.view.ensureVisible(row, col, true); var r = this.store.getAt(row); var field = this.colModel.getDataIndex(col); var e = { grid: this, record: r, field: field, value: r.data[field], row: row, column: col, cancel:false }; if(this.fireEvent("beforeedit", e) !== false && !e.cancel){ this.editing = true; var ed = this.colModel.getCellEditor(col, row); if(!ed.rendered){ ed.render(this.view.getEditorParent(ed)); } (function(){ ed.row = row; ed.col = col; ed.record = r; ed.on("complete", this.onEditComplete, this, {single: true}); ed.on("specialkey", this.selModel.onEditorKey, this.selModel); this.activeEditor = ed; var v = this.preEditValue(r, field); ed.startEdit(this.view.getCell(row, col), v); }).defer(50, this); } } }, preEditValue : function(r, field){ return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlDecode(r.data[field]) : r.data[field]; }, postEditValue : function(value, originalValue, r, field){ return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlEncode(value) : value; }, stopEditing : function(cancel){ if(this.activeEditor){ this.activeEditor[cancel === true ? 'cancelEdit' : 'completeEdit'](); } this.activeEditor = null; } }); Ext.reg('editorgrid', Ext.grid.EditorGridPanel); Ext.grid.GridEditor = function(field, config){ Ext.grid.GridEditor.superclass.constructor.call(this, field, config); field.monitorTab = false; }; Ext.extend(Ext.grid.GridEditor, Ext.Editor, { alignment: "tl-tl", autoSize: "width", hideEl : false, cls: "x-small-editor x-grid-editor", shim:false, shadow:false }); Ext.grid.PropertyRecord = Ext.data.Record.create([ {name:'name',type:'string'}, 'value' ]); Ext.grid.PropertyStore = function(grid, source){ this.grid = grid; this.store = new Ext.data.Store({ recordType : Ext.grid.PropertyRecord }); this.store.on('update', this.onUpdate, this); if(source){ this.setSource(source); } Ext.grid.PropertyStore.superclass.constructor.call(this); }; Ext.extend(Ext.grid.PropertyStore, Ext.util.Observable, { setSource : function(o){ this.source = o; this.store.removeAll(); var data = []; for(var k in o){ if(this.isEditableValue(o[k])){ data.push(new Ext.grid.PropertyRecord({name: k, value: o[k]}, k)); } } this.store.loadRecords({records: data}, {}, true); }, onUpdate : function(ds, record, type){ if(type == Ext.data.Record.EDIT){ var v = record.data['value']; var oldValue = record.modified['value']; if(this.grid.fireEvent('beforepropertychange', this.source, record.id, v, oldValue) !== false){ this.source[record.id] = v; record.commit(); this.grid.fireEvent('propertychange', this.source, record.id, v, oldValue); }else{ record.reject(); } } }, getProperty : function(row){ return this.store.getAt(row); }, isEditableValue: function(val){ if(Ext.isDate(val)){ return true; }else if(typeof val == 'object' || typeof val == 'function'){ return false; } return true; }, setValue : function(prop, value){ this.source[prop] = value; this.store.getById(prop).set('value', value); }, getSource : function(){ return this.source; } }); Ext.grid.PropertyColumnModel = function(grid, store){ this.grid = grid; var g = Ext.grid; g.PropertyColumnModel.superclass.constructor.call(this, [ {header: this.nameText, width:50, sortable: true, dataIndex:'name', id: 'name', menuDisabled:true}, {header: this.valueText, width:50, resizable:false, dataIndex: 'value', id: 'value', menuDisabled:true} ]); this.store = store; this.bselect = Ext.DomHelper.append(document.body, { tag: 'select', cls: 'x-grid-editor x-hide-display', children: [ {tag: 'option', value: 'true', html: 'true'}, {tag: 'option', value: 'false', html: 'false'} ] }); var f = Ext.form; var bfield = new f.Field({ el:this.bselect, bselect : this.bselect, autoShow: true, getValue : function(){ return this.bselect.value == 'true'; } }); this.editors = { 'date' : new g.GridEditor(new f.DateField({selectOnFocus:true})), 'string' : new g.GridEditor(new f.TextField({selectOnFocus:true})), 'number' : new g.GridEditor(new f.NumberField({selectOnFocus:true, style:'text-align:left;'})), 'boolean' : new g.GridEditor(bfield) }; this.renderCellDelegate = this.renderCell.createDelegate(this); this.renderPropDelegate = this.renderProp.createDelegate(this); }; Ext.extend(Ext.grid.PropertyColumnModel, Ext.grid.ColumnModel, { nameText : 'Name', valueText : 'Value', dateFormat : 'm/j/Y', renderDate : function(dateVal){ return dateVal.dateFormat(this.dateFormat); }, renderBool : function(bVal){ return bVal ? 'true' : 'false'; }, isCellEditable : function(colIndex, rowIndex){ return colIndex == 1; }, getRenderer : function(col){ return col == 1 ? this.renderCellDelegate : this.renderPropDelegate; }, renderProp : function(v){ return this.getPropertyName(v); }, renderCell : function(val){ var rv = val; if(Ext.isDate(val)){ rv = this.renderDate(val); }else if(typeof val == 'boolean'){ rv = this.renderBool(val); } return Ext.util.Format.htmlEncode(rv); }, getPropertyName : function(name){ var pn = this.grid.propertyNames; return pn && pn[name] ? pn[name] : name; }, getCellEditor : function(colIndex, rowIndex){ var p = this.store.getProperty(rowIndex); var n = p.data['name'], val = p.data['value']; if(this.grid.customEditors[n]){ return this.grid.customEditors[n]; } if(Ext.isDate(val)){ return this.editors['date']; }else if(typeof val == 'number'){ return this.editors['number']; }else if(typeof val == 'boolean'){ return this.editors['boolean']; }else{ return this.editors['string']; } } }); Ext.grid.PropertyGrid = Ext.extend(Ext.grid.EditorGridPanel, { enableColumnMove:false, stripeRows:false, trackMouseOver: false, clicksToEdit:1, enableHdMenu : false, viewConfig : { forceFit:true }, initComponent : function(){ this.customEditors = this.customEditors || {}; this.lastEditRow = null; var store = new Ext.grid.PropertyStore(this); this.propStore = store; var cm = new Ext.grid.PropertyColumnModel(this, store); store.store.sort('name', 'ASC'); this.addEvents( 'beforepropertychange', 'propertychange' ); this.cm = cm; this.ds = store.store; Ext.grid.PropertyGrid.superclass.initComponent.call(this); this.selModel.on('beforecellselect', function(sm, rowIndex, colIndex){ if(colIndex === 0){ this.startEditing.defer(200, this, [rowIndex, 1]); return false; } }, this); }, onRender : function(){ Ext.grid.PropertyGrid.superclass.onRender.apply(this, arguments); this.getGridEl().addClass('x-props-grid'); }, afterRender: function(){ Ext.grid.PropertyGrid.superclass.afterRender.apply(this, arguments); if(this.source){ this.setSource(this.source); } }, setSource : function(source){ this.propStore.setSource(source); }, getSource : function(){ return this.propStore.getSource(); } }); Ext.grid.RowNumberer = function(config){ Ext.apply(this, config); if(this.rowspan){ this.renderer = this.renderer.createDelegate(this); } }; Ext.grid.RowNumberer.prototype = { header: "", width: 23, sortable: false, fixed:true, menuDisabled:true, dataIndex: '', id: 'numberer', rowspan: undefined, renderer : function(v, p, record, rowIndex){ if(this.rowspan){ p.cellAttr = 'rowspan="'+this.rowspan+'"'; } return rowIndex+1; } }; Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { header: '<div class="x-grid3-hd-checker">&#160;</div>', width: 20, sortable: false, menuDisabled:true, fixed:true, dataIndex: '', id: 'checker', initEvents : function(){ Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); this.grid.on('render', function(){ var view = this.grid.getView(); view.mainBody.on('mousedown', this.onMouseDown, this); Ext.fly(view.innerHd).on('mousedown', this.onHdMouseDown, this); }, this); }, onMouseDown : function(e, t){ if(e.button === 0 && t.className == 'x-grid3-row-checker'){ e.stopEvent(); var row = e.getTarget('.x-grid3-row'); if(row){ var index = row.rowIndex; if(this.isSelected(index)){ this.deselectRow(index); }else{ this.selectRow(index, true); } } } }, onHdMouseDown : function(e, t){ if(t.className == 'x-grid3-hd-checker'){ e.stopEvent(); var hd = Ext.fly(t.parentNode); var isChecked = hd.hasClass('x-grid3-hd-checker-on'); if(isChecked){ hd.removeClass('x-grid3-hd-checker-on'); this.clearSelections(); }else{ hd.addClass('x-grid3-hd-checker-on'); this.selectAll(); } } }, renderer : function(v, p, record){ return '<div class="x-grid3-row-checker">&#160;</div>'; } }); Ext.LoadMask = function(el, config){ this.el = Ext.get(el); Ext.apply(this, config); if(this.store){ this.store.on('beforeload', this.onBeforeLoad, this); this.store.on('load', this.onLoad, this); this.store.on('loadexception', this.onLoad, this); this.removeMask = Ext.value(this.removeMask, false); }else{ var um = this.el.getUpdater(); um.showLoadIndicator = false; um.on('beforeupdate', this.onBeforeLoad, this); um.on('update', this.onLoad, this); um.on('failure', this.onLoad, this); this.removeMask = Ext.value(this.removeMask, true); } }; Ext.LoadMask.prototype = { msg : 'Loading...', msgCls : 'x-mask-loading', disabled: false, disable : function(){ this.disabled = true; }, enable : function(){ this.disabled = false; }, onLoad : function(){ this.el.unmask(this.removeMask); }, onBeforeLoad : function(){ if(!this.disabled){ this.el.mask(this.msg, this.msgCls); } }, show: function(){ this.onBeforeLoad(); }, hide: function(){ this.onLoad(); }, destroy : function(){ if(this.store){ this.store.un('beforeload', this.onBeforeLoad, this); this.store.un('load', this.onLoad, this); this.store.un('loadexception', this.onLoad, this); }else{ var um = this.el.getUpdater(); um.un('beforeupdate', this.onBeforeLoad, this); um.un('update', this.onLoad, this); um.un('failure', this.onLoad, this); } } }; Ext.ProgressBar = Ext.extend(Ext.BoxComponent, { baseCls : 'x-progress', waitTimer : null, initComponent : function(){ Ext.ProgressBar.superclass.initComponent.call(this); this.addEvents( "update" ); }, onRender : function(ct, position){ Ext.ProgressBar.superclass.onRender.call(this, ct, position); var tpl = new Ext.Template( '<div class="{cls}-wrap">', '<div class="{cls}-inner">', '<div class="{cls}-bar">', '<div class="{cls}-text">', '<div>&#160;</div>', '</div>', '</div>', '<div class="{cls}-text {cls}-text-back">', '<div>&#160;</div>', '</div>', '</div>', '</div>' ); if(position){ this.el = tpl.insertBefore(position, {cls: this.baseCls}, true); }else{ this.el = tpl.append(ct, {cls: this.baseCls}, true); } if(this.id){ this.el.dom.id = this.id; } var inner = this.el.dom.firstChild; this.progressBar = Ext.get(inner.firstChild); if(this.textEl){ this.textEl = Ext.get(this.textEl); delete this.textTopEl; }else{ this.textTopEl = Ext.get(this.progressBar.dom.firstChild); var textBackEl = Ext.get(inner.childNodes[1]); this.textTopEl.setStyle("z-index", 99).addClass('x-hidden'); this.textEl = new Ext.CompositeElement([this.textTopEl.dom.firstChild, textBackEl.dom.firstChild]); this.textEl.setWidth(inner.offsetWidth); } if(this.value){ this.updateProgress(this.value, this.text); }else{ this.updateText(this.text); } this.setSize(this.width || 'auto', 'auto'); this.progressBar.setHeight(inner.offsetHeight); }, updateProgress : function(value, text){ this.value = value || 0; if(text){ this.updateText(text); } var w = Math.floor(value*this.el.dom.firstChild.offsetWidth); this.progressBar.setWidth(w); if(this.textTopEl){ this.textTopEl.removeClass('x-hidden').setWidth(w); } this.fireEvent('update', this, value, text); return this; }, wait : function(o){ if(!this.waitTimer){ var scope = this; o = o || {}; this.waitTimer = Ext.TaskMgr.start({ run: function(i){ var inc = o.increment || 10; this.updateProgress(((((i+inc)%inc)+1)*(100/inc))*.01); }, interval: o.interval || 1000, duration: o.duration, onStop: function(){ if(o.fn){ o.fn.apply(o.scope || this); } this.reset(); }, scope: scope }); } return this; }, isWaiting : function(){ return this.waitTimer != null; }, updateText : function(text){ this.text = text || '&#160;'; this.textEl.update(this.text); return this; }, setSize : function(w, h){ Ext.ProgressBar.superclass.setSize.call(this, w, h); if(this.textTopEl){ var inner = this.el.dom.firstChild; this.textEl.setSize(inner.offsetWidth, inner.offsetHeight); } return this; }, reset : function(hide){ this.updateProgress(0); if(this.textTopEl){ this.textTopEl.addClass('x-hidden'); } if(this.waitTimer){ this.waitTimer.onStop = null; Ext.TaskMgr.stop(this.waitTimer); this.waitTimer = null; } if(hide === true){ this.hide(); } return this; } }); Ext.reg('progress', Ext.ProgressBar); Ext.debug = {}; (function(){ var cp; function createConsole(){ var scriptPanel = new Ext.debug.ScriptsPanel(); var logView = new Ext.debug.LogPanel(); var tree = new Ext.debug.DomTree(); var tabs = new Ext.TabPanel({ activeTab: 0, border: false, tabPosition: 'bottom', items: [{ title: 'Debug Console', layout:'border', items: [logView, scriptPanel] },{ title: 'DOM Inspector', layout:'border', items: [tree] }] }); cp = new Ext.Panel({ id: 'x-debug-browser', title: 'Console', collapsible: true, animCollapse: false, style: 'position:absolute;left:0;bottom:0;', height:200, logView: logView, layout: 'fit', tools:[{ id: 'close', handler: function(){ cp.destroy(); cp = null; Ext.EventManager.removeResizeListener(handleResize); } }], items: tabs }); cp.render(document.body); cp.resizer = new Ext.Resizable(cp.el, { minHeight:50, handles: "n", pinned: true, transparent:true, resizeElement : function(){ var box = this.proxy.getBox(); this.proxy.hide(); cp.setHeight(box.height); return box; } }); function handleResize(){ cp.setWidth(Ext.getBody().getViewSize().width); } Ext.EventManager.onWindowResize(handleResize); handleResize(); } Ext.apply(Ext, { log : function(){ if(!cp){ createConsole(); } cp.logView.log.apply(cp.logView, arguments); }, logf : function(format, arg1, arg2, etc){ Ext.log(String.format.apply(String, arguments)); }, dump : function(o){ if(typeof o == 'string' || typeof o == 'number' || typeof o == 'undefined' || Ext.isDate(o)){ Ext.log(o); }else if(!o){ Ext.log("null"); }else if(typeof o != "object"){ Ext.log('Unknown return type'); }else if(Ext.isArray(o)){ Ext.log('['+o.join(',')+']'); }else{ var b = ["{\n"]; for(var key in o){ var to = typeof o[key]; if(to != "function" && to != "object"){ b.push(String.format(" {0}: {1},\n", key, o[key])); } } var s = b.join(""); if(s.length > 3){ s = s.substr(0, s.length-2); } Ext.log(s + "\n}"); } }, _timers : {}, time : function(name){ name = name || "def"; Ext._timers[name] = new Date().getTime(); }, timeEnd : function(name, printResults){ var t = new Date().getTime(); name = name || "def"; var v = String.format("{0} ms", t-Ext._timers[name]); Ext._timers[name] = new Date().getTime(); if(printResults !== false){ Ext.log('Timer ' + (name == "def" ? v : name + ": " + v)); } return v; } }); })(); Ext.debug.ScriptsPanel = Ext.extend(Ext.Panel, { id:'x-debug-scripts', region: 'east', minWidth: 200, split: true, width: 350, border: false, layout:'anchor', style:'border-width:0 0 0 1px;', initComponent : function(){ this.scriptField = new Ext.form.TextArea({ anchor: '100% -26', style:'border-width:0;' }); this.trapBox = new Ext.form.Checkbox({ id: 'console-trap', boxLabel: 'Trap Errors', checked: true }); this.toolbar = new Ext.Toolbar([{ text: 'Run', scope: this, handler: this.evalScript },{ text: 'Clear', scope: this, handler: this.clear }, '->', this.trapBox, ' ', ' ' ]); this.items = [this.toolbar, this.scriptField]; Ext.debug.ScriptsPanel.superclass.initComponent.call(this); }, evalScript : function(){ var s = this.scriptField.getValue(); if(this.trapBox.getValue()){ try{ var rt = eval(s); Ext.dump(rt === undefined? '(no return)' : rt); }catch(e){ Ext.log(e.message || e.descript); } }else{ var rt = eval(s); Ext.dump(rt === undefined? '(no return)' : rt); } }, clear : function(){ this.scriptField.setValue(''); this.scriptField.focus(); } }); Ext.debug.LogPanel = Ext.extend(Ext.Panel, { autoScroll: true, region: 'center', border: false, style:'border-width:0 1px 0 0', log : function(){ var markup = [ '<div style="padding:5px !important;border-bottom:1px solid #ccc;">', Ext.util.Format.htmlEncode(Array.prototype.join.call(arguments, ', ')).replace(/\n/g, '<br />').replace(/\s/g, '&#160;'), '</div>'].join(''); this.body.insertHtml('beforeend', markup); this.body.scrollTo('top', 100000); }, clear : function(){ this.body.update(''); this.body.dom.scrollTop = 0; } }); Ext.debug.DomTree = Ext.extend(Ext.tree.TreePanel, { enableDD:false , lines:false, rootVisible:false, animate:false, hlColor:'ffff9c', autoScroll: true, region:'center', border:false, initComponent : function(){ Ext.debug.DomTree.superclass.initComponent.call(this); var styles = false, hnode; var nonSpace = /^\s*$/; var html = Ext.util.Format.htmlEncode; var ellipsis = Ext.util.Format.ellipsis; var styleRe = /\s?([a-z\-]*)\:([^;]*)(?:[;\s\n\r]*)/gi; function findNode(n){ if(!n || n.nodeType != 1 || n == document.body || n == document){ return false; } var pn = [n], p = n; while((p = p.parentNode) && p.nodeType == 1 && p.tagName.toUpperCase() != 'HTML'){ pn.unshift(p); } var cn = hnode; for(var i = 0, len = pn.length; i < len; i++){ cn.expand(); cn = cn.findChild('htmlNode', pn[i]); if(!cn){ return false; } } cn.select(); var a = cn.ui.anchor; treeEl.dom.scrollTop = Math.max(0 ,a.offsetTop-10); cn.highlight(); return true; } function nodeTitle(n){ var s = n.tagName; if(n.id){ s += '#'+n.id; }else if(n.className){ s += '.'+n.className; } return s; } function onNodeSelect(t, n, last){ return; if(last && last.unframe){ last.unframe(); } var props = {}; if(n && n.htmlNode){ if(frameEl.pressed){ n.frame(); } if(inspecting){ return; } addStyle.enable(); reload.setDisabled(n.leaf); var dom = n.htmlNode; stylePanel.setTitle(nodeTitle(dom)); if(styles && !showAll.pressed){ var s = dom.style ? dom.style.cssText : ''; if(s){ var m; while ((m = styleRe.exec(s)) != null){ props[m[1].toLowerCase()] = m[2]; } } }else if(styles){ var cl = Ext.debug.cssList; var s = dom.style, fly = Ext.fly(dom); if(s){ for(var i = 0, len = cl.length; i<len; i++){ var st = cl[i]; var v = s[st] || fly.getStyle(st); if(v != undefined && v !== null && v !== ''){ props[st] = v; } } } }else{ for(var a in dom){ var v = dom[a]; if((isNaN(a+10)) && v != undefined && v !== null && v !== '' && !(Ext.isGecko && a[0] == a[0].toUpperCase())){ props[a] = v; } } } }else{ if(inspecting){ return; } addStyle.disable(); reload.disabled(); } stylesGrid.setSource(props); stylesGrid.treeNode = n; stylesGrid.view.fitColumns(); } this.loader = new Ext.tree.TreeLoader(); this.loader.load = function(n, cb){ var isBody = n.htmlNode == document.body; var cn = n.htmlNode.childNodes; for(var i = 0, c; c = cn[i]; i++){ if(isBody && c.id == 'x-debug-browser'){ continue; } if(c.nodeType == 1){ n.appendChild(new Ext.debug.HtmlNode(c)); }else if(c.nodeType == 3 && !nonSpace.test(c.nodeValue)){ n.appendChild(new Ext.tree.TreeNode({ text:'<em>' + ellipsis(html(String(c.nodeValue)), 35) + '</em>', cls: 'x-tree-noicon' })); } } cb(); }; this.root = this.setRootNode(new Ext.tree.TreeNode('Ext')); hnode = this.root.appendChild(new Ext.debug.HtmlNode( document.getElementsByTagName('html')[0] )); } }); Ext.debug.HtmlNode = function(){ var html = Ext.util.Format.htmlEncode; var ellipsis = Ext.util.Format.ellipsis; var nonSpace = /^\s*$/; var attrs = [ {n: 'id', v: 'id'}, {n: 'className', v: 'class'}, {n: 'name', v: 'name'}, {n: 'type', v: 'type'}, {n: 'src', v: 'src'}, {n: 'href', v: 'href'} ]; function hasChild(n){ for(var i = 0, c; c = n.childNodes[i]; i++){ if(c.nodeType == 1){ return true; } } return false; } function renderNode(n, leaf){ var tag = n.tagName.toLowerCase(); var s = '&lt;' + tag; for(var i = 0, len = attrs.length; i < len; i++){ var a = attrs[i]; var v = n[a.n]; if(v && !nonSpace.test(v)){ s += ' ' + a.v + '=&quot;<i>' + html(v) +'</i>&quot;'; } } var style = n.style ? n.style.cssText : ''; if(style){ s += ' style=&quot;<i>' + html(style.toLowerCase()) +'</i>&quot;'; } if(leaf && n.childNodes.length > 0){ s+='&gt;<em>' + ellipsis(html(String(n.innerHTML)), 35) + '</em>&lt;/'+tag+'&gt;'; }else if(leaf){ s += ' /&gt;'; }else{ s += '&gt;'; } return s; } var HtmlNode = function(n){ var leaf = !hasChild(n); this.htmlNode = n; this.tagName = n.tagName.toLowerCase(); var attr = { text : renderNode(n, leaf), leaf : leaf, cls: 'x-tree-noicon' }; HtmlNode.superclass.constructor.call(this, attr); this.attributes.htmlNode = n; if(!leaf){ this.on('expand', this.onExpand, this); this.on('collapse', this.onCollapse, this); } }; Ext.extend(HtmlNode, Ext.tree.AsyncTreeNode, { cls: 'x-tree-noicon', preventHScroll: true, refresh : function(highlight){ var leaf = !hasChild(this.htmlNode); this.setText(renderNode(this.htmlNode, leaf)); if(highlight){ Ext.fly(this.ui.textNode).highlight(); } }, onExpand : function(){ if(!this.closeNode && this.parentNode){ this.closeNode = this.parentNode.insertBefore(new Ext.tree.TreeNode({ text:'&lt;/' + this.tagName + '&gt;', cls: 'x-tree-noicon' }), this.nextSibling); }else if(this.closeNode){ this.closeNode.ui.show(); } }, onCollapse : function(){ if(this.closeNode){ this.closeNode.ui.hide(); } }, render : function(bulkRender){ HtmlNode.superclass.render.call(this, bulkRender); }, highlightNode : function(){ }, highlight : function(){ }, frame : function(){ this.htmlNode.style.border = '1px solid #0000ff'; }, unframe : function(){ this.htmlNode.style.border = ''; } }); return HtmlNode; }();
js/Header.js
CdrXander/FEM-React-Learning
import React from 'react' import { Link } from 'react-router' class Header extends React.Component { render () { let utilSpace if (this.props.showSearch) { utilSpace = <input onChange={this.props.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' /> } else { utilSpace = ( <h2> <Link to='/search'> Back </Link> </h2> ) } return ( <header> <h1> <Link to='/'> svideo </Link> </h1> {utilSpace} </header> ) } } const {func, bool, string } = React.PropTypes Header.propTypes = { handleSearchTermChange:func, showSearch: bool, searchTerm: string } export default Header
15-react-router-v4/src/components/repo.js
iproduct/course-node-express-react
import React from 'react'; import { PropTypes } from 'prop-types'; const Repo = ({ match }) => { return ( <div> <h3>User: {match.params.userName}</h3> <h3>Repo: {match.params.repoName}</h3> </div> ); } Repo.propTypes = { params: PropTypes.object } export default Repo;
app/javascript/mastodon/features/hashtag_timeline/index.js
d6rkaiz/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import ColumnSettingsContainer from './containers/column_settings_container'; import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage } from 'react-intl'; import { connectHashtagStream } from '../../actions/streaming'; import { isEqual } from 'lodash'; const mapStateToProps = (state, props) => ({ hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}`, 'unread']) > 0, }); export default @connect(mapStateToProps) class HashtagTimeline extends React.PureComponent { disconnects = []; static propTypes = { params: PropTypes.object.isRequired, columnId: PropTypes.string, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HASHTAG', { id: this.props.params.id })); } } title = () => { let title = [this.props.params.id]; if (this.additionalFor('any')) { title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />); } if (this.additionalFor('all')) { title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />); } if (this.additionalFor('none')) { title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />); } return title; } additionalFor = (mode) => { const { tags } = this.props.params; if (tags && (tags[mode] || []).length > 0) { return tags[mode].map(tag => tag.value).join('/'); } else { return ''; } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } _subscribe (dispatch, id, tags = {}) { let any = (tags.any || []).map(tag => tag.value); let all = (tags.all || []).map(tag => tag.value); let none = (tags.none || []).map(tag => tag.value); [id, ...any].map(tag => { this.disconnects.push(dispatch(connectHashtagStream(id, tag, status => { let tags = status.tags.map(tag => tag.name); return all.filter(tag => tags.includes(tag)).length === all.length && none.filter(tag => tags.includes(tag)).length === 0; }))); }); } _unsubscribe () { this.disconnects.map(disconnect => disconnect()); this.disconnects = []; } componentDidMount () { const { dispatch } = this.props; const { id, tags } = this.props.params; this._subscribe(dispatch, id, tags); dispatch(expandHashtagTimeline(id, { tags })); } componentWillReceiveProps (nextProps) { const { dispatch, params } = this.props; const { id, tags } = nextProps.params; if (id !== params.id || !isEqual(tags, params.tags)) { this._unsubscribe(); this._subscribe(dispatch, id, tags); this.props.dispatch(clearTimeline(`hashtag:${id}`)); this.props.dispatch(expandHashtagTimeline(id, { tags })); } } componentWillUnmount () { this._unsubscribe(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { id, tags } = this.props.params; this.props.dispatch(expandHashtagTimeline(id, { maxId, tags })); } render () { const { shouldUpdateScroll, hasUnread, columnId, multiColumn } = this.props; const { id } = this.props.params; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={`#${id}`}> <ColumnHeader icon='hashtag' active={hasUnread} title={this.title()} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton > {columnId && <ColumnSettingsContainer columnId={columnId} />} </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`hashtag_timeline-${columnId}`} timelineId={`hashtag:${id}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
ajax/libs/forerunnerdb/1.3.608/fdb-core.min.js
BenjaminVanRyseghem/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Shim.IE8":29}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":25,"./Shared":28}],3:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),l=a("./Crc"),e=d.modules.Db,m=a("./Overload"),n=a("./ReactorIO"),o=new h,p.prototype.crc=l,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b);var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.emit("immediateChange",{type:"update",data:e}),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L=this._metrics.create("find"),M=this.primaryKey(),N=this,O=!0,P={},Q=[],R=[],S=[],T={},U={};if(b instanceof Array||(b=this.options(b)),K=function(c){return N._match(c,a,b,"and",T)},L.start(),a){if(a instanceof Array){for(J=this,A=0;A<a.length;A++)J=J.subset(a[A],b&&b[A]?b[A]:{});return J.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(L.time("analyseQuery"),c=this._analyseQuery(N.decouple(a),b,L),L.time("analyseQuery"),L.data("analysis",c),c.hasJoin&&c.queriesJoin){for(L.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],P[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];L.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(L.data("index.potential",c.indexMatch),L.data("index.used",c.indexMatch[0].index),L.time("indexLookup"),e=c.indexMatch[0].lookup||[],L.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(O=!1)):L.flag("usedIndex",!1),O&&(e&&e.length?(d=e.length,L.time("tableScan: "+d),e=e.filter(K)):(d=this._data.length,L.time("tableScan: "+d),e=this._data.filter(K)),L.time("tableScan: "+d)),b.$orderBy&&(L.time("sort"),e=this.sort(b.$orderBy,e),L.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(U.page=b.$page,U.pages=Math.ceil(e.length/b.$limit),U.records=e.length,b.$page&&b.$limit>0&&(L.data("cursor",U),e.splice(0,b.$page*b.$limit))),b.$skip&&(U.skip=b.$skip,e.splice(0,b.$skip),L.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(U.limit=b.$limit,e.length=b.$limit,L.data("limit",b.$limit)),b.$decouple&&(L.time("decouple"),e=this.decouple(e),L.time("decouple"),L.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(x=k,l=P[k]?P[k]:this._db.collection(k),m=b.$join[f][k],y=0;y<e.length;y++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if(w=m[n],"$"===n.substr(0,1))switch(n){case"$where":if(!w.$query&&!w.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';w.$query&&(o=N._resolveDynamicQuery(w.$query,e[y])),w.$options&&(p=w.$options);break;case"$as":x=w;break;case"$multi":q=w;break;case"$require":r=w;break;case"$prefix":v=w}else o[n]=N._resolveDynamicQuery(w,e[y]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===x){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[y];for(D in t)t.hasOwnProperty(D)&&void 0===u[v+D]&&(u[v+D]=t[D])}else e[y][x]=q===!1?s[0]:s;else Q.push(e[y])}L.data("flag.join",!0)}if(Q.length){for(L.time("removalQueue"),A=0;A<Q.length;A++)z=e.indexOf(Q[A]),z>-1&&e.splice(z,1);L.time("removalQueue")}if(b.$transform){for(L.time("transform"),A=0;A<e.length;A++)e.splice(A,1,b.$transform(e[A]));L.time("transform"),L.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(L.time("transformOut"),e=this.transformOut(e),L.time("transformOut")),L.data("results",e.length)}else e=[];if(!b.$aggregate){L.time("scanFields");for(A in b)b.hasOwnProperty(A)&&0!==A.indexOf("$")&&(1===b[A]?R.push(A):0===b[A]&&S.push(A));if(L.time("scanFields"),R.length||S.length){for(L.data("flag.limitFields",!0),L.data("limitFields.on",R),L.data("limitFields.off",S),L.time("limitFields"),A=0;A<e.length;A++){H=e[A];for(B in H)H.hasOwnProperty(B)&&(R.length&&B!==M&&-1===R.indexOf(B)&&delete H[B],S.length&&S.indexOf(B)>-1&&delete H[B])}L.time("limitFields")}if(b.$elemMatch){L.data("flag.elemMatch",!0),L.time("projection-elemMatch");for(A in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(A))for(E=new h(A),B=0;B<e.length;B++)if(F=E.value(e[B])[0],F&&F.length)for(C=0;C<F.length;C++)if(N._match(F[C],b.$elemMatch[A],b,"",{})){E.set(e[B],A,[F[C]]);break}L.time("projection-elemMatch")}if(b.$elemsMatch){L.data("flag.elemsMatch",!0),L.time("projection-elemsMatch");for(A in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(A))for(E=new h(A),B=0;B<e.length;B++)if(F=E.value(e[B])[0],F&&F.length){for(G=[],C=0;C<F.length;C++)N._match(F[C],b.$elemsMatch[A],b,"",{})&&G.push(F[C]);E.set(e[B],A,G)}L.time("projection-elemsMatch")}}return b.$aggregate&&(L.data("flag.aggregate",!0),L.time("aggregate"),I=new h(b.$aggregate),e=I.value(e),L.time("aggregate")),L.stop(),e.__fdbOp=L,e.$cursor=U,e},p.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f); }}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},s=[],t=[];if(c.time("checkIndexes"),m=new h,n=m.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(o=typeof a[this._primaryKey],("string"===o||"number"===o||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),p=this._primaryIndex.lookup(a,b),r.indexMatch.push({lookup:p,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(q in this._indexById)if(this._indexById.hasOwnProperty(q)&&(j=this._indexById[q],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),r.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),r.indexMatch.length>1&&(c.time("findOptimalIndex"),r.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(r.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(s.push(e),"$as"in b.$join[d][e]?t.push(b.$join[d][e].$as):t.push(e));for(g=0;g<t.length;g++)f=this._queryReferencesCollection(a,t[g],""),f&&(r.joinQueries[s[g]]=f,r.queriesJoin=!0);r.joinsOn=s,r.queriesOn=r.queriesOn.concat(s)}return r},p.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":5,"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],4:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],5:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":28}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":28}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":23,"./Shared":28}],13:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],14:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g; d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":24,"./Serialiser":27}],16:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],17:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":24}],18:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":24}],22:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":25,"./Shared":28}],24:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature "'+d+'" for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":28}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":28}],27:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){var b=typeof a;return"object"===b?new RegExp(a.source,a.params):"string"===b?new RegExp(a):void 0})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.608",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]);
src/components/Header/Header.js
mikemunsie/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header extends Component { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Your Company</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">React</h1> <p className="Header-bannerDesc">Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
src/demos/building-a-geospatial-app/starting-code/src/app.js
uber-common/vis-academy
import React, { Component } from 'react'; const MAPBOX_STYLE = 'mapbox://styles/mapbox/light-v9'; const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line function SetToken() { return ( <div style={{fontSize: '20px'}}> <div>You don't have a Mapbox token set in your environemnt.</div> <ul> <li> Go to <a href="http://mapbox.com">Mapbox</a> and log in or sign up to get a token. </li> <li>Copy the token to your clipboard.</li> <li>Stop this app in the terminal (ctrl+c)</li> <li> <p>type: </p> <p> <code>export MapboxAccessToken="</code>, then paste your token, then type a closing ". </p>{' '} ie <code>export MapboxAcessToken="pk.123456"</code> </li> <li> Restart the app from the terminal (<code>yarn start</code>) </li> </ul> </div> ); } export default class App extends Component { constructor(props) { super(props); } render() { return ( <div> <div className="intro"> {MAPBOX_TOKEN ? ( `You mapbox token is set. You're good to go!` ) : ( <SetToken /> )} </div> </div> ); } }
src/svg-icons/content/mail.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentMail = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/> </SvgIcon> ); ContentMail = pure(ContentMail); ContentMail.displayName = 'ContentMail'; ContentMail.muiName = 'SvgIcon'; export default ContentMail;
ajax/libs/jquery/1.11.0/jquery.min.js
ankitjamuar/cdnjs
/*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},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(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n});
app/components/Footer/index.js
matusmarcin/special-disco
/** * * Footer * */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; import styles from './styles.css'; function Footer() { const year = new Date().getFullYear(); return ( <footer> <h2><FormattedMessage {...messages.topText} values={{ year }} /></h2> <a href="http://twitter.com" className={`${styles.iconButton} ${styles.twitter}`}><i className="fa fa-twitter"></i><span></span></a> <a href="http://facebook.com" className={`${styles.iconButton} ${styles.facebook}`}><i className="fa fa-facebook"></i><span></span></a> <a href="http://plus.google.com" className={`${styles.iconButton} ${styles.googlePlus}`}><i className="fa fa-google-plus"></i><span></span></a> <br /> <span className="licence-text"> <FormattedMessage {...messages.licenseMessage} values={{ year }} /> </span> </footer> ); } export default Footer;
src/svg-icons/av/volume-off.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVolumeOff = (props) => ( <SvgIcon {...props}> <path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/> </SvgIcon> ); AvVolumeOff = pure(AvVolumeOff); AvVolumeOff.displayName = 'AvVolumeOff'; AvVolumeOff.muiName = 'SvgIcon'; export default AvVolumeOff;
ajax/libs/yui/3.4.1/yui/yui.js
Kaakati/cdnjs
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. If YUI is already defined, the existing YUI object will not be overwritten so that defined namespaces are preserved. It is the constructor for the object the end user interacts with. As indicated below, each instance has full custom event support, but only if the event system is available. This is a self-instantiable factory function. You can invoke it directly like this: YUI().use('*', function(Y) { // ready }); But it also works like this: var Y = YUI(); @class YUI @constructor @global @uses EventTarget @param o* {Object} 0..n optional configuration objects. these values are store in Y.config. See <a href="config.html">Config</a> for the list of supported properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** YUI.GlobalConfig is a master configuration that might span multiple contexts in a non-browser environment. It is applied first to all instances in all contexts. @property GlobalConfig @type {Object} @global @static @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** YUI_config is a page-level config. It is applied to all instances created on the page. This is applied after YUI.GlobalConfig, and before the instance level configuration objects. @global @property YUI_config @type {Object} @example //Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, [ 'loader-base', 'loader-rollup', 'loader-yui3' ])); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {Object} o the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, rls = config.rls, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (rls && name == 'rls') { clobber(rls, attr); } else if (name == 'win') { config[name] = attr.contentWindow || attr; config.doc = config[name].document; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { win: win, doc: doc, debug: true, useBrowserConsole: true, throwFail: true, bootstrap: true, cacheUse: true, fetchCSS: true, use_rls: false, rls_timeout: 2000 }; if (YUI.Env.rls_disabled) { Y.config.use_rls = false; } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, //extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3']; extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m.apply(instance, args); } return null; }, /** Registers a module with the YUI global. The easiest way to create a first-class YUI module is to use the YUI component build tool. http://yuilibrary.com/projects/builder The build system will produce the `YUI.add` wrapper for you module, along with any configuration info required for the module. @method add @param name {String} module name. @param fn {Function} entry point into the module that is used to bind module to the YUI instance. @param {YUI} fn.Y The YUI instance this module is executed in. @param {String} fn.name The name of the module @param version {String} version string. @param details {Object} optional config data: @param details.requires {Array} features that must be present before this module can be attached. @param details.optional {Array} optional features that should be present if loadOptional is defined. Note: modules are not often loaded this way in YUI 3, but this field is still useful to inform the user that certain features in the component will require additional dependencies. @param details.use {Array} features that are included within this module which need to be attached automatically when this module is attached. This supports the YUI 3 rollup system -- a module with submodules defined will need to have the submodules listed in the 'use' config. The YUI component build tool does this for you. @return {YUI} the YUI instance. @example YUI.add('davglass', function(Y, name) { Y.davglass = function() { alert('Dav was here!'); }; }, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] }); */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name]) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @param {Array} r The array of modules to attach * @param {Boolean} [moot=false] Don't throw a warning if the module is not attached * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { Y.Object.each(loader.conditions[name], function(def) { var go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } }); } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { if (!names.length) { return; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = false; Y._use(args, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); // loader.partial(missing, (fetchCSS) ? null : 'js'); } else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) { G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue(); // server side loader service handleRLS = function(instance, argz) { var rls_end = function(o) { handleLoader(o); instance.rls_advance(); }, rls_url = instance._rls(argz); if (rls_url) { instance.rls_oncomplete(function(o) { rls_end(o); }); instance.Get.script(rls_url, { data: argz, timeout: instance.config.rls_timeout, onFailure: instance.rls_handleFailure, onTimeout: instance.rls_handleTimeout }); } else { rls_end({ success: true, data: argz }); } }; G_ENV._rls_queue.add(function() { G_ENV._rls_in_progress = true; Y.rls_callback = callback; Y.rls_locals(Y, args, handleRLS); }); if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) { G_ENV._rls_queue.next()(); } } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Adds a namespace object onto the YUI global if called statically. // creates YUI.your.namespace.here as nested objects YUI.namespace("your.namespace.here"); If called as a method on a YUI <em>instance</em>, it creates the namespace on the instance. // creates Y.property.package Y.namespace("property.package"); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", the token is discarded. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace("really.long.nested.namespace"); @method namespace @param {String} namespace* namespaces to create. @return {Object} A reference to the last namespace object created. **/ namespace: function() { var a = arguments, o = this, i = 0, j, d, arg; for (; i < a.length; i++) { // d = ('' + a[i]).split('.'); arg = a[i]; if (arg.indexOf(PERIOD)) { d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param data Optional additional info * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, data) { var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error'); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default). * * @property core * @type string[] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js' * } * } * * @property modules * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.8.1 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 1 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * The parameter defaults for the remote loader service. **Requires the rls seed file.** The properties that are supported: * * * `m`: comma separated list of module requirements. This * must be the param name even for custom implemetations. * * `v`: the version of YUI to load. Defaults to the version * of YUI that is being used. * * `gv`: the version of the gallery to load (see the gallery config) * * `env`: comma separated list of modules already on the page. * this must be the param name even for custom implemetations. * * `lang`: the languages supported on the page (see the lang config) * * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config). * * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers * * `filt`: a filter def to apply to the urls (see the filter config). * * `filts`: a list of custom filters to apply per module * * `tests`: this is a map of conditional module test function id keys * with the values of 1 if the test passes, 0 if not. This must be * the name of the querystring param in custom templates. * * @since 3.2.0 * @property rls * @type {Object} */ /** * The base path to the remote loader service. **Requires the rls seed file.** * * @since 3.2.0 * @property rls_base * @type {String} */ /** * The template to use for building the querystring portion * of the remote loader service url. The default is determined * by the rls config -- each property that has a value will be * represented. **Requires the rls seed file.** * * @since 3.2.0 * @property rls_tmpl * @type {String} * @example * m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests} * */ /** * Configure the instance to use a remote loader service instead of * the client loader. **Requires the rls seed file.** * * @since 3.2.0 * @property use_rls * @type {Boolean} */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementation. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype); /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = (!unsafeNatives && Array.isArray) || function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * <p> * Returns a string representing the type of the item passed in. * </p> * * <p> * Known issues: * </p> * * <ul> * <li> * <code>typeof HTMLElementCollection</code> returns function in Safari, but * <code>Y.type()</code> reports object, which could be a good thing -- * but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. * </li> * </ul> * * @method type * @param o the item to test. * @return {string} the detected type. * @static */ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Native.indexOf ? function (array, value) { // TODO: support fromIndex return Native.indexOf.call(array, value); } : function (array, value) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && array[i] === value) { return i; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Native.some ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var hasOwn = Object.prototype.hasOwnProperty, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementations. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype), UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = (!unsafeNatives && Object.keys) || function (obj) { if (!Y.Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Y.Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(obj).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @returns {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome o.safari = 0; //Reset safari back to 0 } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //It was a parsed UA, do not assign the global value. if (!subUA) { YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["controller","model","model-list","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"] }; }, '@VERSION@' ); YUI.add('get', function(Y) { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ var ua = Y.UA, L = Y.Lang, TYPE_JS = 'text/javascript', TYPE_CSS = 'text/css', STYLESHEET = 'stylesheet', SCRIPT = 'script', AUTOPURGE = 'autopurge', UTF8 = 'utf-8', LINK = 'link', ASYNC = 'async', ALL = true, // FireFox does not support the onload event for link nodes, so // there is no way to make the css requests synchronous. This means // that the css rules in multiple files could be applied out of order // in this browser if a later request returns before an earlier one. // Safari too. ONLOAD_SUPPORTED = { script: ALL, css: !(ua.webkit || ua.gecko) }, /** * hash of queues to manage multiple requests * @property queues * @private */ queues = {}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx = 0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging, /** * Clear timeout state * * @method _clearTimeout * @param {Object} q Queue data * @private */ _clearTimeout = function(q) { var timer = q.timer; if (timer) { clearTimeout(timer); q.timer = null; } }, /** * Generates an HTML element, this is not appended to a document * @method _node * @param {string} type the type of element. * @param {Object} attr the fixed set of attribute for the type. * @param {Object} custAttrs optional Any custom attributes provided by the user. * @param {Window} win optional window to create the element in. * @return {HTMLElement} the generated node. * @private */ _node = function(type, attr, custAttrs, win) { var w = win || Y.config.win, d = w.document, n = d.createElement(type), i; if (custAttrs) { Y.mix(attr, custAttrs); } for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param {string} url the url for the css file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _linkNode = function(url, win, attributes) { return _node(LINK, { id: Y.guid(), type: TYPE_CSS, rel: STYLESHEET, href: url }, attributes, win); }, /** * Generates a script node * @method _scriptNode * @param {string} url the url for the script file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _scriptNode = function(url, win, attributes) { return _node(SCRIPT, { id: Y.guid(), type: TYPE_JS, src: url }, attributes, win); }, /** * Returns the data payload for callback functions. * @method _returnData * @param {object} q the queue. * @param {string} msg the result message. * @param {string} result the status message from the request. * @return {object} the state data from the request. * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param {string} id the id of the request. * @param {string} msg the result message. * @param {string} result the status message from the request. * @private */ _end = function(id, msg, result) { var q = queues[id], onEnd = q && q.onEnd; q.finished = true; if (onEnd) { onEnd.call(q.context, _returnData(q, msg, result)); } }, /** * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param {string} id the id of the request * @private */ _fail = function(id, msg) { var q = queues[id], onFailure = q.onFailure; _clearTimeout(q); if (onFailure) { onFailure.call(q.context, _returnData(q, msg)); } _end(id, msg, 'failure'); }, /** * Abort the transaction * * @method _abort * @param {Object} id * @private */ _abort = function(id) { _fail(id, 'transaction ' + id + ' was aborted'); }, /** * The request is complete, so executing the requester's callback * @method _complete * @param {string} id the id of the request. * @private */ _complete = function(id) { var q = queues[id], onSuccess = q.onSuccess; _clearTimeout(q); if (q.aborted) { _abort(id); } else { if (onSuccess) { onSuccess.call(q.context, _returnData(q)); } // 3.3.0 had undefined msg for this path. _end(id, undefined, 'OK'); } }, /** * Get node reference, from string * * @method _getNodeRef * @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned. * @param {String} tId Queue id, used to determine document for queue * @private */ _getNodeRef = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, 'target node not found: ' + nId); } return n; }, /** * Removes the nodes for the specified queue * @method _purge * @param {string} tId the transaction id. * @private */ _purge = function(tId) { var nodes, doc, parent, sibling, node, attr, insertBefore, i, l, q = queues[tId]; if (q) { nodes = q.nodes; l = nodes.length; // TODO: Why is node.parentNode undefined? Which forces us to do this... /* doc = q.win.document; parent = doc.getElementsByTagName('head')[0]; insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0]; if (insertBefore) { sibling = _getNodeRef(insertBefore, tId); if (sibling) { parent = sibling.parentNode; } } */ for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parentNode; if (node.clearAttributes) { node.clearAttributes(); } else { // This destroys parentNode ref, so we hold onto it above first. for (attr in node) { if (node.hasOwnProperty(attr)) { delete node[attr]; } } } parent.removeChild(node); } } q.nodes = []; }, /** * Progress callback * * @method _progress * @param {string} id The id of the request. * @param {string} The url which just completed. * @private */ _progress = function(id, url) { var q = queues[id], onProgress = q.onProgress, o; if (onProgress) { o = _returnData(q); o.url = url; onProgress.call(q.context, o); } }, /** * Timeout detected * @method _timeout * @param {string} id the id of the request. * @private */ _timeout = function(id) { var q = queues[id], onTimeout = q.onTimeout; if (onTimeout) { onTimeout.call(q.context, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * onload callback * @method _loaded * @param {string} id the id of the request. * @return {string} the result. * @private */ _loaded = function(id, url) { var q = queues[id], sync = (q && !q.async); if (!q) { return; } if (sync) { _clearTimeout(q); } _progress(id, url); // TODO: Cleaning up flow to have a consistent end point // !q.finished check is for the async case, // where scripts may still be loading when we've // already aborted. Ideally there should be a single path // for this. if (!q.finished) { if (q.aborted) { _abort(id); } else { if ((--q.remaining) === 0) { _complete(id); } else if (sync) { _next(id); } } } }, /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _trackLoad * @param {string} type the type of node to track. * @param {HTMLElement} n the node to track. * @param {string} id the id of the request. * @param {string} url the url that is being loaded. * @private */ _trackLoad = function(type, n, id, url) { // TODO: Can we massage this to use ONLOAD_SUPPORTED[type]? // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ('loaded' === rs || 'complete' === rs) { n.onreadystatechange = null; _loaded(id, url); } }; } else if (ua.webkit) { // webkit prior to 3.x is no longer supported if (type === SCRIPT) { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener('load', function() { _loaded(id, url); }, false); } } else { // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link nodes. n.onload = function() { _loaded(id, url); }; n.onerror = function(e) { _fail(id, e + ': ' + url); }; } }, _insertInDoc = function(node, id, win) { // Add it to the head or insert it before 'insertBefore'. // Work around IE bug if there is a base tag. var q = queues[id], doc = win.document, insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0], sibling; if (insertBefore) { sibling = _getNodeRef(insertBefore, id); if (sibling) { sibling.parentNode.insertBefore(node, sibling); } } else { // 3.3.0 assumed head is always around. doc.getElementsByTagName('head')[0].appendChild(node); } }, /** * Loads the next item for a given request * @method _next * @param {string} id the id of the request. * @return {string} the result. * @private */ _next = function(id) { // Assigning out here for readability var q = queues[id], type = q.type, attrs = q.attributes, win = q.win, timeout = q.timeout, node, url; if (q.url.length > 0) { url = q.url.shift(); // !q.timer ensures that this only happens once for async if (timeout && !q.timer) { q.timer = setTimeout(function() { _timeout(id); }, timeout); } if (type === SCRIPT) { node = _scriptNode(url, win, attrs); } else { node = _linkNode(url, win, attrs); } // add the node to the queue so we can return it in the callback q.nodes.push(node); _trackLoad(type, node, id, url); _insertInDoc(node, id, win); if (!ONLOAD_SUPPORTED[type]) { _loaded(id, url); } if (q.async) { // For sync, the _next call is chained in _loaded _next(id); } } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param {string} type the type of node to insert. * @param {string} url the url to load. * @param {object} opts the hash of options for this request. * @return {object} transaction object. * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = 'q' + (qidx++), thresh = opts.purgethreshold || Y.Get.PURGE_THRESH, q; if (qidx % thresh === 0) { _autoPurge(); } // Merge to protect opts (grandfathered in). q = queues[id] = Y.merge(opts); // Avoid mix, merge overhead. Known set of props. q.tId = id; q.type = type; q.url = url; q.finished = false; q.nodes = []; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || UTF8; if (ASYNC in q && type === SCRIPT) { q.attributes.async = q.async; } q.url = (L.isString(q.url)) ? [q.url] : q.url; // TODO: Do we really need to account for this developer error? // If the url is undefined, this is probably a trailing comma problem in IE. if (!q.url[0]) { q.url.shift(); } q.remaining = q.url.length; _next(id); return { tId: id }; }; Y.Get = { /** * The number of request required before an automatic purge. * Can be configured via the 'purgethreshold' config * @property PURGE_THRESH * @static * @type int * @default 20 * @private */ PURGE_THRESH: 20, /** * Abort a transaction * @method abort * @static * @param {string|object} o Either the tId or the object returned from * script() or css(). */ abort : function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param {string|string[]} url the url or urls to the script(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, * regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading * (useful when passing in an array of js files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> * property, which identifies the file which was loaded.</dd> * <dt>async</dt> * <dd> * <p>When passing in an array of JS files, setting this flag to true * will insert them into the document in parallel, as opposed to the * default behavior, which is to chain load them serially. It will also * set the async attribute on the script node to true.</p> * <p>Setting async:true * will lead to optimal file download performance allowing the browser to * download multiple scripts in parallel, and execute them as soon as they * are available.</p> * <p>Note that async:true does not guarantee execution order of the * scripts being downloaded. They are executed in whichever order they * are received.</p> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling. * If this is not specified, nodes will be inserted before a base * tag should it exist. Otherwise, the nodes will be appended to the * end of the document head.</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing * the timeout event</dd> * <pre> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ script: function(url, opts) { return _queue(SCRIPT, url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param {string} url the url or urls to the css file(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers, * where onload for css is detected accurately.</dd> * <dt>async</dt> * <dd>When passing in an array of css files, setting this flag to true will insert them * into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible). * This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * </dl> * <pre> * Y.Get.css("http://localhost/css/menu.css"); * </pre> * <pre> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ css: function(url, opts) { return _queue('css', url, opts); } }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // graphics-canvas-default add('load', '0', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-svg add('load', '2', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // history-hash-ie add('load', '3', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // graphics-vml-default add('load', '4', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-svg-default add('load', '5', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // widget-base-ie add('load', '6', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // transition-timer add('load', '7', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // dom-style-ie add('load', '8', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // selector-css2 add('load', '9', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // event-base-ie add('load', '10', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // dd-gestures add('load', '11', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // scrollview-base-ie add('load', '12', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // graphics-canvas add('load', '13', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml add('load', '14', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('loader-base', function(Y) { /** * The YUI loader core * @module loader * @submodule loader-base */ if (!YUI.Env[Y.version]) { (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + BUILD, CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2011.09.14-20-40', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.9.0', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: ['cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context']}, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD; groups.yui2.base = CDN_BASE + root; groups.yui2.root = root; }, galleryUpdate = function(tag) { var root = (tag || GALLERY_VERSION) + BUILD; groups.gallery.base = CDN_BASE + root; groups.gallery.root = root; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': { }, 'lang/gallery-': {}, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); YUI.Env[VERSION] = META; }()); } /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @main loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = 2048, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, YArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, cache, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; if (YUI.Env.aliases) { YUI.Env.aliases = {}; //Don't need aliases if Loader is present } /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * While the loader can be instantiated by the end user, it normally is not. * @see YUI.use for the normal use case. The use function automatically will * pull in missing dependencies. * * @constructor * @class Loader * @param {object} o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>comboBase: * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: * The root path to prepend to module names for the combo service. * Ex: 2.5.2/build/</li> * <li>filter:. * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified * for a given component, this overrides the filter config. _Note:_ This does not work on combo urls, use the filter property instead.</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections * required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if * already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for * new nodes</li> * <li>charset: * charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes) * </li> * <li>jsAttributes: object literal containing attributes to add to script * nodes</li> * <li>cssAttributes: object literal containing attributes to add to link * nodes</li> * <li>timeout: * The number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI * components with CSS the CSS is loaded first, then the script. This * provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported * module metadata</li> * <li>groups: * A list of group definitions. Each group can contain specific definitions * for base, comboBase, combine, and accepts a list of modules. See above * for the description of these properties.</li> * <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic * support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 * components inside YUI 3 module wrappers. These wrappers * change over time to accomodate the issues that arise from running YUI 2 * in a YUI 3 sandbox.</li> * <li>yui2: when using the 2in3 project, you can select the version of * YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0, * 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2 * going forward.</li> * </ul> */ Y.Loader = function(o) { var defaults = META.modules, self = this; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components * with CSS the CSS is loaded first, then the script. This provides * a moment you can tie into to improve the presentation of the page * while the script is loading. * @method onCSS * @type function */ // self.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base + Y.Env.meta.root; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * The default seperator to use between files in a combo URL * @property comboSep * @type {String} * @default Ampersand */ self.comboSep = '&'; /** * Max url length for combo urls. The default is 2048. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ // self.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default false */ self.allowRollup = false; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * The library metadata * @property moduleInfo */ // self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * <code> * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * </code> * @property skin */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; cache = GLOBAL_ENV._renderedMods; if (cache) { oeach(cache, function modCache(v, k) { //self.moduleInfo[k] = Y.merge(v); self.moduleInfo[k] = v; }); cache = GLOBAL_ENV._conditions; oeach(cache, function condCache(v, k) { //self.conditions[k] = Y.merge(v); self.conditions[k] = v; }); } else { oeach(defaults, self.addModule, self); } if (!GLOBAL_ENV._renderedMods) { //GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo); //GLOBAL_ENV._conditions = Y.merge(self.conditions); GLOBAL_ENV._renderedMods = self.moduleInfo; GLOBAL_ENV._conditions = self.conditions; } self._inspectPage(); self._internal = false; self._config(o); self.testresults = null; if (Y.config.tests) { self.testresults = Y.config.tests; } /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; }; Y.Loader.prototype = { FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' } }, /* * Check the pages meta-data and cache the result. * @method _inspectPage * @private */ _inspectPage: function() { oeach(ON_PAGE, function(v, k) { if (v.details) { var m = this.moduleInfo[k], req = v.details.requires, mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length != req.length) { // console.log('deleting ' + m.name); // m.requres = YObject.keys(Y.merge(YArray.hash(req), YArray.hash(mr))); delete m.expanded; // delete m.expanded_map; } } else { m = this.addModule(v.details, k); } m._inspected = true; } }, this); }, /* * returns true if b is not loaded, and is required directly or by means of modules it supersedes. * @private * @method _requires * @param {String} mod1 The first module to compare * @param {String} mod2 The second module to compare */ _requires: function(mod1, mod2) { var i, rm, after_map, s, info = this.moduleInfo, m = info[mod1], other = info[mod2]; if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = info[mod2] && info[mod2].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = info[mod1] && info[mod1].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && YArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }, /** * Apply a new config to the Loader instance * @method _config * @param {Object} o The new configuration */ _config: function(o) { var i, j, val, f, group, groupName, self = this; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; if (i == 'require') { self.require(val); } else if (i == 'skin') { Y.mix(self.skin, o[i], true); } else if (i == 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { groupName = j; group = val[j]; self.addGroup(group, groupName); } } } else if (i == 'modules') { // add a hash of module definitions oeach(val, self.addModule, self); } else if (i == 'gallery') { this.groups.gallery.update(val); } else if (i == 'yui2' || i == '2in3') { this.groups.yui2.update(o['2in3'], o.yui2); } else if (i == 'maxURLLength') { self[i] = Math.min(MAX_URL_LENGTH, val); } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f == 'DEBUG') { self.require('yui-log', 'dump'); } } if (self.lang) { self.require('intl-base', 'intl'); } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var mdef, pkg, name, nmod, info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; nmod = { name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }; if (mdef.base) { nmod.base = mdef.base; } if (mdef.configFn) { nmod.configFn = mdef.configFn; } this.addModule(nmod, name); } } return name; }, /** * Add a new module group * <dl> * <dt>name:</dt> <dd>required, the group name</dd> * <dt>base:</dt> <dd>The base dir for this module group</dd> * <dt>root:</dt> <dd>The root path to add to each combo * resource path</dd> * <dt>combine:</dt> <dd>combo handle</dd> * <dt>comboBase:</dt> <dd>combo service base path</dd> * <dt>modules:</dt> <dd>the group of modules</dd> * </dl> * @method addGroup * @param {object} o An object containing the module data. * @param {string} name the group name. */ addGroup: function(o, name) { var mods = o.modules, self = this; name = name || o.name; o.name = name; self.groups[name] = o; if (o.patterns) { oeach(o.patterns, function(v, k) { v.group = name; self.patterns[k] = v; }); } if (mods) { oeach(mods, function(v, k) { v.group = name; self.addModule(v, k); }, self); } }, /** * Add a new module to the component metadata. * <dl> * <dt>name:</dt> <dd>required, the component name</dd> * <dt>type:</dt> <dd>required, the component type (js or css) * </dd> * <dt>path:</dt> <dd>required, the path to the script from * "base"</dd> * <dt>requires:</dt> <dd>array of modules required by this * component</dd> * <dt>optional:</dt> <dd>array of optional modules for this * component</dd> * <dt>supersedes:</dt> <dd>array of the modules this component * replaces</dd> * <dt>after:</dt> <dd>array of modules the components which, if * present, should be sorted above this one</dd> * <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply * a hash instead of an array</dd> * <dt>rollup:</dt> <dd>the number of superseded modules required * for automatic rollup</dd> * <dt>fullpath:</dt> <dd>If fullpath is specified, this is used * instead of the configured base + path</dd> * <dt>skinnable:</dt> <dd>flag to determine if skin assets should * automatically be pulled in</dd> * <dt>submodules:</dt> <dd>a hash of submodules</dd> * <dt>group:</dt> <dd>The group the module belongs to -- this * is set automatically when it is added as part of a group * configuration.</dd> * <dt>lang:</dt> * <dd>array of BCP 47 language tags of languages for which this * module has localized resource bundles, * e.g., ["en-GB","zh-Hans-CN"]</dd> * <dt>condition:</dt> * <dd>Specifies that the module should be loaded automatically if * a condition is met. This is an object with up to three fields: * [trigger] - the name of a module that can trigger the auto-load * [test] - a function that returns true when the module is to be * loaded. * [when] - specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: 'before', 'after', or * 'instead'. The default is 'after'. * </dd> * <dt>testresults:</dt><dd>a hash of test results from Y.Features.all()</dd> * </dl> * @method addModule * @param {object} o An object containing the module data. * @param {string} name the module name (optional), required if not * in the module data. * @return {object} the module definition or null if * the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; //Only merge this data if the temp flag is set //from an earlier pass from a pattern or else //an override module (YUI_config) can not be used to //replace a default module. if (this.moduleInfo[name] && this.moduleInfo[name].temp) { //This catches temp modules loaded via a pattern // The module will be added twice, once from the pattern and // Once from the actual add call, this ensures that properties // that were added to the module the first time around (group: gallery) // are also added the second time around too. o = Y.merge(this.moduleInfo[name], o); } o.name = name; if (!o || !o.name) { return null; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = this.filterRequires(o.requires) || []; // Handle submodule logic var subs = o.submodules, i, l, t, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, conditions = this.conditions, trigger; // , existing = this.moduleInfo[name], newr; this.moduleInfo[name] = o; if (!o.langPack && o.lang) { langs = YArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = YArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || YArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || YArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Add rollup file, need to add to supersedes list too } } l++; } } //o.supersedes = YObject.keys(YArray.hash(sup)); o.supersedes = YArray.dedupe(sup); if (this.allowRollup) { o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { t = o.condition.trigger; if (YUI.Env.aliases[t]) { t = YUI.Env.aliases[t]; } if (!Y.Lang.isArray(t)) { t = [t]; } for (i = 0; i < t.length; i++) { trigger = t[i]; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when != 'after') { if (when == 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } else { // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } } if (o.after) { o.after_map = YArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; o = null; } } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? YArray(arguments) : what; this.dirty = true; this.required = Y.merge(this.required, YArray.hash(this.filterRequires(a))); this._explodeRollups(); }, /** * Grab all the items that were asked for, check to see if the Loader * meta-data contains a "use" array. If it doesm remove the asked item and replace it with * the content of the "use". * This will make asking for: "dd" * Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin" * @private * @method _explodeRollups */ _explodeRollups: function() { var self = this, m, r = self.required; if (!self.allowRollup) { oeach(r, function(v, name) { m = self.getModule(name); if (m && m.use) { //delete r[name]; YArray.each(m.use, function(v) { m = self.getModule(v); if (m && m.use) { //delete r[v]; YArray.each(m.use, function(v) { r[v] = true; }); } else { r[v] = true; } }); } }); self.required = r; } }, /** * Explodes the required array to remove aliases and replace them with real modules * @method filterRequires * @param {Array} r The original requires array * @return {Array} The new array of exploded requirements */ filterRequires: function(r) { if (r) { if (!Y.Lang.isArray(r)) { r = [r]; } r = Y.Array(r); var c = [], i, mod, o, m; for (i = 0; i < r.length; i++) { mod = this.getModule(r[i]); if (mod && mod.use) { for (o = 0; o < mod.use.length; o++) { //Must walk the other modules in case a module is a rollup of rollups (datatype) m = this.getModule(mod.use[o]); if (m && m.use) { c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use))); } else { c.push(mod.use[o]); } } } else { c.push(r[i]); } } r = c; } return r; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod || mod._parsed) { return NO_REQUIREMENTS; } var i, m, j, add, packName, lang, testresults = this.testresults, name = mod.name, cond, go, adddef = ON_PAGE[name] && ON_PAGE[name].details, d, k, m1, r, old_mod, o, skinmod, skindef, skinpar, skinname, intl = mod.lang || mod.intl, info = this.moduleInfo, ftests = Y.Features && Y.Features.tests.load, hash; // console.log(name); // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // console.log('cache: ' + mod.langCache + ' == ' + this.lang); // if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) { if (mod.expanded && (!this.lang || mod.langCache === this.lang)) { return mod.expanded; } d = []; hash = {}; r = this.filterRequires(mod.requires); if (mod.lang) { //If a module has a lang attribute, auto add the intl requirement. d.unshift('intl'); r.unshift('intl'); intl = true; } o = this.filterRequires(mod.optional); mod._parsed = true; mod.langCache = this.lang; for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = this.filterRequires(mod.supersedes); if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = info[o[i]]; if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { if (testresults && ftests) { oeach(testresults, function(result, id) { var condmod = ftests[id].name; if (!hash[condmod] && ftests[id].trigger == name) { if (result && ftests[id]) { hash[condmod] = true; d.push(condmod); } } }); } else { oeach(cond, function(def, condmod) { if (!hash[condmod]) { go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[condmod] = true; d.push(condmod); m = this.getModule(condmod); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } }, this); } } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; oeach(YUI.Env.aliases, function(o, n) { if (Y.Array.indexOf(o, name) > -1) { skinpar = n; } }); if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) { skinname = name; if (skindef[skinpar]) { skinname = skinpar; } for (i = 0; i < skindef[skinname].length; i++) { skinmod = this._addSkin(skindef[skinname][i], name); d.push(skinmod); } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); d.push(skinmod); } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = YArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { YArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } else { this._explodeRollups(); } this._reduce(); this._sort(); } }, /** * Creates a "psuedo" package for languages provided in the lang array * @method _addLangPack * @param {String} lang The language to create * @param {Object} m The module definition to create the language pack around * @param {String} packName The name of the package (e.g: lang/datatype-date-en-US) * @return {Object} The module definition */ _addLangPack: function(lang, m, packName) { var name = m.name, packPath, existing = this.moduleInfo[packName]; if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); this.addModule({ path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }, packName); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.moduleInfo[packName]; }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups //m.requires = YObject.keys(YArray.hash(m.requires)); m.requires = YArray.dedupe(m.requires); // Create lang pack modules if (m.lang && m.lang.length) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, YArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { var r = this.required, m, reqs, done = {}, self = this; // the setup phase is over, all modules have been created self.dirty = false; self._explodeRollups(); r = self.required; oeach(r, function(v, name) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { var expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, YArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, YArray.hash(reqs)); } } }); }, /** * Get's the loader meta data for the requested module * @method getModule * @param {String} mname The module name to get * @return {Object} The module metadata */ getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.moduleInfo[mname], patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m) { for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { p = patterns[pname]; // use the metadata supplied for the pattern // as the module definition. if (mname.indexOf(pname) > -1) { found = p; break; } } } if (found) { if (p.action) { p.action.call(this, mname, pname); } else { // ext true or false? m = this.addModule(Y.merge(found), mname); m.temp = true; } } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType, ignore = this.ignore ? YArray.hash(this.ignore) : false; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type != type)) { delete r[i]; } if (ignore && ignore[i]) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, /** * Handles the queue when a module has been loaded for all cases * @method _finish * @private * @param {String} msg The message from Loader * @param {Boolean} success A boolean denoting success or failure */ _finish: function(msg, success) { _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, /** * The default Loader onSuccess handler, calls this.onSuccess with a payload * @method _onSuccess * @private */ _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg; oeach(skipped, function(k) { delete self.inserted[k]; }); self.skipped = {}; oeach(self.inserted, function(v, k) { var mod = self.getModule(k); if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) { failed.push(k); } else { Y.mix(self.loaded, self.getProvides(k)); } }); fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, /** * The default Loader onFailure handler, calls this.onFailure with a payload * @method _onFailure * @private */ _onFailure: function(o) { var f = this.onFailure, msg = 'failure: ' + o.msg; if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, /** * The default Loader onTimeout handler, calls this.onTimeout with a payload * @method _onTimeout * @private */ _onTimeout: function() { var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } this._finish('timeout', false); }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s = YObject.keys(this.required), // loaded = this.loaded, done = {}, p = 0, l, a, b, j, k, moved, doneKey; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j = p; j < l; j++) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k = j + 1; k < l; k++) { doneKey = a + s[k]; if (!done[doneKey] && this._requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); // only swap two dependencies once to short circut // circular dependencies done[doneKey] = true; // keep working moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p++; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, /** * (Unimplemented) * @method partial * @unimplemented */ partial: function(partial, o, type) { this.sorted = partial; this.insert(o, type, true); }, /** * Handles the actual insertion of script/link tags * @method _insert * @param {Object} source The YUI instance the request came from * @param {Object} o The metadata to include * @param {String} type JS or CSS * @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta */ _insert: function(source, o, type, skipcalc) { // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. if (!skipcalc) { this.calculate(o); } this.loadType = type; if (!type) { var self = this; this._internalCallback = function() { var f = self.onCSS, n, p, sib; // IE hack for style overrides that are not being applied if (this.insertBefore && Y.UA.ie) { n = Y.config.doc.getElementById(this.insertBefore); p = n.parentNode; sib = n.nextSibling; p.removeChild(n); if (sib) { p.insertBefore(n, sib); } else { p.appendChild(n); } } if (f) { f.call(self.context, Y); } self._internalCallback = null; self._insert(null, null, JS); }; this._insert(null, null, CSS); return; } // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually this._combineComplete = {}; // start the load this.loadNext(); }, /** * Once a loader operation is completely finished, process any additional queued items. * @method _continue * @private */ _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function(mname) { // It is possible that this function is executed due to something // else on the page loading a YUI module. Only react when we // are actively loading something if (!this._loading) { return; } var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag, comboSource, comboSources, mods, combining, urls, comboBase, self = this, type = self.loadType, handleSuccess = function(o) { self.loadNext(o.data); }, handleCombo = function(o) { self._combineComplete[type] = true; var i, len = combining.length; for (i = 0; i < len; i++) { self.inserted[combining[i]] = true; } handleSuccess(o); }; if (self.combine && (!self._combineComplete[type])) { combining = []; self._combining = combining; s = self.sorted; len = s.length; // the default combo base comboBase = self.comboBase; url = comboBase; urls = []; comboSources = {}; for (i = 0; i < len; i++) { comboSource = comboBase; m = self.getModule(s[i]); groupName = m && m.group; if (groupName) { group = self.groups[groupName]; if (!group.combine) { m.combine = false; continue; } m.combine = true; if (group.comboBase) { comboSource = group.comboBase; } if ("root" in group && L.isValue(group.root)) { m.root = group.root; } } comboSources[comboSource] = comboSources[comboSource] || []; comboSources[comboSource].push(m); } for (j in comboSources) { if (comboSources.hasOwnProperty(j)) { url = j; mods = comboSources[j]; len = mods.length; for (i = 0; i < len; i++) { // m = self.getModule(s[i]); m = mods[i]; // Do not try to combine non-yui JS unless combo def // is found if (m && (m.type === type) && (m.combine || !m.ext)) { frag = ((L.isValue(m.root)) ? m.root : self.root) + m.path; frag = self._filter(frag, m.name); if ((url !== j) && (i <= (len - 1)) && ((frag.length + url.length) > self.maxURLLength)) { //Hack until this is rewritten to use an array and not string concat: if (url.substr(url.length - 1, 1) === self.comboSep) { url = url.substr(0, (url.length - 1)); } urls.push(self._filter(url)); url = j; } url += frag; if (i < (len - 1)) { url += self.comboSep; } combining.push(m.name); } } if (combining.length && (url != j)) { //Hack until this is rewritten to use an array and not string concat: if (url.substr(url.length - 1, 1) === self.comboSep) { url = url.substr(0, (url.length - 1)); } urls.push(self._filter(url)); } } } if (combining.length) { // if (m.type === CSS) { if (type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } fn(urls, { data: self._loading, onSuccess: handleCombo, onFailure: self._onFailure, onTimeout: self._onTimeout, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, timeout: self.timeout, autopurge: false, context: self }); return; } else { self._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== self._loading) { return; } // The global handler that is called when each module is loaded // will pass that module name to this function. Storing this // data to avoid loading the same module multiple times // centralize this in the callback self.inserted[mname] = true; // self.loaded[mname] = true; // provided = self.getProvides(mname); // Y.mix(self.loaded, provided); // Y.mix(self.inserted, provided); if (self.onProgress) { self.onProgress.call(self.context, { name: mname, data: self.data }); } } s = self.sorted; len = s.length; for (i = 0; i < len; i = i + 1) { // this.inserted keeps track of what the loader has loaded. // move on if this item is done. if (s[i] in self.inserted) { continue; } // Because rollups will cause multiple load notifications // from Y, loadNext may be called multiple times for // the same module when loading a rollup. We can safely // skip the subsequent requests if (s[i] === self._loading) { return; } // log("inserting " + s[i]); m = self.getModule(s[i]); if (!m) { if (!self.skipped[s[i]]) { msg = 'Undefined module ' + s[i] + ' skipped'; // self.inserted[s[i]] = true; self.skipped[s[i]] = true; } continue; } group = (m.group && self.groups[m.group]) || NOT_FOUND; // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { self._loading = s[i]; if (m.type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } url = (m.fullpath) ? self._filter(m.fullpath, s[i]) : self._url(m.path, s[i], group.base || m.base); fn(url, { data: s[i], onSuccess: handleSuccess, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, onFailure: self._onFailure, onTimeout: self._onTimeout, timeout: self.timeout, autopurge: false, context: self }); return; } } // we are finished self._loading = null; fn = self._internalCallback; // internal callback for loading css first if (fn) { self._internalCallback = null; fn.call(self); } else { self._onSuccess(); } }, /** * Apply filter defined for this instance to a url/path * @method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name], groupName = this.moduleInfo[name] ? this.moduleInfo[name].group:null; if (groupName && this.groups[groupName].filter) { modFilter = this.groups[groupName].filter; hasFilter = true; }; if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * @method _url * @param {string} path the path fragment. * @param {String} name The name of the module * @pamra {String} [base=self.base] The base url to use * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); }, /** * Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules. * @method resolve * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [s=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two arrays of file lists * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.resolve(true); * */ resolve: function(calc, s) { var self = this, i, m, url, out = { js: [], css: [] }; if (calc) { self.calculate(); } s = s || self.sorted; for (i = 0; i < s.length; i++) { m = self.getModule(s[i]); if (m) { if (self.combine) { url = self._filter((self.root + m.path), m.name, self.root); } else { url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name); } out[m.type].push(url); } } if (self.combine) { out.js = [self.comboBase + out.js.join(self.comboSep)]; out.css = [self.comboBase + out.css.join(self.comboSep)]; } return out; }, /** * Returns an Object hash of hashes built from `loader.sorted` or from an arbitrary list of sorted modules. * @method hash * @private * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [s=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two object hashes of file lists, with the module name as the key * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.hash(true); * */ hash: function(calc, s) { var self = this, i, m, url, out = { js: {}, css: {} }; if (calc) { self.calculate(); } s = s || self.sorted; for (i = 0; i < s.length; i++) { m = self.getModule(s[i]); if (m) { url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name); out[m.type][m.name] = url; } } return out; } }; }, '@VERSION@' ,{requires:['get']}); YUI.add('loader-rollup', function(Y) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } this.forceMap = (this.force) ? Y.Array.hash(this.force) : {}; } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type == smod.type) { c++; roll = (c >= m.rollup); if (roll) { break; } } } if (roll) { // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('loader-yui3', function(Y) { /* This file is auto-generated by src/loader/scripts/meta_join.py */ /** * YUI 3 module metadata * @module loader * @submodule yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "anim": { "use": [ "anim-base", "anim-color", "anim-curve", "anim-easing", "anim-node-plugin", "anim-scroll", "anim-xy" ] }, "anim-base": { "requires": [ "base-base", "node-style" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] }, "app": { "use": [ "controller", "model", "model-list", "view" ] }, "array-extras": { "requires": [ "yui-base" ] }, "array-invoke": { "requires": [ "yui-base" ] }, "arraylist": { "requires": [ "yui-base" ] }, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] }, "arraysort": { "requires": [ "yui-base" ] }, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "use": [ "attribute-base", "attribute-complex" ] }, "attribute-base": { "requires": [ "event-custom" ] }, "attribute-complex": { "requires": [ "attribute-base" ] }, "autocomplete": { "use": [ "autocomplete-base", "autocomplete-sources", "autocomplete-list", "autocomplete-plugin" ] }, "autocomplete-base": { "optional": [ "autocomplete-sources" ], "requires": [ "array-extras", "base-build", "escape", "event-valuechange", "node-base" ] }, "autocomplete-filters": { "requires": [ "array-extras", "text-wordbreak" ] }, "autocomplete-filters-accentfold": { "requires": [ "array-extras", "text-accentfold", "text-wordbreak" ] }, "autocomplete-highlighters": { "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "requires": [ "array-extras", "highlight-accentfold" ] }, "autocomplete-list": { "after": [ "autocomplete-sources" ], "lang": [ "en" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }, "autocomplete-list-keys": { "condition": { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "requires": [ "autocomplete-list", "node-pluginhost" ] }, "autocomplete-sources": { "optional": [ "io-base", "json-parse", "jsonp", "yql" ], "requires": [ "autocomplete-base" ] }, "base": { "use": [ "base-base", "base-pluginhost", "base-build" ] }, "base-base": { "after": [ "attribute-complex" ], "requires": [ "attribute-base" ] }, "base-build": { "requires": [ "base-base" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] }, "cache": { "use": [ "cache-base", "cache-offline", "cache-plugin" ] }, "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] }, "cache-plugin": { "requires": [ "plugin", "cache-base" ] }, "calendar": { "lang": [ "en", "ja", "ru" ], "requires": [ "calendar-base", "calendarnavigator" ], "skinnable": true }, "calendar-base": { "lang": [ "en", "ja", "ru" ], "requires": [ "widget", "substitute", "datatype-date", "datatype-date-math", "cssgrids" ], "skinnable": true }, "calendarnavigator": { "requires": [ "plugin", "classnamemanager", "datatype-date", "node", "substitute" ], "skinnable": true }, "charts": { "requires": [ "dom", "datatype-number", "datatype-date", "event-custom", "event-mouseenter", "widget", "widget-position", "widget-stack", "graphics" ] }, "classnamemanager": { "requires": [ "yui-base" ] }, "clickable-rail": { "requires": [ "slider-base" ] }, "collection": { "use": [ "array-extras", "arraylist", "arraylist-add", "arraylist-filter", "array-invoke" ] }, "console": { "lang": [ "en", "es", "ja" ], "requires": [ "yui-log", "widget", "substitute" ], "skinnable": true }, "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true }, "controller": { "optional": [ "querystring-parse" ], "requires": [ "array-extras", "base-build", "history" ] }, "cookie": { "requires": [ "yui-base" ] }, "createlink-base": { "requires": [ "editor-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssfonts": { "type": "css" }, "cssfonts-context": { "type": "css" }, "cssgrids": { "optional": [ "cssreset", "cssfonts" ], "type": "css" }, "cssreset": { "type": "css" }, "cssreset-context": { "type": "css" }, "dataschema": { "use": [ "dataschema-base", "dataschema-json", "dataschema-xml", "dataschema-array", "dataschema-text" ] }, "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] }, "datasource": { "use": [ "datasource-local", "datasource-io", "datasource-get", "datasource-function", "datasource-cache", "datasource-jsonschema", "datasource-xmlschema", "datasource-arrayschema", "datasource-textschema", "datasource-polling" ] }, "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "plugin", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "dataschema-xml" ] }, "datatable": { "use": [ "datatable-base", "datatable-datasource", "datatable-sort", "datatable-scroll" ] }, "datatable-base": { "requires": [ "recordset-base", "widget", "substitute", "event-mouseenter" ], "skinnable": true }, "datatable-datasource": { "requires": [ "datatable-base", "plugin", "datasource-local" ] }, "datatable-scroll": { "requires": [ "datatable-base", "plugin" ] }, "datatable-sort": { "lang": [ "en" ], "requires": [ "datatable-base", "plugin", "recordset-sort" ] }, "datatype": { "use": [ "datatype-number", "datatype-date", "datatype-xml" ] }, "datatype-date": { "supersedes": [ "datatype-date-format" ], "use": [ "datatype-date-parse", "datatype-date-format" ] }, "datatype-date-format": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ] }, "datatype-date-math": { "requires": [ "yui-base" ] }, "datatype-date-parse": {}, "datatype-number": { "use": [ "datatype-number-parse", "datatype-number-format" ] }, "datatype-number-format": {}, "datatype-number-parse": {}, "datatype-xml": { "use": [ "datatype-xml-parse", "datatype-xml-format" ] }, "datatype-xml-format": {}, "datatype-xml-parse": {}, "dd": { "use": [ "dd-ddm-base", "dd-ddm", "dd-ddm-drop", "dd-drag", "dd-proxy", "dd-constrain", "dd-drop", "dd-scroll", "dd-delegate" ] }, "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base" ] }, "dd-drop": { "requires": [ "dd-drag", "dd-ddm-drop" ] }, "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }, "requires": [ "dd-drag", "event-synthetic", "event-gestures" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] }, "dial": { "lang": [ "en", "es" ], "requires": [ "widget", "dd-drag", "substitute", "event-mouseenter", "event-move", "event-key", "transition", "intl" ], "skinnable": true }, "dom": { "use": [ "dom-base", "dom-screen", "dom-style", "selector-native", "selector" ] }, "dom-base": { "requires": [ "dom-core" ] }, "dom-core": { "requires": [ "oop", "features" ] }, "dom-deprecated": { "requires": [ "dom-base" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base" ] }, "dom-style-ie": { "condition": { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }, "requires": [ "dom-style" ] }, "dump": { "requires": [ "yui-base" ] }, "editor": { "use": [ "frame", "selection", "exec-command", "editor-base", "editor-para", "editor-br", "editor-bidi", "editor-tab", "createlink-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "selection" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-br": { "requires": [ "editor-base" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "editor-base" ] }, "editor-tab": { "requires": [ "editor-base" ] }, "escape": { "requires": [ "yui-base" ] }, "event": { "after": [ "node-base" ], "use": [ "event-base", "event-delegate", "event-synthetic", "event-mousewheel", "event-mouseenter", "event-key", "event-focus", "event-resize", "event-hover", "event-outside" ] }, "event-base": { "after": [ "node-base" ], "requires": [ "event-custom-base" ] }, "event-base-ie": { "after": [ "event-base" ], "condition": { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }, "requires": [ "node-base" ] }, "event-custom": { "use": [ "event-custom-base", "event-custom-complex" ] }, "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-gestures": { "use": [ "event-flick", "event-move" ] }, "event-hover": { "requires": [ "event-mouseenter" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "node-base" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-outside": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "node-base", "event-synthetic" ] }, "event-simulate": { "requires": [ "event-base" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] }, "event-touch": { "requires": [ "node-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "exec-command": { "requires": [ "frame" ] }, "features": { "requires": [ "yui-base" ] }, "frame": { "requires": [ "base", "node", "selector-css3", "substitute", "yui-throttle" ] }, "get": { "requires": [ "yui-base" ] }, "graphics": { "requires": [ "node", "event-custom", "pluginhost" ] }, "graphics-canvas": { "condition": { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-canvas-default": { "condition": { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" } }, "graphics-svg": { "condition": { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-svg-default": { "condition": { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" } }, "graphics-vml": { "condition": { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-vml-default": { "condition": { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "highlight": { "use": [ "highlight-base", "highlight-accentfold" ] }, "highlight-accentfold": { "requires": [ "highlight-base", "text-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "classnamemanager", "escape", "text-wordbreak" ] }, "history": { "use": [ "history-base", "history-hash", "history-hash-ie", "history-html5" ] }, "history-base": { "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-hash-ie": { "condition": { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "intl-base": { "requires": [ "yui-base" ] }, "io": { "use": [ "io-base", "io-xdr", "io-form", "io-upload-iframe", "io-queue" ] }, "io-base": { "requires": [ "event-custom-base", "querystring-stringify-simple" ] }, "io-form": { "requires": [ "io-base", "node-base" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml-parse" ] }, "json": { "use": [ "json-parse", "json-stringify" ] }, "json-parse": { "requires": [ "yui-base" ] }, "json-stringify": { "requires": [ "yui-base" ] }, "jsonp": { "requires": [ "get", "oop" ] }, "jsonp-url": { "requires": [ "jsonp" ] }, "loader": { "use": [ "loader-base", "loader-rollup", "loader-yui3" ] }, "loader-base": { "requires": [ "get" ] }, "loader-rollup": { "requires": [ "loader-base" ] }, "loader-yui3": { "requires": [ "loader-base" ] }, "model": { "requires": [ "base-build", "escape", "json-parse" ] }, "model-list": { "requires": [ "array-extras", "array-invoke", "arraylist", "base-build", "escape", "json-parse", "model" ] }, "node": { "use": [ "node-base", "node-event-delegate", "node-pluginhost", "node-screen", "node-style" ] }, "node-base": { "requires": [ "event-base", "node-core", "dom-base" ] }, "node-core": { "requires": [ "dom-core", "selector" ] }, "node-deprecated": { "requires": [ "node-base" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-event-html5": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate" ] }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "panel": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain", "widget-modality", "widget-autohide", "widget-buttons" ], "skinnable": true }, "plugin": { "requires": [ "base-base" ] }, "pluginhost": { "use": [ "pluginhost-base", "pluginhost-config" ] }, "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] }, "profiler": { "requires": [ "yui-base" ] }, "querystring": { "use": [ "querystring-parse", "querystring-stringify" ] }, "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-parse-simple": { "requires": [ "yui-base" ] }, "querystring-stringify": { "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "recordset": { "use": [ "recordset-base", "recordset-sort", "recordset-filter", "recordset-indexer" ] }, "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras", "plugin" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base", "plugin" ] }, "resize": { "use": [ "resize-base", "resize-proxy", "resize-constrain" ] }, "resize-base": { "requires": [ "base", "widget", "substitute", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-plugin": { "optional": [ "resize-constrain" ], "requires": [ "resize-base", "plugin" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] }, "rls": { "requires": [ "get", "features" ] }, "scrollview": { "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "scrollview-base": { "requires": [ "widget", "event-gestures", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-list": { "requires": [ "plugin", "classnamemanager" ], "skinnable": true }, "scrollview-paginator": { "requires": [ "plugin" ] }, "scrollview-scrollbars": { "requires": [ "classnamemanager", "transition", "plugin" ], "skinnable": true }, "selection": { "requires": [ "node" ] }, "selector": { "requires": [ "selector-native" ] }, "selector-css2": { "condition": { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }, "requires": [ "selector-native" ] }, "selector-css3": { "requires": [ "selector-native", "selector-css2" ] }, "selector-native": { "requires": [ "dom-base" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "slider": { "use": [ "slider-base", "slider-value-range", "clickable-rail", "range-slider" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "substitute" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] }, "sortable": { "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "sortable-scroll": { "requires": [ "dd-scroll", "sortable" ] }, "stylesheet": { "requires": [ "yui-base" ] }, "substitute": { "optional": [ "dump" ], "requires": [ "yui-base" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect", "escape" ] }, "swfdetect": { "requires": [ "yui-base" ] }, "tabview": { "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager", "skin-sam-tabview" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] }, "test": { "requires": [ "event-simulate", "event-custom", "substitute", "json-stringify" ], "skinnable": true }, "text": { "use": [ "text-accentfold", "text-wordbreak" ] }, "text-accentfold": { "requires": [ "array-extras", "text-data-accentfold" ] }, "text-data-accentfold": { "requires": [ "yui-base" ] }, "text-data-wordbreak": { "requires": [ "yui-base" ] }, "text-wordbreak": { "requires": [ "array-extras", "text-data-wordbreak" ] }, "transition": { "requires": [ "node-style" ] }, "transition-timer": { "condition": { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }, "requires": [ "transition" ] }, "uploader": { "requires": [ "event-custom", "node", "base", "swf" ] }, "view": { "requires": [ "base-build", "node-event-delegate" ] }, "widget": { "use": [ "widget-base", "widget-htmlparser", "widget-uievents", "widget-skin" ] }, "widget-anim": { "requires": [ "plugin", "anim-base", "widget" ] }, "widget-autohide": { "requires": [ "widget", "event-outside", "base-build", "event-key" ], "skinnable": false }, "widget-base": { "requires": [ "attribute", "event-focus", "base-base", "base-pluginhost", "node-base", "node-style", "classnamemanager" ], "skinnable": true }, "widget-base-ie": { "condition": { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-buttons": { "requires": [ "widget", "base-build", "widget-stdmod" ], "skinnable": true }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-locale": { "requires": [ "widget-base" ] }, "widget-modality": { "requires": [ "widget", "event-outside", "base-build" ], "skinnable": false }, "widget-parent": { "requires": [ "base-build", "arraylist", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] }, "widget-uievents": { "requires": [ "widget-base", "node-event-delegate" ] }, "yql": { "requires": [ "jsonp", "jsonp-url" ] }, "yui": {}, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-rls": {}, "yui-throttle": { "requires": [ "yui-base" ] } }; YUI.Env[Y.version].md5 = '105ebffae27a0e3d7331f8cf5c0bb282'; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3' ]});
ajax/libs/yui/3.0.0/event-custom/event-custom-debug.js
sullivanmatt/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var BEFORE = 0, AFTER = 1; Y.Do = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ Y.Do.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ Y.Do.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case Y.Do.Halt: return ret.retVal; case Y.Do.AlterArgs: args = ret.newArgs; break; case Y.Do.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == Y.Do.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == Y.Do.AlterReturn) { ret = newRet.newRetVal; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ Y.Do.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ Y.Do.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ Y.Do.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ Y.Do.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ Y.Do.Error = Y.Do.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); })(); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param evt {CustomEvent} the custom event * @param sub {Subscriber} the subscriber */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'details', 'emitFacade', 'fireOnce', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { /** * Detaches this subscriber * @method detach */ detach: function() { var evt = this.evt, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i=0; i<evt.length; i++) { evt[i].detach(); } } else { evt._delete(this.sub); } } } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param o configuration object * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber{} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber{} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log("Invalid callback for CE: " + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { Y.later(0, this, Y.bind(this._notify, this, s, this.firedWith)); } if (when == AFTER) { this.afters[s.id] = s; this.hasAfters = true; } else { this.subscribers[s.id] = s; this.hasSubscribers = true; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute * @return {EventHandle|EventTarget} unsubscribe handle or a * chainable event target depending on the 'chain' config. * @deprecated use on */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute * @return {EventHandle|EventTarget} unsubscribe handle or a * chainable event target depending on the 'chain' config. */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute * @return {EventHandle|EventTarget} unsubscribe handle or a * chainable event target depending on the 'chain' config. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int|EventTarget} returns a chainable event target * or the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var found = 0, subs = this.subscribers, i, s; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {boolean|EventTarget} returns a chainable event target * or a boolean for legacy detach support. * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param s {Subscriber} the subscriber * @param args {Array} the arguments array to apply to the listener * @private */ _notify: function(s, args, ef) { this.log(this.type + "->" + "sub: " + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + " cancelled by subscriber"); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param msg {string} message to log * @param cat {string} log category */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || "info", "event"); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { if (this.hasSubscribers || this.hasAfters) { this._procSubs(Y.merge(this.subscribers, this.afters), args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object * @private */ _delete: function(s) { if (s) { delete s.fn; delete s.context; delete this.subscribers[s.id]; delete this.afters[s.id]; } } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute * @param {Object} context The value of the keyword 'this' in the listener * @param {Array} args* 0..n additional arguments to supply the listener * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ this.events = null; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber * @param ce {CustomEvent} The custom event that sent the notification */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch(e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} context optional 'this' keyword for the listener * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory, menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, broadcast: o.broadcast, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context, x) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent; if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = Y.Array(arguments, 0, true); ret = {}; after = type._after; delete type._after; Y.each(type, function(v, k) { if (v) { f = v.fn || ((Y.Lang.isFunction(v)) ? v : f); c = v.context || c; } args[0] = (after) ? AFTER_PREFIX + k : k; args[1] = f; args[2] = c; ret[k] = this.on.apply(this, args); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) { args = Y.Array(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (this instanceof YUI) { adapt = Y.Env.evt.plugins[type]; args = Y.Array(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (n instanceof Y.NodeList) { n = Y.NodeList.getDOMNodes(n); } else if (n instanceof Node) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, ret, Node = Y.Node, isNode = (this instanceof Node); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { ret = evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return ret; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, handle, adapt, store = Y.Env.evt.handles, cat, args, ce, keyDetacher = function(lcat, ltype) { var handles = lcat[ltype]; if (handles) { while (handles.length) { handle = handles.pop(); handle.detach(); } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; if (cat) { if (type) { keyDetacher(cat, type); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i); } } } return (this._yuievt.chain) ? this : true; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { ret = type.detach(); return (this._yuievt.chain) ? this : ret; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = Y.Array(arguments, 0, true); args[2] = Node.getDOMNode(this); return Y.detach.apply(Y, args); } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (this instanceof YUI) { args = Y.Array(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { return adapt.detach.apply(Y, args); // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; return Y.Event.detach.apply(Y.Event, args); } } ce = evts[type]; if (ce) { ret = ce.detach(fn, context); } return (this._yuievt.chain) ? this : ret; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {Event.Custom} the custom event * */ publish: function(type, opts) { var events, ce, ret, pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = this._yuievt.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * @method addTarget * @param o {EventTarget} the target to add */ addTarget: function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }, /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove */ removeTarget: function(o) { delete this._yuievt.targets[Y.stamp(o)]; }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {Event.Target} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, a, ret, pre=this._yuievt.config.prefix; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { a = (typeIncluded) ? arguments : Y.Array(arguments, 0, true).unshift(t); return this.bubble(null, a, this); } // otherwise there is nothing to be done ret = true; } else { a = Y.Array(arguments, (typeIncluded) ? 1 : 0, true); ret = ce.fire.apply(ce, a); // clear target for next fire() ce.target = null; } return (this._yuievt.chain) ? this : ret; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {Event.Custom} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return (e && type in e) ? e[type] : null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = Y.Array(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle * @deprecated use the on method */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? })(); /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('domready', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param target a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ (function() { var FACADE, FACADE_KEYS, CEProto = Y.CustomEvent.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || {}; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type * @property type * @type string */ this.type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @propery target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; /** * Stops the propagation to the next bubble target * @method stopPropagation */ this.stopPropagation = function() { e.stopPropagation(); }; /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { e.stopImmediatePropagation(); }; /** * Prevents the event's default behavior * @method preventDefault */ this.preventDefault = function() { e.preventDefault(); }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ this.halt = function(immediate) { e.halt(immediate); }; }; CEProto.fireComplex = function(args) { var es = Y.Env._eventstack, ef, q, queue, ce, ret, events; if (es) { // queue this event if the current item in the queue bubbles if (this.queuable && this.type != es.next.type) { this.log('queue ' + this.type); es.queue.push([this, args]); return true; } } else { Y.Env._eventstack = { // id of the first event in the stack id: this.id, next: this, silent: this.silent, stopped: 0, prevented: 0, queue: [] }; es = Y.Env._eventstack; } this.stopped = 0; this.prevented = 0; this.target = this.target || this.host; events = new Y.EventTarget({ fireOnce: true, context: this.host }); this.events = events; if (this.preventedFn) { events.on('prevented', this.preventedFn); } if (this.stoppedFn) { events.on('stopped', this.stoppedFn); } this.currentTarget = this.host || this.currentTarget; this.details = args.slice(); // original arguments in the details // this.log("Firing " + this + ", " + "args: " + args); this.log("Firing " + this.type); this._facade = null; // kill facade to eliminate stale properties ef = this._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (this.hasSubscribers) { this._procSubs(Y.merge(this.subscribers), args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (this.bubbles && this.host && this.host.bubble && !this.stopped) { es.stopped = 0; es.prevented = 0; ret = this.host.bubble(this); this.stopped = Math.max(this.stopped, es.stopped); this.prevented = Math.max(this.prevented, es.prevented); } // execute the default behavior if not prevented if (this.defaultFn && !this.prevented) { this.defaultFn.apply(this.host || this, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. this._broadcast(args); // process after listeners. If the default behavior was // prevented, the after events don't fire. if (this.hasAfters && !this.prevented && this.stopped < 2) { this._procSubs(Y.merge(this.afters), args, ef); } if (es.id === this.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; es.stopped = 0; es.prevented = 0; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } Y.Env._eventstack = null; } return this.stopped ? false : true; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; ef.target = this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; Y.Env._eventstack.stopped = 1; this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; Y.Env._eventstack.stopped = 2; this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; Y.Env._eventstack.prevented = 1; this.events.fire('prevented', this); } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {Event.Custom} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ Y.EventTarget.prototype.bubble = function(evt, args, target) { var targs = this._yuievt.targets, ret = true, t, type, ce, i, bc; if (!evt || ((!evt.stopped) && targs)) { // Y.log('Bubbling ' + evt.type); for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; type = evt && evt.type; ce = t.getEvent(type, true); // if this event was not published on the bubble target, // publish it with sensible default properties if (!ce) { if (t._yuievt.hasTargets) { t.bubble.call(t, evt, args, target); } } else { ce.target = target || (evt && evt.target) || this; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; ret = ret && ce.fire.apply(ce, args || evt.details); ce.broadcast = bc; // stopPropagation() was called if (ce.stopped) { break; } } } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); })(); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('event-custom', function(Y){}, '@VERSION@' ,{use:['event-custom-base', 'event-custom-complex']});
node_modules/babel-preset-es2015/node_modules/babel-plugin-transform-es2015-computed-properties/node_modules/babel-helper-define-map/node_modules/babel-helper-function-name/node_modules/babel-traverse/lib/path/lib/hoister.js
vivekparekh8/LearningReact
"use strict"; exports.__esModule = true; var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); 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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var referenceVisitor = { ReferencedIdentifier: function ReferencedIdentifier(path, state) { if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name)) { return; } // direct references that we need to track to hoist this to the highest scope we can var binding = path.scope.getBinding(path.node.name); if (!binding) return; // this binding isn't accessible from the parent scope so we can safely ignore it // eg. it's in a closure etc if (binding !== state.scope.getBinding(path.node.name)) return; if (binding.constant) { state.bindings[path.node.name] = binding; } else { for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var violationPath = _ref; state.breakOnScopePaths = state.breakOnScopePaths.concat(violationPath.getAncestry()); } } } }; var PathHoister = function () { function PathHoister(path, scope) { (0, _classCallCheck3.default)(this, PathHoister); this.breakOnScopePaths = []; this.bindings = {}; this.scopes = []; this.scope = scope; this.path = path; } PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { for (var key in this.bindings) { var binding = this.bindings[key]; if (!scope.bindingIdentifierEquals(key, binding.identifier)) { return false; } } return true; }; PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { var scope = this.path.scope; do { if (this.isCompatibleScope(scope)) { this.scopes.push(scope); } else { break; } if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { break; } } while (scope = scope.parent); }; PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { var path = this._getAttachmentPath(); if (!path) return; var targetScope = path.scope; // don't allow paths that have their own lexical environments to pollute if (targetScope.path === path) { targetScope = path.scope.parent; } // avoid hoisting to a scope that contains bindings that are executed after our attachment path if (targetScope.path.isProgram() || targetScope.path.isFunction()) { for (var name in this.bindings) { // check binding is a direct child of this paths scope if (!targetScope.hasOwnBinding(name)) continue; var binding = this.bindings[name]; // allow parameter references if (binding.kind === "param") continue; // if this binding appears after our attachment point then don't hoist it if (binding.path.getStatementParent().key > path.key) return; } } return path; }; PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { var scopes = this.scopes; var scope = scopes.pop(); if (!scope) return; if (scope.path.isFunction()) { if (this.hasOwnParamBindings(scope)) { // should ignore this scope since it's ourselves if (this.scope === scope) return; // needs to be attached to the body return scope.path.get("body").get("body")[0]; } else { // doesn't need to be be attached to this scope return this.getNextScopeStatementParent(); } } else if (scope.path.isProgram()) { return this.getNextScopeStatementParent(); } }; PathHoister.prototype.getNextScopeStatementParent = function getNextScopeStatementParent() { var scope = this.scopes.pop(); if (scope) return scope.path.getStatementParent(); }; PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { for (var name in this.bindings) { if (!scope.hasOwnBinding(name)) continue; var binding = this.bindings[name]; if (binding.kind === "param") return true; } return false; }; PathHoister.prototype.run = function run() { var node = this.path.node; if (node._hoisted) return; node._hoisted = true; this.path.traverse(referenceVisitor, this); this.getCompatibleScopes(); var attachTo = this.getAttachmentPath(); if (!attachTo) return; // don't bother hoisting to the same function as this will cause multiple branches to be evaluated more than once leading to a bad optimisation if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; // generate declaration and insert it to our point var uid = attachTo.scope.generateUidIdentifier("ref"); attachTo.insertBefore([t.variableDeclaration("var", [t.variableDeclarator(uid, this.path.node)])]); var parent = this.path.parentPath; if (parent.isJSXElement() && this.path.container === parent.node.children) { // turning the `span` in `<div><span /></div>` to an expression so we need to wrap it with // an expression container uid = t.JSXExpressionContainer(uid); } this.path.replaceWith(uid); }; return PathHoister; }(); exports.default = PathHoister; module.exports = exports["default"];
components/__tests__/OrderedList-test.js
hellobrian/carbon-components-react
import React from 'react'; import OrderedList from '../OrderedList'; import ListItem from '../ListItem'; import { shallow } from 'enzyme'; describe('OrderedList', () => { describe('Renders as expected', () => { const list = shallow( <OrderedList className="some-class"><ListItem>Item</ListItem></OrderedList> ); it('should be an ol element', () => { expect(list.find('ol').length).toEqual(1); }); it('should render with the appropriate classes', () => { expect(list.hasClass('bx--list--ordered')).toEqual(true); expect(list.hasClass('some-class')).toEqual(true); }); it('should render children as expected', () => { expect(list.find(ListItem).length).toEqual(1); }); it('should render nested lists', () => { list.setProps({ nested: true }); expect(list.hasClass('bx--list--nested')).toEqual(true); list.setProps({ nested: false }); expect(list.hasClass('bx--list--nested')).toEqual(false); }); }); });
demo/index.js
markmur/react-slack-feedback
/* eslint-disable import/no-unassigned-import */ import React from 'react' import ReactDOM from 'react-dom' import fetch from 'isomorphic-fetch' import styled from 'styled-components' import SyntaxHighlighter, { registerLanguage } from 'react-syntax-highlighter/dist/prism-light' import jsx from 'react-syntax-highlighter/dist/languages/prism/jsx' import json from 'react-syntax-highlighter/dist/languages/prism/json' import syntax from 'react-syntax-highlighter/dist/styles/prism/atom-dark' import SlackFeedback from '../src/slack-feedback' import defaultTheme from '../src/themes/default' import darkTheme from '../src/themes/dark' import { version } from '../package' import './index.css' registerLanguage('json', json) registerLanguage('jsx', jsx) const themes = { default: defaultTheme, dark: darkTheme } const root = document.querySelector('#root') const parseJSON = res => res.json() const API_URL = 'http://localhost:8080/api' const sendToSlack = (payload, success, error) => { if (process.env.USE_SERVER) { return success() } return fetch(`${API_URL}/slack`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }) .then(res => { if (!res.ok) { error(res) throw res } return res }) .then(parseJSON) .then(success) } function uploadImage(file, success, error) { if (process.env.USE_SERVER) { return success(file.preview) } const form = new FormData() form.append('image', file) fetch(`${API_URL}/upload`, { method: 'POST', body: form }) .then(res => { if (res.status < 200 || res.status >= 300) { error(res.statusText) throw res } return res.json() }) .then(({ url }) => success(url)) } const Button = styled.button` border-radius: 4px; outline: none; font-size: 15px; padding: 1em 2em; background: white; margin-right: 1em; cursor: pointer; font-weight: 600; margin-bottom: 2em; box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.05); transition: all 0.2s; border: 2px solid ${p => (p.selected ? '#0087ff' : 'transparent')}; &:hover { box-shadow: 0 2px 14px 0 rgba(0, 0, 0, 0.1); } ` const App = () => { const [theme, setTheme] = React.useState('default') return ( <div> <h1>React Slack Feedback</h1> <p>Latest: {version}</p> <h3>Choose theme</h3> <Button selected={theme === 'default'} onClick={() => setTheme('default')} > Default </Button> <Button selected={theme === 'dark'} onClick={() => setTheme('dark')}> Dark </Button> <h3>Usage</h3> <h5>Install module + peer dependencies</h5> <SyntaxHighlighter language="jsx" style={syntax}> {`yarn add react-slack-feedback styled-components`} </SyntaxHighlighter> <SyntaxHighlighter language="jsx" style={syntax}> {`import SlackFeedback from 'react-slack-feedback' <SlackFeedback open channel="#feedback" disabled={false} errorTimeout={8 * 1000} icon={() => <SlackIcon />} onClose={() => {}} onOpen={() => {}} sentTimeout={5 * 1000} showChannel={true} showIcon={true} theme={defaultTheme} translations={defaultTranslations} user="Anonymous" onSubmit={(payload, success, error) => {}} onImageUpload={(file, success, error) => {}} />`} </SyntaxHighlighter> <h5>CURRENT THEME</h5> <SyntaxHighlighter language="json" style={syntax}> {JSON.stringify(themes[theme], null, 2)} </SyntaxHighlighter> <SlackFeedback open theme={themes[theme]} channel="#feedback" onSubmit={(payload, success, error) => sendToSlack(payload, success, error) } onImageUpload={(file, success, error) => uploadImage(file, success, error) } /> </div> ) } ReactDOM.render(<App />, root)
ajax/libs/js-data/2.2.0/js-data-debug.min.js
schoren/cdnjs
/*! * js-data * @version 2.2.0 - Homepage <http://www.js-data.io/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2014-2015 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Robust framework-agnostic data store. */ (function webpackUniversalModuleDefinition(a,b){if(typeof exports==="object"&&typeof module==="object"){module.exports=b()}else{if(typeof define==="function"&&define.amd){define(b)}else{if(typeof exports==="object"){exports.JSData=b()}else{a.JSData=b()}}}})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)})([function(module,exports,__webpack_require__){var _datastoreIndex=__webpack_require__(1);var _utils=__webpack_require__(2);var _errors=__webpack_require__(3);module.exports={DS:_datastoreIndex["default"],DSUtils:_utils["default"],DSErrors:_errors["default"],createStore:function createStore(options){return new _datastoreIndex["default"](options)},version:{full:"2.2.0",major:parseInt("2",10),minor:parseInt("2",10),patch:parseInt("0",10),alpha:true?"false":false,beta:true?"false":false}}},function(module,exports,__webpack_require__){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}})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var _utils=__webpack_require__(2);var _errors=__webpack_require__(3);var _sync_methodsIndex=__webpack_require__(5);var _async_methodsIndex=__webpack_require__(6);function lifecycleNoopCb(resource,attrs,cb){cb(null,attrs)}function lifecycleNoop(resource,attrs){return attrs}function compare(_x,_x2,_x3,_x4){var _again=true;_function:while(_again){var orderBy=_x,index=_x2,a=_x3,b=_x4;def=cA=cB=undefined;_again=false;var def=orderBy[index];var cA=_utils["default"].get(a,def[0]),cB=_utils["default"].get(b,def[0]);if(_utils["default"]._s(cA)){cA=_utils["default"].upperCase(cA)}if(_utils["default"]._s(cB)){cB=_utils["default"].upperCase(cB)}if(def[1]==="DESC"){if(cB<cA){return -1}else{if(cB>cA){return 1}else{if(index<orderBy.length-1){_x=orderBy;_x2=index+1;_x3=a;_x4=b;_again=true;continue _function}else{return 0}}}}else{if(cA<cB){return -1}else{if(cA>cB){return 1}else{if(index<orderBy.length-1){_x=orderBy;_x2=index+1;_x3=a;_x4=b;_again=true;continue _function}else{return 0}}}}}}var Defaults=(function(){function Defaults(){_classCallCheck(this,Defaults)}_createClass(Defaults,[{key:"errorFn",value:function errorFn(a,b){if(this.error&&typeof this.error==="function"){try{if(typeof a==="string"){throw new Error(a)}else{throw a}}catch(err){a=err}this.error(this.name||null,a||null,b||null)}}}]);return Defaults})();var defaultsPrototype=Defaults.prototype;defaultsPrototype.actions={};defaultsPrototype.afterCreate=lifecycleNoopCb;defaultsPrototype.afterCreateCollection=lifecycleNoop;defaultsPrototype.afterCreateInstance=lifecycleNoop;defaultsPrototype.afterDestroy=lifecycleNoopCb;defaultsPrototype.afterEject=lifecycleNoop;defaultsPrototype.afterInject=lifecycleNoop;defaultsPrototype.afterReap=lifecycleNoop;defaultsPrototype.afterUpdate=lifecycleNoopCb;defaultsPrototype.afterValidate=lifecycleNoopCb;defaultsPrototype.allowSimpleWhere=true;defaultsPrototype.basePath="";defaultsPrototype.beforeCreate=lifecycleNoopCb;defaultsPrototype.beforeCreateCollection=lifecycleNoop;defaultsPrototype.beforeCreateInstance=lifecycleNoop;defaultsPrototype.beforeDestroy=lifecycleNoopCb;defaultsPrototype.beforeEject=lifecycleNoop;defaultsPrototype.beforeInject=lifecycleNoop;defaultsPrototype.beforeReap=lifecycleNoop;defaultsPrototype.beforeUpdate=lifecycleNoopCb;defaultsPrototype.beforeValidate=lifecycleNoopCb;defaultsPrototype.bypassCache=false;defaultsPrototype.cacheResponse=!!_utils["default"].w;defaultsPrototype.clearEmptyQueries=true;defaultsPrototype.computed={};defaultsPrototype.defaultAdapter="http";defaultsPrototype.debug=false;defaultsPrototype.defaultValues={};defaultsPrototype.eagerEject=false;defaultsPrototype.eagerInject=false;defaultsPrototype.endpoint="";defaultsPrototype.error=console?function(a,b,c){return console[typeof console.error==="function"?"error":"log"](a,b,c)}:false;defaultsPrototype.fallbackAdapters=["http"];defaultsPrototype.findStrictCache=false;defaultsPrototype.idAttribute="id";defaultsPrototype.ignoredChanges=[/\$/];defaultsPrototype.instanceEvents=!!_utils["default"].w;defaultsPrototype.keepChangeHistory=false;defaultsPrototype.linkRelations=true;defaultsPrototype.log=console?function(a,b,c,d,e){return console[typeof console.info==="function"?"info":"log"](a,b,c,d,e)}:false;defaultsPrototype.logFn=function(a,b,c,d){var _this=this;if(_this.debug&&_this.log&&typeof _this.log==="function"){_this.log(_this.name||null,a||null,b||null,c||null,d||null)}};defaultsPrototype.maxAge=false;defaultsPrototype.methods={};defaultsPrototype.notify=!!_utils["default"].w;defaultsPrototype.omit=[];defaultsPrototype.onConflict="merge";defaultsPrototype.reapAction=!!_utils["default"].w?"inject":"none";defaultsPrototype.reapInterval=!!_utils["default"].w?30000:false;defaultsPrototype.relationsEnumerable=false;defaultsPrototype.resetHistoryOnInject=true;defaultsPrototype.returnMeta=false;defaultsPrototype.strategy="single";defaultsPrototype.upsert=!!_utils["default"].w;defaultsPrototype.useClass=true;defaultsPrototype.useFilter=false;defaultsPrototype.validate=lifecycleNoopCb;defaultsPrototype.defaultFilter=function(collection,resourceName,params,options){var filtered=collection;var where=null;var reserved={skip:"",offset:"",where:"",limit:"",orderBy:"",sort:""};params=params||{};options=options||{};if(_utils["default"]._o(params.where)){where=params.where}else{where={}}if(options.allowSimpleWhere){_utils["default"].forOwn(params,function(value,key){if(!(key in reserved)&&!(key in where)){where[key]={"==":value}}})}if(_utils["default"].isEmpty(where)){where=null}if(where){filtered=_utils["default"].filter(filtered,function(attrs){var first=true;var keep=true;_utils["default"].forOwn(where,function(clause,field){if(!_utils["default"]._o(clause)){clause={"==":clause}}_utils["default"].forOwn(clause,function(term,op){var expr=undefined;var isOr=op[0]==="|";var val=_utils["default"].get(attrs,field);op=isOr?op.substr(1):op;if(op==="=="){expr=val==term}else{if(op==="==="){expr=val===term}else{if(op==="!="){expr=val!=term}else{if(op==="!=="){expr=val!==term}else{if(op===">"){expr=val>term}else{if(op===">="){expr=val>=term}else{if(op==="<"){expr=val<term}else{if(op==="<="){expr=val<=term}else{if(op==="isectEmpty"){expr=!_utils["default"].intersection(val||[],term||[]).length}else{if(op==="isectNotEmpty"){expr=_utils["default"].intersection(val||[],term||[]).length}else{if(op==="in"){if(_utils["default"]._s(term)){expr=term.indexOf(val)!==-1}else{expr=_utils["default"].contains(term,val)}}else{if(op==="notIn"){if(_utils["default"]._s(term)){expr=term.indexOf(val)===-1}else{expr=!_utils["default"].contains(term,val)}}else{if(op==="contains"){if(_utils["default"]._s(val)){expr=val.indexOf(term)!==-1}else{expr=_utils["default"].contains(val,term)}}else{if(op==="notContains"){if(_utils["default"]._s(val)){expr=val.indexOf(term)===-1}else{expr=!_utils["default"].contains(val,term)}}}}}}}}}}}}}}}if(expr!==undefined){keep=first?expr:isOr?keep||expr:keep&&expr}first=false})});return keep})}var orderBy=null;if(_utils["default"]._s(params.orderBy)){orderBy=[[params.orderBy,"ASC"]]}else{if(_utils["default"]._a(params.orderBy)){orderBy=params.orderBy}}if(!orderBy&&_utils["default"]._s(params.sort)){orderBy=[[params.sort,"ASC"]]}else{if(!orderBy&&_utils["default"]._a(params.sort)){orderBy=params.sort}}if(orderBy){(function(){var index=0;_utils["default"].forEach(orderBy,function(def,i){if(_utils["default"]._s(def)){orderBy[i]=[def,"ASC"]}else{if(!_utils["default"]._a(def)){throw new _errors["default"].IA('DS.filter("'+resourceName+'"[, params][, options]): '+_utils["default"].toJson(def)+": Must be a string or an array!",{params:{"orderBy[i]":{actual:typeof def,expected:"string|array"}}})}}});filtered=_utils["default"].sort(filtered,function(a,b){return compare(orderBy,index,a,b)})})()}var limit=_utils["default"]._n(params.limit)?params.limit:null;var skip=null;if(_utils["default"]._n(params.skip)){skip=params.skip}else{if(_utils["default"]._n(params.offset)){skip=params.offset}}if(limit&&skip){filtered=_utils["default"].slice(filtered,skip,Math.min(filtered.length,skip+limit))}else{if(_utils["default"]._n(limit)){filtered=_utils["default"].slice(filtered,0,Math.min(filtered.length,limit))}else{if(_utils["default"]._n(skip)){if(skip<filtered.length){filtered=_utils["default"].slice(filtered,skip)}else{filtered=[]}}}}if(filtered===collection){return filtered.slice()}else{return filtered}};var DS=(function(){function DS(options){_classCallCheck(this,DS);var _this=this;options=options||{};_this.store={};_this.s=_this.store;_this.definitions={};_this.defs=_this.definitions;_this.adapters={};_this.defaults=new Defaults();_this.observe=_utils["default"].observe;_utils["default"].forOwn(options,function(v,k){if(k==="omit"){_this.defaults.omit=v.concat(Defaults.prototype.omit)}else{_this.defaults[k]=v}});_this.defaults.logFn("new data store created",_this.defaults);var P=_utils["default"].Promise;if(P&&!P.prototype.spread){P.prototype.spread=function(cb){return this.then(function(arr){return cb.apply(this,arr)})}}_utils["default"].Events(_this)}_createClass(DS,[{key:"getAdapterName",value:function getAdapterName(options){var errorIfNotExist=false;options=options||{};this.defaults.logFn("getAdapterName",options);if(_utils["default"]._s(options)){errorIfNotExist=true;options={adapter:options}}if(this.adapters[options.adapter]){return options.adapter}else{if(errorIfNotExist){throw new Error(options.adapter+" is not a registered adapter!")}else{return options.defaultAdapter}}}},{key:"getAdapter",value:function getAdapter(options){options=options||{};this.defaults.logFn("getAdapter",options);return this.adapters[this.getAdapterName(options)]}},{key:"registerAdapter",value:function registerAdapter(name,Adapter,options){var _this=this;options=options||{};_this.defaults.logFn("registerAdapter",name,Adapter,options);if(_utils["default"].isFunction(Adapter)){_this.adapters[name]=new Adapter(options)}else{_this.adapters[name]=Adapter}if(options["default"]){_this.defaults.defaultAdapter=name}_this.defaults.logFn("default adapter is "+_this.defaults.defaultAdapter)}},{key:"is",value:function is(resourceName,instance){var definition=this.defs[resourceName];if(!definition){throw new _errors["default"].NER(resourceName)}return instance instanceof definition[definition["class"]]}},{key:"clear",value:function clear(){var _this2=this;var ejected={};_utils["default"].forOwn(this.definitions,function(definition){var name=definition.name;ejected[name]=definition.ejectAll();_this2.store[name].completedQueries={};_this2.store[name].queryData={}});return ejected}}]);return DS})();var dsPrototype=DS.prototype;dsPrototype.getAdapterName.shorthand=false;dsPrototype.getAdapter.shorthand=false;dsPrototype.registerAdapter.shorthand=false;dsPrototype.errors=_errors["default"];dsPrototype.utils=_utils["default"];function addMethods(target,obj){_utils["default"].forOwn(obj,function(v,k){target[k]=v;target[k].before=function(fn){var orig=target[k];target[k]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}return orig.apply(this,fn.apply(this,args)||args)}}})}addMethods(dsPrototype,_sync_methodsIndex["default"]);addMethods(dsPrototype,_async_methodsIndex["default"]);exports["default"]=DS},function(module,exports,__webpack_require__){var _errors=__webpack_require__(3);var BinaryHeap=__webpack_require__(7);var forEach=__webpack_require__(8);var slice=__webpack_require__(9);var forOwn=__webpack_require__(13);var contains=__webpack_require__(10);var deepMixIn=__webpack_require__(14);var pascalCase=__webpack_require__(19);var remove=__webpack_require__(11);var pick=__webpack_require__(15);var _keys=__webpack_require__(16);var sort=__webpack_require__(12);var upperCase=__webpack_require__(20);var get=__webpack_require__(17);var set=__webpack_require__(18);var observe=__webpack_require__(4);var w=undefined;var objectProto=Object.prototype;var toString=objectProto.toString;var P=undefined;try{P=Promise}catch(err){console.error("js-data requires a global Promise constructor!")}var isArray=Array.isArray||function isArray(value){return toString.call(value)=="[object Array]"||false};var isRegExp=function isRegExp(value){return toString.call(value)=="[object RegExp]"||false};var isString=function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)=="[object String]"||false};var isObject=function isObject(value){return toString.call(value)=="[object Object]"||false};var isDate=function isDate(value){return value&&typeof value=="object"&&toString.call(value)=="[object Date]"||false};var isNumber=function isNumber(value){var type=typeof value;return type=="number"||value&&type=="object"&&toString.call(value)=="[object Number]"||false};var isFunction=function isFunction(value){return typeof value=="function"||value&&toString.call(value)==="[object Function]"||false};var isStringOrNumber=function isStringOrNumber(value){return isString(value)||isNumber(value)};var isStringOrNumberErr=function isStringOrNumberErr(field){return new _errors["default"].IA('"'+field+'" must be a string or a number!')};var isObjectErr=function isObjectErr(field){return new _errors["default"].IA('"'+field+'" must be an object!')};var isArrayErr=function isArrayErr(field){return new _errors["default"].IA('"'+field+'" must be an array!')};var isEmpty=function isEmpty(val){if(val==null){return true}else{if(typeof val==="string"||isArray(val)){return !val.length}else{if(typeof val==="object"){var result=true;forOwn(val,function(){result=false;return false});return result}else{return true}}}};var intersection=function intersection(array1,array2){if(!array1||!array2){return[]}var result=[];var item=undefined;for(var i=0,_length=array1.length;i<_length;i++){item=array1[i];if(contains(result,item)){continue}if(contains(array2,item)){result.push(item)}}return result};var filter=function filter(array,cb,thisObj){var results=[];forEach(array,function(value,key,arr){if(cb(value,key,arr)){results.push(value)}},thisObj);return results};try{w=window;w={}}catch(e){w=null}function Events(target){var events={};target=target||this;target.on=function(type,func,ctx){events[type]=events[type]||[];events[type].push({f:func,c:ctx})};target.off=function(type,func){var listeners=events[type];if(!listeners){events={}}else{if(func){for(var i=0;i<listeners.length;i++){if(listeners[i]===func){listeners.splice(i,1);break}}}else{listeners.splice(0,listeners.length)}}};target.emit=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var listeners=events[args.shift()]||[];if(listeners){for(var i=0;i<listeners.length;i++){listeners[i].f.apply(listeners[i].c,args)}}}}var toPromisify=["beforeValidate","validate","afterValidate","beforeCreate","afterCreate","beforeUpdate","afterUpdate","beforeDestroy","afterDestroy"];var isBlacklisted=observe.isBlacklisted;var copy=function copy(source,destination,stackSource,stackDest,blacklist){if(!destination){destination=source;if(source){if(isArray(source)){destination=copy(source,[],stackSource,stackDest,blacklist)}else{if(isDate(source)){destination=new Date(source.getTime())}else{if(isRegExp(source)){destination=new RegExp(source.source,source.toString().match(/[^\/]*$/)[0]);destination.lastIndex=source.lastIndex}else{if(isObject(source)){destination=copy(source,Object.create(Object.getPrototypeOf(source)),stackSource,stackDest,blacklist)}}}}}}else{if(source===destination){throw new Error("Cannot copy! Source and destination are identical.")}stackSource=stackSource||[];stackDest=stackDest||[];if(isObject(source)){var index=stackSource.indexOf(source);if(index!==-1){return stackDest[index]}stackSource.push(source);stackDest.push(destination)}var result=undefined;if(isArray(source)){var i=undefined;destination.length=0;for(i=0;i<source.length;i++){result=copy(source[i],null,stackSource,stackDest,blacklist);if(isObject(source[i])){stackSource.push(source[i]);stackDest.push(result)}destination.push(result)}}else{if(isArray(destination)){destination.length=0}else{forEach(destination,function(value,key){delete destination[key]})}for(var key in source){if(source.hasOwnProperty(key)){if(isBlacklisted(key,blacklist)){continue}result=copy(source[key],null,stackSource,stackDest,blacklist);if(isObject(source[key])){stackSource.push(source[key]);stackDest.push(result)}destination[key]=result}}}}return destination};var equals=function equals(_x,_x2){var _again=true;_function:while(_again){var o1=_x,o2=_x2;t1=t2=length=key=keySet=undefined;_again=false;if(o1===o2){return true}if(o1===null||o2===null){return false}if(o1!==o1&&o2!==o2){return true}var t1=typeof o1,t2=typeof o2,length,key,keySet;if(t1==t2){if(t1=="object"){if(isArray(o1)){if(!isArray(o2)){return false}if((length=o1.length)==o2.length){for(key=0;key<length;key++){if(!equals(o1[key],o2[key])){return false}}return true}}else{if(isDate(o1)){if(!isDate(o2)){return false}_x=o1.getTime();_x2=o2.getTime();_again=true;continue _function}else{if(isRegExp(o1)&&isRegExp(o2)){return o1.toString()==o2.toString()}else{if(isArray(o2)){return false}keySet={};for(key in o1){if(key.charAt(0)==="$"||isFunction(o1[key])){continue}if(!equals(o1[key],o2[key])){return false}keySet[key]=true}for(key in o2){if(!keySet.hasOwnProperty(key)&&key.charAt(0)!=="$"&&o2[key]!==undefined&&!isFunction(o2[key])){return false}}return true}}}}}return false}};var resolveId=function resolveId(definition,idOrInstance){if(isString(idOrInstance)||isNumber(idOrInstance)){return idOrInstance}else{if(idOrInstance&&definition){return idOrInstance[definition.idAttribute]||idOrInstance}else{return idOrInstance}}};var resolveItem=function resolveItem(resource,idOrInstance){if(resource&&(isString(idOrInstance)||isNumber(idOrInstance))){return resource.index[idOrInstance]||idOrInstance}else{return idOrInstance}};var isValidString=function isValidString(val){return val!=null&&val!==""};var join=function join(items,separator){separator=separator||"";return filter(items,isValidString).join(separator)};var makePath=function makePath(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}var result=join(args,"/");return result.replace(/([^:\/]|^)\/{2,}/g,"$1/")};exports["default"]={Promise:P,_:function _(parent,options){var _this=this;options=options||{};if(options&&options.constructor===parent.constructor){return options}else{if(!isObject(options)){throw new _errors["default"].IA('"options" must be an object!')}}forEach(toPromisify,function(name){if(typeof options[name]==="function"&&options[name].toString().indexOf("for (var _len = arg")===-1){options[name]=_this.promisify(options[name])}});var O=function Options(attrs){var self=this;forOwn(attrs,function(value,key){self[key]=value})};O.prototype=parent;O.prototype.orig=function(){var orig={};forOwn(this,function(value,key){orig[key]=value});return orig};return new O(options)},_n:isNumber,_s:isString,_sn:isStringOrNumber,_snErr:isStringOrNumberErr,_o:isObject,_oErr:isObjectErr,_a:isArray,_aErr:isArrayErr,compute:function compute(fn,field){var _this=this;var args=[];forEach(fn.deps,function(dep){args.push(get(_this,dep))});set(_this,field,fn[fn.length-1].apply(_this,args))},contains:contains,copy:copy,deepMixIn:deepMixIn,diffObjectFromOldObject:observe.diffObjectFromOldObject,BinaryHeap:BinaryHeap,equals:equals,Events:Events,filter:filter,fillIn:function fillIn(target,obj){forOwn(obj,function(v,k){if(!(k in target)){target[k]=v}});return target},forEach:forEach,forOwn:forOwn,fromJson:function fromJson(json){return isString(json)?JSON.parse(json):json},get:get,intersection:intersection,isArray:isArray,isBlacklisted:isBlacklisted,isEmpty:isEmpty,isFunction:isFunction,isObject:isObject,isNumber:isNumber,isString:isString,keys:_keys,makePath:makePath,observe:observe,omit:function omit(obj,bl){var toRemove=[];forOwn(obj,function(v,k){if(isBlacklisted(k,bl)){toRemove.push(k)}});forEach(toRemove,function(k){delete obj[k]});return obj},pascalCase:pascalCase,pick:pick,promisify:function promisify(fn,target){var _this=this;if(!fn){return}else{if(typeof fn!=="function"){throw new Error("Can only promisify functions!")}}return function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}return new _this.Promise(function(resolve,reject){args.push(function(err,result){if(err){reject(err)}else{resolve(result)}});try{var promise=fn.apply(target||this,args);if(promise&&promise.then){promise.then(resolve,reject)}}catch(err){reject(err)}})}},remove:remove,set:set,slice:slice,sort:sort,toJson:JSON.stringify,updateTimestamp:function updateTimestamp(timestamp){var newTimestamp=typeof Date.now==="function"?Date.now():new Date().getTime();if(timestamp&&newTimestamp<=timestamp){return timestamp+1}else{return newTimestamp}},upperCase:upperCase,removeCircular:function removeCircular(object){return(function rmCirc(value,ctx){var i=undefined;var nu=undefined;if(typeof value==="object"&&value!==null&&!(value instanceof Boolean)&&!(value instanceof Date)&&!(value instanceof Number)&&!(value instanceof RegExp)&&!(value instanceof String)){var cur=ctx.cur;var parent=ctx.ctx;while(parent){if(parent.cur===cur){return undefined}parent=parent.ctx}if(isArray(value)){nu=[];for(i=0;i<value.length;i+=1){nu[i]=rmCirc(value[i],{ctx:ctx,cur:value[i]})}}else{nu={};forOwn(value,function(v,k){nu[k]=rmCirc(value[k],{ctx:ctx,cur:value[k]})})}return nu}return value})(object,{ctx:null,cur:object})},resolveItem:resolveItem,resolveId:resolveId,respond:function respond(response,meta,options){if(options.returnMeta==="array"){return[response,meta]}else{if(options.returnMeta==="object"){return{response:response,meta:meta}}else{return response}}},w:w,applyRelationGettersToTarget:function applyRelationGettersToTarget(store,definition,target){this.forEach(definition.relationList,function(def){var relationName=def.relation;var localField=def.localField;var localKey=def.localKey;var foreignKey=def.foreignKey;var localKeys=def.localKeys;var enumerable=typeof def.enumerable==="boolean"?def.enumerable:!!definition.relationsEnumerable;if(typeof def.link==="boolean"?def.link:!!definition.linkRelations){delete target[localField];var prop={enumerable:enumerable,set:function set(){}};if(def.type==="belongsTo"){prop.get=function(){return this[localKey]?definition.getResource(relationName).get(this[localKey]):undefined}}else{if(def.type==="hasMany"){prop.get=function(){var params={};if(foreignKey){params[foreignKey]=this[definition.idAttribute];return definition.getResource(relationName).defaultFilter.call(store,store.s[relationName].collection,relationName,params,{allowSimpleWhere:true})}else{if(localKeys){var keys=this[localKeys]||[];return definition.getResource(relationName).getAll(isArray(keys)?keys:_keys(keys))}}return undefined}}else{if(def.type==="hasOne"){if(localKey){prop.get=function(){return this[localKey]?definition.getResource(relationName).get(this[localKey]):undefined}}else{prop.get=function(){var params={};params[foreignKey]=this[definition.idAttribute];var items=params[foreignKey]?definition.getResource(relationName).defaultFilter.call(store,store.s[relationName].collection,relationName,params,{allowSimpleWhere:true}):[];if(items.length){return items[0]}return undefined}}}}}if(def.get){(function(){var orig=prop.get;prop.get=function(){var _this2=this;return def.get(definition,def,this,function(){for(var _len4=arguments.length,args=Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return orig.apply(_this2,args)})}})()}Object.defineProperty(target,def.localField,prop)}})}}},function(module,exports,__webpack_require__){var _get=function get(_x,_x2,_x3){var _again=true;_function:while(_again){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=undefined;_again=false;if(object===null){object=Function.prototype}var desc=Object.getOwnPropertyDescriptor(object,property);if(desc===undefined){var parent=Object.getPrototypeOf(object);if(parent===null){return undefined}else{_x=parent;_x2=property;_x3=receiver;_again=true;continue _function}}else{if("value" in desc){return desc.value}else{var getter=desc.get;if(getter===undefined){return undefined}return getter.call(receiver)}}}};function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}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){subClass.__proto__=superClass}}var IllegalArgumentError=(function(_Error){function IllegalArgumentError(message){_classCallCheck(this,IllegalArgumentError);_get(Object.getPrototypeOf(IllegalArgumentError.prototype),"constructor",this).call(this);if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}this.type=this.constructor.name;this.message=message}_inherits(IllegalArgumentError,_Error);return IllegalArgumentError})(Error);var RuntimeError=(function(_Error2){function RuntimeError(message){_classCallCheck(this,RuntimeError);_get(Object.getPrototypeOf(RuntimeError.prototype),"constructor",this).call(this);if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}this.type=this.constructor.name;this.message=message}_inherits(RuntimeError,_Error2);return RuntimeError})(Error);var NonexistentResourceError=(function(_Error3){function NonexistentResourceError(resourceName){_classCallCheck(this,NonexistentResourceError);_get(Object.getPrototypeOf(NonexistentResourceError.prototype),"constructor",this).call(this);if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(this,this.constructor)}this.type=this.constructor.name;this.message=resourceName+" is not a registered resource!"}_inherits(NonexistentResourceError,_Error3);return NonexistentResourceError})(Error);exports["default"]={IllegalArgumentError:IllegalArgumentError,IA:IllegalArgumentError,RuntimeError:RuntimeError,R:RuntimeError,NonexistentResourceError:NonexistentResourceError,NER:NonexistentResourceError}},function(module,exports,__webpack_require__){(function(global){var testingExposeCycleCount=global.testingExposeCycleCount;function detectObjectObserve(){if(typeof Object.observe!=="function"||typeof Array.observe!=="function"){return false}var records=[];function callback(recs){records=recs}var test={};var arr=[];Object.observe(test,callback);Array.observe(arr,callback);test.id=1;test.id=2;delete test.id;arr.push(1,2);arr.length=0;Object.deliverChangeRecords(callback);if(records.length!==5){return false}if(records[0].type!="add"||records[1].type!="update"||records[2].type!="delete"||records[3].type!="splice"||records[4].type!="splice"){return false}Object.unobserve(test,callback);Array.unobserve(arr,callback);return true}var hasObserve=detectObjectObserve();var createObject=("__proto__" in {})?function(obj){return obj}:function(obj){var proto=obj.__proto__;if(!proto){return obj}var newObject=Object.create(proto);Object.getOwnPropertyNames(obj).forEach(function(name){Object.defineProperty(newObject,name,Object.getOwnPropertyDescriptor(obj,name))});return newObject};var MAX_DIRTY_CHECK_CYCLES=1000;function dirtyCheck(observer){var cycles=0;while(cycles<MAX_DIRTY_CHECK_CYCLES&&observer.check_()){cycles++}if(testingExposeCycleCount){global.dirtyCheckCycleCount=cycles}return cycles>0}function objectIsEmpty(object){for(var prop in object){return false}return true}function diffIsEmpty(diff){return objectIsEmpty(diff.added)&&objectIsEmpty(diff.removed)&&objectIsEmpty(diff.changed)}function isBlacklisted(prop,bl){if(!bl||!bl.length){return false}var matches;for(var i=0;i<bl.length;i++){if((Object.prototype.toString.call(bl[i])==="[object RegExp]"&&bl[i].test(prop))||bl[i]===prop){return matches=prop}}return !!matches}function diffObjectFromOldObject(object,oldObject,equals,bl){var added={};var removed={};var changed={};for(var prop in oldObject){var newValue=object[prop];if(isBlacklisted(prop,bl)){continue}if(newValue!==undefined&&(equals?equals(newValue,oldObject[prop]):newValue===oldObject[prop])){continue}if(!(prop in object)){removed[prop]=undefined;continue}if(equals?!equals(newValue,oldObject[prop]):newValue!==oldObject[prop]){changed[prop]=newValue}}for(var prop in object){if(prop in oldObject){continue}if(isBlacklisted(prop,bl)){continue}added[prop]=object[prop]}if(Array.isArray(object)&&object.length!==oldObject.length){changed.length=object.length}return{added:added,removed:removed,changed:changed}}var eomTasks=[];function runEOMTasks(){if(!eomTasks.length){return false}for(var i=0;i<eomTasks.length;i++){eomTasks[i]()}eomTasks.length=0;return true}var runEOM=hasObserve?(function(){return function(fn){return Promise.resolve().then(fn)}})():(function(){return function(fn){eomTasks.push(fn)}})();var observedObjectCache=[];function newObservedObject(){var observer;var object;var discardRecords=false;var first=true;function callback(records){if(observer&&observer.state_===OPENED&&!discardRecords){observer.check_(records)}}return{open:function(obs){if(observer){throw Error("ObservedObject in use")}if(!first){Object.deliverChangeRecords(callback)}observer=obs;first=false},observe:function(obj,arrayObserve){object=obj;if(arrayObserve){Array.observe(object,callback)}else{Object.observe(object,callback)}},deliver:function(discard){discardRecords=discard;Object.deliverChangeRecords(callback);discardRecords=false},close:function(){observer=undefined;Object.unobserve(object,callback);observedObjectCache.push(this)}}}function getObservedObject(observer,object,arrayObserve){var dir=observedObjectCache.pop()||newObservedObject();dir.open(observer);dir.observe(object,arrayObserve);return dir}var UNOPENED=0;var OPENED=1;var CLOSED=2;var nextObserverId=1;function Observer(){this.state_=UNOPENED;this.callback_=undefined;this.target_=undefined;this.directObserver_=undefined;this.value_=undefined;this.id_=nextObserverId++}Observer.prototype={open:function(callback,target){if(this.state_!=UNOPENED){throw Error("Observer has already been opened.")}addToAll(this);this.callback_=callback;this.target_=target;this.connect_();this.state_=OPENED;return this.value_},close:function(){if(this.state_!=OPENED){return}removeFromAll(this);this.disconnect_();this.value_=undefined;this.callback_=undefined;this.target_=undefined;this.state_=CLOSED},deliver:function(){if(this.state_!=OPENED){return}dirtyCheck(this)},report_:function(changes){try{this.callback_.apply(this.target_,changes)}catch(ex){Observer._errorThrownDuringCallback=true;console.error("Exception caught during observer callback: "+(ex.stack||ex))}},discardChanges:function(){this.check_(undefined,true);return this.value_}};var collectObservers=!hasObserve;var allObservers;Observer._allObserversCount=0;if(collectObservers){allObservers=[]}function addToAll(observer){Observer._allObserversCount++;if(!collectObservers){return}allObservers.push(observer)}function removeFromAll(observer){Observer._allObserversCount--}var runningMicrotaskCheckpoint=false;global.Platform=global.Platform||{};global.Platform.performMicrotaskCheckpoint=function(){if(runningMicrotaskCheckpoint){return}if(!collectObservers){return}runningMicrotaskCheckpoint=true;var cycles=0;var anyChanged,toCheck;do{cycles++;toCheck=allObservers;allObservers=[];anyChanged=false;for(var i=0;i<toCheck.length;i++){var observer=toCheck[i];if(observer.state_!=OPENED){continue}if(observer.check_()){anyChanged=true}allObservers.push(observer)}if(runEOMTasks()){anyChanged=true}}while(cycles<MAX_DIRTY_CHECK_CYCLES&&anyChanged);if(testingExposeCycleCount){global.dirtyCheckCycleCount=cycles}runningMicrotaskCheckpoint=false};if(collectObservers){global.Platform.clearObservers=function(){allObservers=[]}}function ObjectObserver(object){Observer.call(this);this.value_=object;this.oldObject_=undefined}ObjectObserver.prototype=createObject({__proto__:Observer.prototype,arrayObserve:false,connect_:function(callback,target){if(hasObserve){this.directObserver_=getObservedObject(this,this.value_,this.arrayObserve)}else{this.oldObject_=this.copyObject(this.value_)}},copyObject:function(object){var copy=Array.isArray(object)?[]:{};for(var prop in object){copy[prop]=object[prop]}if(Array.isArray(object)){copy.length=object.length}return copy},check_:function(changeRecords,skipChanges){var diff;var oldValues;if(hasObserve){if(!changeRecords){return false}oldValues={};diff=diffObjectFromChangeRecords(this.value_,changeRecords,oldValues)}else{oldValues=this.oldObject_;diff=diffObjectFromOldObject(this.value_,this.oldObject_)}if(diffIsEmpty(diff)){return false}if(!hasObserve){this.oldObject_=this.copyObject(this.value_)}this.report_([diff.added||{},diff.removed||{},diff.changed||{},function(property){return oldValues[property]}]);return true},disconnect_:function(){if(hasObserve){this.directObserver_.close();this.directObserver_=undefined}else{this.oldObject_=undefined}},deliver:function(){if(this.state_!=OPENED){return}if(hasObserve){this.directObserver_.deliver(false)}else{dirtyCheck(this)}},discardChanges:function(){if(this.directObserver_){this.directObserver_.deliver(true)}else{this.oldObject_=this.copyObject(this.value_)}return this.value_}});var observerSentinel={};var expectedRecordTypes={add:true,update:true,"delete":true};function diffObjectFromChangeRecords(object,changeRecords,oldValues){var added={};var removed={};for(var i=0;i<changeRecords.length;i++){var record=changeRecords[i];if(!expectedRecordTypes[record.type]){console.error("Unknown changeRecord type: "+record.type);console.error(record);continue}if(!(record.name in oldValues)){oldValues[record.name]=record.oldValue}if(record.type=="update"){continue}if(record.type=="add"){if(record.name in removed){delete removed[record.name]}else{added[record.name]=true}continue}if(record.name in added){delete added[record.name];delete oldValues[record.name]}else{removed[record.name]=true}}for(var prop in added){added[prop]=object[prop]}for(var prop in removed){removed[prop]=undefined}var changed={};for(var prop in oldValues){if(prop in added||prop in removed){continue}var newValue=object[prop];if(oldValues[prop]!==newValue){changed[prop]=newValue}}return{added:added,removed:removed,changed:changed}}global.Observer=Observer;global.isBlacklisted=isBlacklisted;global.Observer.runEOM_=runEOM;global.Observer.observerSentinel_=observerSentinel;global.Observer.hasObjectObserve=hasObserve;global.diffObjectFromOldObject=diffObjectFromOldObject;global.ObjectObserver=ObjectObserver})(exports)},function(module,exports,__webpack_require__){var _utils=__webpack_require__(2);var _errors=__webpack_require__(3);var NER=_errors["default"].NER;var IA=_errors["default"].IA;var R=_errors["default"].R;var fakeId="DS_"+new Date().getTime();function diffIsEmpty(diff){return !(_utils["default"].isEmpty(diff.added)&&_utils["default"].isEmpty(diff.removed)&&_utils["default"].isEmpty(diff.changed))}function check(fnName,resourceName,id,options){var _this=this;var definition=_this.defs[resourceName];options=options||{};id=_utils["default"].resolveId(definition,id);if(!definition){throw new NER(resourceName)}else{if(!_utils["default"]._sn(id)){throw _utils["default"]._snErr("id")}}id=id===fakeId?undefined:id;options=_utils["default"]._(definition,options);options.logFn(fnName,id,options);return{_this:_this,definition:definition,_resourceName:resourceName,_id:id,_options:options}}exports["default"]={changes:function changes(resourceName,id,options){var _check$call=check.call(this,"changes",resourceName,id,options);var _this=_check$call._this;var definition=_check$call.definition;var _resourceName=_check$call._resourceName;var _id=_check$call._id;var _options=_check$call._options;var item=definition.get(_id);if(item){var _ret=(function(){if(_utils["default"].w){_this.s[_resourceName].observers[_id].deliver()}var ignoredChanges=_options.ignoredChanges||[];_utils["default"].forEach(definition.relationFields,function(field){if(!_utils["default"].contains(ignoredChanges,field)){ignoredChanges.push(field)}});var diff=_utils["default"].diffObjectFromOldObject(item,_this.s[_resourceName].previousAttributes[_id],_utils["default"].equals,ignoredChanges);_utils["default"].forOwn(diff,function(changeset,name){var toKeep=[];_utils["default"].forOwn(changeset,function(value,field){if(!_utils["default"].isFunction(value)){toKeep.push(field)}});diff[name]=_utils["default"].pick(diff[name],toKeep)});_utils["default"].forEach(definition.relationFields,function(field){delete diff.added[field];delete diff.removed[field];delete diff.changed[field]});return{v:diff}})();if(typeof _ret==="object"){return _ret.v}}},changeHistory:function changeHistory(resourceName,id){var _check$call2=check.call(this,"changeHistory",resourceName,id||fakeId);var _this=_check$call2._this;var definition=_check$call2.definition;var _resourceName=_check$call2._resourceName;var _id=_check$call2._id;var resource=_this.s[_resourceName];if(!definition.keepChangeHistory){definition.errorFn("changeHistory is disabled for this resource!")}else{if(_resourceName){var item=definition.get(_id);if(item){return resource.changeHistories[_id]}}else{return resource.changeHistory}}},compute:function compute(resourceName,instance){var _this=this;var definition=_this.defs[resourceName];instance=_utils["default"].resolveItem(_this.s[resourceName],instance);if(!definition){throw new NER(resourceName)}else{if(!instance){throw new R("Item not in the store!")}else{if(!_utils["default"]._o(instance)&&!_utils["default"]._sn(instance)){throw new IA('"instance" must be an object, string or number!')}}}definition.logFn("compute",instance);_utils["default"].forOwn(definition.computed,function(fn,field){_utils["default"].compute.call(instance,fn,field)});return instance},createInstance:function createInstance(resourceName,attrs,options){var definition=this.defs[resourceName];var item=undefined;attrs=attrs||{};if(!definition){throw new NER(resourceName)}else{if(attrs&&!_utils["default"].isObject(attrs)){throw new IA('"attrs" must be an object!')}}options=_utils["default"]._(definition,options);options.logFn("createInstance",attrs,options);options.beforeCreateInstance(options,attrs);var Constructor=definition[definition["class"]];item=new Constructor();if(options.defaultValues){_utils["default"].deepMixIn(item,options.defaultValues)}_utils["default"].deepMixIn(item,attrs);if(definition.computed){definition.compute(item)}options.afterCreateInstance(options,item);return item},createCollection:function createCollection(resourceName,arr,params,options){var _this=this;var definition=_this.defs[resourceName];arr=arr||[];params=params||{};if(!definition){throw new NER(resourceName)}else{if(arr&&!_utils["default"].isArray(arr)){throw new IA('"arr" must be an array!')}}options=_utils["default"]._(definition,options);options.logFn("createCollection",arr,options);options.beforeCreateCollection(options,arr);Object.defineProperties(arr,{fetch:{value:function value(params,options){var __this=this;__this.params=params||__this.params;return definition.findAll(__this.params,options).then(function(data){if(data===__this){return __this}data.unshift(__this.length);data.unshift(0);__this.splice.apply(__this,data);data.shift();data.shift();if(data.$$injected){_this.s[resourceName].queryData[_utils["default"].toJson(__this.params)]=__this;__this.$$injected=true}return __this})}},params:{value:params,writable:true},resourceName:{value:resourceName}});options.afterCreateCollection(options,arr);return arr},defineResource:__webpack_require__(29),digest:function digest(){this.observe.Platform.performMicrotaskCheckpoint()},eject:__webpack_require__(30),ejectAll:__webpack_require__(31),filter:__webpack_require__(32),get:function get(resourceName,id){var _check$call3=check.call(this,"get",resourceName,id);var _this=_check$call3._this;var _resourceName=_check$call3._resourceName;var _id=_check$call3._id;return _this.s[_resourceName].index[_id]},getAll:function getAll(resourceName,ids){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var collection=[];if(!definition){throw new NER(resourceName)}else{if(ids&&!_utils["default"]._a(ids)){throw _utils["default"]._aErr("ids")}}definition.logFn("getAll",ids);if(_utils["default"]._a(ids)){var _length=ids.length;for(var i=0;i<_length;i++){if(resource.index[ids[i]]){collection.push(resource.index[ids[i]])}}}else{collection=resource.collection.slice()}return collection},hasChanges:function hasChanges(resourceName,id){var _check$call4=check.call(this,"hasChanges",resourceName,id);var definition=_check$call4.definition;var _id=_check$call4._id;return definition.get(_id)?diffIsEmpty(definition.changes(_id)):false},inject:__webpack_require__(33),lastModified:function lastModified(resourceName,id){var _check$call5=check.call(this,"lastModified",resourceName,id||fakeId);var _this=_check$call5._this;var _resourceName=_check$call5._resourceName;var _id=_check$call5._id;var resource=_this.s[_resourceName];if(_id){if(!(_id in resource.modified)){resource.modified[_id]=0}return resource.modified[_id]}return resource.collectionModified},lastSaved:function lastSaved(resourceName,id){var _check$call6=check.call(this,"lastSaved",resourceName,id||fakeId);var _this=_check$call6._this;var _resourceName=_check$call6._resourceName;var _id=_check$call6._id;var resource=_this.s[_resourceName];if(!(_id in resource.saved)){resource.saved[_id]=0}return resource.saved[_id]},previous:function previous(resourceName,id){var _check$call7=check.call(this,"previous",resourceName,id);var _this=_check$call7._this;var _resourceName=_check$call7._resourceName;var _id=_check$call7._id;var resource=_this.s[_resourceName];return resource.previousAttributes[_id]?_utils["default"].copy(resource.previousAttributes[_id]):undefined},revert:function revert(resourceName,id){var _check$call8=check.call(this,"revert",resourceName,id);var _this=_check$call8._this;var definition=_check$call8.definition;var _resourceName=_check$call8._resourceName;var _id=_check$call8._id;return definition.inject(_this.previous(_resourceName,_id))}}},function(module,exports,__webpack_require__){exports["default"]={create:__webpack_require__(34),destroy:__webpack_require__(35),destroyAll:__webpack_require__(36),find:__webpack_require__(37),findAll:__webpack_require__(38),loadRelations:__webpack_require__(39),reap:__webpack_require__(40),refresh:function refresh(resourceName,id,options){var _this=this;var DSUtils=_this.utils;return new DSUtils.Promise(function(resolve,reject){var definition=_this.defs[resourceName];id=DSUtils.resolveId(_this.defs[resourceName],id);if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.bypassCache=true;options.logFn("refresh",id,options);resolve(_this.get(resourceName,id))}}}).then(function(item){return item?_this.find(resourceName,id,options):item})},refreshAll:function refreshAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];params=params||{};return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("params"))}else{options=DSUtils._(definition,options);options.bypassCache=true;options.logFn("refreshAll",params,options);resolve(_this.filter(resourceName,params,options))}}}).then(function(existing){options.bypassCache=true;return _this.findAll(resourceName,params,options).then(function(found){DSUtils.forEach(existing,function(item){if(found.indexOf(item)===-1){definition.eject(item)}});return found})})},save:__webpack_require__(41),update:__webpack_require__(42),updateAll:__webpack_require__(43)}},function(module,exports,__webpack_require__){ /*! * yabh * @version 1.0.1 - Homepage <http://jmdobry.github.io/yabh/> * @author Jason Dobry <jason.dobry@gmail.com> * @copyright (c) 2015 Jason Dobry * @license MIT <https://github.com/jmdobry/yabh/blob/master/LICENSE> * * @overview Yet another Binary Heap. */ (function webpackUniversalModuleDefinition(root,factory){if(true){module.exports=factory()}else{if(typeof define==="function"&&define.amd){define("yabh",factory)}else{if(typeof exports==="object"){exports.BinaryHeap=factory()}else{root.BinaryHeap=factory()}}}})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)})([function(module,exports,__webpack_require__){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}})();Object.defineProperty(exports,"__esModule",{value:true});function bubbleUp(heap,weightFunc,n){var element=heap[n];var weight=weightFunc(element);while(n>0){var parentN=Math.floor((n+1)/2)-1;var _parent=heap[parentN];if(weight>=weightFunc(_parent)){break}else{heap[parentN]=element;heap[n]=_parent;n=parentN}}}var bubbleDown=function bubbleDown(heap,weightFunc,n){var length=heap.length;var node=heap[n];var nodeWeight=weightFunc(node);while(true){var child2N=(n+1)*2,child1N=child2N-1;var swap=null;if(child1N<length){var child1=heap[child1N],child1Weight=weightFunc(child1);if(child1Weight<nodeWeight){swap=child1N}}if(child2N<length){var child2=heap[child2N],child2Weight=weightFunc(child2);if(child2Weight<(swap===null?nodeWeight:weightFunc(heap[child1N]))){swap=child2N}}if(swap===null){break}else{heap[n]=heap[swap];heap[swap]=node;n=swap}}};var BinaryHeap=(function(){function BinaryHeap(weightFunc,compareFunc){_classCallCheck(this,BinaryHeap);if(!weightFunc){weightFunc=function(x){return x}}if(!compareFunc){compareFunc=function(x,y){return x===y}}if(typeof weightFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!')}if(typeof compareFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!')}this.weightFunc=weightFunc;this.compareFunc=compareFunc;this.heap=[]}_createClass(BinaryHeap,[{key:"push",value:function push(node){this.heap.push(node);bubbleUp(this.heap,this.weightFunc,this.heap.length-1)}},{key:"peek",value:function peek(){return this.heap[0]}},{key:"pop",value:function pop(){var front=this.heap[0];var end=this.heap.pop();if(this.heap.length>0){this.heap[0]=end;bubbleDown(this.heap,this.weightFunc,0)}return front}},{key:"remove",value:function remove(node){var length=this.heap.length;for(var i=0;i<length;i++){if(this.compareFunc(this.heap[i],node)){var removed=this.heap[i];var end=this.heap.pop();if(i!==length-1){this.heap[i]=end;bubbleUp(this.heap,this.weightFunc,i);bubbleDown(this.heap,this.weightFunc,i)}return removed}}return null}},{key:"removeAll",value:function removeAll(){this.heap=[]}},{key:"size",value:function size(){return this.heap.length}}]);return BinaryHeap})();exports["default"]=BinaryHeap;module.exports=exports["default"]}])})},function(module,exports,__webpack_require__){function forEach(arr,callback,thisObj){if(arr==null){return}var i=-1,len=arr.length;while(++i<len){if(callback.call(thisObj,arr[i],i,arr)===false){break}}}module.exports=forEach},function(module,exports,__webpack_require__){function slice(arr,start,end){var len=arr.length;if(start==null){start=0}else{if(start<0){start=Math.max(len+start,0)}else{start=Math.min(start,len)}}if(end==null){end=len}else{if(end<0){end=Math.max(len+end,0)}else{end=Math.min(end,len)}}var result=[];while(start<end){result.push(arr[start++])}return result}module.exports=slice},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(21);function contains(arr,val){return indexOf(arr,val)!==-1}module.exports=contains},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(21);function remove(arr,item){var idx=indexOf(arr,item);if(idx!==-1){arr.splice(idx,1)}}module.exports=remove},function(module,exports,__webpack_require__){function mergeSort(arr,compareFn){if(arr==null){return[]}else{if(arr.length<2){return arr}}if(compareFn==null){compareFn=defaultCompare}var mid,left,right;mid=~~(arr.length/2);left=mergeSort(arr.slice(0,mid),compareFn);right=mergeSort(arr.slice(mid,arr.length),compareFn);return merge(left,right,compareFn)}function defaultCompare(a,b){return a<b?-1:(a>b?1:0)}function merge(left,right,compareFn){var result=[];while(left.length&&right.length){if(compareFn(left[0],right[0])<=0){result.push(left.shift())}else{result.push(right.shift())}}if(left.length){result.push.apply(result,left)}if(right.length){result.push.apply(result,right)}return result}module.exports=mergeSort},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(22);var forIn=__webpack_require__(23);function forOwn(obj,fn,thisObj){forIn(obj,function(val,key){if(hasOwn(obj,key)){return fn.call(thisObj,obj[key],key,obj)}})}module.exports=forOwn},function(module,exports,__webpack_require__){var forOwn=__webpack_require__(13);var isPlainObject=__webpack_require__(24);function deepMixIn(target,objects){var i=0,n=arguments.length,obj;while(++i<n){obj=arguments[i];if(obj){forOwn(obj,copyProp,target)}}return target}function copyProp(val,key){var existing=this[key];if(isPlainObject(val)&&isPlainObject(existing)){deepMixIn(existing,val)}else{this[key]=val}}module.exports=deepMixIn},function(module,exports,__webpack_require__){var slice=__webpack_require__(9);function pick(obj,var_keys){var keys=typeof arguments[1]!=="string"?arguments[1]:slice(arguments,1),out={},i=0,key;while(key=keys[i++]){out[key]=obj[key]}return out}module.exports=pick},function(module,exports,__webpack_require__){var forOwn=__webpack_require__(13);var keys=Object.keys||function(obj){var keys=[];forOwn(obj,function(val,key){keys.push(key)});return keys};module.exports=keys},function(module,exports,__webpack_require__){var isPrimitive=__webpack_require__(25);function get(obj,prop){var parts=prop.split("."),last=parts.pop();while(prop=parts.shift()){obj=obj[prop];if(obj==null){return}}return obj[last]}module.exports=get},function(module,exports,__webpack_require__){var namespace=__webpack_require__(26);function set(obj,prop,val){var parts=(/^(.+)\.(.+)$/).exec(prop);if(parts){namespace(obj,parts[1])[parts[2]]=val}else{obj[prop]=val}}module.exports=set},function(module,exports,__webpack_require__){var toString=__webpack_require__(27);var camelCase=__webpack_require__(28);var upperCase=__webpack_require__(20);function pascalCase(str){str=toString(str);return camelCase(str).replace(/^[a-z]/,upperCase)}module.exports=pascalCase},function(module,exports,__webpack_require__){var toString=__webpack_require__(27);function upperCase(str){str=toString(str);return str.toUpperCase()}module.exports=upperCase},function(module,exports,__webpack_require__){function indexOf(arr,item,fromIndex){fromIndex=fromIndex||0;if(arr==null){return -1}var len=arr.length,i=fromIndex<0?len+fromIndex:fromIndex;while(i<len){if(arr[i]===item){return i}i++}return -1}module.exports=indexOf},function(module,exports,__webpack_require__){function hasOwn(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=hasOwn},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(22);var _hasDontEnumBug,_dontEnums;function checkDontEnum(){_dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];_hasDontEnumBug=true;for(var key in {toString:null}){_hasDontEnumBug=false}}function forIn(obj,fn,thisObj){var key,i=0;if(_hasDontEnumBug==null){checkDontEnum()}for(key in obj){if(exec(fn,obj,key,thisObj)===false){break}}if(_hasDontEnumBug){var ctor=obj.constructor,isProto=!!ctor&&obj===ctor.prototype;while(key=_dontEnums[i++]){if((key!=="constructor"||(!isProto&&hasOwn(obj,key)))&&obj[key]!==Object.prototype[key]){if(exec(fn,obj,key,thisObj)===false){break}}}}}function exec(fn,obj,key,thisObj){return fn.call(thisObj,obj[key],key,obj)}module.exports=forIn},function(module,exports,__webpack_require__){function isPlainObject(value){return(!!value&&typeof value==="object"&&value.constructor===Object)}module.exports=isPlainObject},function(module,exports,__webpack_require__){function isPrimitive(value){switch(typeof value){case"string":case"number":case"boolean":return true}return value==null}module.exports=isPrimitive},function(module,exports,__webpack_require__){var forEach=__webpack_require__(8);function namespace(obj,path){if(!path){return obj}forEach(path.split("."),function(key){if(!obj[key]){obj[key]={}}obj=obj[key]});return obj}module.exports=namespace},function(module,exports,__webpack_require__){function toString(val){return val==null?"":val.toString()}module.exports=toString},function(module,exports,__webpack_require__){var toString=__webpack_require__(27);var replaceAccents=__webpack_require__(44);var removeNonWord=__webpack_require__(45);var upperCase=__webpack_require__(20);var lowerCase=__webpack_require__(46);function camelCase(str){str=toString(str);str=replaceAccents(str);str=removeNonWord(str).replace(/[\-_]/g," ").replace(/\s[a-z]/g,upperCase).replace(/\s+/g,"").replace(/^[A-Z]/g,lowerCase);return str}module.exports=camelCase},function(module,exports,__webpack_require__){var _utils=__webpack_require__(2);var _errors=__webpack_require__(3);var instanceMethods=["compute","eject","refresh","save","update","destroy","loadRelations","changeHistory","changes","hasChanges","lastModified","lastSaved","previous","revert"];module.exports=function defineResource(definition){var _this=this;var definitions=_this.defs;if(_utils["default"]._s(definition)){definition={name:definition.replace(/\s/gi,"")}}if(!_utils["default"]._o(definition)){throw _utils["default"]._oErr("definition")}else{if(!_utils["default"]._s(definition.name)){throw new _errors["default"].IA('"name" must be a string!')}else{if(definitions[definition.name]){throw new _errors["default"].R(definition.name+" is already registered!")}}}function Resource(options){this.defaultValues={};this.methods={};this.computed={};_utils["default"].deepMixIn(this,options);var parent=_this.defaults;if(definition["extends"]&&definitions[definition["extends"]]){parent=definitions[definition["extends"]]}_utils["default"].fillIn(this.defaultValues,parent.defaultValues);_utils["default"].fillIn(this.methods,parent.methods);_utils["default"].fillIn(this.computed,parent.computed);this.endpoint="endpoint" in options?options.endpoint:this.name}try{var def;var _class;var _ret=(function(){if(definition["extends"]&&definitions[definition["extends"]]){Resource.prototype=definitions[definition["extends"]]}else{Resource.prototype=_this.defaults}definitions[definition.name]=new Resource(definition);def=definitions[definition.name];def.getResource=function(resourceName){return _this.defs[resourceName]};def.logFn("Preparing resource.");if(!_utils["default"]._s(def.idAttribute)){throw new _errors["default"].IA('"idAttribute" must be a string!')}if(def.relations){def.relationList=[];def.relationFields=[];_utils["default"].forOwn(def.relations,function(relatedModels,type){_utils["default"].forOwn(relatedModels,function(defs,relationName){if(!_utils["default"]._a(defs)){relatedModels[relationName]=[defs]}_utils["default"].forEach(relatedModels[relationName],function(d){d.type=type;d.relation=relationName;d.name=def.name;def.relationList.push(d);if(d.localField){def.relationFields.push(d.localField)}})})});if(def.relations.belongsTo){_utils["default"].forOwn(def.relations.belongsTo,function(relatedModel,modelName){_utils["default"].forEach(relatedModel,function(relation){if(relation.parent){def.parent=modelName;def.parentKey=relation.localKey;def.parentField=relation.localField}})})}if(typeof Object.freeze==="function"){Object.freeze(def.relations);Object.freeze(def.relationList)}}_class=def["class"]=_utils["default"].pascalCase(def.name);try{if(typeof def.useClass==="function"){eval("function "+_class+"() { def.useClass.call(this); }");def[_class]=eval(_class);def[_class].prototype=(function(proto){function Ctor(){}Ctor.prototype=proto;return new Ctor()})(def.useClass.prototype)}else{eval("function "+_class+"() {}");def[_class]=eval(_class)}}catch(e){def[_class]=function(){}}_utils["default"].forOwn(def.methods,function(fn,m){def[_class].prototype[m]=fn});def[_class].prototype.set=function(key,value){var _this2=this;_utils["default"].set(this,key,value);def.compute(this);if(def.instanceEvents){setTimeout(function(){_this2.emit("DS.change",def,_this2)},0)}def.handleChange(this);return this};def[_class].prototype.get=function(key){return _utils["default"].get(this,key)};if(def.instanceEvents){_utils["default"].Events(def[_class].prototype)}_utils["default"].applyRelationGettersToTarget(_this,def,def[_class].prototype);var parentOmit=null;if(!def.hasOwnProperty("omit")){parentOmit=def.omit;def.omit=[]}else{parentOmit=_this.defaults.omit}def.omit=def.omit.concat(parentOmit||[]);_utils["default"].forOwn(def.computed,function(fn,field){if(_utils["default"].isFunction(fn)){def.computed[field]=[fn];fn=def.computed[field]}if(def.methods&&field in def.methods){def.errorFn('Computed property "'+field+'" conflicts with previously defined prototype method!')}def.omit.push(field);var deps;if(fn.length===1){var match=fn[0].toString().match(/function.*?\(([\s\S]*?)\)/);deps=match[1].split(",");def.computed[field]=deps.concat(fn);fn=def.computed[field];if(deps.length){def.errorFn("Use the computed property array syntax for compatibility with minified code!")}}deps=fn.slice(0,fn.length-1);_utils["default"].forEach(deps,function(val,index){deps[index]=val.trim()});fn.deps=_utils["default"].filter(deps,function(dep){return !!dep})});_utils["default"].forEach(instanceMethods,function(name){def[_class].prototype["DS"+_utils["default"].pascalCase(name)]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}args.unshift(this[def.idAttribute]||this);args.unshift(def.name);return _this[name].apply(_this,args)}});def[_class].prototype.DSCreate=function(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}args.unshift(this);args.unshift(def.name);return _this.create.apply(_this,args)};_this.s[def.name]={collection:[],expiresHeap:new _utils["default"].BinaryHeap(function(x){return x.expires},function(x,y){return x.item===y}),completedQueries:{},queryData:{},pendingQueries:{},index:{},modified:{},saved:{},previousAttributes:{},observers:{},changeHistories:{},changeHistory:[],collectionModified:0};var resource=_this.s[def.name];if(def.reapInterval){setInterval(function(){return def.reap()},def.reapInterval)}var fns=["registerAdapter","getAdapterName","getAdapter","is","!clear"];for(var key in _this){if(typeof _this[key]==="function"){fns.push(key)}}_utils["default"].forEach(fns,function(key){var k=key;if(k[0]==="!"){return}if(_this[k].shorthand!==false){def[k]=function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}args.unshift(def.name);return _this[k].apply(_this,args)};def[k].before=function(fn){var orig=def[k];def[k]=function(){for(var _len4=arguments.length,args=Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return orig.apply(def,fn.apply(def,args)||args)}}}else{def[k]=function(){for(var _len5=arguments.length,args=Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5]}return _this[k].apply(_this,args)}}});def.beforeValidate=_utils["default"].promisify(def.beforeValidate);def.validate=_utils["default"].promisify(def.validate);def.afterValidate=_utils["default"].promisify(def.afterValidate);def.beforeCreate=_utils["default"].promisify(def.beforeCreate);def.afterCreate=_utils["default"].promisify(def.afterCreate);def.beforeUpdate=_utils["default"].promisify(def.beforeUpdate);def.afterUpdate=_utils["default"].promisify(def.afterUpdate);def.beforeDestroy=_utils["default"].promisify(def.beforeDestroy);def.afterDestroy=_utils["default"].promisify(def.afterDestroy);var defaultAdapter=undefined;if(def.hasOwnProperty("defaultAdapter")){defaultAdapter=def.defaultAdapter}_utils["default"].forOwn(def.actions,function(action,name){if(def[name]&&!def.actions[name]){throw new Error('Cannot override existing method "'+name+'"!')}action.request=action.request||function(config){return config};action.response=action.response||function(response){return response};action.responseError=action.responseError||function(err){return _utils["default"].Promise.reject(err)};def[name]=function(id,options){if(_utils["default"]._o(id)){options=id}options=options||{};var adapter=def.getAdapter(action.adapter||defaultAdapter||"http");var config=_utils["default"].deepMixIn({},action);if(!options.hasOwnProperty("endpoint")&&config.endpoint){options.endpoint=config.endpoint}if(typeof options.getEndpoint==="function"){config.url=options.getEndpoint(def,options)}else{var args=[options.basePath||adapter.defaults.basePath||def.basePath,adapter.getEndpoint(def,_utils["default"]._sn(id)?id:null,options)];if(_utils["default"]._sn(id)){args.push(id)}args.push(action.pathname||name);config.url=_utils["default"].makePath.apply(null,args)}config.method=config.method||"GET";_utils["default"].deepMixIn(config,options);return new _utils["default"].Promise(function(r){return r(config)}).then(options.request||action.request).then(function(config){return adapter.HTTP(config)}).then(options.response||action.response,options.responseError||action.responseError)}});_utils["default"].Events(def);def.handleChange=function(data){resource.collectionModified=_utils["default"].updateTimestamp(resource.collectionModified);if(def.notify){setTimeout(function(){def.emit("DS.change",def,data)},0)}};def.logFn("Done preparing resource.");return{v:def}})();if(typeof _ret==="object"){return _ret.v}}catch(err){_this.defaults.errorFn(err);delete definitions[definition.name];delete _this.s[definition.name];throw err}}},function(module,exports,__webpack_require__){module.exports=function eject(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var item=undefined;var found=false;id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}}options=DSUtils._(definition,options);options.logFn("eject",id,options);for(var i=0;i<resource.collection.length;i++){if(resource.collection[i][definition.idAttribute]==id){item=resource.collection[i];resource.expiresHeap.remove(item);found=true;break}}if(found){var _ret=(function(){definition.beforeEject(options,item);if(options.notify){definition.emit("DS.beforeEject",definition,item)}var toRemove=[];DSUtils.forOwn(resource.queryData,function(items,queryHash){if(items.$$injected){DSUtils.remove(items,item)}if(!items.length&&options.clearEmptyQueries){toRemove.push(queryHash)}});DSUtils.forEach(resource.changeHistories[id],function(changeRecord){DSUtils.remove(resource.changeHistory,changeRecord)});DSUtils.forEach(toRemove,function(queryHash){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]});if(DSUtils.w){resource.observers[id].close()}delete resource.observers[id];delete resource.index[id];delete resource.previousAttributes[id];delete resource.completedQueries[id];delete resource.pendingQueries[id];delete resource.changeHistories[id];delete resource.modified[id];delete resource.saved[id];resource.collection.splice(i,1);definition.handleChange(item);definition.afterEject(options,item);if(options.notify){definition.emit("DS.afterEject",definition,item)}return{v:item}})();if(typeof _ret==="object"){return _ret.v}}}},function(module,exports,__webpack_require__){module.exports=function ejectAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];params=params||{};if(!definition){throw new _this.errors.NER(resourceName)}else{if(!DSUtils._o(params)){throw DSUtils._oErr("params")}}definition.logFn("ejectAll",params,options);var resource=_this.s[resourceName];var queryHash=DSUtils.toJson(params);var items=definition.filter(params);if(DSUtils.isEmpty(params)){resource.completedQueries={}}else{delete resource.completedQueries[queryHash]}DSUtils.forEach(items,function(item){if(item&&item[definition.idAttribute]){definition.eject(item[definition.idAttribute],options)}});definition.handleChange(items);return items}},function(module,exports,__webpack_require__){module.exports=function filter(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];if(!definition){throw new _this.errors.NER(resourceName)}else{if(params&&!DSUtils._o(params)){throw DSUtils._oErr("params")}}params=params||{};options=DSUtils._(definition,options);options.logFn("filter",params,options);return definition.defaultFilter.call(_this,_this.s[resourceName].collection,resourceName,params,options)}},function(module,exports,__webpack_require__){var _utils=__webpack_require__(2);var _errors=__webpack_require__(3);function makeObserverHandler(definition,resource){var DS=this;var name=definition.name;return function _react(added,removed,changed,oldValueFn,firstTime){var target=this;var item=undefined;var innerId=oldValueFn&&oldValueFn(definition.idAttribute)?oldValueFn(definition.idAttribute):target[definition.idAttribute];_utils["default"].forEach(definition.relationFields,function(field){delete added[field];delete removed[field];delete changed[field]});if(!_utils["default"].isEmpty(added)||!_utils["default"].isEmpty(removed)||!_utils["default"].isEmpty(changed)||firstTime){item=DS.get(name,innerId);resource.modified[innerId]=_utils["default"].updateTimestamp(resource.modified[innerId]);if(item&&definition.instanceEvents){setTimeout(function(){item.emit("DS.change",definition,item)},0)}definition.handleChange(item);if(definition.keepChangeHistory){var changeRecord={resourceName:name,target:item,added:added,removed:removed,changed:changed,timestamp:resource.modified[innerId]};resource.changeHistories[innerId].push(changeRecord);resource.changeHistory.push(changeRecord)}}if(definition.computed){item=item||DS.get(name,innerId);_utils["default"].forOwn(definition.computed,function(fn,field){var compute=false;_utils["default"].forEach(fn.deps,function(dep){if(dep in added||dep in removed||dep in changed||!(field in item)){compute=true}});compute=compute||!fn.deps.length;if(compute){_utils["default"].compute.call(item,fn,field)}})}if(definition.idAttribute in changed){definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "'+name+'" resource is now in an undefined (probably broken) state.')}}}function _inject(definition,resource,attrs,options){var _this=this;var injected=undefined;if(_utils["default"]._a(attrs)){injected=[];for(var i=0;i<attrs.length;i++){injected.push(_inject.call(_this,definition,resource,attrs[i],options))}}else{var _react=makeObserverHandler.call(_this,definition,resource);var c=definition.computed;var idA=definition.idAttribute;if(c&&c[idA]){(function(){var args=[];_utils["default"].forEach(c[idA].deps,function(dep){args.push(attrs[dep])});attrs[idA]=c[idA][c[idA].length-1].apply(attrs,args)})()}if(!(idA in attrs)){var error=new _errors["default"].R(definition.name+'.inject: "attrs" must contain the property specified by "idAttribute"!');options.errorFn(error);throw error}else{try{(function(){_utils["default"].forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=_this.defs[relationName];var toInject=attrs[def.localField];if(toInject){if(!relationDef){throw new _errors["default"].R(definition.name+" relation is defined but the resource is not!")}if(_utils["default"]._a(toInject)){(function(){var items=[];_utils["default"].forEach(toInject,function(toInjectItem){if(toInjectItem!==_this.s[relationName].index[toInjectItem[relationDef.idAttribute]]){try{var injectedItem=relationDef.inject(toInjectItem,options.orig());if(def.foreignKey){injectedItem[def.foreignKey]=attrs[definition.idAttribute]}items.push(injectedItem)}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}})})()}else{if(toInject!==_this.s[relationName].index[toInject[relationDef.idAttribute]]){try{var _injected=relationDef.inject(attrs[def.localField],options.orig());if(def.foreignKey){_injected[def.foreignKey]=attrs[definition.idAttribute]}}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}}}});var id=attrs[idA];var item=definition.get(id);var initialLastModified=item?resource.modified[id]:0;if(!item){if(attrs instanceof definition[definition["class"]]){item=attrs}else{item=new definition[definition["class"]]()}_utils["default"].forEach(definition.relationList,function(def){delete attrs[def.localField]});_utils["default"].deepMixIn(item,attrs);resource.collection.push(item);resource.changeHistories[id]=[];if(_utils["default"].w){resource.observers[id]=new _this.observe.ObjectObserver(item);resource.observers[id].open(_react,item)}resource.index[id]=item;_react.call(item,{},{},{},null,true);resource.previousAttributes[id]=_utils["default"].copy(item,null,null,null,definition.relationFields)}else{if(options.onConflict==="merge"){_utils["default"].deepMixIn(item,attrs)}else{if(options.onConflict==="replace"){_utils["default"].forOwn(item,function(v,k){if(k!==definition.idAttribute){if(!attrs.hasOwnProperty(k)){delete item[k]}}});_utils["default"].forOwn(attrs,function(v,k){if(k!==definition.idAttribute){item[k]=v}})}}if(definition.resetHistoryOnInject){resource.previousAttributes[id]=_utils["default"].copy(item,null,null,null,definition.relationFields);if(resource.changeHistories[id].length){_utils["default"].forEach(resource.changeHistories[id],function(changeRecord){_utils["default"].remove(resource.changeHistory,changeRecord)});resource.changeHistories[id].splice(0,resource.changeHistories[id].length)}}if(_utils["default"].w){resource.observers[id].deliver()}}resource.modified[id]=initialLastModified&&resource.modified[id]===initialLastModified?_utils["default"].updateTimestamp(resource.modified[id]):resource.modified[id];resource.expiresHeap.remove(item);var timestamp=new Date().getTime();resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE});injected=item})()}catch(err){options.errorFn(err,attrs)}}}return injected}module.exports=function inject(resourceName,attrs,options){var _this=this;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var injected=undefined;if(!definition){throw new _errors["default"].NER(resourceName)}else{if(!_utils["default"]._o(attrs)&&!_utils["default"]._a(attrs)){throw new _errors["default"].IA(resourceName+'.inject: "attrs" must be an object or an array!')}}options=_utils["default"]._(definition,options);options.logFn("inject",attrs,options);options.beforeInject(options,attrs);if(options.notify){definition.emit("DS.beforeInject",definition,attrs)}injected=_inject.call(_this,definition,resource,attrs,options);definition.handleChange(injected);options.afterInject(options,injected);if(options.notify){definition.emit("DS.afterInject",definition,injected)}return injected}},function(module,exports,__webpack_require__){module.exports=function create(resourceName,attrs,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var adapter=undefined;options=options||{};attrs=attrs||{};var rejectionError=undefined;if(!definition){rejectionError=new _this.errors.NER(resourceName)}else{if(!DSUtils._o(attrs)){rejectionError=DSUtils._oErr("attrs")}else{options=DSUtils._(definition,options);if(options.upsert&&DSUtils._sn(attrs[definition.idAttribute])){return _this.update(resourceName,attrs[definition.idAttribute],attrs,options)}options.logFn("create",attrs,options)}}return new DSUtils.Promise(function(resolve,reject){if(rejectionError){reject(rejectionError)}else{resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeCreate",definition,attrs)}adapter=_this.getAdapterName(options);return _this.adapters[adapter].create(definition,DSUtils.omit(attrs,options.omit),options)}).then(function(attrs){return options.afterCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.afterCreate",definition,attrs)}if(options.cacheResponse){var created=_this.inject(definition.name,attrs,options.orig());var id=created[definition.idAttribute];var resource=_this.s[resourceName];resource.completedQueries[id]=new Date().getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return created}else{return _this.createInstance(resourceName,attrs,options)}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)})}},function(module,exports,__webpack_require__){module.exports=function destroy(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var item=undefined;var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{item=definition.get(id)||{id:id};options=DSUtils._(definition,options);options.logFn("destroy",id,options);resolve(item)}}}).then(function(attrs){return options.beforeDestroy.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeDestroy",definition,attrs)}if(options.eagerEject){definition.eject(id)}adapter=definition.getAdapter(options);return adapter.destroy(definition,id,options)}).then(function(){return options.afterDestroy.call(item,options,item)}).then(function(item){if(options.notify){definition.emit("DS.afterDestroy",definition,item)}definition.eject(id);return DSUtils.respond(id,{adapter:adapter},options)})["catch"](function(err){if(options&&options.eagerEject&&item){definition.inject(item,{notify:false})}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){module.exports=function destroyAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var ejected=undefined,toEject=undefined,adapter=undefined;params=params||{};return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("attrs"))}else{options=DSUtils._(definition,options);options.logFn("destroyAll",params,options);resolve()}}}).then(function(){toEject=definition.defaultFilter.call(_this,resourceName,params);return options.beforeDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.beforeDestroy",definition,toEject)}if(options.eagerEject){ejected=definition.ejectAll(params)}adapter=definition.getAdapterName(options);return _this.adapters[adapter].destroyAll(definition,params,options)}).then(function(){return options.afterDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.afterDestroy",definition,toEject)}return ejected||definition.ejectAll(params)}).then(function(items){return DSUtils.respond(items,{adapter:adapter},options)})["catch"](function(err){if(options&&options.eagerEject&&ejected){definition.inject(ejected,{notify:false})}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){module.exports=function find(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("find",id,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[id]}if((!options.findStrictCache||id in resource.completedQueries)&&definition.get(id)&&!options.bypassCache){resolve(definition.get(id))}else{delete resource.completedQueries[id];resolve()}}}}).then(function(item){if(!item){if(!(id in resource.pendingQueries)){var promise=undefined;var strategy=options.findStrategy||options.strategy;if(strategy==="fallback"){(function(){var makeFallbackCall=function makeFallbackCall(index){adapter=definition.getAdapterName((options.findFallbackAdapters||options.fallbackAdapters)[index]);return _this.adapters[adapter].find(definition,id,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)})()}else{adapter=definition.getAdapterName(options);promise=_this.adapters[adapter].find(definition,id,options)}resource.pendingQueries[id]=promise.then(function(data){delete resource.pendingQueries[id];if(options.cacheResponse){var injected=definition.inject(data,options.orig());resource.completedQueries[id]=new Date().getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return injected}else{return definition.createInstance(data,options.orig())}})}return resource.pendingQueries[id]}else{return item}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)})["catch"](function(err){if(resource){delete resource.pendingQueries[id]}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){function processResults(data,resourceName,queryHash,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var idAttribute=_this.defs[resourceName].idAttribute;var date=new Date().getTime();data=data||[];delete resource.pendingQueries[queryHash];resource.completedQueries[queryHash]=date;var injected=definition.inject(data,options.orig());if(DSUtils._a(injected)){DSUtils.forEach(injected,function(item){if(item){var id=item[idAttribute];if(id){resource.completedQueries[id]=date;resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id])}}})}else{options.errorFn("response is expected to be an array!");resource.completedQueries[injected[idAttribute]]=date}return injected}module.exports=function findAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var queryHash=undefined,adapter=undefined;return new DSUtils.Promise(function(resolve,reject){params=params||{};if(!_this.defs[resourceName]){reject(new _this.errors.NER(resourceName))}else{if(!DSUtils._o(params)){reject(DSUtils._oErr("params"))}else{options=DSUtils._(definition,options);queryHash=DSUtils.toJson(params);options.logFn("findAll",params,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]}if(queryHash in resource.completedQueries){if(options.useFilter){if(options.localKeys){resolve(definition.getAll(options.localKeys,options.orig()))}else{resolve(definition.filter(params,options.orig()))}}else{resolve(resource.queryData[queryHash])}}else{resolve()}}}}).then(function(items){if(!(queryHash in resource.completedQueries)){if(!(queryHash in resource.pendingQueries)){var promise=undefined;var strategy=options.findAllStrategy||options.strategy;if(strategy==="fallback"){(function(){var makeFallbackCall=function makeFallbackCall(index){adapter=definition.getAdapterName((options.findAllFallbackAdapters||options.fallbackAdapters)[index]);return _this.adapters[adapter].findAll(definition,params,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)})()}else{adapter=definition.getAdapterName(options);promise=_this.adapters[adapter].findAll(definition,params,options)}resource.pendingQueries[queryHash]=promise.then(function(data){delete resource.pendingQueries[queryHash];if(options.cacheResponse){resource.queryData[queryHash]=processResults.call(_this,data,resourceName,queryHash,options);resource.queryData[queryHash].$$injected=true;return resource.queryData[queryHash]}else{DSUtils.forEach(data,function(item,i){data[i]=definition.createInstance(item,options.orig())});return data}})}return resource.pendingQueries[queryHash]}else{return items}}).then(function(items){return DSUtils.respond(items,{adapter:adapter},options)})["catch"](function(err){if(resource){delete resource.pendingQueries[queryHash]}return DSUtils.Promise.reject(err)})}},function(module,exports,__webpack_require__){function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}module.exports=function loadRelations(resourceName,instance,relations,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];return new DSUtils.Promise(function(resolve,reject){if(DSUtils._sn(instance)){instance=definition.get(instance)}if(DSUtils._s(relations)){relations=[relations]}relations=relations||[];if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._o(instance)){reject(new DSErrors.IA('"instance(id)" must be a string, number or object!'))}else{if(!DSUtils._a(relations)){reject(new DSErrors.IA('"relations" must be a string or an array!'))}else{(function(){var _options=DSUtils._(definition,options);_options.logFn("loadRelations",instance,relations,_options);var tasks=[];DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=definition.getResource(relationName);var __options=DSUtils._(relationDef,options);if(!relations.length||DSUtils.contains(relations,relationName)||DSUtils.contains(relations,def.localField)){var task=undefined;var params={};if(__options.allowSimpleWhere){params[def.foreignKey]=instance[definition.idAttribute]}else{params.where={};params.where[def.foreignKey]={"==":instance[definition.idAttribute]}}if(def.type==="hasMany"){var orig=__options.orig();if(def.localKeys){delete params[def.foreignKey];var keys=instance[def.localKeys]||[];keys=DSUtils._a(keys)?keys:DSUtils.keys(keys);params.where=_defineProperty({},relationDef.idAttribute,{"in":keys});orig.localKeys=keys}task=relationDef.findAll(params,orig)}else{if(def.type==="hasOne"){if(def.localKey&&instance[def.localKey]){task=relationDef.find(instance[def.localKey],__options.orig())}else{if(def.foreignKey){task=relationDef.findAll(params,__options.orig()).then(function(hasOnes){return hasOnes.length?hasOnes[0]:null})}}}else{if(instance[def.localKey]){task=relationDef.find(instance[def.localKey],__options.orig())}}}if(task){tasks.push(task)}}});resolve(tasks)})()}}}}).then(function(tasks){return DSUtils.Promise.all(tasks)}).then(function(){return instance})}},function(module,exports,__webpack_require__){module.exports=function reap(resourceName,options){var _this=this;var DSUtils=_this.utils;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{options=DSUtils._(definition,options);if(!options.hasOwnProperty("notify")){options.notify=false}options.logFn("reap",options);var items=[];var now=new Date().getTime();var expiredItem=undefined;while((expiredItem=resource.expiresHeap.peek())&&expiredItem.expires<now){items.push(expiredItem.item);delete expiredItem.item;resource.expiresHeap.pop()}resolve(items)}}).then(function(items){if(items.length){definition.beforeReap(options,items);if(options.notify){definition.emit("DS.beforeReap",definition,items)}}if(options.reapAction==="inject"){(function(){var timestamp=new Date().getTime();DSUtils.forEach(items,function(item){resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE})})})()}else{if(options.reapAction==="eject"){DSUtils.forEach(items,function(item){definition.eject(item[definition.idAttribute])})}else{if(options.reapAction==="refresh"){var _ret2=(function(){var tasks=[];DSUtils.forEach(items,function(item){tasks.push(definition.refresh(item[definition.idAttribute]))});return{v:DSUtils.Promise.all(tasks)}})();if(typeof _ret2==="object"){return _ret2.v}}}}return items}).then(function(items){if(items.length){definition.afterReap(options,items);if(options.notify){definition.emit("DS.afterReap",definition,items)}}return items})}},function(module,exports,__webpack_require__){module.exports=function save(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];var resource=_this.s[resourceName];var item=undefined,noChanges=undefined,adapter=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{if(!definition.get(id)){reject(new DSErrors.R('id "'+id+'" not found in cache!'))}else{item=definition.get(id);options=DSUtils._(definition,options);options.logFn("save",id,options);resolve(item)}}}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}if(options.changesOnly){if(DSUtils.w){resource.observers[id].deliver()}var toKeep=[];var changes=definition.changes(id);for(var key in changes.added){toKeep.push(key)}for(key in changes.changed){toKeep.push(key)}changes=DSUtils.pick(attrs,toKeep);if(DSUtils.isEmpty(changes)){options.logFn("save - no changes",id,options);noChanges=true;return attrs}else{attrs=changes}}adapter=definition.getAdapterName(options);return _this.adapters[adapter].update(definition,id,DSUtils.omit(attrs,options.omit),options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(noChanges){return attrs}else{if(options.cacheResponse){var injected=definition.inject(attrs,options.orig());var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return definition.createInstance(attrs,options.orig())}}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)})}},function(module,exports,__webpack_require__){module.exports=function update(resourceName,id,attrs,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else{if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("update",id,attrs,options);resolve(attrs)}}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}adapter=definition.getAdapterName(options);return _this.adapters[adapter].update(definition,id,DSUtils.omit(attrs,options.omit),options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(options.cacheResponse){var injected=definition.inject(attrs,options.orig());var resource=_this.s[resourceName];var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return definition.createInstance(attrs,options.orig())}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)})}},function(module,exports,__webpack_require__){module.exports=function updateAll(resourceName,attrs,params,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.defs[resourceName];var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new DSErrors.NER(resourceName))}else{options=DSUtils._(definition,options);options.logFn("updateAll",attrs,params,options);resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}adapter=definition.getAdapterName(options);return _this.adapters[adapter].updateAll(definition,DSUtils.omit(attrs,options.omit),params,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(data){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}var origOptions=options.orig();if(options.cacheResponse){var _ret=(function(){var injected=definition.inject(data,origOptions);var resource=_this.s[resourceName];DSUtils.forEach(injected,function(i){var id=i[definition.idAttribute];resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[id]=DSUtils.copy(i,null,null,null,definition.relationFields)}});return{v:injected}})();if(typeof _ret==="object"){return _ret.v}}else{var _ret2=(function(){var instances=[];DSUtils.forEach(data,function(item){instances.push(definition.createInstance(item,origOptions))});return{v:instances}})();if(typeof _ret2==="object"){return _ret2.v}}}).then(function(items){return DSUtils.respond(items,{adapter:adapter},options)})}},function(module,exports,__webpack_require__){var toString=__webpack_require__(27);function replaceAccents(str){str=toString(str);if(str.search(/[\xC0-\xFF]/g)>-1){str=str.replace(/[\xC0-\xC5]/g,"A").replace(/[\xC6]/g,"AE").replace(/[\xC7]/g,"C").replace(/[\xC8-\xCB]/g,"E").replace(/[\xCC-\xCF]/g,"I").replace(/[\xD0]/g,"D").replace(/[\xD1]/g,"N").replace(/[\xD2-\xD6\xD8]/g,"O").replace(/[\xD9-\xDC]/g,"U").replace(/[\xDD]/g,"Y").replace(/[\xDE]/g,"P").replace(/[\xE0-\xE5]/g,"a").replace(/[\xE6]/g,"ae").replace(/[\xE7]/g,"c").replace(/[\xE8-\xEB]/g,"e").replace(/[\xEC-\xEF]/g,"i").replace(/[\xF1]/g,"n").replace(/[\xF2-\xF6\xF8]/g,"o").replace(/[\xF9-\xFC]/g,"u").replace(/[\xFE]/g,"p").replace(/[\xFD\xFF]/g,"y")}return str}module.exports=replaceAccents},function(module,exports,__webpack_require__){var toString=__webpack_require__(27);var PATTERN=/[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;function removeNonWord(str){str=toString(str);return str.replace(PATTERN,"")}module.exports=removeNonWord},function(module,exports,__webpack_require__){var toString=__webpack_require__(27);function lowerCase(str){str=toString(str);return str.toLowerCase()}module.exports=lowerCase}])});
test/fixtures/hoc/actual.js
layershifter/babel-plugin-transform-react-handled-props
import PropTypes from 'prop-types'; import React from 'react'; export default function Foo() { return function Bar(Component) { return class Baz extends React.Component { static propTypes = { children: PropTypes.node } render() { return <Component />; } } } }
app/components/Dashboard/AnalyticsGrid.js
cdiezmoran/AlphaStage-desktop
/* eslint-disable import/extensions */ // @flow import React, { Component } from 'react'; import Chart from 'chart.js'; import type { DevGame } from '../../utils/globalTypes'; type Props = { game: DevGame }; let churnBarChart; class AnalyticsGrid extends Component { createBarChart: () => void; static chartClick(e: SyntheticMouseEvent, arr: Array<Object>) { if (arr.length === 0) { return; } // eslint-disable-next-line no-underscore-dangle const index = arr[0]._index; console.log(index); // Display users that stayed in x stage } constructor(props: Props) { super(props); this.createBarChart = this.createBarChart.bind(this); } componentDidMount() { this.createBarChart(); } componentWillUpdate() { if (churnBarChart) { churnBarChart.destroy(); } } componentDidUpdate() { this.createBarChart(); } createBarChart() { const { game } = this.props; const { pageViewUsers, downloadUsers, playingUsers, uninstallUsers } = game.analytics; const barData = [ pageViewUsers.length, downloadUsers.length, playingUsers.length, uninstallUsers.length ]; const data = { labels: ['Page Views', 'Downloads', 'Unique Sessions', 'Uninstalls'], datasets: [ { label: 'Players', backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', ], borderWidth: 1, data: barData, } ] }; const ctx = document.getElementById('myChart'); churnBarChart = new Chart(ctx, { type: 'bar', data, options: { scales: { color: '#ccc', xAxes: [{ gridLines: { color: '#777', drawBorder: true, drawOnChartArea: false }, ticks: { fontColor: '#ccc', // this here }, }], yAxes: [{ gridLines: { color: '#777', drawBorder: true, drawOnChartArea: false }, ticks: { fontColor: '#ccc', // this here min: 0 }, }], }, onClick: AnalyticsGrid.chartClick, legend: { display: false } } }); } render() { const { game } = this.props; const { downloads, pageViews, sessions, players } = game.analytics; return ( <div className="analytics-grid"> <div className="container"> <h2>Analytics</h2> <div className="row"> <div className="col-md-4"> <div className="analytics-card graph"> <div className="ac-header"> <span className="ev-title">Churn</span> </div> <div className="ac-content"> <canvas id="myChart" width="400" height="400" /> </div> </div> </div> <div className="col-md-8"> <div className="row"> <div className="col-md-6"> <div className="analytics-card"> <div className="ac-header"> <span className="ev-title">Page Views</span> </div> <div className="ac-content"> <span className="ev-value">{pageViews}</span> </div> </div> </div> <div className="col-md-6"> <div className="analytics-card"> <div className="ac-header"> <span className="ev-title">Total Players</span> </div> <div className="ac-content"> <span className="ev-value">{players}</span> </div> </div> </div> </div> <div className="row"> <div className="col-md-6"> <div className="analytics-card"> <div className="ac-header"> <span className="ev-title">Sessions</span> </div> <div className="ac-content"> <span className="ev-value">{sessions}</span> </div> </div> </div> <div className="col-md-6"> <div className="analytics-card"> <div className="ac-header"> <span className="ev-title">Total Downloads</span> </div> <div className="ac-content"> <span className="ev-value">{downloads}</span> </div> </div> </div> </div> </div> </div> </div> </div> ); } } export default AnalyticsGrid;
src/shared/components/join/join.js
alexspence/operationcode_frontend
import React from 'react'; // import PropTypes from 'prop-types'; import Section from 'shared/components/section/section'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './join.css'; const Join = (props) => { const { ...otherProps } = props; return ( <Section title="Join Today!" {...otherProps} className={styles.joinSection} theme="gray" headingLines={false} > <div className={styles.join} > <p> Operation Code is leading the way to expand opportunities for military veterans and their families to learn new skills, and build a career in the fast-growing technology sector. </p> <p>Join our community for free and jumpstart your skills today!</p> <LinkButton text="Join" link="/join" theme="red" /> </div> </Section> ); }; Join.propTypes = {}; export default Join;
test/DropdownButtonSpec.js
herojobs/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import DropdownButton from '../src/DropdownButton'; import DropdownMenu from '../src/DropdownMenu'; import MenuItem from '../src/MenuItem'; import { shouldWarn } from './helpers'; describe('DropdownButton', function() { const simpleDropdown = ( <DropdownButton title='Simple Dropdown' id='test-id'> <MenuItem>Item 1</MenuItem> <MenuItem>Item 2</MenuItem> <MenuItem>Item 3</MenuItem> <MenuItem>Item 4</MenuItem> </DropdownButton> ); it('renders title prop', function() { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); buttonNode.innerText.should.match(/Simple Dropdown/); }); it('renders dropdown toggle button', function() { const instance = ReactTestUtils.renderIntoDocument(simpleDropdown); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); buttonNode.tagName.should.equal('BUTTON'); buttonNode.className.should.match(/\bbtn[ $]/); buttonNode.className.should.match(/\bbtn-default\b/); buttonNode.className.should.match(/\bdropdown-toggle\b/); buttonNode.getAttribute('type').should.equal('button'); buttonNode.getAttribute('aria-expanded').should.equal('false'); buttonNode.getAttribute('id').should.be.ok; }); it('renders single MenuItem child', function() { const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title='Single child' id='test-id'> <MenuItem>Item 1</MenuItem> </DropdownButton> ); const menuNode = React.findDOMNode( ReactTestUtils.findRenderedComponentWithType(instance, DropdownMenu)); expect(menuNode.children.length).to.equal(1); }); it('forwards pullRight to menu', function() { const instance = ReactTestUtils.renderIntoDocument( <DropdownButton pullRight title='blah' id='test-id'> <MenuItem>Item 1</MenuItem> </DropdownButton> ); const menu = ReactTestUtils.findRenderedComponentWithType(instance, DropdownMenu); menu.props.pullRight.should.be.true; }); it('renders bsSize', function() { const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title='blah' bsSize='small' id='test-id'> <MenuItem>Item 1</MenuItem> </DropdownButton> ); const node = React.findDOMNode(instance); node.className.should.match(/\bbtn-group-sm\b/); }); it('renders bsStyle', function() { const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title='blah' bsStyle='success' id='test-id'> <MenuItem>Item 1</MenuItem> </DropdownButton> ); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); buttonNode.className.should.match(/\bbtn-success\b/); }); it('forwards onSelect handler to MenuItems', function(done) { const selectedEvents = []; const onSelect = (event, eventKey) => { selectedEvents.push(eventKey); if (selectedEvents.length === 4) { selectedEvents.should.eql(['1', '2', '3', '4']); done(); } }; const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title='Simple Dropdown' onSelect={onSelect} id='test-id'> <MenuItem eventKey='1'>Item 1</MenuItem> <MenuItem eventKey='2'>Item 2</MenuItem> <MenuItem eventKey='3'>Item 3</MenuItem> <MenuItem eventKey='4'>Item 4</MenuItem> </DropdownButton> ); const menuItems = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A'); menuItems.forEach(item => { ReactTestUtils.Simulate.click(item); }); }); it('closes when child MenuItem is selected', function() { const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title='Simple Dropdown' id='test-id'> <MenuItem eventKey='1'>Item 1</MenuItem> </DropdownButton> ); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); const menuItem = React.findDOMNode( ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A')); ReactTestUtils.Simulate.click(buttonNode); node.className.should.match(/\bopen\b/); ReactTestUtils.Simulate.click(menuItem); node.className.should.not.match(/\bopen\b/); }); it('does not close when onToggle is controlled', function() { const handleSelect = () => {}; const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title='Simple Dropdown' open={true} onToggle={handleSelect} id='test-id'> <MenuItem eventKey='1'>Item 1</MenuItem> </DropdownButton> ); const node = React.findDOMNode(instance); const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); const menuItem = React.findDOMNode( ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A')); ReactTestUtils.Simulate.click(buttonNode); node.className.should.match(/\bopen\b/); ReactTestUtils.Simulate.click(menuItem); node.className.should.match(/\bopen\b/); }); it('warn about the navItem deprecation', function() { const props = { title: 'some title', navItem: true }; DropdownButton.propTypes.navItem(props, 'navItem', 'DropdownButton'); shouldWarn(/navItem.*NavDropdown component/); }); it('Should pass props to button', function () { const instance = ReactTestUtils.renderIntoDocument( <DropdownButton title="Title" bsStyle="primary" id="testId" disabled> <MenuItem eventKey="1">MenuItem 1 content</MenuItem> <MenuItem eventKey="2">MenuItem 2 content</MenuItem> </DropdownButton> ); const buttonNode = React.findDOMNode( ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON')); assert.ok(buttonNode.className.match(/\bbtn-primary\b/)); assert.equal(buttonNode.getAttribute('id'), 'testId'); assert.ok(buttonNode.disabled); }); });
src/index.js
dpastoor/n-queens
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; render(<App />, document.getElementById('root'));
packages/material-ui-icons/src/PermScanWifiTwoTone.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 5c-3.26 0-6.2.85-9.08 2.65L12 18.83l9.08-11.16C18.18 5.85 15.25 5 12 5zm1 11h-2v-6h2v6zm-2-8V6h2v2h-2z" opacity=".3" /><path d="M12 3C6.95 3 3.15 4.85 0 7.23L12 22 24 7.25C20.85 4.87 17.05 3 12 3zM2.92 7.65C5.8 5.85 8.74 5 12 5c3.25 0 6.18.85 9.08 2.67L12 18.83 2.92 7.65z" /><path d="M11 10h2v6h-2zM11 6h2v2h-2z" /></React.Fragment> , 'PermScanWifiTwoTone');
src/Carousel/chevron_left.js
kambi-sportsbook-widgets/widget-components
import React from 'react' export default function ChevronLeft() { return ( <svg fill="#fff" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" > <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" /> <path d="M0 0h24v24H0z" fill="none" /> </svg> ) }
node_modules/react/lib/ReactComponentWithPureRenderMixin.js
thenatural09/Bread
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var shallowCompare = require('./shallowCompare'); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. * * See https://facebook.github.io/react/docs/pure-render-mixin.html */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function (nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } }; module.exports = ReactComponentWithPureRenderMixin;
examples/04 Sortable/Simple/index.js
zetkin/react-dnd
import React from 'react'; import Container from './Container'; export default class SortableSimple { render() { return ( <div> <p> <b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/04%20Sortable/Simple'>Browse the Source</a></b> </p> <p> It is easy to implement a sortable interface with React DnD. Just make the same component both a drag source and a drop target, and reorder the data in the <code>hover</code> handler. </p> <Container /> </div> ); } }
UI/src/pages/mine/index.js
sunzy0212/local-event
import React, { Component } from 'react'; export default class Mine extends Component { render() { return ( <div className="page3"> Page3 </div> ); } }
components/Header.js
ramprasath25/react-app
import React from 'react'; import {Link} from 'react-router'; import {connect} from 'react-redux'; import {isLoggedIn, getUserDetails} from './authorization'; import * as action from '../actions/login-action'; import * as ReactBootstrap from 'react-bootstrap'; class Header extends React.Component { logout() { this.props.logout(); } render() { const islogin = ((this.props.loginStatus.loginDetails !== '') ? true : false); const p_img = this.props.loginStatus.loginDetails.pictureUrl; const p_name = this.props.loginStatus.loginDetails.firstName +" "+this.props.loginStatus.loginDetails.lastName; return( <div> <ReactBootstrap.Navbar> <ReactBootstrap.Navbar.Header> <ReactBootstrap.Navbar.Brand> <small>React-App</small> </ReactBootstrap.Navbar.Brand> </ReactBootstrap.Navbar.Header> <ReactBootstrap.Nav> <ReactBootstrap.NavItem eventKey={1} href="/">Home</ReactBootstrap.NavItem> <ReactBootstrap.NavItem eventKey={2} href="/about">About us</ReactBootstrap.NavItem> { (islogin) ? <ReactBootstrap.NavItem eventKey={3} href="/dashboard/timeline">Dashboard</ReactBootstrap.NavItem> : ''} </ReactBootstrap.Nav> { (islogin) ? <ReactBootstrap.Nav pullRight> <ReactBootstrap.Navbar.Brand> <ReactBootstrap.Image className="headerProfileImage" src={p_img} circle /> </ReactBootstrap.Navbar.Brand> <ReactBootstrap.NavDropdown eventKey={5} title={"Hi "+p_name} id="basic-nav-dropdown"> <ReactBootstrap.MenuItem eventKey={5.1} href="/dashboard/account">Account</ReactBootstrap.MenuItem> <ReactBootstrap.MenuItem divider /> <ReactBootstrap.MenuItem eventKey={5.4} onClick={this.logout.bind(this)}>Logout</ReactBootstrap.MenuItem> </ReactBootstrap.NavDropdown> </ReactBootstrap.Nav> : <ReactBootstrap.Nav pullRight> <ReactBootstrap.NavItem eventKey={4} href="/login">Sign In</ReactBootstrap.NavItem> </ReactBootstrap.Nav> } </ReactBootstrap.Navbar> <div> {this.props.children} </div> </div> ) } } const mapStateToProps = (state) => { return { loginStatus: state.loginDetails } } const mapDispatchToProps = (dispatch)=> { return { logout : () => dispatch(action.logoutUser()) } } export default connect(mapStateToProps, mapDispatchToProps)(Header);
dashboard/client/src/js/components/modules/base/Header.js
arawind/sieve
import React from 'react'; import {Link} from '../../../utils/router'; import Logo from '../../../../img/logo.svg'; export default function () { return ( <header className="header has-shadow"> <div className="container"> <Link to="/" className="header__title" > <img src={Logo} title="Sieve" alt="Sieve Logo" className="header__logo" /> Sieve </Link> </div> </header> ); }
src/components/users/users-list-item.js
johnamiahford/widgets-spa
'use strict'; import React from 'react'; import { Link } from 'react-router'; class UsersListItem extends React.Component { render() { let params = { id: this.props.id, userName: this.props.name.trim().toLowerCase() }; return ( <tr key={this.props.id}> <td className="text-center">{this.props.id}</td> <td><Link to="usersdetail" params={params}>{this.props.name}</Link></td> <td className="text-center"> <img className="UserGravatar--small" src={this.props.gravatar} alt="" /> </td> </tr> ); } } export default UsersListItem;
app/javascript/mastodon/features/hashtag_timeline/index.js
summoners-riftodon/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandHashtagTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage } from 'react-intl'; import { connectHashtagStream } from '../../actions/streaming'; const mapStateToProps = (state, props) => ({ hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}`, 'unread']) > 0, }); @connect(mapStateToProps) export default class HashtagTimeline extends React.PureComponent { static propTypes = { params: PropTypes.object.isRequired, columnId: PropTypes.string, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HASHTAG', { id: this.props.params.id })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } _subscribe (dispatch, id) { this.disconnect = dispatch(connectHashtagStream(id)); } _unsubscribe () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } componentDidMount () { const { dispatch } = this.props; const { id } = this.props.params; dispatch(expandHashtagTimeline(id)); this._subscribe(dispatch, id); } componentWillReceiveProps (nextProps) { if (nextProps.params.id !== this.props.params.id) { this.props.dispatch(expandHashtagTimeline(nextProps.params.id)); this._unsubscribe(); this._subscribe(this.props.dispatch, nextProps.params.id); } } componentWillUnmount () { this._unsubscribe(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { this.props.dispatch(expandHashtagTimeline(this.props.params.id, { maxId })); } render () { const { shouldUpdateScroll, hasUnread, columnId, multiColumn } = this.props; const { id } = this.props.params; const pinned = !!columnId; return ( <Column ref={this.setRef} label={`#${id}`}> <ColumnHeader icon='hashtag' active={hasUnread} title={id} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusListContainer trackScroll={!pinned} scrollKey={`hashtag_timeline-${columnId}`} timelineId={`hashtag:${id}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />} shouldUpdateScroll={shouldUpdateScroll} /> </Column> ); } }
src/svg-icons/av/skip-previous.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSkipPrevious = (props) => ( <SvgIcon {...props}> <path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/> </SvgIcon> ); AvSkipPrevious = pure(AvSkipPrevious); AvSkipPrevious.displayName = 'AvSkipPrevious'; AvSkipPrevious.muiName = 'SvgIcon'; export default AvSkipPrevious;
import/jquery-1.8.2.min.js
Kyon15498/izhihu
/*! jQuery v1.8.2 jquery.com | jquery.org/license */ (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cA(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cv;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cC(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cD(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cN||cU(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cX(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cc(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cP.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete")setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.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%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")||(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)d=p._data(g[h],a+"queueHooks"),d&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)f.indexOf(" "+b[g]+" ")<0&&(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},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(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=b+""}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,needsContext:f&&p.expr.match.needsContext.test(f),namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),!V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length===1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.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(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=!c.nodeType&&c[0]||c,c=c.ownerDocument||c,a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cZ.propHooks.scrollTop=cZ.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cW(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cR.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:c$("show"),slideUp:c$("hide"),slideToggle:c$("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cZ.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c_=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
src/components/Toolbar/inputs/link.js
crossfield/react-drafts
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDropzone from 'react-dropzone'; import { SUPPORTED_DOCUMENT_TYPES } from '../../../constants/file'; import Modal from '../../shared/modal'; import InputControls from './controls'; const ERROR_MSG = 'We\'re sorry, there was an upload error. Please try again.'; class LinkInput extends Component { constructor(props) { super(props); this.state = { linkValue: '', linkIsTargetBlank: false, textValue: this.props.linkText || '', file: null, error: null }; this.handleLinkChange = this.handleLinkChange.bind(this); this.handleLinkTextChange = this.handleLinkTextChange.bind(this); this.handleToggleTarget = this.handleToggleTarget.bind(this); this.handleDrop = this.handleDrop.bind(this); this.handleConfirm = this.handleConfirm.bind(this); this.handleCancel = this.handleCancel.bind(this); } handleLinkChange(event) { this.setState({ linkValue: event.target.value }); } handleLinkTextChange(event) { this.setState({ textValue: event.target.value }); } handleToggleTarget(event) { this.setState({ linkIsTargetBlank: event.target.checked }); } handleDrop(acceptedFiles, rejectedFiles) { if (rejectedFiles && rejectedFiles.length) { this.setState({ error: ERROR_MSG }); } else { const file = acceptedFiles[0]; if (window.FileReader) { const reader = new FileReader(); reader.addEventListener('load', () => { file.src = reader.result; this.setState({ file }); }, false); reader.readAsDataURL(file); } else { this.setState({ file }); } } } handleConfirm() { const { blockType, onFileUpload, onAddLink } = this.props; const { linkValue, linkIsTargetBlank, textValue, file } = this.state; if (file) { onFileUpload(file) .then(resp => { onAddLink(blockType, { url: resp.src, text: textValue || resp.name, target: linkIsTargetBlank }); }) .catch(err => { this.setState({ error: ERROR_MSG }); }); } else { onAddLink(blockType, { url: linkValue, text: textValue, target: linkIsTargetBlank }); } } handleCancel() { this.setState({ file: null, linkValue: '', linkIsTargetBlank: false, textValue: this.props.linkText || '', error: null }); } render() { const { linkInputAcceptsFiles, onCloseClick } = this.props; const { linkValue, textValue, linkIsTargetBlank, file, error } = this.state; return ( <Modal onCloseClick={onCloseClick}> <div className="drafts-editor__input link"> { file ? ( <div key="preview" className="preview"> <a className="upload-name" href={file.src}>{file.name}</a> </div> ) : ( <div> <input value={linkValue} placeholder="Paste or type link (or email address if mailto)" onChange={this.handleLinkChange} /> { linkInputAcceptsFiles && ([ <div key="separator" className="separator">or add downloadable file as link</div>, <div key="add" className="add"> <ReactDropzone className="react-dropzone" multiple={false} accept={SUPPORTED_DOCUMENT_TYPES} onDrop={this.handleDrop} > <div className="dropzone"> <span>Drag file or click to upload (pdf, docx, xls, txt)</span> </div> </ReactDropzone> { error && <p className="input-error">{error}</p> } </div> ]) } </div> ) } <div className="separator">and</div> <input value={textValue} placeholder="Add link text" onChange={this.handleLinkTextChange} /> <div className="target"> <span>Open link in a new tab:</span> <input name="target" type="checkbox" checked={linkIsTargetBlank} onChange={this.handleToggleTarget} /> </div> <InputControls confirmText="Add Link" onConfirm={this.handleConfirm} onCancel={onCloseClick} /> </div> </Modal> ); } } LinkInput.propTypes = { blockType: PropTypes.string, linkText: PropTypes.string, linkInputAcceptsFiles: PropTypes.bool, onFileUpload: PropTypes.func, onAddLink: PropTypes.func, onCloseClick: PropTypes.func }; export default LinkInput;
lib/components/Uploader.js
hanford/filepizza
import Arrow from '@app/components/Arrow'; import React from 'react'; import UploadActions from '@app/actions/UploadActions'; export default class UploadPage extends React.Component { uploadFile(file) { UploadActions.uploadFile(file); } render() { switch (this.props.status) { case 'ready': return <div> <DropZone onDrop={this.uploadFile.bind(this)} /> <Arrow dir="up" /> </div>; break; case 'processing': return <div> <Arrow dir="up" animated /> <FileDescription file={this.props.file} /> </div>; break; case 'uploading': return <div> <Arrow dir="up" animated /> <FileDescription file={this.props.file} /> <Temaplink token={this.props.token} /> </div>; break; } } }
src/views/components/button/button.spec.js
connorbanderson/CoinREXX
import React from 'react'; import { render, shallow } from 'enzyme'; import Button from './button'; describe('Button', () => { it('should render a button with text node', () => { const wrapper = render(<Button>Foo</Button>); const button = wrapper.find('button'); expect(button.length).toBe(1); expect(button.text()).toBe('Foo'); }); it('should render a button with child element', () => { const wrapper = shallow(<Button><span>Foo</span></Button>); const button = wrapper.find('button'); expect(button.length).toBe(1); expect(button.contains(<span>Foo</span>)).toBe(true); }); it('should set default className', () => { const wrapper = render(<Button />); const button = wrapper.find('button'); expect(button.hasClass('btn')).toBe(true); }); it('should add provided props.className', () => { const wrapper = render(<Button className="foo bar" />); const button = wrapper.find('button'); expect(button.hasClass('btn foo bar')).toBe(true); }); it('should set type=button by default', () => { const wrapper = render(<Button />); const button = wrapper.find('button'); expect(button.attr('type')).toBe('button'); }); it('should set type with provided props.type', () => { const wrapper = render(<Button type="submit" />); const button = wrapper.find('button'); expect(button.attr('type')).toBe('submit'); }); it('should set onClick with provided props.onClick', () => { const handleClick = jasmine.createSpy('handleClick'); const wrapper = shallow(<Button onClick={handleClick} />); wrapper.simulate('click'); expect(handleClick).toHaveBeenCalledTimes(1); }); });
smart-css/button.js
martinandert/css-in-js
import React from 'react'; import SmartCSS from 'smart-css'; const css = new SmartCSS(); css.setClass('.container', { textAlign: 'center' }); css.setClass('.button', { backgroundColor: '#ff0000', width: '320px', padding: '20px', borderRadius: '5px', border: 'none', outline: 'none' }); css.setClass('.button:hover', { color: '#fff' }); css.setClass('.button:active', { position: 'relative', top: '2px' }); css.setClass('.button', { width: '160px' }, { media: '(max-width: 480px)' }); const Button = React.createClass({ render() { return ( <div className={css.getClass('container')}> <button className={css.getClass('button')}>Click me!</button> </div> ); } }); SmartCSS.injectStyles(); React.render(<Button />, document.getElementById('content'));
examples/auth0/pages/advanced/ssr-profile.js
BlancheXu/test
import React from 'react' // This import is only needed when checking authentication status directly from getInitialProps import auth0 from '../../lib/auth0' import { fetchUser } from '../../lib/user' import Layout from '../../components/layout' function Profile ({ user }) { return ( <Layout user={user}> <h1>Profile</h1> <div> <h3>Profile (server rendered)</h3> <img src={user.picture} alt='user picture' /> <p>nickname: {user.nickname}</p> <p>name: {user.name}</p> </div> </Layout> ) } Profile.getInitialProps = async ({ req, res }) => { // On the server-side you can check authentication status directly // However in general you might want to call API Routes to fetch data // An example of directly checking authentication: if (typeof window === 'undefined') { const { user } = await auth0.getSession(req) if (!user) { res.writeHead(302, { Location: '/api/login' }) res.end() return } return { user } } // To do fetches to API routes you can pass the cookie coming from the incoming request on to the fetch // so that a request to the API is done on behalf of the user // keep in mind that server-side fetches need a full URL, meaning that the full url has to be provided to the application const cookie = req && req.headers.cookie const user = await fetchUser(cookie) // A redirect is needed to authenticate to Auth0 if (!user) { if (typeof window === 'undefined') { res.writeHead(302, { Location: '/api/login' }) return res.end() } window.location.href = '/api/login' } return { user } } export default Profile
src/App.js
availabs/avail_app_bootstrap
import React, { Component } from 'react'; import Routes from './Routes'; import { login, logout } from './store/modules/user'; import SideNav from './components/SideNav/SideNav'; import { connect } from 'react-redux'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { isAuthenticating: true }; } //https://stackoverflow.com/a/38563897/3970755 componentDidMount() { if (typeof Storage !== 'undefined' && localStorage.getItem('user')) { try { const user = JSON.parse(localStorage.getItem('user')); console.log('===== App sent auth user request ====='); this.setState({ isAuthenticating: true }); this.props.login(user); } catch (err) { this.setState({ isAuthenticating: false }); localStorage.removeItem('user'); console.error(err); } } this.setState({ isAuthenticating: false }); } componentWillReceiveProps(nextProps) { if (nextProps.authAttempts) { this.setState({ isAuthenticating: false }); } } render() { if (this.state.isAuthenticating) { return <div>Authenticating user</div>; } const childProps = { isAuthenticated: this.props.isAuthenticated }; console.log(childProps); console.log('<rootProps>', this.props); if (this.props.routing.location.pathname === '/map') { return ( <div> <SideNav /> <div className="Map"> <Routes childProps={childProps} /> </div> </div> ); } if (this.props.isAuthenticated) { return ( <div> <SideNav /> <div className="App App-Auth"> <Routes childProps={childProps} /> </div> </div> ); } return ( <div className="App "> <div className="row"> <Routes childProps={childProps} /> </div> </div> ); } } const mapStateToProps = state => { return { isAuthenticated: !!state.user.authed, authAttempts: state.user.attempts, routing: state.routing }; }; const mapDispatchToProps = { login, logout }; export default connect(mapStateToProps, mapDispatchToProps)(App);
src/components/shell/header/Header.js
fredmarques/petshop
import React, { Component } from 'react'; import logo from '../../../logo.svg'; class Header extends Component { render() { return ( <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <span style={{fontSize: 30, color: "#42cef4"}}>PetCare</span> </div> ); } } export default Header;
src/components/layout/Header.js
gReis89/redux-todo
import React from 'react'; /** * React dumb component to list todos */ const Header = () => { return ( <section className="hero is-small is-primary is-bold"> <div className="hero-body"> <div className="container"> <h1 className="title"> React + Redux Todo List </h1> <h2 className="subtitle"> Styled with <a href="http://bulma.io/" target="_blank">Bulma</a> by <a href="https://github.com/gReis89" target="_blank">Guilherme Rodrigues</a> </h2> </div> </div> </section> ); }; export default Header;
src/containers/List.js
blaqbern/lists
import React from 'react'; import { connect } from 'react-redux'; import { addItem } from '../actions'; import AddNew from '../components/AddNew'; import Item from './Item'; function List({ items, handleAddItemClick }) { return ( <div> <AddNew what="item" handleAddClick={handleAddItemClick} /> <ul> {items.map(item => <li key={item.id}><Item item={item} /></li> )} </ul> </div> ); } const { array, func } = React.PropTypes; List.propTypes = { items: array, handleAddItemClick: func, }; function mapStateToProps(state) { return { items: state.list.filter(item => state.visibilityFilter === 'SHOW_ALL' || item.tags.includes(state.visibilityFilter) ), }; } function mapDispatchToProps(dispatch) { return { handleAddItemClick: text => dispatch(addItem(text)), }; } export default connect( mapStateToProps, mapDispatchToProps )(List);
tests/components/Error-test.js
jmcolella/unique-twitter-followers
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import Error from '../../app/components/Error'; describe ( 'Error component', () => { it ( 'renders to the DOM', () => { expect( shallow( <Error /> ) ).to.exist; }); });
site/components/Cover.js
jchristman/react-context-menus
import React, { Component } from 'react'; import './Cover.less'; export default class Cover extends Component { render() { return ( <div className="Cover"> <div className="Cover-header"> <p className="Cover-description"> Drag and Drop for React </p> </div> </div> ); } }
ajax/libs/rxjs/2.2.28/rx.lite.compat.js
mirthy/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (typeof el.item === 'function' && typeof el.length === 'number') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { var p = normalizeTime(period); return new AnonymousObservable(function (observer) { var count = 0, d = dueTime; return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { var now; if (p > 0) { now = scheduler.now(); d = d + p; if (d <= now) { d = now + p; } } observer.onNext(count++); self(d); }); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * var res = Rx.Observable.timer(5000); * var res = Rx.Observable.timer(5000, 1000); * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { scheduler = periodOrScheduler; } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * var res = Rx.Observable.delay(5000); * var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); var createTimer = function () { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previous = true; var subscription = combineLatestSource( this.source, this.subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (results.shouldFire && previous) { observer.onNext(results.data); } if (results.shouldFire && !previous) { while (q.length > 0) { observer.onNext(q.shift()); } previous = true; } else if (!results.shouldFire && !previous) { q.push(results.data); } else if (!results.shouldFire && previous) { previous = false; } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/routes/about.js
danii1/react-beginner-boilerplate
'use strict'; import React from 'react'; export default React.createClass({ render() { return ( <div className='about-route'> <h1>About</h1> </div> ); } });
benchmarks/dom-comparison/src/implementations/react-fela-useFela/Box.js
risetechnologies/fela
import React from 'react' import { useFela } from 'react-fela' const rule = ({ color, fixed = false, layout = 'column', outer = false }) => ({ alignItems: 'stretch', borderWidth: '0px', borderStyle: 'solid', boxSizing: 'border-box', display: 'flex', flexBasis: 'auto', flexDirection: 'column', flexShrink: '0', margin: '0px', padding: '0px', position: 'relative', // fix flexbox bugs minHeight: '0px', minWidth: '0px', ...styles[`color${color}`], ...(fixed && styles.fixed), ...(layout === 'row' && styles.row), ...(outer && styles.outer), }) const Box = ({ children, color, fixed, layout, outer }) => { const { css } = useFela({ color, fixed, layout, outer }) return <div className={css(rule)}>{children}</div> } const styles = { outer: { alignSelf: 'flex-start', padding: '4px', }, row: { flexDirection: 'row', }, color0: { backgroundColor: '#14171A', }, color1: { backgroundColor: '#AAB8C2', }, color2: { backgroundColor: '#E6ECF0', }, color3: { backgroundColor: '#FFAD1F', }, color4: { backgroundColor: '#F45D22', }, color5: { backgroundColor: '#E0245E', }, fixed: { width: '6px', height: '6px', }, } export default Box
expo/www/core/modules/quickedit/js/views/AppView.js
318io/318-io
/** * @file * A Backbone View that controls the overall "in-place editing application". * * @see Drupal.quickedit.AppModel */ (function ($, _, Backbone, Drupal) { 'use strict'; // Indicates whether the page should be reloaded after in-place editing has // shut down. A page reload is necessary to re-instate the original HTML of // the edited fields if in-place editing has been canceled and one or more of // the entity's fields were saved to PrivateTempStore: one of them may have // been changed to the empty value and hence may have been rerendered as the // empty string, which makes it impossible for Quick Edit to know where to // restore the original HTML. var reload = false; Drupal.quickedit.AppView = Backbone.View.extend(/** @lends Drupal.quickedit.AppView# */{ /** * @constructs * * @augments Backbone.View * * @param {object} options * An object with the following keys: * @param {Drupal.quickedit.AppModel} options.model * The application state model. * @param {Drupal.quickedit.EntityCollection} options.entitiesCollection * All on-page entities. * @param {Drupal.quickedit.FieldCollection} options.fieldsCollection * All on-page fields */ initialize: function (options) { // AppView's configuration for handling states. // @see Drupal.quickedit.FieldModel.states this.activeFieldStates = ['activating', 'active']; this.singleFieldStates = ['highlighted', 'activating', 'active']; this.changedFieldStates = ['changed', 'saving', 'saved', 'invalid']; this.readyFieldStates = ['candidate', 'highlighted']; // Track app state. this.listenTo(options.entitiesCollection, 'change:state', this.appStateChange); this.listenTo(options.entitiesCollection, 'change:isActive', this.enforceSingleActiveEntity); // Track app state. this.listenTo(options.fieldsCollection, 'change:state', this.editorStateChange); // Respond to field model HTML representation change events. this.listenTo(options.fieldsCollection, 'change:html', this.renderUpdatedField); this.listenTo(options.fieldsCollection, 'change:html', this.propagateUpdatedField); // Respond to addition. this.listenTo(options.fieldsCollection, 'add', this.rerenderedFieldToCandidate); // Respond to destruction. this.listenTo(options.fieldsCollection, 'destroy', this.teardownEditor); }, /** * Handles setup/teardown and state changes when the active entity changes. * * @param {Drupal.quickedit.EntityModel} entityModel * An instance of the EntityModel class. * @param {string} state * The state of the associated field. One of * {@link Drupal.quickedit.EntityModel.states}. */ appStateChange: function (entityModel, state) { var app = this; var entityToolbarView; switch (state) { case 'launching': reload = false; // First, create an entity toolbar view. entityToolbarView = new Drupal.quickedit.EntityToolbarView({ model: entityModel, appModel: this.model }); entityModel.toolbarView = entityToolbarView; // Second, set up in-place editors. // They must be notified of state changes, hence this must happen // while the associated fields are still in the 'inactive' state. entityModel.get('fields').each(function (fieldModel) { app.setupEditor(fieldModel); }); // Third, transition the entity to the 'opening' state, which will // transition all fields from 'inactive' to 'candidate'. _.defer(function () { entityModel.set('state', 'opening'); }); break; case 'closed': entityToolbarView = entityModel.toolbarView; // First, tear down the in-place editors. entityModel.get('fields').each(function (fieldModel) { app.teardownEditor(fieldModel); }); // Second, tear down the entity toolbar view. if (entityToolbarView) { entityToolbarView.remove(); delete entityModel.toolbarView; } // A page reload may be necessary to re-instate the original HTML of // the edited fields. if (reload) { reload = false; location.reload(); } break; } }, /** * Accepts or reject editor (Editor) state changes. * * This is what ensures that the app is in control of what happens. * * @param {string} from * The previous state. * @param {string} to * The new state. * @param {null|object} context * The context that is trying to trigger the state change. * @param {Drupal.quickedit.FieldModel} fieldModel * The fieldModel to which this change applies. * * @return {bool} * Whether the editor change was accepted or rejected. */ acceptEditorStateChange: function (from, to, context, fieldModel) { var accept = true; // If the app is in view mode, then reject all state changes except for // those to 'inactive'. if (context && (context.reason === 'stop' || context.reason === 'rerender')) { if (from === 'candidate' && to === 'inactive') { accept = true; } } // Handling of edit mode state changes is more granular. else { // In general, enforce the states sequence. Disallow going back from a // "later" state to an "earlier" state, except in explicitly allowed // cases. if (!Drupal.quickedit.FieldModel.followsStateSequence(from, to)) { accept = false; // Allow: activating/active -> candidate. // Necessary to stop editing a field. if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') { accept = true; } // Allow: changed/invalid -> candidate. // Necessary to stop editing a field when it is changed or invalid. else if ((from === 'changed' || from === 'invalid') && to === 'candidate') { accept = true; } // Allow: highlighted -> candidate. // Necessary to stop highlighting a field. else if (from === 'highlighted' && to === 'candidate') { accept = true; } // Allow: saved -> candidate. // Necessary when successfully saved a field. else if (from === 'saved' && to === 'candidate') { accept = true; } // Allow: invalid -> saving. // Necessary to be able to save a corrected, invalid field. else if (from === 'invalid' && to === 'saving') { accept = true; } // Allow: invalid -> activating. // Necessary to be able to correct a field that turned out to be // invalid after the user already had moved on to the next field // (which we explicitly allow to have a fluent UX). else if (from === 'invalid' && to === 'activating') { accept = true; } } // If it's not against the general principle, then here are more // disallowed cases to check. if (accept) { var activeField; var activeFieldState; // Ensure only one field (editor) at a time is active … but allow a // user to hop from one field to the next, even if we still have to // start saving the field that is currently active: assume it will be // valid, to allow for a fluent UX. (If it turns out to be invalid, // this block of code also handles that.) if ((this.readyFieldStates.indexOf(from) !== -1 || from === 'invalid') && this.activeFieldStates.indexOf(to) !== -1) { activeField = this.model.get('activeField'); if (activeField && activeField !== fieldModel) { activeFieldState = activeField.get('state'); // Allow the state change. If the state of the active field is: // - 'activating' or 'active': change it to 'candidate' // - 'changed' or 'invalid': change it to 'saving' // - 'saving' or 'saved': don't do anything. if (this.activeFieldStates.indexOf(activeFieldState) !== -1) { activeField.set('state', 'candidate'); } else if (activeFieldState === 'changed' || activeFieldState === 'invalid') { activeField.set('state', 'saving'); } // If the field that's being activated is in fact already in the // invalid state (which can only happen because above we allowed // the user to move on to another field to allow for a fluent UX; // we assumed it would be saved successfully), then we shouldn't // allow the field to enter the 'activating' state, instead, we // simply change the active editor. All guarantees and // assumptions for this field still hold! if (from === 'invalid') { this.model.set('activeField', fieldModel); accept = false; } // Do not reject: the field is either in the 'candidate' or // 'highlighted' state and we allow it to enter the 'activating' // state! } } // Reject going from activating/active to candidate because of a // mouseleave. else if (_.indexOf(this.activeFieldStates, from) !== -1 && to === 'candidate') { if (context && context.reason === 'mouseleave') { accept = false; } } // When attempting to stop editing a changed/invalid property, ask for // confirmation. else if ((from === 'changed' || from === 'invalid') && to === 'candidate') { if (context && context.reason === 'mouseleave') { accept = false; } else { // Check whether the transition has been confirmed? if (context && context.confirmed) { accept = true; } } } } } return accept; }, /** * Sets up the in-place editor for the given field. * * Must happen before the fieldModel's state is changed to 'candidate'. * * @param {Drupal.quickedit.FieldModel} fieldModel * The field for which an in-place editor must be set up. */ setupEditor: function (fieldModel) { // Get the corresponding entity toolbar. var entityModel = fieldModel.get('entity'); var entityToolbarView = entityModel.toolbarView; // Get the field toolbar DOM root from the entity toolbar. var fieldToolbarRoot = entityToolbarView.getToolbarRoot(); // Create in-place editor. var editorName = fieldModel.get('metadata').editor; var editorModel = new Drupal.quickedit.EditorModel(); var editorView = new Drupal.quickedit.editors[editorName]({ el: $(fieldModel.get('el')), model: editorModel, fieldModel: fieldModel }); // Create in-place editor's toolbar for this field — stored inside the // entity toolbar, the entity toolbar will position itself appropriately // above (or below) the edited element. var toolbarView = new Drupal.quickedit.FieldToolbarView({ el: fieldToolbarRoot, model: fieldModel, $editedElement: $(editorView.getEditedElement()), editorView: editorView, entityModel: entityModel }); // Create decoration for edited element: padding if necessary, sets // classes on the element to style it according to the current state. var decorationView = new Drupal.quickedit.FieldDecorationView({ el: $(editorView.getEditedElement()), model: fieldModel, editorView: editorView }); // Track these three views in FieldModel so that we can tear them down // correctly. fieldModel.editorView = editorView; fieldModel.toolbarView = toolbarView; fieldModel.decorationView = decorationView; }, /** * Tears down the in-place editor for the given field. * * Must happen after the fieldModel's state is changed to 'inactive'. * * @param {Drupal.quickedit.FieldModel} fieldModel * The field for which an in-place editor must be torn down. */ teardownEditor: function (fieldModel) { // Early-return if this field was not yet decorated. if (typeof fieldModel.editorView === 'undefined') { return; } // Unbind event handlers; remove toolbar element; delete toolbar view. fieldModel.toolbarView.remove(); delete fieldModel.toolbarView; // Unbind event handlers; delete decoration view. Don't remove the element // because that would remove the field itself. fieldModel.decorationView.remove(); delete fieldModel.decorationView; // Unbind event handlers; delete editor view. Don't remove the element // because that would remove the field itself. fieldModel.editorView.remove(); delete fieldModel.editorView; }, /** * Asks the user to confirm whether he wants to stop editing via a modal. * * @param {Drupal.quickedit.EntityModel} entityModel * An instance of the EntityModel class. * * @see Drupal.quickedit.AppView#acceptEditorStateChange */ confirmEntityDeactivation: function (entityModel) { var that = this; var discardDialog; function closeDiscardDialog(action) { discardDialog.close(action); // The active modal has been removed. that.model.set('activeModal', null); // If the targetState is saving, the field must be saved, then the // entity must be saved. if (action === 'save') { entityModel.set('state', 'committing', {confirmed: true}); } else { entityModel.set('state', 'deactivating', {confirmed: true}); // Editing has been canceled and the changes will not be saved. Mark // the page for reload if the entityModel declares that it requires // a reload. if (entityModel.get('reload')) { reload = true; entityModel.set('reload', false); } } } // Only instantiate if there isn't a modal instance visible yet. if (!this.model.get('activeModal')) { var $unsavedChanges = $('<div>' + Drupal.t('You have unsaved changes') + '</div>'); discardDialog = Drupal.dialog($unsavedChanges.get(0), { title: Drupal.t('Discard changes?'), dialogClass: 'quickedit-discard-modal', resizable: false, buttons: [ { text: Drupal.t('Save'), click: function () { closeDiscardDialog('save'); }, primary: true }, { text: Drupal.t('Discard changes'), click: function () { closeDiscardDialog('discard'); } } ], // Prevent this modal from being closed without the user making a // choice as per http://stackoverflow.com/a/5438771. closeOnEscape: false, create: function () { $(this).parent().find('.ui-dialog-titlebar-close').remove(); }, beforeClose: false, close: function (event) { // Automatically destroy the DOM element that was used for the // dialog. $(event.target).remove(); } }); this.model.set('activeModal', discardDialog); discardDialog.showModal(); } }, /** * Reacts to field state changes; tracks global state. * * @param {Drupal.quickedit.FieldModel} fieldModel * The `fieldModel` holding the state. * @param {string} state * The state of the associated field. One of * {@link Drupal.quickedit.FieldModel.states}. */ editorStateChange: function (fieldModel, state) { var from = fieldModel.previous('state'); var to = state; // Keep track of the highlighted field in the global state. if (_.indexOf(this.singleFieldStates, to) !== -1 && this.model.get('highlightedField') !== fieldModel) { this.model.set('highlightedField', fieldModel); } else if (this.model.get('highlightedField') === fieldModel && to === 'candidate') { this.model.set('highlightedField', null); } // Keep track of the active field in the global state. if (_.indexOf(this.activeFieldStates, to) !== -1 && this.model.get('activeField') !== fieldModel) { this.model.set('activeField', fieldModel); } else if (this.model.get('activeField') === fieldModel && to === 'candidate') { // Discarded if it transitions from a changed state to 'candidate'. if (from === 'changed' || from === 'invalid') { fieldModel.editorView.revert(); } this.model.set('activeField', null); } }, /** * Render an updated field (a field whose 'html' attribute changed). * * @param {Drupal.quickedit.FieldModel} fieldModel * The FieldModel whose 'html' attribute changed. * @param {string} html * The updated 'html' attribute. * @param {object} options * An object with the following keys: * @param {bool} options.propagation * Whether this change to the 'html' attribute occurred because of the * propagation of changes to another instance of this field. */ renderUpdatedField: function (fieldModel, html, options) { // Get data necessary to rerender property before it is unavailable. var $fieldWrapper = $(fieldModel.get('el')); var $context = $fieldWrapper.parent(); var renderField = function () { // Destroy the field model; this will cause all attached views to be // destroyed too, and removal from all collections in which it exists. fieldModel.destroy(); // Replace the old content with the new content. $fieldWrapper.replaceWith(html); // Attach behaviors again to the modified piece of HTML; this will // create a new field model and call rerenderedFieldToCandidate() with // it. Drupal.attachBehaviors($context.get(0)); }; // When propagating the changes of another instance of this field, this // field is not being actively edited and hence no state changes are // necessary. So: only update the state of this field when the rerendering // of this field happens not because of propagation, but because it is // being edited itself. if (!options.propagation) { // Deferred because renderUpdatedField is reacting to a field model // change event, and we want to make sure that event fully propagates // before making another change to the same model. _.defer(function () { // First set the state to 'candidate', to allow all attached views to // clean up all their "active state"-related changes. fieldModel.set('state', 'candidate'); // Similarly, the above .set() call's change event must fully // propagate before calling it again. _.defer(function () { // Set the field's state to 'inactive', to enable the updating of // its DOM value. fieldModel.set('state', 'inactive', {reason: 'rerender'}); renderField(); }); }); } else { renderField(); } }, /** * Propagates changes to an updated field to all instances of that field. * * @param {Drupal.quickedit.FieldModel} updatedField * The FieldModel whose 'html' attribute changed. * @param {string} html * The updated 'html' attribute. * @param {object} options * An object with the following keys: * @param {bool} options.propagation * Whether this change to the 'html' attribute occurred because of the * propagation of changes to another instance of this field. * * @see Drupal.quickedit.AppView#renderUpdatedField */ propagateUpdatedField: function (updatedField, html, options) { // Don't propagate field updates that themselves were caused by // propagation. if (options.propagation) { return; } var htmlForOtherViewModes = updatedField.get('htmlForOtherViewModes'); Drupal.quickedit.collections.fields // Find all instances of fields that display the same logical field // (same entity, same field, just a different instance and maybe a // different view mode). .where({logicalFieldID: updatedField.get('logicalFieldID')}) .forEach(function (field) { // Ignore the field that was already updated. if (field === updatedField) { return; } // If this other instance of the field has the same view mode, we can // update it easily. else if (field.getViewMode() === updatedField.getViewMode()) { field.set('html', updatedField.get('html')); } // If this other instance of the field has a different view mode, and // that is one of the view modes for which a re-rendered version is // available (and that should be the case unless this field was only // added to the page after editing of the updated field began), then // use that view mode's re-rendered version. else { if (field.getViewMode() in htmlForOtherViewModes) { field.set('html', htmlForOtherViewModes[field.getViewMode()], {propagation: true}); } } }); }, /** * If the new in-place editable field is for the entity that's currently * being edited, then transition it to the 'candidate' state. * * This happens when a field was modified, saved and hence rerendered. * * @param {Drupal.quickedit.FieldModel} fieldModel * A field that was just added to the collection of fields. */ rerenderedFieldToCandidate: function (fieldModel) { var activeEntity = Drupal.quickedit.collections.entities.findWhere({isActive: true}); // Early-return if there is no active entity. if (!activeEntity) { return; } // If the field's entity is the active entity, make it a candidate. if (fieldModel.get('entity') === activeEntity) { this.setupEditor(fieldModel); fieldModel.set('state', 'candidate'); } }, /** * EntityModel Collection change handler. * * Handler is called `change:isActive` and enforces a single active entity. * * @param {Drupal.quickedit.EntityModel} changedEntityModel * The entityModel instance whose active state has changed. */ enforceSingleActiveEntity: function (changedEntityModel) { // When an entity is deactivated, we don't need to enforce anything. if (changedEntityModel.get('isActive') === false) { return; } // This entity was activated; deactivate all other entities. changedEntityModel.collection.chain() .filter(function (entityModel) { return entityModel.get('isActive') === true && entityModel !== changedEntityModel; }) .each(function (entityModel) { entityModel.set('state', 'deactivating'); }); } }); }(jQuery, _, Backbone, Drupal));
ajax/libs/react-dom/18.1.0-next-0568c0f8c-20220409/umd/react-dom-test-utils.development.min.js
cdnjs/cdnjs
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-dom"],t):t((e=e||self).ReactTestUtils={},e.React,e.ReactDOM)}(this,function(e,s,u){"use strict";var o=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function a(e,t,n){var r=o.ReactDebugCurrentFrame.getStackAddendum();""!==r&&(t+="%s",n=n.concat([r]));n=n.map(function(e){return String(e)});n.unshift("Warning: "+t),Function.prototype.apply.call(console[e],console,n)}function r(e){return e._reactInternals}var i=0,c=1,d=3,l=5,p=6;o.ReactCurrentOwner;function f(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else for(var r=t;0!=(4098&(t=r).flags)&&(n=t.return),r=t.return;);return t.tag===d?n:null}function h(e){if(f(e)!==e)throw new Error("Unable to find node on an unmounted component.")}var m=Object.assign;function n(e){var t,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,32<=(t=10===t?13:t)||13===t?t:0}function y(){return!0}function v(){return!1}function t(s){function e(e,t,n,r,o){for(var a in this._reactName=e,this._targetInst=n,this.type=t,this.nativeEvent=r,this.target=o,this.currentTarget=null,s){var i;s.hasOwnProperty(a)&&(i=s[a],this[a]=i?i(r):r[a])}o=null!=r.defaultPrevented?r.defaultPrevented:!1===r.returnValue;return this.isDefaultPrevented=o?y:v,this.isPropagationStopped=v,this}return m(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=y)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=y)},persist:function(){},isPersistent:y}),e}var w,g,E,b={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},C=t(b),k=m({},b,{view:0,detail:0});t(k);var D=m({},k,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:O,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:((e=e)!==E&&(g=E&&"mousemove"===e.type?(w=e.screenX-E.screenX,e.screenY-E.screenY):w=0,E=e),w)},movementY:function(e){return"movementY"in e?e.movementY:g}}),T=(t(D),t(m({},D,{dataTransfer:0})),t(m({},k,{relatedTarget:0})),t(m({},b,{animationName:0,elapsedTime:0,pseudoElement:0})),t(m({},b,{clipboardData:function(e){return("clipboardData"in e?e:window).clipboardData}})),t(m({},b,{data:0})),{Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"}),_={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};var M={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function R(e){var t=this.nativeEvent;if(t.getModifierState)return t.getModifierState(e);e=M[e];return!!e&&!!t[e]}function O(e){return R}t(m({},k,{key:function(e){if(e.key){var t=T[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"!==e.type?"keydown"===e.type||"keyup"===e.type?_[e.keyCode]||"Unidentified":"":13===(e=n(e))?"Enter":String.fromCharCode(e)},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:O,charCode:function(e){return"keypress"===e.type?n(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?n(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}})),t(m({},D,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),t(m({},k,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:O})),t(m({},b,{propertyName:0,elapsedTime:0,pseudoElement:0})),t(m({},D,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}));var S=1;function P(e,t,n,r,o,a,i,s,u){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(e){this.onError(e)}}var U,D=P;"undefined"!=typeof window&&"function"==typeof window.dispatchEvent&&"undefined"!=typeof document&&"function"==typeof document.createEvent&&(U=document.createElement("react"),D=function(e,t,n,r,o,a,i,s,u){if("undefined"==typeof document||null===document)throw new Error("The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.");var c=document.createEvent("Event"),l=!1,d=!0,p=window.event,f=Object.getOwnPropertyDescriptor(window,"event");function h(){U.removeEventListener(b,v,!1),void 0!==window.event&&window.hasOwnProperty("event")&&(window.event=p)}var m,y=Array.prototype.slice.call(arguments,3);function v(){l=!0,h(),t.apply(n,y),d=!1}var w=!1,g=!1;function E(e){if(m=e.error,w=!0,null===m&&0===e.colno&&0===e.lineno&&(g=!0),e.defaultPrevented&&null!=m&&"object"==typeof m)try{m._suppressLogging=!0}catch(e){}}var b="react-"+(e||"invokeguardedcallback");if(window.addEventListener("error",E),U.addEventListener(b,v,!1),c.initEvent(b,!1,!1),U.dispatchEvent(c),f&&Object.defineProperty(window,"event",f),l&&d&&(w?g&&(m=new Error("A cross-origin error was thrown. React doesn't have access to the actual error object in development. See https://reactjs.org/link/crossorigin-error for more information.")):m=new Error("An error was thrown inside one of your components, but React doesn't know what it was. This is likely due to browser flakiness. React does its best to preserve the \"Pause on exceptions\" behavior of the DevTools, which requires some DEV-mode only tricks. It's possible that these don't work in your browser. Try triggering the error in production mode, or switching to a modern browser. If you suspect that this is actually an issue with React, please file an issue."),this.onError(m)),window.removeEventListener("error",E),!l)return h(),P.apply(this,arguments)});var L=D,I=!1,N=null,A=!1,W=null,x={onError:function(e){I=!0,N=e}};function K(){var e;!function(e,t,n,r,o,a,i,s,u){I=!1,N=null,L.apply(x,arguments)}.apply(this,arguments),I&&(e=function(){{if(I){var e=N;return I=!1,N=null,e}throw new Error("clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.")}}(),A||(A=!0,W=e))}var Y=Array.isArray;function F(e){return Y(e)}var D=u.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events,X=D[0],j=D[1],V=D[2],B=D[3],q=D[4],D=s.unstable_act;function z(e){}var H=!1;function Z(e,t){if(!e)return[];var n=function(e){var t=e.alternate;if(!t){var n=f(e);if(null===n)throw new Error("Unable to find node on an unmounted component.");return n!==e?null:e}for(var r=e,o=t;;){var a=r.return;if(null===a)break;var i=a.alternate;if(null!==i){if(a.child===i.child){for(var s=a.child;s;){if(s===r)return h(a),e;if(s===o)return h(a),t;s=s.sibling}throw new Error("Unable to find node on an unmounted component.")}if(r.return!==o.return)r=a,o=i;else{for(var u=!1,c=a.child;c;){if(c===r){u=!0,r=a,o=i;break}if(c===o){u=!0,o=a,r=i;break}c=c.sibling}if(!u){for(c=i.child;c;){if(c===r){u=!0,r=i,o=a;break}if(c===o){u=!0,o=i,r=a;break}c=c.sibling}if(!u)throw new Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.")}}if(r.alternate!==o)throw new Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.")}else{var l=a.return;if(null===l)break;r=o=l}}if(r.tag!==d)throw new Error("Unable to find node on an unmounted component.");return r.stateNode.current===r?e:t}(e);if(!n)return[];for(var r,o=n,a=[];;)if(o.tag!==l&&o.tag!==p&&o.tag!==c&&o.tag!==i||t(r=o.stateNode)&&a.push(r),o.child)o=(o.child.return=o).child;else{if(o===n)return a;for(;!o.sibling;){if(!o.return||o.return===n)return a;o=o.return}o.sibling.return=o.return,o=o.sibling}}function G(e,t){if(e&&!r(e)){var n=String(e),n=F(e)?"an array":e&&e.nodeType===S&&e.tagName?"a DOM node":"[object Object]"===n?"object with keys {"+Object.keys(e).join(", ")+"}":n;throw new Error(t+"(...): the first argument must be a React class instance. Instead received: "+n+".")}}function J(e){return!(!e||e.nodeType!==S||!e.tagName)}function Q(e){return!J(e)&&(null!=e&&"function"==typeof e.render&&"function"==typeof e.setState)}function $(e,t){return!!Q(e)&&r(e).type===t}function ee(e,t){return G(e,"findAllInRenderedTree"),e?Z(r(e),t):[]}function te(e,r){return G(e,"scryRenderedDOMComponentsWithClass"),ee(e,function(e){if(J(e)){var t=e.className,n=(t="string"!=typeof t?e.getAttribute("class")||"":t).split(/\s+/);if(!F(r)){if(void 0===r)throw new Error("TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.");r=r.split(/\s+/)}return r.every(function(e){return-1!==n.indexOf(e)})}return!1})}function ne(e,t){return G(e,"scryRenderedDOMComponentsWithTag"),ee(e,function(e){return J(e)&&e.tagName.toUpperCase()===t.toUpperCase()})}function re(e,t){return G(e,"scryRenderedComponentsWithType"),ee(e,function(e){return $(e,t)})}function oe(e,t,n){var r=e.type||"unknown-event";e.currentTarget=j(n),K(r,t,void 0,e),e.currentTarget=null}var ae=function(e){e&&(function(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(F(t))for(var r=0;r<t.length&&!e.isPropagationStopped();r++)oe(e,t[r],n[r]);else t&&oe(e,t,n);e._dispatchListeners=null,e._dispatchInstances=null}(e),e.isPersistent()||e.constructor.release(e))};function ie(e,t,n){for(var r,o=[];e;)o.push(e),e=function(e){for(;(e=e.return)&&e.tag!==l;);return e||null}(e);for(r=o.length;0<r--;)t(o[r],"captured",n);for(r=0;r<o.length;r++)t(o[r],"bubbled",n)}function se(e,t){var n=e.stateNode;if(!n)return null;var r=V(n);if(!r)return null;n=r[t];if(function(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":return n.disabled&&("button"===(r=t)||"input"===r||"select"===r||"textarea"===r);default:return}var r}(t,e.type,r))return null;if(n&&"function"!=typeof n)throw new Error("Expected `"+t+"` listener to be a function, instead got a value of `"+typeof n+"` type.");return n}function ue(e,t,n){e||function(e){for(var t=arguments.length,n=new Array(1<t?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];a("error",e,n)}("Dispatching inst must not be null");var r,r=(r=(r=n)._reactName,"captured"===t&&(r+="Capture"),se(e,r));r&&(null==n._dispatchListeners&&(n._dispatchListeners=[]),null==n._dispatchInstances&&(n._dispatchInstances=[]),n._dispatchListeners.push(r),n._dispatchInstances.push(e))}function ce(e){var t,n;e&&e._reactName&&(t=e._targetInst,n=e,t&&n&&n._reactName&&((e=se(t,n._reactName))&&(null==n._dispatchListeners&&(n._dispatchListeners=[]),null==n._dispatchInstances&&(n._dispatchInstances=[]),n._dispatchListeners.push(e),n._dispatchInstances.push(t))))}var le={},de=new Set(["mouseEnter","mouseLeave","pointerEnter","pointerLeave"]);function pe(i){return function(e,t){if(s.isValidElement(e))throw new Error("TestUtils.Simulate expected a DOM node as the first argument but received a React element. Pass the DOM node you wish to simulate the event on instead. Note that TestUtils.Simulate will not work if you are using shallow rendering.");if(Q(e))throw new Error("TestUtils.Simulate expected a DOM node as the first argument but received a component instance. Pass the DOM node you wish to simulate the event on instead.");var n="on"+i[0].toUpperCase()+i.slice(1),r=new z;r.target=e,r.type=i.toLowerCase();var o=X(e),a=new C(n,r.type,o,r,e);a.persist(),m(a,t),de.has(i)?ce(a):(t=a)&&t._reactName&&ie(t._targetInst,ue,t),u.unstable_batchedUpdates(function(){B(e),ae(a),function(){if(A){var e=W;throw A=!1,W=null,e}}()}),q()}}["blur","cancel","click","close","contextMenu","copy","cut","auxClick","doubleClick","dragEnd","dragStart","drop","focus","input","invalid","keyDown","keyPress","keyUp","mouseDown","mouseUp","paste","pause","play","pointerCancel","pointerDown","pointerUp","rateChange","reset","resize","seeked","submit","touchCancel","touchEnd","touchStart","volumeChange","drag","dragEnter","dragExit","dragLeave","dragOver","mouseMove","mouseOut","mouseOver","pointerMove","pointerOut","pointerOver","scroll","toggle","touchMove","wheel","abort","animationEnd","animationIteration","animationStart","canPlay","canPlayThrough","durationChange","emptied","encrypted","ended","error","gotPointerCapture","load","loadedData","loadedMetadata","loadStart","lostPointerCapture","playing","progress","seeking","stalled","suspend","timeUpdate","transitionEnd","waiting","mouseEnter","mouseLeave","pointerEnter","pointerLeave","change","select","beforeInput","compositionEnd","compositionStart","compositionUpdate"].forEach(function(e){le[e]=pe(e)}),e.Simulate=le,e.act=D,e.findAllInRenderedTree=ee,e.findRenderedComponentWithType=function(e,t){if(G(e,"findRenderedComponentWithType"),1!==(e=re(e,t)).length)throw new Error("Did not find exactly one match (found: "+e.length+") for componentType:"+t);return e[0]},e.findRenderedDOMComponentWithClass=function(e,t){if(G(e,"findRenderedDOMComponentWithClass"),1!==(e=te(e,t)).length)throw new Error("Did not find exactly one match (found: "+e.length+") for class:"+t);return e[0]},e.findRenderedDOMComponentWithTag=function(e,t){if(G(e,"findRenderedDOMComponentWithTag"),1!==(e=ne(e,t)).length)throw new Error("Did not find exactly one match (found: "+e.length+") for tag:"+t);return e[0]},e.isCompositeComponent=Q,e.isCompositeComponentWithType=$,e.isDOMComponent=J,e.isDOMComponentElement=function(e){return!!(e&&s.isValidElement(e)&&e.tagName)},e.isElement=function(e){return s.isValidElement(e)},e.isElementOfType=function(e,t){return s.isValidElement(e)&&e.type===t},e.mockComponent=function(e,t){return H||(H=!0,function(e){for(var t=arguments.length,n=new Array(1<t?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];a("warn",e,n)}("ReactTestUtils.mockComponent() is deprecated. Use shallow rendering or jest.mock() instead.\n\nSee https://reactjs.org/link/test-utils-mock-component for more information.")),t=t||e.mockTagName||"div",e.prototype.render.mockImplementation(function(){return s.createElement(t,null,this.props.children)}),this},e.nativeTouchData=function(e,t){return{touches:[{pageX:e,pageY:t}]}},e.renderIntoDocument=function(e){var t=document.createElement("div");return u.render(e,t)},e.scryRenderedComponentsWithType=re,e.scryRenderedDOMComponentsWithClass=te,e.scryRenderedDOMComponentsWithTag=ne,e.traverseTwoPhase=ie});
ajax/libs/analytics.js/2.3.19/analytics.min.js
steakknife/cdnjs
(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require})({1:[function(require,module,exports){var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("./version");each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"./version":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/awesm"),require("./lib/awesomatic"),require("./lib/bing-ads"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hublo"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/leadlander"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/awesm":13,"./lib/awesomatic":14,"./lib/bing-ads":15,"./lib/bronto":16,"./lib/bugherd":17,"./lib/bugsnag":18,"./lib/chartbeat":19,"./lib/churnbee":20,"./lib/clicktale":21,"./lib/clicky":22,"./lib/comscore":23,"./lib/crazy-egg":24,"./lib/curebit":25,"./lib/customerio":26,"./lib/drip":27,"./lib/errorception":28,"./lib/evergage":29,"./lib/facebook-conversion-tracking":30,"./lib/foxmetrics":31,"./lib/frontleaf":32,"./lib/gauges":33,"./lib/get-satisfaction":34,"./lib/google-analytics":35,"./lib/google-tag-manager":36,"./lib/gosquared":37,"./lib/heap":38,"./lib/hellobar":39,"./lib/hittail":40,"./lib/hublo":41,"./lib/hubspot":42,"./lib/improvely":43,"./lib/insidevault":44,"./lib/inspectlet":45,"./lib/intercom":46,"./lib/keen-io":47,"./lib/kenshoo":48,"./lib/kissmetrics":49,"./lib/klaviyo":50,"./lib/leadlander":51,"./lib/livechat":52,"./lib/lucky-orange":53,"./lib/lytics":54,"./lib/mixpanel":55,"./lib/mojn":56,"./lib/mouseflow":57,"./lib/mousestats":58,"./lib/navilytics":59,"./lib/olark":60,"./lib/optimizely":61,"./lib/perfect-audience":62,"./lib/pingdom":63,"./lib/piwik":64,"./lib/preact":65,"./lib/qualaroo":66,"./lib/quantcast":67,"./lib/rollbar":68,"./lib/saasquatch":69,"./lib/sentry":70,"./lib/snapengage":71,"./lib/spinnakr":72,"./lib/tapstream":73,"./lib/trakio":74,"./lib/twitter-ads":75,"./lib/uservoice":76,"./lib/vero":77,"./lib/visual-website-optimizer":78,"./lib/webengage":79,"./lib/woopra":80,"./lib/yandex-metrica":81}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;each(events,function(event){var data={};if(user.id())data.user_id=user.id();data.adroll_conversion_value_in_dollars=total;data.order_id=orderId;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){var data={};if(user.id())data.user_id=user.id();data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":82,"to-snake-case":83,"use-https":84,each:4,is:85}],82:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{bind:86,callback:87,clone:88,debug:89,defaults:90,"./protos":91,slug:92,"./statics":93}],86:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:94,"bind-all":95}],94:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],95:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:94,type:7}],87:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":96}],96:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],88:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],89:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":97,"./debug":98}],97:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],98:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],90:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],91:[function(require,module,exports){var loadScript=require("segmentio/load-script");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var events=require("./events");var tick=require("next-tick");var assert=require("assert");var after=require("after");var each=require("component/each");var type=require("type");var fmt=require("yields/fmt");var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=null;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];assert(template,fmt('Template "%s" not defined.',name));var attrs=render(template,locals);var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,fn);delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"segmentio/load-script":99,"to-no-case":100,callback:87,emitter:101,"./events":102,"next-tick":96,assert:103,after:104,"component/each":105,type:7,"yields/fmt":106}],99:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":107,"next-tick":96,type:7}],107:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}},{}],100:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],101:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:108}],108:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],102:[function(require,module,exports){module.exports={removedProduct:/removed[ _]?product/i,viewedProduct:/viewed[ _]?product/i,addedProduct:/added[ _]?product/i,completedOrder:/completed[ _]?order/i}},{}],103:[function(require,module,exports){var equals=require("equals");var fmt=require("fmt");var stack=require("stack");module.exports=exports=function(expr,msg){if(expr)return;throw new Error(msg||message())};exports.equal=function(actual,expected,msg){if(actual==expected)return;throw new Error(msg||fmt("Expected %o to equal %o.",actual,expected))};exports.notEqual=function(actual,expected,msg){if(actual!=expected)return;throw new Error(msg||fmt("Expected %o not to equal %o.",actual,expected))};exports.deepEqual=function(actual,expected,msg){if(equals(actual,expected))return;throw new Error(msg||fmt("Expected %o to deeply equal %o.",actual,expected))};exports.notDeepEqual=function(actual,expected,msg){if(!equals(actual,expected))return;throw new Error(msg||fmt("Expected %o not to deeply equal %o.",actual,expected))};exports.strictEqual=function(actual,expected,msg){if(actual===expected)return;throw new Error(msg||fmt("Expected %o to strictly equal %o.",actual,expected))};exports.notStrictEqual=function(actual,expected,msg){if(actual!==expected)return;throw new Error(msg||fmt("Expected %o not to strictly equal %o.",actual,expected))};exports.throws=function(block,error,msg){var err;try{block()}catch(e){err=e}if(!err)throw new Error(msg||fmt("Expected %s to throw an error.",block.toString()));if(error&&!(err instanceof error)){throw new Error(msg||fmt("Expected %s to throw an %o.",block.toString(),error))}};exports.doesNotThrow=function(block,error,msg){var err;try{block()}catch(e){err=e}if(err)throw new Error(msg||fmt("Expected %s not to throw an error.",block.toString()));if(error&&err instanceof error){throw new Error(msg||fmt("Expected %s not to throw an %o.",block.toString(),error))}};function message(){if(!Error.captureStackTrace)return"assertion failed";var callsite=stack()[2];var fn=callsite.getFunctionName();var file=callsite.getFileName();var line=callsite.getLineNumber()-1;var col=callsite.getColumnNumber()-1;var src=get(file);line=src.split("\n")[line].slice(col);var m=line.match(/assert\((.*)\)/);return m&&m[1].trim()}function get(script){var xhr=new XMLHttpRequest;xhr.open("GET",script,false);xhr.send(null);return xhr.responseText}},{equals:109,fmt:106,stack:110}],109:[function(require,module,exports){var type=require("type");module.exports=equals;equals.compare=compare;function equals(){var i=arguments.length-1;while(i>0){if(!compare(arguments[i],arguments[--i]))return false}return true}function compare(a,b,memos){if(a===b)return true;var fnA=types[type(a)];var fnB=types[type(b)];return fnA&&fnA===fnB?fnA(a,b,memos):false}var types={};types.number=function(a){return a!==a};types["function"]=function(a,b,memos){return a.toString()===b.toString()&&types.object(a,b,memos)&&compare(a.prototype,b.prototype)};types.date=function(a,b){return+a===+b};types.regexp=function(a,b){return a.toString()===b.toString()};types.element=function(a,b){return a.outerHTML===b.outerHTML};types.textnode=function(a,b){return a.textContent===b.textContent};function memoGaurd(fn){return function(a,b,memos){if(!memos)return fn(a,b,[]);var i=memos.length,memo;while(memo=memos[--i]){if(memo[0]===a&&memo[1]===b)return true}return fn(a,b,memos)}}types["arguments"]=types.array=memoGaurd(compareArrays);function compareArrays(a,b,memos){var i=a.length;if(i!==b.length)return false;memos.push([a,b]);while(i--){if(!compare(a[i],b[i],memos))return false}return true}types.object=memoGaurd(compareObjects);function compareObjects(a,b,memos){var ka=getEnumerableProperties(a);var kb=getEnumerableProperties(b);var i=ka.length;if(i!==kb.length)return false;ka.sort();kb.sort();while(i--)if(ka[i]!==kb[i])return false;memos.push([a,b]);i=ka.length;while(i--){var key=ka[i];if(!compare(a[key],b[key],memos))return false}return true}function getEnumerableProperties(object){var result=[];for(var k in object)if(k!=="constructor"){result.push(k)}return result}},{type:111}],111:[function(require,module,exports){var toString={}.toString;var DomNode=typeof window!="undefined"?window.Node:Function;module.exports=exports=function(x){var type=typeof x;if(type!="object")return type;type=types[toString.call(x)];if(type)return type;if(x instanceof DomNode)switch(x.nodeType){case 1:return"element";case 3:return"text-node";case 9:return"document";case 11:return"document-fragment";default:return"dom-node"}};var types=exports.types={"[object Function]":"function","[object Date]":"date","[object RegExp]":"regexp","[object Arguments]":"arguments","[object Array]":"array","[object String]":"string","[object Null]":"null","[object Undefined]":"undefined","[object Number]":"number","[object Boolean]":"boolean","[object Object]":"object","[object Text]":"text-node","[object Uint8Array]":"bit-array","[object Uint16Array]":"bit-array","[object Uint32Array]":"bit-array","[object Uint8ClampedArray]":"bit-array","[object Error]":"error","[object FormData]":"form-data","[object File]":"file","[object Blob]":"blob"}},{}],106:[function(require,module,exports){module.exports=fmt;fmt.o=JSON.stringify;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],110:[function(require,module,exports){module.exports=stack;function stack(){var orig=Error.prepareStackTrace;Error.prepareStackTrace=function(_,stack){return stack};var err=new Error;Error.captureStackTrace(err,arguments.callee);var stack=err.stack;Error.prepareStackTrace=orig;return stack}},{}],104:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],105:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:7,"component-type":7,"to-function":112}],112:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:113,"component-props":113}],113:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],92:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],93:[function(require,module,exports){var after=require("after");var domify=require("component/domify");var each=require("component/each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key); return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:104,"component/domify":114,"component/each":105,emitter:101}],114:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],83:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":115}],115:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":116}],116:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],84:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],85:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":117,type:7,"component-type":7}],117:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();window.google_trackConversion({google_conversion_id:id,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":82,domify:118,each:4}],118:[function(require,module,exports){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":82}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load(this.ready)};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}},{"analytics.js-integration":82}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":82,"load-script":119,is:85}],119:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":107,"next-tick":96,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":82,each:4}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var noop=function(){};var onBody=require("on-body");var Awesomatic=module.exports=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","").tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');Awesomatic.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.ready()})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)}},{"analytics.js-integration":82,is:85,"on-body":120}],120:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:105}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").option("siteId","").option("domainId","").tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">').mapping("events");Bing.prototype.initialize=function(page){if(!window.mstag){window.mstag={loadTag:noop,time:(new Date).getTime(),_write:writeToAppend}}var self=this;onbody(function(){self.load(function(){var loaded=bind(self,self.loaded);when(loaded,self.ready)})})};Bing.prototype.loaded=function(){return!!(window.mstag&&window.mstag.loadTag!==noop)};Bing.prototype.track=function(track){var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(goal){window.mstag.loadTag("analytics",{domainId:self.options.domainId,revenue:revenue,dedup:"1",type:"1",actionid:goal})})};function writeToAppend(str){var first=document.getElementsByTagName("script")[0];var el=domify(str);if("script"==el.tagName.toLowerCase()&&el.getAttribute("src")){var tmp=document.createElement("script");tmp.src=el.getAttribute("src");tmp.async=true;el=tmp}document.body.appendChild(el)}},{"analytics.js-integration":82,"on-body":120,domify:118,extend:121,bind:94,when:122,each:4}],121:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],122:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:87}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":82,facade:123,"load-pixel":124,querystring:125,each:4}],123:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":126,"./alias":127,"./group":128,"./identify":129,"./track":130,"./page":131,"./screen":132}],126:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":133,"./is-enabled":134,"./utils":135,"./address":136,"obj-case":137,"new-date":138}],133:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:139,isodate:140,each:4}],139:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":117,type:7,"component-type":7}],140:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],134:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],135:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:141,clone:142,type:7}],141:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],142:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":7,type:7}],136:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();var props=this.properties?this.properties():{};return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)||get(props,"address."+a)||get(props,a)||(b?get(props,"address."+b):null)||(b?get(props,b):null)}}}},{"obj-case":137}],137:[function(require,module,exports){var identity=function(_){return _};module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,path,val){path=normalize(path);var key;var finished=false;while(!finished)loop();function loop(){for(key in obj){var normalizedKey=normalize(key);if(0===path.indexOf(normalizedKey)){var temp=path.substr(normalizedKey.length);if(temp.charAt(0)==="."||temp.length===0){path=temp.substr(1);var child=obj[key];if(null==child){finished=true;obj=null;return}if(!path.length){finished=true;return}obj=child;return}}}key=undefined;finished=true}if(!key)return;return fn(obj,key,val)}}function find(obj,key){if(obj.hasOwnProperty(key))return obj[key]}function del(obj,key){if(obj.hasOwnProperty(key))delete obj[key];return obj}function replace(obj,key,val){if(obj.hasOwnProperty(key))obj[key]=val;return obj}function normalize(path){return path.replace(/[^a-zA-Z0-9\.]+/g,"").toLowerCase()}},{}],138:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:143,isodate:140,"./milliseconds":144,"./seconds":145}],143:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":117,type:7}],144:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],145:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],127:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":135,"./facade":126}],128:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":135,"./address":136,"is-email":146,"new-date":138,"./facade":126}],146:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],129:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday(); var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":136,"./facade":126,"is-email":146,"new-date":138,"./utils":135,"obj-case":137,trim:147}],147:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],130:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.properties(),"subtotal");var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;return total};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":135,"./facade":126,"./identify":129,"is-email":146,"obj-case":137}],131:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":135,"./facade":126,"./track":130}],132:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":135,"./page":131,"./track":130}],124:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:125,substitute:148}],125:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:147,type:7}],148:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":82,"next-tick":96}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">');Bugsnag.prototype.initialize=function(page){var self=this;this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":82,is:85,extend:121,"on-error":149}],149:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":82,defaults:150,"on-body":120}],150:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":82,"global-queue":151,each:4}],151:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],21:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":152,domify:118,each:4,"analytics.js-integration":82,is:85,"use-https":84,"on-body":120}],152:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],22:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:123,extend:121,"analytics.js-integration":82,is:85}],23:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE}},{"analytics.js-integration":82,"use-https":84}],24:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":82}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":82,"global-queue":151,facade:123,throttle:153,"to-iso-string":154,clone:155,each:4,bind:94}],153:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],154:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],155:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],26:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").assumesPageview().global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:156,"convert-dates":157,facade:123,"analytics.js-integration":82}],156:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:142}],157:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:85,clone:88}],27:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("dc").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:156,"analytics.js-integration":82,is:85,"load-script":119,"global-queue":151}],28:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:121,"analytics.js-integration":82,"on-error":149,"global-queue":151}],29:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":82,"global-queue":151}],30:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})});if(!events.length){var data=track.properties();push("track",event,data)}}},{"analytics.js-integration":82,"global-queue":151,each:4}],31:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":151,"analytics.js-integration":82,facade:123,each:4}],32:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").assumesPageview().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue }if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":82,bind:94,when:122,is:85}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":82,"global-queue":151}],34:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":82,"on-body":120}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var keys=require("object").keys;var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();window.ga("send","event",{eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId,currency:track.currency()})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}},{"analytics.js-integration":82,"global-queue":151,object:158,canonical:159,"use-https":84,facade:123,callback:87,"load-script":119,"obj-case":160,each:4,type:7,url:161,is:85}],158:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],159:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],160:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}},{"case":162}],162:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":163}],163:[function(require,module,exports){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none},{"to-camel-case":164,"to-capital-case":165,"to-constant-case":166,"to-dot-case":167,"to-no-case":116,"to-pascal-case":168,"to-sentence-case":169,"to-slug-case":170,"to-snake-case":171,"to-space-case":172,"to-title-case":173}],164:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":172}],172:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":116}],165:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":116}],166:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":171}],171:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":172}],167:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":172}],168:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":172}],169:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":116}],170:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":172}],173:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":165,"escape-regexp":174,map:175,"title-case-minors":176}],174:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],175:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:105}],176:[function(require,module,exports){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]},{}],161:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],36:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":151,"analytics.js-integration":82}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":82,facade:123,callback:87,"load-script":119,"on-body":120,each:4}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").assumesPageview().global("heap").global("_heapid").option("apiKey","").tag('<script src="//d36lvucg9kzous.cloudfront.net">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":82,alias:156}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":82}],40:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":82,is:85}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var Hublo=module.exports=integration("Hublo").assumesPageview().global("_hublo_").option("apiKey",null).tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">');Hublo.prototype.initialize=function(page){this.load(this.ready)};Hublo.prototype.loaded=function(){return!!(window._hublo_&&typeof window._hublo_.setup==="function")}},{"analytics.js-integration":82}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":82,"global-queue":151,"convert-dates":157}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":82,alias:156}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.options.events;var event=track.event();var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";if(!has.call(events,event))return;event=events[event];if(event!="sale"){push("trackEvent",event,value,eventId)}}},{"analytics.js-integration":82,"global-queue":151,facade:123,is:85}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//www.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}},{"analytics.js-integration":82,"global-queue":151,alias:156,clone:155}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(traits.company&&companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company)traits.company=alias(traits.company,{created:"created_at"});if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":82,"convert-dates":157,defaults:150,"is-email":146,"load-script":119,"is-empty":117,alias:156,each:4,when:122,is:85}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};var options=this.options;if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});props.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});props.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});props.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});props.referrer_url=document.referrer;props.page_url=document.location.href}props.keen={timestamp:identify.timestamp(),addons:addons};this.client.setGlobalProperties(function(){return props})};Keen.prototype.track=function(track){this.client.addEvent(track.event(),track.properties())}},{"analytics.js-integration":82}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">'); Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":82,indexof:108,is:85}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var Batch=require("batch");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("useless",'<script src="//i.kissmetrics.com/i.js">').tag("library",'<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});var batch=new Batch;batch.push(function(done){self.load("useless",done)});batch.push(function(done){self.load("library",done)});batch.end(function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var temp=new Track({event:event,properties:product});var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":82,"global-queue":151,facade:123,alias:156,batch:177,each:4,is:85}],177:[function(require,module,exports){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}},{emitter:178}],178:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":82,"global-queue":151,"next-tick":96,alias:156}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var LeadLander=module.exports=integration("LeadLander").assumesPageview().global("llactid").global("trackalyzer").option("accountId",null).tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load(this.ready)};LeadLander.prototype.loaded=function(){return!!window.trackalyzer}},{"analytics.js-integration":82}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":82,clone:155,each:4,facade:123,when:122}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":82,facade:123,"use-https":84}],54:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":82,alias:156}],55:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:156,clone:155,"convert-dates":157,"analytics.js-integration":82,is:85,"to-iso-string":154,indexof:108,"obj-case":160,some:179}],179:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],56:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":82,bind:94,when:122,is:85}],57:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":151,"analytics.js-integration":82,each:4}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":82,"use-https":84,each:4,is:85}],59:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":82,"global-queue":151}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":82,"use-https":84,"next-tick":96}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":82,"global-queue":151,callback:87,"next-tick":96,bind:94,each:4}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pa").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}},{"analytics.js-integration":82}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":82,"global-queue":151,"load-date":152}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue()||0;each(goals,function(goal){push("trackGoal",goal,revenue)})}},{"analytics.js-integration":82,"global-queue":151,each:4}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_lnq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":82,"convert-dates":157,"global-queue":151,alias:156}],66:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":82,"global-queue":151,facade:123,bind:94,when:122}],67:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var settings={event:"refresh",labels:this.labels("page",category,name),qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var settings={event:"click",labels:this.labels("event",name),qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var labels=this.labels("event",name);var category=track.category();if(this.options.advertise&&category){labels+=","+this.labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype.labels=function(type){var args=[].slice.call(arguments,1);var advertise=this.options.advertise;var ret=[];if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;for(var i=0;i<args.length;++i){if(null==args[i])continue;var value=String(args[i]);ret.push(value.replace(/,/g,";"))}ret=advertise?ret.join(" "):ret.join(".");return[type,ret].join(".")}},{"global-queue":151,"analytics.js-integration":82,"use-https":84}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true); RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":82,extend:121,is:85}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":82}],70:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');Sentry.prototype.initialize=function(){var config=this.options.config;var self=this;this.load(function(){window.Raven.config(config).install();self.ready()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":82,is:85}],71:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":82,is:85}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":82,bind:94,when:122}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":82,slug:92,"global-queue":151}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":82,alias:156,clone:155}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":82,each:4}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":82,"global-queue":151,"convert-dates":157,"to-unix-timestamp":180,alias:156,clone:155}],180:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}},{"analytics.js-integration":82,"global-queue":151,"component/cookie":181}],181:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}},{}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":82,"next-tick":96,each:4}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":82,"use-https":84}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":82,"to-snake-case":83,"is-email":146,extend:121,each:4,type:7}],81:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":82,"next-tick":96,bind:94,when:122}],3:[function(require,module,exports){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",message(Identify,{options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",message(Group,{options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",message(Track,{properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);properties.url=properties.url||canonicalUrl(properties.search);this._invoke("page",message(Page,{properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",message(Alias,{options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}function message(Type,msg){var ctx=msg.options||{};if(ctx.timestamp||ctx.integrations||ctx.context||ctx.anonymousId){msg=defaults(ctx,msg);delete msg.options}return new Type(msg)}},{after:104,bind:182,callback:87,canonical:159,clone:88,"./cookie":183,debug:184,defaults:90,each:4,emitter:101,"./group":185,is:85,"is-email":146,"is-meta":186,"new-date":138,event:187,prevent:188,querystring:189,object:158,"./store":190,url:161,"./user":191,facade:123}],182:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:94,"bind-all":95}],183:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:184,bind:182,cookie:181,clone:88,defaults:90,json:192,"top-domain":193}],184:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":194,"./debug":195}],194:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt; console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],195:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],192:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":196}],196:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],193:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:161}],185:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:184,"./entity":197,inherit:198,bind:182}],197:[function(require,module,exports){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.protocol=window.location.protocol;this.options(options)}Entity.prototype.storage=function(){return"file:"==this.protocol||"chrome-extension:"==this.protocol?store:cookie};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var storage=this.storage();var ret=this._options.persist?storage.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){var storage=this.storage();if(this._options.persist){storage.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{"isodate-traverse":133,defaults:90,"./cookie":183,"./store":190,extend:121,clone:88}],190:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:182,defaults:90,"store.js":199}],199:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:192}],198:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],186:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],187:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],188:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],189:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:147,type:7}],191:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{debug:184,"./entity":197,inherit:198,bind:182,"./cookie":183}],5:[function(require,module,exports){module.exports="2.3.19"},{}]},{},{1:"analytics"});
src/AsyncCreatable.js
DanielHeath/react-select
import React from 'react'; import Select from './Select'; const AsyncCreatable = React.createClass({ displayName: 'AsyncCreatableSelect', render () { return ( <Select.Async {...this.props}> {(asyncProps) => ( <Select.Creatable {...this.props}> {(creatableProps) => ( <Select {...asyncProps} {...creatableProps} onInputChange={(input) => { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); }} /> )} </Select.Creatable> )} </Select.Async> ); } }); module.exports = AsyncCreatable;
src/js/components/Carousel.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import Box from './Box'; import Tiles from './Tiles'; import Tile from './Tile'; import Button from './Button'; import PreviousIcon from './icons/base/Previous'; import NextIcon from './icons/base/Next'; import { findScrollParents } from '../utils/DOM'; import CSSClassnames from '../utils/CSSClassnames'; import Intl from '../utils/Intl'; import { announce } from '../utils/Announcer'; import Props from '../utils/Props'; const CLASS_ROOT = CSSClassnames.CAROUSEL; export default class Carousel extends Component { constructor(props, context) { super(props, context); this._onSelect = this._onSelect.bind(this); this._stopAutoplay = this._stopAutoplay.bind(this); this._startAutoplay = this._startAutoplay.bind(this); this._onResize = this._onResize.bind(this); this._slidePrev = this._slidePrev.bind(this); this._slideNext = this._slideNext.bind(this); this._handleScroll = this._handleScroll.bind(this); this._announce = this._announce.bind(this); this.state = { activeIndex: props.activeIndex || 0, animate: typeof props.activeIndex == 'undefined', hideControls: ! props.persistentNav, sequence: 1, width: 0, slide: false }; } componentDidMount () { if (this.carouselRef) { this.setState({ width: this.carouselRef.offsetWidth }); window.addEventListener('resize', this._onResize); const Hammer = require('hammerjs'); this.hammer = new Hammer(this.carouselRef); this._updateHammer(); this._handleScroll(); const scrollParents = findScrollParents(this.carouselRef); scrollParents.forEach((scrollParent) => { scrollParent.addEventListener('scroll', this._handleScroll); }, this); } } componentWillReceiveProps(nextProps) { if ((nextProps.activeIndex || 0 === nextProps.activeIndex) && this.state.activeIndex !== nextProps.activeIndex) { this.setState( { activeIndex: nextProps.activeIndex, animate: true }, this._announce ); } } componentDidUpdate () { const { autoplay } = this.props; this._updateHammer(); if (autoplay) { this._startAutoplay(); } else if (!autoplay) { this._stopAutoplay(); } } componentWillUnmount () { clearInterval(this._slideAnimation); window.removeEventListener('resize', this._onResize); const scrollParents = findScrollParents(this.carouselRef); scrollParents.forEach((scrollParent) => { scrollParent.removeEventListener('scroll', this._handleScroll); }, this); this._unmountHammer(); } _unmountHammer () { if (this.hammer) { this.hammer.stop(); this.hammer.destroy(); } this.hammer = undefined; } _updateHammer () { if (this.hammer) { this.hammer.get('swipe').set({ direction: Hammer.DIRECTION_HORIZONTAL }); this.hammer.off('panend'); this.hammer.on('panend', (event) => { if (event.direction === 4) { this._slidePrev(); } else if (event.direction === 2) { this._slideNext(); } }); } } _handleScroll () { const { autoplay } = this.props; const { slide } = this.state; const viewportHeight = document.documentElement.clientHeight; const carouselTopPosition = this.carouselRef.getBoundingClientRect().top; const carouselHeight = this.carouselRef.offsetHeight; const startScroll = viewportHeight - (carouselHeight / 2); if (autoplay && carouselTopPosition <= startScroll && carouselTopPosition >= -carouselHeight / 2) { if (slide === false) { this._setSlideInterval(); this.setState({ slide: true }); } } else { clearInterval(this._slideAnimation); this.setState({ slide: false }); } } _announce() { const { intl } = this.context; const slideNumber = Intl.getMessage(intl, 'Slide Number', { slideNumber: this.state.activeIndex + 1 }); const activatedMessage = Intl.getMessage(intl, 'Activated'); announce(`${slideNumber} ${activatedMessage}`, 'polite'); } _setSlideInterval () { const { autoplaySpeed } = this.props; clearInterval(this._slideAnimation); this._slideAnimation = setInterval(function () { const { children, infinite } = this.props; const { activeIndex } = this.state; const numSlides = children.length; const index = (activeIndex + 1) % numSlides; if (! this.props.hasOwnProperty('activeIndex')) { this.setState({ activeIndex: index }, this._announce ); } if (!infinite && activeIndex === numSlides - 1) { clearInterval(this._slideAnimation); } if (this.props.onActive) { this.props.onActive(index); } }.bind(this), autoplaySpeed); } _onSelect (index) { if (! this.props.hasOwnProperty('activeIndex') && index !== this.state.activeIndex) { this.setState({ activeIndex: index }, this._announce); } if (this.props.onActive) { this.props.onActive(index); } } _stopAutoplay () { const { persistentNav } = this.props; if (this._slideAnimation) { clearInterval(this._slideAnimation); } if (!persistentNav) { this.setState({ hideControls: false }); } } _startAutoplay () { const { activeIndex } = this.state; const { autoplay, children, infinite, persistentNav } = this.props; if (autoplay && (infinite || activeIndex !== children.length - 1) && // making sure to only start autoplay if the focus is not inside // the carousel !this.carouselRef.contains(document.activeElement)) { this._setSlideInterval(); } if (!persistentNav) { this.setState({ hideControls: true }); } } _onResize () { this.setState({ width: this.carouselRef.offsetWidth }); } _slidePrev () { const { children } = this.props; const { activeIndex } = this.state; const numSlides = children.length; const index = !this.props.infinite && activeIndex === 0 ? activeIndex : (activeIndex + numSlides - 1) % numSlides; if(! this.props.hasOwnProperty('activeIndex')) { this.setState({ activeIndex: index }, this._announce); } if (this.props.onActive) { this.props.onActive(index); } } _slideNext () { const { children } = this.props; const { activeIndex } = this.state; const numSlides = children.length; const index = !this.props.infinite && activeIndex === children.length - 1 ? activeIndex : (activeIndex + 1) % numSlides; if(! this.props.hasOwnProperty('activeIndex')) { this.setState({ activeIndex: index }, this._announce); } if (this.props.onActive) { this.props.onActive(index); } } _renderPrevButton () { const { infinite } = this.props; const { activeIndex } = this.state; const { intl } = this.context; let prevButton; if (infinite || activeIndex !== 0) { const prevMessage = Intl.getMessage(intl, 'Previous Slide'); prevButton = ( <Button icon={<PreviousIcon size="large" />} a11yTitle={prevMessage} className={`${CLASS_ROOT}__arrow ${CLASS_ROOT}__arrow--prev`} onClick={this._slidePrev} /> ); } return prevButton; } _renderNextButton () { const { children, infinite } = this.props; const { activeIndex } = this.state; const { intl } = this.context; let nextButton; if (infinite || activeIndex !== children.length - 1) { const nextMessage = Intl.getMessage(intl, 'Next Slide'); nextButton = ( <Button icon={<NextIcon size="large" />} a11yTitle={nextMessage} className={`${CLASS_ROOT}__arrow ${CLASS_ROOT}__arrow--next`} onClick={this._slideNext} /> ); } return nextButton; } render () { const { a11yTitle, children, className, ...props } = this.props; delete props.activeIndex; delete props.onActive; const restProps = Props.omit({...props}, Object.keys(Carousel.propTypes)); const { activeIndex, hideControls, width } = this.state; const { intl } = this.context; const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--hide-controls`]: hideControls }, className ); const trackWidth = width * children.length; const trackOffset = width * activeIndex; const tiles = React.Children.map(children, (child, index) => { const ariaHidden = activeIndex !== index ? true : false; return ( <Tile className={`${CLASS_ROOT}__item`} aria-hidden={ariaHidden}> {child} </Tile> ); }); const controls = React.Children.map(children, (child, index) => { const active = index === activeIndex; const controlClasses = classnames( `${CLASS_ROOT}__control`, { [`${CLASS_ROOT}__control--active`]: active } ); const activateMessage = Intl.getMessage(intl, 'Activate'); const slideNumberMessage = Intl.getMessage(intl, 'Slide Number', { slideNumber: index + 1 }); let currentlyActiveMessage = ''; if (active) { currentlyActiveMessage = ( `(${Intl.getMessage(intl, 'Currently Active')})` ); } return ( <Button plain={true} onClick={this._onSelect.bind(this, index)} a11yTitle={ `${activateMessage} ${slideNumberMessage} ${currentlyActiveMessage}` }> <svg className={controlClasses} viewBox="0 0 24 24" version="1.1"> <circle cx={12} cy={12} r={6} /> </svg> </Button> ); }, this); const carouselMessage = a11yTitle || Intl.getMessage(intl, 'Carousel'); const trackClasses = classnames(`${CLASS_ROOT}__track`,{ [`${CLASS_ROOT}__track--animate`]: this.state.animate }); return ( <div ref={ref => this.carouselRef = ref} {...restProps} className={classes} role='group' aria-label={carouselMessage} onFocus={this._stopAutoplay} onBlur={this._startAutoplay} onMouseOver={this._stopAutoplay} onMouseOut={this._startAutoplay}> <div className={trackClasses} style={{ width: (trackWidth && trackWidth > 0) ? trackWidth : '', marginLeft: - trackOffset, marginRight: - (trackWidth - trackOffset - width) }}> <Tiles fill={true} responsive={false} wrap={false} direction="row"> {tiles} </Tiles> </div> {this._renderPrevButton()} {this._renderNextButton()} <Box className={CLASS_ROOT + "__controls"} direction="row" justify="center" responsive={false}> {controls} </Box> </div> ); } } Carousel.contextTypes = { intl: PropTypes.object }; Carousel.defaultProps = { autoplay: true, autoplaySpeed: 5000, infinite: true, persistentNav: true }; Carousel.propTypes = { a11yTitle: PropTypes.string, activeIndex: PropTypes.number, autoplay: PropTypes.bool, autoplaySpeed: PropTypes.number, infinite: PropTypes.bool, onActive: PropTypes.func, persistentNav: PropTypes.bool };
tests/components/testOperator.js
notfier/touristique-client
import React from 'react'; import { shallow } from 'enzyme'; import { Operator } from '../../src/js/components/Operator'; describe( 'Test Operator component |', function() { it( 'test componentWillMount logic', function() { localStorage.setItem( 'token', 'olalah' ); var test; const wrapper = shallow( <Operator findTourist={ () => {} } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => { test = token; } } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); expect( test ).toBe( 'olalah' ); } ); it( 'test componentWillReceiveProps logic', function() { const wrapper = shallow( <Operator findTourist={ () => {} } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => {} } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); wrapper.setState({touristCardPk: 1}); expect( wrapper.state( 'touristCardPk' ) ).toBe( 1 ); // simulate new props update wrapper.setProps({fake: true}); expect( wrapper.state( 'touristCardPk' ) ).toBe( '' ); } ); it( 'test findTourist method', function() { localStorage.setItem( 'token', 'ololo' ); var test; const wrapper = shallow( <Operator findTourist={ ( val1, val2 ) => { test = {val1: val1, val2: val2} } } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => {} } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); // check error changing in the state wrapper.setState({error: 'ERROR!', touristCardPk: 'CARD!'}); wrapper.find( 'button' ).first().simulate( 'click', { preventDefault() {} }); expect( wrapper.state( 'error' ) ).toBe( '' ); expect( test.val1 ).toBe( 'ololo' ); expect( test.val2 ).toBe( 'CARD!' ); } ); it( 'test findTourist method getting error', function() { localStorage.setItem( 'token', 'ololo' ); var test; const wrapper = shallow( <Operator findTourist={ ( val1, val2 ) => { test = {val1: val1, val2: val2} } } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => {} } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); wrapper.find( 'button' ).first().simulate( 'click', { preventDefault() {} }); expect( wrapper.state( 'error' ) ).toBe( 'Enter a card id in the beginning' ); expect( test ).toBe( undefined ); } ); } );
packages/mineral-ui-icons/src/IconSettingsOverscan.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconSettingsOverscan(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M12.01 5.5L10 8h4l-1.99-2.5zM18 10v4l2.5-1.99L18 10zM6 10l-2.5 2.01L6 14v-4zm8 6h-4l2.01 2.5L14 16zm7-13H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/> </g> </Icon> ); } IconSettingsOverscan.displayName = 'IconSettingsOverscan'; IconSettingsOverscan.category = 'action';
Frontend/src/index/invite_list.js
zsefvlol/threedegrees
"use strict"; import React from 'react'; import { render } from 'react-dom'; import WeUI from 'react-weui'; import Ajax from '../lib/Ajax'; const {Cells, CellsTitle, CellBody, Cell, Button, CellFooter} = WeUI; export default class InviteList extends React.Component { state = { invite_list : this.props.user_info.invite_list, allow_invite_count: this.props.user_info.allow_invite_count, button_enable: this.props.user_info.allow_invite_count - this.props.user_info.invite_list.length > 0 }; generateInviteCode(){ this.setState({ button_enable: false }); Ajax.get('/api/user/generate_code').end((err, res) => { var invite_list = this.state.invite_list; var allow_invite_count = this.state.allow_invite_count; if(res.body.error_code == 0){ invite_list.push({ 'code': res.body.data.code, 'truename': '', 'invite_id': parseInt(1000+Math.random() * 1000) }) } this.setState({ invite_list: invite_list, allow_invite_count: allow_invite_count, button_enable: true }); }) } render() { class InviteLinkItem extends React.Component{ handleInviteClick(e){ console.log(this.state); window.location.hash = '#/user/'+this.state.code.to_uid; } state = { code : this.props.code }; render(){ return this.state.code.to_uid > 0 && this.state.code.is_single == 1?( <p className="desc" onClick={this.handleInviteClick.bind(this)}>{this.state.code.truename} ></p> ):( <p className="desc">{this.state.code.truename}</p> ); } } let lists = this.state.invite_list.length ? this.state.invite_list.map(function(code){ if(!code.truename) code.truename = '未使用'; return ( <Cell className="list_item" key={code.invite_id}> <CellBody> <h2 className="title">{code.code}</h2> </CellBody> <CellFooter> <InviteLinkItem code={code} /> </CellFooter> </Cell> ) }) : ''; let generateButton = this.state.button_enable ? ( <Button type="primary" onClick={this.generateInviteCode.bind(this)}> 生成邀请码 </Button> ):( <Button type="default" disabled={true} > 生成邀请码 </Button> ); return (<section> <Cell className="list_item"> <CellBody> <h2 className="title">邀请码列表</h2> </CellBody> <CellFooter> <p className="desc">您已生成{this.state.invite_list.length}/{this.state.allow_invite_count}个邀请码</p> </CellFooter> </Cell> {lists} <Cell className="list_item"> {generateButton} </Cell> <Cell className="list_item"> <p className="desc">目前仅允许一度邀请12个好友。<br/>详情参考<a href={`${window._BASE_}/index/term`} >了解 ThreeDegrees</a></p> </Cell> </section>); } }
vendor/firebug-lite/src/firebug-lite-debug.js
IveWong/lodash
(function(){ /*!************************************************************* * * Firebug Lite 1.4.0 * * Copyright (c) 2007, Parakey Inc. * Released under BSD license. * More information: http://getfirebug.com/firebuglite * **************************************************************/ /*! * CSS selectors powered by: * * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ /** @namespace describe lib */ // FIXME: xxxpedro if we use "var FBL = {}" the FBL won't appear in the DOM Panel in IE var FBL = {}; ( /** @scope s_lib @this FBL */ function() { // ************************************************************************************************ // ************************************************************************************************ // Constants var productionDir = "http://getfirebug.com/releases/lite/"; var bookmarkletVersion = 4; // ************************************************************************************************ var reNotWhitespace = /[^\s]/; var reSplitFile = /:\/{1,3}(.*?)\/([^\/]*?)\/?($|\?.*)/; // Globals this.reJavascript = /\s*javascript:\s*(.*)/; this.reChrome = /chrome:\/\/([^\/]*)\//; this.reFile = /file:\/\/([^\/]*)\//; // ************************************************************************************************ // properties var userAgent = navigator.userAgent.toLowerCase(); this.isFirefox = /firefox/.test(userAgent); this.isOpera = /opera/.test(userAgent); this.isSafari = /webkit/.test(userAgent); this.isIE = /msie/.test(userAgent) && !/opera/.test(userAgent); this.isIE6 = /msie 6/i.test(navigator.appVersion); this.browserVersion = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1]; this.isIElt8 = this.isIE && (this.browserVersion-0 < 8); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.NS = null; this.pixelsPerInch = null; // ************************************************************************************************ // Namespaces var namespaces = []; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.ns = function(fn) { var ns = {}; namespaces.push(fn, ns); return ns; }; var FBTrace = null; this.initialize = function() { // Firebug Lite is already running in persistent mode so we just quit if (window.firebug && firebug.firebuglite || window.console && console.firebuglite) return; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize environment // point the FBTrace object to the local variable if (FBL.FBTrace) FBTrace = FBL.FBTrace; else FBTrace = FBL.FBTrace = {}; // check if the actual window is a persisted chrome context var isChromeContext = window.Firebug && typeof window.Firebug.SharedEnv == "object"; // chrome context of the persistent application if (isChromeContext) { // TODO: xxxpedro persist - make a better synchronization sharedEnv = window.Firebug.SharedEnv; delete window.Firebug.SharedEnv; FBL.Env = sharedEnv; FBL.Env.isChromeContext = true; FBTrace.messageQueue = FBL.Env.traceMessageQueue; } // non-persistent application else { FBL.NS = document.documentElement.namespaceURI; FBL.Env.browser = window; FBL.Env.destroy = destroyEnvironment; if (document.documentElement.getAttribute("debug") == "true") FBL.Env.Options.startOpened = true; // find the URL location of the loaded application findLocation(); // TODO: get preferences here... // The problem is that we don't have the Firebug object yet, so we can't use // Firebug.loadPrefs. We're using the Store module directly instead. var prefs = FBL.Store.get("FirebugLite") || {}; FBL.Env.DefaultOptions = FBL.Env.Options; FBL.Env.Options = FBL.extend(FBL.Env.Options, prefs.options || {}); if (FBL.isFirefox && typeof FBL.Env.browser.console == "object" && FBL.Env.browser.console.firebug && FBL.Env.Options.disableWhenFirebugActive) return; } // exposes the FBL to the global namespace when in debug mode if (FBL.Env.isDebugMode) { FBL.Env.browser.FBL = FBL; } // check browser compatibilities this.isQuiksMode = FBL.Env.browser.document.compatMode == "BackCompat"; this.isIEQuiksMode = this.isIE && this.isQuiksMode; this.isIEStantandMode = this.isIE && !this.isQuiksMode; this.noFixedPosition = this.isIE6 || this.isIEQuiksMode; // after creating/synchronizing the environment, initialize the FBTrace module if (FBL.Env.Options.enableTrace) FBTrace.initialize(); if (FBTrace.DBG_INITIALIZE && isChromeContext) FBTrace.sysout("FBL.initialize - persistent application", "initialize chrome context"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize namespaces if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FBL.initialize", namespaces.length/2+" namespaces BEGIN"); for (var i = 0; i < namespaces.length; i += 2) { var fn = namespaces[i]; var ns = namespaces[i+1]; fn.apply(ns); } if (FBTrace.DBG_INITIALIZE) { FBTrace.sysout("FBL.initialize", namespaces.length/2+" namespaces END"); FBTrace.sysout("FBL waitForDocument", "waiting document load"); } FBL.Ajax.initialize(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // finish environment initialization FBL.Firebug.loadPrefs(); if (FBL.Env.Options.enablePersistent) { // TODO: xxxpedro persist - make a better synchronization if (isChromeContext) { FBL.FirebugChrome.clone(FBL.Env.FirebugChrome); } else { FBL.Env.FirebugChrome = FBL.FirebugChrome; FBL.Env.traceMessageQueue = FBTrace.messageQueue; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // wait document load waitForDocument(); }; var waitForDocument = function waitForDocument() { // document.body not available in XML+XSL documents in Firefox var doc = FBL.Env.browser.document; var body = doc.getElementsByTagName("body")[0]; if (body) { calculatePixelsPerInch(doc, body); onDocumentLoad(); } else setTimeout(waitForDocument, 50); }; var onDocumentLoad = function onDocumentLoad() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FBL onDocumentLoad", "document loaded"); // fix IE6 problem with cache of background images, causing a lot of flickering if (FBL.isIE6) fixIE6BackgroundImageCache(); // chrome context of the persistent application if (FBL.Env.Options.enablePersistent && FBL.Env.isChromeContext) { // finally, start the application in the chrome context FBL.Firebug.initialize(); // if is not development mode, remove the shared environment cache object // used to synchronize the both persistent contexts if (!FBL.Env.isDevelopmentMode) { sharedEnv.destroy(); sharedEnv = null; } } // non-persistent application else { FBL.FirebugChrome.create(); } }; // ************************************************************************************************ // Env var sharedEnv; this.Env = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Env Options (will be transported to Firebug options) Options: { saveCookies: true, saveWindowPosition: false, saveCommandLineHistory: false, startOpened: false, startInNewWindow: false, showIconWhenHidden: true, overrideConsole: true, ignoreFirebugElements: true, disableWhenFirebugActive: true, disableXHRListener: false, disableResourceFetching: false, enableTrace: false, enablePersistent: false }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Library location Location: { sourceDir: null, baseDir: null, skinDir: null, skin: null, app: null }, skin: "xp", useLocalSkin: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Env states isDevelopmentMode: false, isDebugMode: false, isChromeContext: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Env references browser: null, chrome: null }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var destroyEnvironment = function destroyEnvironment() { setTimeout(function() { FBL = null; }, 100); }; // ************************************************************************************************ // Library location var findLocation = function findLocation() { var reFirebugFile = /(firebug-lite(?:-\w+)?(?:\.js|\.jgz))(?:#(.+))?$/; var reGetFirebugSite = /(?:http|https):\/\/getfirebug.com\//; var isGetFirebugSite; var rePath = /^(.*\/)/; var reProtocol = /^\w+:\/\//; var path = null; var doc = document; // Firebug Lite 1.3.0 bookmarklet identification var script = doc.getElementById("FirebugLite"); var scriptSrc; var hasSrcAttribute = true; // If the script was loaded via bookmarklet, we already have the script tag if (script) { scriptSrc = script.src; file = reFirebugFile.exec(scriptSrc); var version = script.getAttribute("FirebugLite"); var number = version ? parseInt(version) : 0; if (!version || !number || number < bookmarkletVersion) { FBL.Env.bookmarkletOutdated = true; } } // otherwise we must search for the correct script tag else { for(var i=0, s=doc.getElementsByTagName("script"), si; si=s[i]; i++) { var file = null; if ( si.nodeName.toLowerCase() == "script" ) { if (file = reFirebugFile.exec(si.getAttribute("firebugSrc"))) { scriptSrc = si.getAttribute("firebugSrc"); hasSrcAttribute = false; } else if (file = reFirebugFile.exec(si.src)) { scriptSrc = si.src; } else continue; script = si; break; } } } // mark the script tag to be ignored by Firebug Lite if (script) script.firebugIgnore = true; if (file) { var fileName = file[1]; var fileOptions = file[2]; // absolute path if (reProtocol.test(scriptSrc)) { path = rePath.exec(scriptSrc)[1]; } // relative path else { var r = rePath.exec(scriptSrc); var src = r ? r[1] : scriptSrc; var backDir = /^((?:\.\.\/)+)(.*)/.exec(src); var reLastDir = /^(.*\/)[^\/]+\/$/; path = rePath.exec(location.href)[1]; // "../some/path" if (backDir) { var j = backDir[1].length/3; var p; while (j-- > 0) path = reLastDir.exec(path)[1]; path += backDir[2]; } else if(src.indexOf("/") != -1) { // "./some/path" if(/^\.\/./.test(src)) { path += src.substring(2); } // "/some/path" else if(/^\/./.test(src)) { var domain = /^(\w+:\/\/[^\/]+)/.exec(path); path = domain[1] + src; } // "some/path" else { path += src; } } } } FBL.Env.isChromeExtension = script && script.getAttribute("extension") == "Chrome"; if (FBL.Env.isChromeExtension) { path = productionDir; FBL.Env.bookmarkletOutdated = false; script = {innerHTML: "{showIconWhenHidden:false}"}; } isGetFirebugSite = reGetFirebugSite.test(path); if (isGetFirebugSite && path.indexOf("/releases/lite/") == -1) { // See Issue 4587 - If we are loading the script from getfirebug.com shortcut, like // https://getfirebug.com/firebug-lite.js, then we must manually add the full path, // otherwise the Env.Location will hold the wrong path, which will in turn lead to // undesirable effects like the problem in Issue 4587 path += "releases/lite/" + (fileName == "firebug-lite-beta.js" ? "beta/" : "latest/"); } var m = path && path.match(/([^\/]+)\/$/) || null; if (path && m) { var Env = FBL.Env; // Always use the local skin when running in the same domain // See Issue 3554: Firebug Lite should use local images when loaded locally Env.useLocalSkin = path.indexOf(location.protocol + "//" + location.host + "/") == 0 && // but we cannot use the locan skin when loaded from getfirebug.com, otherwise // the bookmarklet won't work when visiting getfirebug.com !isGetFirebugSite; // detecting development and debug modes via file name if (fileName == "firebug-lite-dev.js") { Env.isDevelopmentMode = true; Env.isDebugMode = true; } else if (fileName == "firebug-lite-debug.js") { Env.isDebugMode = true; } // process the <html debug="true"> if (Env.browser.document.documentElement.getAttribute("debug") == "true") { Env.Options.startOpened = true; } // process the Script URL Options if (fileOptions) { var options = fileOptions.split(","); for (var i = 0, length = options.length; i < length; i++) { var option = options[i]; var name, value; if (option.indexOf("=") != -1) { var parts = option.split("="); name = parts[0]; value = eval(unescape(parts[1])); } else { name = option; value = true; } if (name == "debug") { Env.isDebugMode = !!value; } else if (name in Env.Options) { Env.Options[name] = value; } else { Env[name] = value; } } } // process the Script JSON Options if (hasSrcAttribute) { var innerOptions = FBL.trim(script.innerHTML); if (innerOptions) { var innerOptionsObject = eval("(" + innerOptions + ")"); for (var name in innerOptionsObject) { var value = innerOptionsObject[name]; if (name == "debug") { Env.isDebugMode = !!value; } else if (name in Env.Options) { Env.Options[name] = value; } else { Env[name] = value; } } } } if (!Env.Options.saveCookies) FBL.Store.remove("FirebugLite"); // process the Debug Mode if (Env.isDebugMode) { Env.Options.startOpened = true; Env.Options.enableTrace = true; Env.Options.disableWhenFirebugActive = false; } var loc = Env.Location; var isProductionRelease = path.indexOf(productionDir) != -1; loc.sourceDir = path; loc.baseDir = path.substr(0, path.length - m[1].length - 1); loc.skinDir = (isProductionRelease ? path : loc.baseDir) + "skin/" + Env.skin + "/"; loc.skin = loc.skinDir + "firebug.html"; loc.app = path + fileName; } else { throw new Error("Firebug Error: Library path not found"); } }; // ************************************************************************************************ // Basics this.bind = function() // fn, thisObject, args => thisObject.fn(args, arguments); { var args = cloneArray(arguments), fn = args.shift(), object = args.shift(); return function() { return fn.apply(object, arrayInsert(cloneArray(args), 0, arguments)); }; }; this.bindFixed = function() // fn, thisObject, args => thisObject.fn(args); { var args = cloneArray(arguments), fn = args.shift(), object = args.shift(); return function() { return fn.apply(object, args); }; }; this.extend = function(l, r) { var newOb = {}; for (var n in l) newOb[n] = l[n]; for (var n in r) newOb[n] = r[n]; return newOb; }; this.descend = function(prototypeParent, childProperties) { function protoSetter() {}; protoSetter.prototype = prototypeParent; var newOb = new protoSetter(); for (var n in childProperties) newOb[n] = childProperties[n]; return newOb; }; this.append = function(l, r) { for (var n in r) l[n] = r[n]; return l; }; this.keys = function(map) // At least sometimes the keys will be on user-level window objects { var keys = []; try { for (var name in map) // enumeration is safe keys.push(name); // name is string, safe } catch (exc) { // Sometimes we get exceptions trying to iterate properties } return keys; // return is safe }; this.values = function(map) { var values = []; try { for (var name in map) { try { values.push(map[name]); } catch (exc) { // Sometimes we get exceptions trying to access properties if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.values FAILED ", exc); } } } catch (exc) { // Sometimes we get exceptions trying to iterate properties if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.values FAILED ", exc); } return values; }; this.remove = function(list, item) { for (var i = 0; i < list.length; ++i) { if (list[i] == item) { list.splice(i, 1); break; } } }; this.sliceArray = function(array, index) { var slice = []; for (var i = index; i < array.length; ++i) slice.push(array[i]); return slice; }; function cloneArray(array, fn) { var newArray = []; if (fn) for (var i = 0; i < array.length; ++i) newArray.push(fn(array[i])); else for (var i = 0; i < array.length; ++i) newArray.push(array[i]); return newArray; } function extendArray(array, array2) { var newArray = []; newArray.push.apply(newArray, array); newArray.push.apply(newArray, array2); return newArray; } this.extendArray = extendArray; this.cloneArray = cloneArray; function arrayInsert(array, index, other) { for (var i = 0; i < other.length; ++i) array.splice(i+index, 0, other[i]); return array; } // ************************************************************************************************ this.createStyleSheet = function(doc, url) { //TODO: xxxpedro //var style = doc.createElementNS("http://www.w3.org/1999/xhtml", "style"); var style = this.createElement("link"); style.setAttribute("charset","utf-8"); style.firebugIgnore = true; style.setAttribute("rel", "stylesheet"); style.setAttribute("type", "text/css"); style.setAttribute("href", url); //TODO: xxxpedro //style.innerHTML = this.getResource(url); return style; }; this.addStyleSheet = function(doc, style) { var heads = doc.getElementsByTagName("head"); if (heads.length) heads[0].appendChild(style); else doc.documentElement.appendChild(style); }; this.appendStylesheet = function(doc, uri) { // Make sure the stylesheet is not appended twice. if (this.$(uri, doc)) return; var styleSheet = this.createStyleSheet(doc, uri); styleSheet.setAttribute("id", uri); this.addStyleSheet(doc, styleSheet); }; this.addScript = function(doc, id, src) { var element = doc.createElementNS("http://www.w3.org/1999/xhtml", "html:script"); element.setAttribute("type", "text/javascript"); element.setAttribute("id", id); if (!FBTrace.DBG_CONSOLE) FBL.unwrapObject(element).firebugIgnore = true; element.innerHTML = src; if (doc.documentElement) doc.documentElement.appendChild(element); else { // See issue 1079, the svg test case gives this error if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.addScript doc has no documentElement:", doc); } return element; }; // ************************************************************************************************ this.getStyle = this.isIE ? function(el, name) { return el.currentStyle[name] || el.style[name] || undefined; } : function(el, name) { return el.ownerDocument.defaultView.getComputedStyle(el,null)[name] || el.style[name] || undefined; }; // ************************************************************************************************ // Whitespace and Entity conversions var entityConversionLists = this.entityConversionLists = { normal : { whitespace : { '\t' : '\u200c\u2192', '\n' : '\u200c\u00b6', '\r' : '\u200c\u00ac', ' ' : '\u200c\u00b7' } }, reverse : { whitespace : { '&Tab;' : '\t', '&NewLine;' : '\n', '\u200c\u2192' : '\t', '\u200c\u00b6' : '\n', '\u200c\u00ac' : '\r', '\u200c\u00b7' : ' ' } } }; var normal = entityConversionLists.normal, reverse = entityConversionLists.reverse; function addEntityMapToList(ccode, entity) { var lists = Array.prototype.slice.call(arguments, 2), len = lists.length, ch = String.fromCharCode(ccode); for (var i = 0; i < len; i++) { var list = lists[i]; normal[list]=normal[list] || {}; normal[list][ch] = '&' + entity + ';'; reverse[list]=reverse[list] || {}; reverse[list]['&' + entity + ';'] = ch; } }; var e = addEntityMapToList, white = 'whitespace', text = 'text', attr = 'attributes', css = 'css', editor = 'editor'; e(0x0022, 'quot', attr, css); e(0x0026, 'amp', attr, text, css); e(0x0027, 'apos', css); e(0x003c, 'lt', attr, text, css); e(0x003e, 'gt', attr, text, css); e(0xa9, 'copy', text, editor); e(0xae, 'reg', text, editor); e(0x2122, 'trade', text, editor); // See http://en.wikipedia.org/wiki/Dash e(0x2012, '#8210', attr, text, editor); // figure dash e(0x2013, 'ndash', attr, text, editor); // en dash e(0x2014, 'mdash', attr, text, editor); // em dash e(0x2015, '#8213', attr, text, editor); // horizontal bar e(0x00a0, 'nbsp', attr, text, white, editor); e(0x2002, 'ensp', attr, text, white, editor); e(0x2003, 'emsp', attr, text, white, editor); e(0x2009, 'thinsp', attr, text, white, editor); e(0x200c, 'zwnj', attr, text, white, editor); e(0x200d, 'zwj', attr, text, white, editor); e(0x200e, 'lrm', attr, text, white, editor); e(0x200f, 'rlm', attr, text, white, editor); e(0x200b, '#8203', attr, text, white, editor); // zero-width space (ZWSP) //************************************************************************************************ // Entity escaping var entityConversionRegexes = { normal : {}, reverse : {} }; var escapeEntitiesRegEx = { normal : function(list) { var chars = []; for ( var ch in list) { chars.push(ch); } return new RegExp('([' + chars.join('') + '])', 'gm'); }, reverse : function(list) { var chars = []; for ( var ch in list) { chars.push(ch); } return new RegExp('(' + chars.join('|') + ')', 'gm'); } }; function getEscapeRegexp(direction, lists) { var name = '', re; var groups = [].concat(lists); for (i = 0; i < groups.length; i++) { name += groups[i].group; } re = entityConversionRegexes[direction][name]; if (!re) { var list = {}; if (groups.length > 1) { for ( var i = 0; i < groups.length; i++) { var aList = entityConversionLists[direction][groups[i].group]; for ( var item in aList) list[item] = aList[item]; } } else if (groups.length==1) { list = entityConversionLists[direction][groups[0].group]; // faster for special case } else { list = {}; // perhaps should print out an error here? } re = entityConversionRegexes[direction][name] = escapeEntitiesRegEx[direction](list); } return re; }; function createSimpleEscape(name, direction) { return function(value) { var list = entityConversionLists[direction][name]; return String(value).replace( getEscapeRegexp(direction, { group : name, list : list }), function(ch) { return list[ch]; } ); }; }; function escapeGroupsForEntities(str, lists) { lists = [].concat(lists); var re = getEscapeRegexp('normal', lists), split = String(str).split(re), len = split.length, results = [], cur, r, i, ri = 0, l, list, last = ''; if (!len) return [ { str : String(str), group : '', name : '' } ]; for (i = 0; i < len; i++) { cur = split[i]; if (cur == '') continue; for (l = 0; l < lists.length; l++) { list = lists[l]; r = entityConversionLists.normal[list.group][cur]; // if (cur == ' ' && list.group == 'whitespace' && last == ' ') // only show for runs of more than one space // r = ' '; if (r) { results[ri] = { 'str' : r, 'class' : list['class'], 'extra' : list.extra[cur] ? list['class'] + list.extra[cur] : '' }; break; } } // last=cur; if (!r) results[ri] = { 'str' : cur, 'class' : '', 'extra' : '' }; ri++; } return results; }; this.escapeGroupsForEntities = escapeGroupsForEntities; function unescapeEntities(str, lists) { var re = getEscapeRegexp('reverse', lists), split = String(str).split(re), len = split.length, results = [], cur, r, i, ri = 0, l, list; if (!len) return str; lists = [].concat(lists); for (i = 0; i < len; i++) { cur = split[i]; if (cur == '') continue; for (l = 0; l < lists.length; l++) { list = lists[l]; r = entityConversionLists.reverse[list.group][cur]; if (r) { results[ri] = r; break; } } if (!r) results[ri] = cur; ri++; } return results.join('') || ''; }; // ************************************************************************************************ // String escaping var escapeForTextNode = this.escapeForTextNode = createSimpleEscape('text', 'normal'); var escapeForHtmlEditor = this.escapeForHtmlEditor = createSimpleEscape('editor', 'normal'); var escapeForElementAttribute = this.escapeForElementAttribute = createSimpleEscape('attributes', 'normal'); var escapeForCss = this.escapeForCss = createSimpleEscape('css', 'normal'); // deprecated compatibility functions //this.deprecateEscapeHTML = createSimpleEscape('text', 'normal'); //this.deprecatedUnescapeHTML = createSimpleEscape('text', 'reverse'); //this.escapeHTML = deprecated("use appropriate escapeFor... function", this.deprecateEscapeHTML); //this.unescapeHTML = deprecated("use appropriate unescapeFor... function", this.deprecatedUnescapeHTML); var escapeForSourceLine = this.escapeForSourceLine = createSimpleEscape('text', 'normal'); var unescapeWhitespace = createSimpleEscape('whitespace', 'reverse'); this.unescapeForTextNode = function(str) { if (Firebug.showTextNodesWithWhitespace) str = unescapeWhitespace(str); if (!Firebug.showTextNodesWithEntities) str = escapeForElementAttribute(str); return str; }; this.escapeNewLines = function(value) { return value.replace(/\r/g, "\\r").replace(/\n/g, "\\n"); }; this.stripNewLines = function(value) { return typeof(value) == "string" ? value.replace(/[\r\n]/g, " ") : value; }; this.escapeJS = function(value) { return value.replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace('"', '\\"', "g"); }; function escapeHTMLAttribute(value) { function replaceChars(ch) { switch (ch) { case "&": return "&amp;"; case "'": return apos; case '"': return quot; } return "?"; }; var apos = "&#39;", quot = "&quot;", around = '"'; if( value.indexOf('"') == -1 ) { quot = '"'; apos = "'"; } else if( value.indexOf("'") == -1 ) { quot = '"'; around = "'"; } return around + (String(value).replace(/[&'"]/g, replaceChars)) + around; } function escapeHTML(value) { function replaceChars(ch) { switch (ch) { case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; case "'": return "&#39;"; case '"': return "&quot;"; } return "?"; }; return String(value).replace(/[<>&"']/g, replaceChars); } this.escapeHTML = escapeHTML; this.cropString = function(text, limit) { text = text + ""; if (!limit) var halfLimit = 50; else var halfLimit = limit / 2; if (text.length > limit) return this.escapeNewLines(text.substr(0, halfLimit) + "..." + text.substr(text.length-halfLimit)); else return this.escapeNewLines(text); }; this.isWhitespace = function(text) { return !reNotWhitespace.exec(text); }; this.splitLines = function(text) { var reSplitLines2 = /.*(:?\r\n|\n|\r)?/mg; var lines; if (text.match) { lines = text.match(reSplitLines2); } else { var str = text+""; lines = str.match(reSplitLines2); } lines.pop(); return lines; }; // ************************************************************************************************ this.safeToString = function(ob) { if (this.isIE) { try { // FIXME: xxxpedro this is failing in IE for the global "external" object return ob + ""; } catch(E) { FBTrace.sysout("Lib.safeToString() failed for ", ob); return ""; } } try { if (ob && "toString" in ob && typeof ob.toString == "function") return ob.toString(); } catch (exc) { // xxxpedro it is not safe to use ob+""? return ob + ""; ///return "[an object with no toString() function]"; } }; // ************************************************************************************************ this.hasProperties = function(ob) { try { for (var name in ob) return true; } catch (exc) {} return false; }; // ************************************************************************************************ // String Util var reTrim = /^\s+|\s+$/g; this.trim = function(s) { return s.replace(reTrim, ""); }; // ************************************************************************************************ // Empty this.emptyFn = function(){}; // ************************************************************************************************ // Visibility this.isVisible = function(elt) { /* if (elt instanceof XULElement) { //FBTrace.sysout("isVisible elt.offsetWidth: "+elt.offsetWidth+" offsetHeight:"+ elt.offsetHeight+" localName:"+ elt.localName+" nameSpace:"+elt.nameSpaceURI+"\n"); return (!elt.hidden && !elt.collapsed); } /**/ return this.getStyle(elt, "visibility") != "hidden" && ( elt.offsetWidth > 0 || elt.offsetHeight > 0 || elt.tagName in invisibleTags || elt.namespaceURI == "http://www.w3.org/2000/svg" || elt.namespaceURI == "http://www.w3.org/1998/Math/MathML" ); }; this.collapse = function(elt, collapsed) { // IE6 doesn't support the [collapsed] CSS selector. IE7 does support the selector, // but it is causing a bug (the element disappears when you set the "collapsed" // attribute, but it doesn't appear when you remove the attribute. So, for those // cases, we need to use the class attribute. if (this.isIElt8) { if (collapsed) this.setClass(elt, "collapsed"); else this.removeClass(elt, "collapsed"); } else elt.setAttribute("collapsed", collapsed ? "true" : "false"); }; this.obscure = function(elt, obscured) { if (obscured) this.setClass(elt, "obscured"); else this.removeClass(elt, "obscured"); }; this.hide = function(elt, hidden) { elt.style.visibility = hidden ? "hidden" : "visible"; }; this.clearNode = function(node) { var nodeName = " " + node.nodeName.toLowerCase() + " "; var ignoreTags = " table tbody thead tfoot th tr td "; // IE can't use innerHTML of table elements if (this.isIE && ignoreTags.indexOf(nodeName) != -1) this.eraseNode(node); else node.innerHTML = ""; }; this.eraseNode = function(node) { while (node.lastChild) node.removeChild(node.lastChild); }; // ************************************************************************************************ // Window iteration this.iterateWindows = function(win, handler) { if (!win || !win.document) return; handler(win); if (win == top || !win.frames) return; // XXXjjb hack for chromeBug for (var i = 0; i < win.frames.length; ++i) { var subWin = win.frames[i]; if (subWin != win) this.iterateWindows(subWin, handler); } }; this.getRootWindow = function(win) { for (; win; win = win.parent) { if (!win.parent || win == win.parent || !this.instanceOf(win.parent, "Window")) return win; } return null; }; // ************************************************************************************************ // Graphics this.getClientOffset = function(elt) { var addOffset = function addOffset(elt, coords, view) { var p = elt.offsetParent; ///var style = isIE ? elt.currentStyle : view.getComputedStyle(elt, ""); var chrome = Firebug.chrome; if (elt.offsetLeft) ///coords.x += elt.offsetLeft + parseInt(style.borderLeftWidth); coords.x += elt.offsetLeft + chrome.getMeasurementInPixels(elt, "borderLeft"); if (elt.offsetTop) ///coords.y += elt.offsetTop + parseInt(style.borderTopWidth); coords.y += elt.offsetTop + chrome.getMeasurementInPixels(elt, "borderTop"); if (p) { if (p.nodeType == 1) addOffset(p, coords, view); } else { var otherView = isIE ? elt.ownerDocument.parentWindow : elt.ownerDocument.defaultView; // IE will fail when reading the frameElement property of a popup window. // We don't need it anyway once it is outside the (popup) viewport, so we're // ignoring the frameElement check when the window is a popup if (!otherView.opener && otherView.frameElement) addOffset(otherView.frameElement, coords, otherView); } }; var isIE = this.isIE; var coords = {x: 0, y: 0}; if (elt) { var view = isIE ? elt.ownerDocument.parentWindow : elt.ownerDocument.defaultView; addOffset(elt, coords, view); } return coords; }; this.getViewOffset = function(elt, singleFrame) { function addOffset(elt, coords, view) { var p = elt.offsetParent; coords.x += elt.offsetLeft - (p ? p.scrollLeft : 0); coords.y += elt.offsetTop - (p ? p.scrollTop : 0); if (p) { if (p.nodeType == 1) { var parentStyle = view.getComputedStyle(p, ""); if (parentStyle.position != "static") { coords.x += parseInt(parentStyle.borderLeftWidth); coords.y += parseInt(parentStyle.borderTopWidth); if (p.localName == "TABLE") { coords.x += parseInt(parentStyle.paddingLeft); coords.y += parseInt(parentStyle.paddingTop); } else if (p.localName == "BODY") { var style = view.getComputedStyle(elt, ""); coords.x += parseInt(style.marginLeft); coords.y += parseInt(style.marginTop); } } else if (p.localName == "BODY") { coords.x += parseInt(parentStyle.borderLeftWidth); coords.y += parseInt(parentStyle.borderTopWidth); } var parent = elt.parentNode; while (p != parent) { coords.x -= parent.scrollLeft; coords.y -= parent.scrollTop; parent = parent.parentNode; } addOffset(p, coords, view); } } else { if (elt.localName == "BODY") { var style = view.getComputedStyle(elt, ""); coords.x += parseInt(style.borderLeftWidth); coords.y += parseInt(style.borderTopWidth); var htmlStyle = view.getComputedStyle(elt.parentNode, ""); coords.x -= parseInt(htmlStyle.paddingLeft); coords.y -= parseInt(htmlStyle.paddingTop); } if (elt.scrollLeft) coords.x += elt.scrollLeft; if (elt.scrollTop) coords.y += elt.scrollTop; var win = elt.ownerDocument.defaultView; if (win && (!singleFrame && win.frameElement)) addOffset(win.frameElement, coords, win); } } var coords = {x: 0, y: 0}; if (elt) addOffset(elt, coords, elt.ownerDocument.defaultView); return coords; }; this.getLTRBWH = function(elt) { var bcrect, dims = {"left": 0, "top": 0, "right": 0, "bottom": 0, "width": 0, "height": 0}; if (elt) { bcrect = elt.getBoundingClientRect(); dims.left = bcrect.left; dims.top = bcrect.top; dims.right = bcrect.right; dims.bottom = bcrect.bottom; if(bcrect.width) { dims.width = bcrect.width; dims.height = bcrect.height; } else { dims.width = dims.right - dims.left; dims.height = dims.bottom - dims.top; } } return dims; }; this.applyBodyOffsets = function(elt, clientRect) { var od = elt.ownerDocument; if (!od.body) return clientRect; var style = od.defaultView.getComputedStyle(od.body, null); var pos = style.getPropertyValue('position'); if(pos === 'absolute' || pos === 'relative') { var borderLeft = parseInt(style.getPropertyValue('border-left-width').replace('px', ''),10) || 0; var borderTop = parseInt(style.getPropertyValue('border-top-width').replace('px', ''),10) || 0; var paddingLeft = parseInt(style.getPropertyValue('padding-left').replace('px', ''),10) || 0; var paddingTop = parseInt(style.getPropertyValue('padding-top').replace('px', ''),10) || 0; var marginLeft = parseInt(style.getPropertyValue('margin-left').replace('px', ''),10) || 0; var marginTop = parseInt(style.getPropertyValue('margin-top').replace('px', ''),10) || 0; var offsetX = borderLeft + paddingLeft + marginLeft; var offsetY = borderTop + paddingTop + marginTop; clientRect.left -= offsetX; clientRect.top -= offsetY; clientRect.right -= offsetX; clientRect.bottom -= offsetY; } return clientRect; }; this.getOffsetSize = function(elt) { return {width: elt.offsetWidth, height: elt.offsetHeight}; }; this.getOverflowParent = function(element) { for (var scrollParent = element.parentNode; scrollParent; scrollParent = scrollParent.offsetParent) { if (scrollParent.scrollHeight > scrollParent.offsetHeight) return scrollParent; } }; this.isScrolledToBottom = function(element) { var onBottom = (element.scrollTop + element.offsetHeight) == element.scrollHeight; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("isScrolledToBottom offsetHeight: "+element.offsetHeight +" onBottom:"+onBottom); return onBottom; }; this.scrollToBottom = function(element) { element.scrollTop = element.scrollHeight; if (FBTrace.DBG_CONSOLE) { FBTrace.sysout("scrollToBottom reset scrollTop "+element.scrollTop+" = "+element.scrollHeight); if (element.scrollHeight == element.offsetHeight) FBTrace.sysout("scrollToBottom attempt to scroll non-scrollable element "+element, element); } return (element.scrollTop == element.scrollHeight); }; this.move = function(element, x, y) { element.style.left = x + "px"; element.style.top = y + "px"; }; this.resize = function(element, w, h) { element.style.width = w + "px"; element.style.height = h + "px"; }; this.linesIntoCenterView = function(element, scrollBox) // {before: int, after: int} { if (!scrollBox) scrollBox = this.getOverflowParent(element); if (!scrollBox) return; var offset = this.getClientOffset(element); var topSpace = offset.y - scrollBox.scrollTop; var bottomSpace = (scrollBox.scrollTop + scrollBox.clientHeight) - (offset.y + element.offsetHeight); if (topSpace < 0 || bottomSpace < 0) { var split = (scrollBox.clientHeight/2); var centerY = offset.y - split; scrollBox.scrollTop = centerY; topSpace = split; bottomSpace = split - element.offsetHeight; } return {before: Math.round((topSpace/element.offsetHeight) + 0.5), after: Math.round((bottomSpace/element.offsetHeight) + 0.5) }; }; this.scrollIntoCenterView = function(element, scrollBox, notX, notY) { if (!element) return; if (!scrollBox) scrollBox = this.getOverflowParent(element); if (!scrollBox) return; var offset = this.getClientOffset(element); if (!notY) { var topSpace = offset.y - scrollBox.scrollTop; var bottomSpace = (scrollBox.scrollTop + scrollBox.clientHeight) - (offset.y + element.offsetHeight); if (topSpace < 0 || bottomSpace < 0) { var centerY = offset.y - (scrollBox.clientHeight/2); scrollBox.scrollTop = centerY; } } if (!notX) { var leftSpace = offset.x - scrollBox.scrollLeft; var rightSpace = (scrollBox.scrollLeft + scrollBox.clientWidth) - (offset.x + element.clientWidth); if (leftSpace < 0 || rightSpace < 0) { var centerX = offset.x - (scrollBox.clientWidth/2); scrollBox.scrollLeft = centerX; } } if (FBTrace.DBG_SOURCEFILES) FBTrace.sysout("lib.scrollIntoCenterView ","Element:"+element.innerHTML); }; // ************************************************************************************************ // CSS var cssKeywordMap = null; var cssPropNames = null; var cssColorNames = null; var imageRules = null; this.getCSSKeywordsByProperty = function(propName) { if (!cssKeywordMap) { cssKeywordMap = {}; for (var name in this.cssInfo) { var list = []; var types = this.cssInfo[name]; for (var i = 0; i < types.length; ++i) { var keywords = this.cssKeywords[types[i]]; if (keywords) list.push.apply(list, keywords); } cssKeywordMap[name] = list; } } return propName in cssKeywordMap ? cssKeywordMap[propName] : []; }; this.getCSSPropertyNames = function() { if (!cssPropNames) { cssPropNames = []; for (var name in this.cssInfo) cssPropNames.push(name); } return cssPropNames; }; this.isColorKeyword = function(keyword) { if (keyword == "transparent") return false; if (!cssColorNames) { cssColorNames = []; var colors = this.cssKeywords["color"]; for (var i = 0; i < colors.length; ++i) cssColorNames.push(colors[i].toLowerCase()); var systemColors = this.cssKeywords["systemColor"]; for (var i = 0; i < systemColors.length; ++i) cssColorNames.push(systemColors[i].toLowerCase()); } return cssColorNames.indexOf ? // Array.indexOf is not available in IE cssColorNames.indexOf(keyword.toLowerCase()) != -1 : (" " + cssColorNames.join(" ") + " ").indexOf(" " + keyword.toLowerCase() + " ") != -1; }; this.isImageRule = function(rule) { if (!imageRules) { imageRules = []; for (var i in this.cssInfo) { var r = i.toLowerCase(); var suffix = "image"; if (r.match(suffix + "$") == suffix || r == "background") imageRules.push(r); } } return imageRules.indexOf ? // Array.indexOf is not available in IE imageRules.indexOf(rule.toLowerCase()) != -1 : (" " + imageRules.join(" ") + " ").indexOf(" " + rule.toLowerCase() + " ") != -1; }; this.copyTextStyles = function(fromNode, toNode, style) { var view = this.isIE ? fromNode.ownerDocument.parentWindow : fromNode.ownerDocument.defaultView; if (view) { if (!style) style = this.isIE ? fromNode.currentStyle : view.getComputedStyle(fromNode, ""); toNode.style.fontFamily = style.fontFamily; // TODO: xxxpedro need to create a FBL.getComputedStyle() because IE // returns wrong computed styles for inherited properties (like font-*) // // Also would be good to create a FBL.getStyle() toNode.style.fontSize = style.fontSize; toNode.style.fontWeight = style.fontWeight; toNode.style.fontStyle = style.fontStyle; return style; } }; this.copyBoxStyles = function(fromNode, toNode, style) { var view = this.isIE ? fromNode.ownerDocument.parentWindow : fromNode.ownerDocument.defaultView; if (view) { if (!style) style = this.isIE ? fromNode.currentStyle : view.getComputedStyle(fromNode, ""); toNode.style.marginTop = style.marginTop; toNode.style.marginRight = style.marginRight; toNode.style.marginBottom = style.marginBottom; toNode.style.marginLeft = style.marginLeft; toNode.style.borderTopWidth = style.borderTopWidth; toNode.style.borderRightWidth = style.borderRightWidth; toNode.style.borderBottomWidth = style.borderBottomWidth; toNode.style.borderLeftWidth = style.borderLeftWidth; return style; } }; this.readBoxStyles = function(style) { var styleNames = { "margin-top": "marginTop", "margin-right": "marginRight", "margin-left": "marginLeft", "margin-bottom": "marginBottom", "border-top-width": "borderTop", "border-right-width": "borderRight", "border-left-width": "borderLeft", "border-bottom-width": "borderBottom", "padding-top": "paddingTop", "padding-right": "paddingRight", "padding-left": "paddingLeft", "padding-bottom": "paddingBottom", "z-index": "zIndex" }; var styles = {}; for (var styleName in styleNames) styles[styleNames[styleName]] = parseInt(style.getPropertyCSSValue(styleName).cssText) || 0; if (FBTrace.DBG_INSPECT) FBTrace.sysout("readBoxStyles ", styles); return styles; }; this.getBoxFromStyles = function(style, element) { var args = this.readBoxStyles(style); args.width = element.offsetWidth - (args.paddingLeft+args.paddingRight+args.borderLeft+args.borderRight); args.height = element.offsetHeight - (args.paddingTop+args.paddingBottom+args.borderTop+args.borderBottom); return args; }; this.getElementCSSSelector = function(element) { var label = element.localName.toLowerCase(); if (element.id) label += "#" + element.id; if (element.hasAttribute("class")) label += "." + element.getAttribute("class").split(" ")[0]; return label; }; this.getURLForStyleSheet= function(styleSheet) { //http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-StyleSheet. For inline style sheets, the value of this attribute is null. return (styleSheet.href ? styleSheet.href : styleSheet.ownerNode.ownerDocument.URL); }; this.getDocumentForStyleSheet = function(styleSheet) { while (styleSheet.parentStyleSheet && !styleSheet.ownerNode) { styleSheet = styleSheet.parentStyleSheet; } if (styleSheet.ownerNode) return styleSheet.ownerNode.ownerDocument; }; /** * Retrieves the instance number for a given style sheet. The instance number * is sheet's index within the set of all other sheets whose URL is the same. */ this.getInstanceForStyleSheet = function(styleSheet, ownerDocument) { // System URLs are always unique (or at least we are making this assumption) if (FBL.isSystemStyleSheet(styleSheet)) return 0; // ownerDocument is an optional hint for performance if (FBTrace.DBG_CSS) FBTrace.sysout("getInstanceForStyleSheet: " + styleSheet.href + " " + styleSheet.media.mediaText + " " + (styleSheet.ownerNode && FBL.getElementXPath(styleSheet.ownerNode)), ownerDocument); ownerDocument = ownerDocument || FBL.getDocumentForStyleSheet(styleSheet); var ret = 0, styleSheets = ownerDocument.styleSheets, href = styleSheet.href; for (var i = 0; i < styleSheets.length; i++) { var curSheet = styleSheets[i]; if (FBTrace.DBG_CSS) FBTrace.sysout("getInstanceForStyleSheet: compare href " + i + " " + curSheet.href + " " + curSheet.media.mediaText + " " + (curSheet.ownerNode && FBL.getElementXPath(curSheet.ownerNode))); if (curSheet == styleSheet) break; if (curSheet.href == href) ret++; } return ret; }; // ************************************************************************************************ // HTML and XML Serialization var getElementType = this.getElementType = function(node) { if (isElementXUL(node)) return 'xul'; else if (isElementSVG(node)) return 'svg'; else if (isElementMathML(node)) return 'mathml'; else if (isElementXHTML(node)) return 'xhtml'; else if (isElementHTML(node)) return 'html'; }; var getElementSimpleType = this.getElementSimpleType = function(node) { if (isElementSVG(node)) return 'svg'; else if (isElementMathML(node)) return 'mathml'; else return 'html'; }; var isElementHTML = this.isElementHTML = function(node) { return node.nodeName == node.nodeName.toUpperCase(); }; var isElementXHTML = this.isElementXHTML = function(node) { return node.nodeName == node.nodeName.toLowerCase(); }; var isElementMathML = this.isElementMathML = function(node) { return node.namespaceURI == 'http://www.w3.org/1998/Math/MathML'; }; var isElementSVG = this.isElementSVG = function(node) { return node.namespaceURI == 'http://www.w3.org/2000/svg'; }; var isElementXUL = this.isElementXUL = function(node) { return node instanceof XULElement; }; this.isSelfClosing = function(element) { if (isElementSVG(element) || isElementMathML(element)) return true; var tag = element.localName.toLowerCase(); return (this.selfClosingTags.hasOwnProperty(tag)); }; this.getElementHTML = function(element) { var self=this; function toHTML(elt) { if (elt.nodeType == Node.ELEMENT_NODE) { if (unwrapObject(elt).firebugIgnore) return; html.push('<', elt.nodeName.toLowerCase()); for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; // Hide attributes set by Firebug if (attr.localName.indexOf("firebug-") == 0) continue; // MathML if (attr.localName.indexOf("-moz-math") == 0) { // just hide for now continue; } html.push(' ', attr.nodeName, '="', escapeForElementAttribute(attr.nodeValue),'"'); } if (elt.firstChild) { html.push('>'); var pureText=true; for (var child = element.firstChild; child; child = child.nextSibling) pureText=pureText && (child.nodeType == Node.TEXT_NODE); if (pureText) html.push(escapeForHtmlEditor(elt.textContent)); else { for (var child = elt.firstChild; child; child = child.nextSibling) toHTML(child); } html.push('</', elt.nodeName.toLowerCase(), '>'); } else if (isElementSVG(elt) || isElementMathML(elt)) { html.push('/>'); } else if (self.isSelfClosing(elt)) { html.push((isElementXHTML(elt))?'/>':'>'); } else { html.push('></', elt.nodeName.toLowerCase(), '>'); } } else if (elt.nodeType == Node.TEXT_NODE) html.push(escapeForTextNode(elt.textContent)); else if (elt.nodeType == Node.CDATA_SECTION_NODE) html.push('<![CDATA[', elt.nodeValue, ']]>'); else if (elt.nodeType == Node.COMMENT_NODE) html.push('<!--', elt.nodeValue, '-->'); } var html = []; toHTML(element); return html.join(""); }; this.getElementXML = function(element) { function toXML(elt) { if (elt.nodeType == Node.ELEMENT_NODE) { if (unwrapObject(elt).firebugIgnore) return; xml.push('<', elt.nodeName.toLowerCase()); for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; // Hide attributes set by Firebug if (attr.localName.indexOf("firebug-") == 0) continue; // MathML if (attr.localName.indexOf("-moz-math") == 0) { // just hide for now continue; } xml.push(' ', attr.nodeName, '="', escapeForElementAttribute(attr.nodeValue),'"'); } if (elt.firstChild) { xml.push('>'); for (var child = elt.firstChild; child; child = child.nextSibling) toXML(child); xml.push('</', elt.nodeName.toLowerCase(), '>'); } else xml.push('/>'); } else if (elt.nodeType == Node.TEXT_NODE) xml.push(elt.nodeValue); else if (elt.nodeType == Node.CDATA_SECTION_NODE) xml.push('<![CDATA[', elt.nodeValue, ']]>'); else if (elt.nodeType == Node.COMMENT_NODE) xml.push('<!--', elt.nodeValue, '-->'); } var xml = []; toXML(element); return xml.join(""); }; // ************************************************************************************************ // CSS classes this.hasClass = function(node, name) // className, className, ... { // TODO: xxxpedro when lib.hasClass is called with more than 2 arguments? // this function can be optimized a lot if assumed 2 arguments only, // which seems to be what happens 99% of the time if (arguments.length == 2) return (' '+node.className+' ').indexOf(' '+name+' ') != -1; if (!node || node.nodeType != 1) return false; else { for (var i=1; i<arguments.length; ++i) { var name = arguments[i]; var re = new RegExp("(^|\\s)"+name+"($|\\s)"); if (!re.exec(node.className)) return false; } return true; } }; this.old_hasClass = function(node, name) // className, className, ... { if (!node || node.nodeType != 1) return false; else { for (var i=1; i<arguments.length; ++i) { var name = arguments[i]; var re = new RegExp("(^|\\s)"+name+"($|\\s)"); if (!re.exec(node.className)) return false; } return true; } }; this.setClass = function(node, name) { if (node && (' '+node.className+' ').indexOf(' '+name+' ') == -1) ///if (node && !this.hasClass(node, name)) node.className += " " + name; }; this.getClassValue = function(node, name) { var re = new RegExp(name+"-([^ ]+)"); var m = re.exec(node.className); return m ? m[1] : ""; }; this.removeClass = function(node, name) { if (node && node.className) { var index = node.className.indexOf(name); if (index >= 0) { var size = name.length; node.className = node.className.substr(0,index-1) + node.className.substr(index+size); } } }; this.toggleClass = function(elt, name) { if ((' '+elt.className+' ').indexOf(' '+name+' ') != -1) ///if (this.hasClass(elt, name)) this.removeClass(elt, name); else this.setClass(elt, name); }; this.setClassTimed = function(elt, name, context, timeout) { if (!timeout) timeout = 1300; if (elt.__setClassTimeout) context.clearTimeout(elt.__setClassTimeout); else this.setClass(elt, name); elt.__setClassTimeout = context.setTimeout(function() { delete elt.__setClassTimeout; FBL.removeClass(elt, name); }, timeout); }; this.cancelClassTimed = function(elt, name, context) { if (elt.__setClassTimeout) { FBL.removeClass(elt, name); context.clearTimeout(elt.__setClassTimeout); delete elt.__setClassTimeout; } }; // ************************************************************************************************ // DOM queries this.$ = function(id, doc) { if (doc) return doc.getElementById(id); else { return FBL.Firebug.chrome.document.getElementById(id); } }; this.$$ = function(selector, doc) { if (doc || !FBL.Firebug.chrome) return FBL.Firebug.Selector(selector, doc); else { return FBL.Firebug.Selector(selector, FBL.Firebug.chrome.document); } }; this.getChildByClass = function(node) // ,classname, classname, classname... { for (var i = 1; i < arguments.length; ++i) { var className = arguments[i]; var child = node.firstChild; node = null; for (; child; child = child.nextSibling) { if (this.hasClass(child, className)) { node = child; break; } } } return node; }; this.getAncestorByClass = function(node, className) { for (var parent = node; parent; parent = parent.parentNode) { if (this.hasClass(parent, className)) return parent; } return null; }; this.getElementsByClass = function(node, className) { var result = []; for (var child = node.firstChild; child; child = child.nextSibling) { if (this.hasClass(child, className)) result.push(child); } return result; }; this.getElementByClass = function(node, className) // className, className, ... { var args = cloneArray(arguments); args.splice(0, 1); for (var child = node.firstChild; child; child = child.nextSibling) { var args1 = cloneArray(args); args1.unshift(child); if (FBL.hasClass.apply(null, args1)) return child; else { var found = FBL.getElementByClass.apply(null, args1); if (found) return found; } } return null; }; this.isAncestor = function(node, potentialAncestor) { for (var parent = node; parent; parent = parent.parentNode) { if (parent == potentialAncestor) return true; } return false; }; this.getNextElement = function(node) { while (node && node.nodeType != 1) node = node.nextSibling; return node; }; this.getPreviousElement = function(node) { while (node && node.nodeType != 1) node = node.previousSibling; return node; }; this.getBody = function(doc) { if (doc.body) return doc.body; var body = doc.getElementsByTagName("body")[0]; if (body) return body; return doc.firstChild; // For non-HTML docs }; this.findNextDown = function(node, criteria) { if (!node) return null; for (var child = node.firstChild; child; child = child.nextSibling) { if (criteria(child)) return child; var next = this.findNextDown(child, criteria); if (next) return next; } }; this.findPreviousUp = function(node, criteria) { if (!node) return null; for (var child = node.lastChild; child; child = child.previousSibling) { var next = this.findPreviousUp(child, criteria); if (next) return next; if (criteria(child)) return child; } }; this.findNext = function(node, criteria, upOnly, maxRoot) { if (!node) return null; if (!upOnly) { var next = this.findNextDown(node, criteria); if (next) return next; } for (var sib = node.nextSibling; sib; sib = sib.nextSibling) { if (criteria(sib)) return sib; var next = this.findNextDown(sib, criteria); if (next) return next; } if (node.parentNode && node.parentNode != maxRoot) return this.findNext(node.parentNode, criteria, true); }; this.findPrevious = function(node, criteria, downOnly, maxRoot) { if (!node) return null; for (var sib = node.previousSibling; sib; sib = sib.previousSibling) { var prev = this.findPreviousUp(sib, criteria); if (prev) return prev; if (criteria(sib)) return sib; } if (!downOnly) { var next = this.findPreviousUp(node, criteria); if (next) return next; } if (node.parentNode && node.parentNode != maxRoot) { if (criteria(node.parentNode)) return node.parentNode; return this.findPrevious(node.parentNode, criteria, true); } }; this.getNextByClass = function(root, state) { var iter = function iter(node) { return node.nodeType == 1 && FBL.hasClass(node, state); }; return this.findNext(root, iter); }; this.getPreviousByClass = function(root, state) { var iter = function iter(node) { return node.nodeType == 1 && FBL.hasClass(node, state); }; return this.findPrevious(root, iter); }; this.isElement = function(o) { try { return o && this.instanceOf(o, "Element"); } catch (ex) { return false; } }; // ************************************************************************************************ // DOM Modification // TODO: xxxpedro use doc fragments in Context API var appendFragment = null; this.appendInnerHTML = function(element, html, referenceElement) { // if undefined, we must convert it to null otherwise it will throw an error in IE // when executing element.insertBefore(firstChild, referenceElement) referenceElement = referenceElement || null; var doc = element.ownerDocument; // doc.createRange not available in IE if (doc.createRange) { var range = doc.createRange(); // a helper object range.selectNodeContents(element); // the environment to interpret the html var fragment = range.createContextualFragment(html); // parse var firstChild = fragment.firstChild; element.insertBefore(fragment, referenceElement); } else { if (!appendFragment || appendFragment.ownerDocument != doc) appendFragment = doc.createDocumentFragment(); var div = doc.createElement("div"); div.innerHTML = html; var firstChild = div.firstChild; while (div.firstChild) appendFragment.appendChild(div.firstChild); element.insertBefore(appendFragment, referenceElement); div = null; } return firstChild; }; // ************************************************************************************************ // DOM creation this.createElement = function(tagName, properties) { properties = properties || {}; var doc = properties.document || FBL.Firebug.chrome.document; var element = doc.createElement(tagName); for(var name in properties) { if (name != "document") { element[name] = properties[name]; } } return element; }; this.createGlobalElement = function(tagName, properties) { properties = properties || {}; var doc = FBL.Env.browser.document; var element = this.NS && doc.createElementNS ? doc.createElementNS(FBL.NS, tagName) : doc.createElement(tagName); for(var name in properties) { var propname = name; if (FBL.isIE && name == "class") propname = "className"; if (name != "document") { element.setAttribute(propname, properties[name]); } } return element; }; //************************************************************************************************ this.safeGetWindowLocation = function(window) { try { if (window) { if (window.closed) return "(window.closed)"; if ("location" in window) return window.location+""; else return "(no window.location)"; } else return "(no context.window)"; } catch(exc) { if (FBTrace.DBG_WINDOWS || FBTrace.DBG_ERRORS) FBTrace.sysout("TabContext.getWindowLocation failed "+exc, exc); FBTrace.sysout("TabContext.getWindowLocation failed window:", window); return "(getWindowLocation: "+exc+")"; } }; // ************************************************************************************************ // Events this.isLeftClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && // others this.noKeyModifiers(event); }; this.isMiddleClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 4 : // IE "click" and "dblclick" button model event.button == 1) && this.noKeyModifiers(event); }; this.isRightClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 2 : // IE "click" and "dblclick" button model event.button == 2) && this.noKeyModifiers(event); }; this.noKeyModifiers = function(event) { return !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey; }; this.isControlClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && this.isControl(event); }; this.isShiftClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && this.isShift(event); }; this.isControl = function(event) { return (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey; }; this.isAlt = function(event) { return event.altKey && !event.ctrlKey && !event.shiftKey && !event.metaKey; }; this.isAltClick = function(event) { return (this.isIE && event.type != "click" && event.type != "dblclick" ? event.button == 1 : // IE "click" and "dblclick" button model event.button == 0) && this.isAlt(event); }; this.isControlShift = function(event) { return (event.metaKey || event.ctrlKey) && event.shiftKey && !event.altKey; }; this.isShift = function(event) { return event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey; }; this.addEvent = function(object, name, handler, useCapture) { if (object.addEventListener) object.addEventListener(name, handler, useCapture); else object.attachEvent("on"+name, handler); }; this.removeEvent = function(object, name, handler, useCapture) { try { if (object.removeEventListener) object.removeEventListener(name, handler, useCapture); else object.detachEvent("on"+name, handler); } catch(e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("FBL.removeEvent error: ", object, name); } }; this.cancelEvent = function(e, preventDefault) { if (!e) return; if (preventDefault) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.addGlobalEvent = function(name, handler) { var doc = this.Firebug.browser.document; var frames = this.Firebug.browser.window.frames; this.addEvent(doc, name, handler); if (this.Firebug.chrome.type == "popup") this.addEvent(this.Firebug.chrome.document, name, handler); for (var i = 0, frame; frame = frames[i]; i++) { try { this.addEvent(frame.document, name, handler); } catch(E) { // Avoid acess denied } } }; this.removeGlobalEvent = function(name, handler) { var doc = this.Firebug.browser.document; var frames = this.Firebug.browser.window.frames; this.removeEvent(doc, name, handler); if (this.Firebug.chrome.type == "popup") this.removeEvent(this.Firebug.chrome.document, name, handler); for (var i = 0, frame; frame = frames[i]; i++) { try { this.removeEvent(frame.document, name, handler); } catch(E) { // Avoid acess denied } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.dispatch = function(listeners, name, args) { if (!listeners) return; try {/**/ if (typeof listeners.length != "undefined") { if (FBTrace.DBG_DISPATCH) FBTrace.sysout("FBL.dispatch", name+" to "+listeners.length+" listeners"); for (var i = 0; i < listeners.length; ++i) { var listener = listeners[i]; if ( listener[name] ) listener[name].apply(listener, args); } } else { if (FBTrace.DBG_DISPATCH) FBTrace.sysout("FBL.dispatch", name+" to listeners of an object"); for (var prop in listeners) { var listener = listeners[prop]; if ( listener[name] ) listener[name].apply(listener, args); } } } catch (exc) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout(" Exception in lib.dispatch "+ name, exc); //FBTrace.dumpProperties(" Exception in lib.dispatch listener", listener); } } /**/ }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var disableTextSelectionHandler = function(event) { FBL.cancelEvent(event, true); return false; }; this.disableTextSelection = function(e) { if (typeof e.onselectstart != "undefined") // IE this.addEvent(e, "selectstart", disableTextSelectionHandler); else // others { e.style.cssText = "user-select: none; -khtml-user-select: none; -moz-user-select: none;"; // canceling the event in FF will prevent the menu popups to close when clicking over // text-disabled elements if (!this.isFirefox) this.addEvent(e, "mousedown", disableTextSelectionHandler); } e.style.cursor = "default"; }; this.restoreTextSelection = function(e) { if (typeof e.onselectstart != "undefined") // IE this.removeEvent(e, "selectstart", disableTextSelectionHandler); else // others { e.style.cssText = "cursor: default;"; // canceling the event in FF will prevent the menu popups to close when clicking over // text-disabled elements if (!this.isFirefox) this.removeEvent(e, "mousedown", disableTextSelectionHandler); } }; // ************************************************************************************************ // DOM Events var eventTypes = { composition: [ "composition", "compositionstart", "compositionend" ], contextmenu: [ "contextmenu" ], drag: [ "dragenter", "dragover", "dragexit", "dragdrop", "draggesture" ], focus: [ "focus", "blur" ], form: [ "submit", "reset", "change", "select", "input" ], key: [ "keydown", "keyup", "keypress" ], load: [ "load", "beforeunload", "unload", "abort", "error" ], mouse: [ "mousedown", "mouseup", "click", "dblclick", "mouseover", "mouseout", "mousemove" ], mutation: [ "DOMSubtreeModified", "DOMNodeInserted", "DOMNodeRemoved", "DOMNodeRemovedFromDocument", "DOMNodeInsertedIntoDocument", "DOMAttrModified", "DOMCharacterDataModified" ], paint: [ "paint", "resize", "scroll" ], scroll: [ "overflow", "underflow", "overflowchanged" ], text: [ "text" ], ui: [ "DOMActivate", "DOMFocusIn", "DOMFocusOut" ], xul: [ "popupshowing", "popupshown", "popuphiding", "popuphidden", "close", "command", "broadcast", "commandupdate" ] }; this.getEventFamily = function(eventType) { if (!this.families) { this.families = {}; for (var family in eventTypes) { var types = eventTypes[family]; for (var i = 0; i < types.length; ++i) this.families[types[i]] = family; } } return this.families[eventType]; }; // ************************************************************************************************ // URLs this.getFileName = function(url) { var split = this.splitURLBase(url); return split.name; }; this.splitURLBase = function(url) { if (this.isDataURL(url)) return this.splitDataURL(url); return this.splitURLTrue(url); }; this.splitDataURL = function(url) { var mark = url.indexOf(':', 3); if (mark != 4) return false; // the first 5 chars must be 'data:' var point = url.indexOf(',', mark+1); if (point < mark) return false; // syntax error var props = { encodedContent: url.substr(point+1) }; var metadataBuffer = url.substr(mark+1, point); var metadata = metadataBuffer.split(';'); for (var i = 0; i < metadata.length; i++) { var nv = metadata[i].split('='); if (nv.length == 2) props[nv[0]] = nv[1]; } // Additional Firebug-specific properties if (props.hasOwnProperty('fileName')) { var caller_URL = decodeURIComponent(props['fileName']); var caller_split = this.splitURLTrue(caller_URL); if (props.hasOwnProperty('baseLineNumber')) // this means it's probably an eval() { props['path'] = caller_split.path; props['line'] = props['baseLineNumber']; var hint = decodeURIComponent(props['encodedContent'].substr(0,200)).replace(/\s*$/, ""); props['name'] = 'eval->'+hint; } else { props['name'] = caller_split.name; props['path'] = caller_split.path; } } else { if (!props.hasOwnProperty('path')) props['path'] = "data:"; if (!props.hasOwnProperty('name')) props['name'] = decodeURIComponent(props['encodedContent'].substr(0,200)).replace(/\s*$/, ""); } return props; }; this.splitURLTrue = function(url) { var m = reSplitFile.exec(url); if (!m) return {name: url, path: url}; else if (!m[2]) return {path: m[1], name: m[1]}; else return {path: m[1], name: m[2]+m[3]}; }; this.getFileExtension = function(url) { if (!url) return null; // Remove query string from the URL if any. var queryString = url.indexOf("?"); if (queryString != -1) url = url.substr(0, queryString); // Now get the file extension. var lastDot = url.lastIndexOf("."); return url.substr(lastDot+1); }; this.isSystemURL = function(url) { if (!url) return true; if (url.length == 0) return true; if (url[0] == 'h') return false; if (url.substr(0, 9) == "resource:") return true; else if (url.substr(0, 16) == "chrome://firebug") return true; else if (url == "XPCSafeJSObjectWrapper.cpp") return true; else if (url.substr(0, 6) == "about:") return true; else if (url.indexOf("firebug-service.js") != -1) return true; else return false; }; this.isSystemPage = function(win) { try { var doc = win.document; if (!doc) return false; // Detect pages for pretty printed XML if ((doc.styleSheets.length && doc.styleSheets[0].href == "chrome://global/content/xml/XMLPrettyPrint.css") || (doc.styleSheets.length > 1 && doc.styleSheets[1].href == "chrome://browser/skin/feeds/subscribe.css")) return true; return FBL.isSystemURL(win.location.href); } catch (exc) { // Sometimes documents just aren't ready to be manipulated here, but don't let that // gum up the works ERROR("tabWatcher.isSystemPage document not ready:"+ exc); return false; } }; this.isSystemStyleSheet = function(sheet) { var href = sheet && sheet.href; return href && FBL.isSystemURL(href); }; this.getURIHost = function(uri) { try { if (uri) return uri.host; else return ""; } catch (exc) { return ""; } }; this.isLocalURL = function(url) { if (url.substr(0, 5) == "file:") return true; else if (url.substr(0, 8) == "wyciwyg:") return true; else return false; }; this.isDataURL = function(url) { return (url && url.substr(0,5) == "data:"); }; this.getLocalPath = function(url) { if (this.isLocalURL(url)) { var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler); var file = fileHandler.getFileFromURLSpec(url); return file.path; } }; this.getURLFromLocalFile = function(file) { var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler); var URL = fileHandler.getURLSpecFromFile(file); return URL; }; this.getDataURLForContent = function(content, url) { // data:text/javascript;fileName=x%2Cy.js;baseLineNumber=10,<the-url-encoded-data> var uri = "data:text/html;"; uri += "fileName="+encodeURIComponent(url)+ ","; uri += encodeURIComponent(content); return uri; }, this.getDomain = function(url) { var m = /[^:]+:\/{1,3}([^\/]+)/.exec(url); return m ? m[1] : ""; }; this.getURLPath = function(url) { var m = /[^:]+:\/{1,3}[^\/]+(\/.*?)$/.exec(url); return m ? m[1] : ""; }; this.getPrettyDomain = function(url) { var m = /[^:]+:\/{1,3}(www\.)?([^\/]+)/.exec(url); return m ? m[2] : ""; }; this.absoluteURL = function(url, baseURL) { return this.absoluteURLWithDots(url, baseURL).replace("/./", "/", "g"); }; this.absoluteURLWithDots = function(url, baseURL) { if (url[0] == "?") return baseURL + url; var reURL = /(([^:]+:)\/{1,2}[^\/]*)(.*?)$/; var m = reURL.exec(url); if (m) return url; var m = reURL.exec(baseURL); if (!m) return ""; var head = m[1]; var tail = m[3]; if (url.substr(0, 2) == "//") return m[2] + url; else if (url[0] == "/") { return head + url; } else if (tail[tail.length-1] == "/") return baseURL + url; else { var parts = tail.split("/"); return head + parts.slice(0, parts.length-1).join("/") + "/" + url; } }; this.normalizeURL = function(url) // this gets called a lot, any performance improvement welcome { if (!url) return ""; // Replace one or more characters that are not forward-slash followed by /.., by space. if (url.length < 255) // guard against monsters. { // Replace one or more characters that are not forward-slash followed by /.., by space. url = url.replace(/[^\/]+\/\.\.\//, "", "g"); // Issue 1496, avoid # url = url.replace(/#.*/,""); // For some reason, JSDS reports file URLs like "file:/" instead of "file:///", so they // don't match up with the URLs we get back from the DOM url = url.replace(/file:\/([^\/])/g, "file:///$1"); if (url.indexOf('chrome:')==0) { var m = reChromeCase.exec(url); // 1 is package name, 2 is path if (m) { url = "chrome://"+m[1].toLowerCase()+"/"+m[2]; } } } return url; }; this.denormalizeURL = function(url) { return url.replace(/file:\/\/\//g, "file:/"); }; this.parseURLParams = function(url) { var q = url ? url.indexOf("?") : -1; if (q == -1) return []; var search = url.substr(q+1); var h = search.lastIndexOf("#"); if (h != -1) search = search.substr(0, h); if (!search) return []; return this.parseURLEncodedText(search); }; this.parseURLEncodedText = function(text) { var maxValueLength = 25000; var params = []; // Unescape '+' characters that are used to encode a space. // See section 2.2.in RFC 3986: http://www.ietf.org/rfc/rfc3986.txt text = text.replace(/\+/g, " "); var args = text.split("&"); for (var i = 0; i < args.length; ++i) { try { var parts = args[i].split("="); if (parts.length == 2) { if (parts[1].length > maxValueLength) parts[1] = this.$STR("LargeData"); params.push({name: decodeURIComponent(parts[0]), value: decodeURIComponent(parts[1])}); } else params.push({name: decodeURIComponent(parts[0]), value: ""}); } catch (e) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("parseURLEncodedText EXCEPTION ", e); FBTrace.sysout("parseURLEncodedText EXCEPTION URI", args[i]); } } } params.sort(function(a, b) { return a.name <= b.name ? -1 : 1; }); return params; }; // TODO: xxxpedro lib. why loops in domplate are requiring array in parameters // as in response/request headers and get/post parameters in Net module? this.parseURLParamsArray = function(url) { var q = url ? url.indexOf("?") : -1; if (q == -1) return []; var search = url.substr(q+1); var h = search.lastIndexOf("#"); if (h != -1) search = search.substr(0, h); if (!search) return []; return this.parseURLEncodedTextArray(search); }; this.parseURLEncodedTextArray = function(text) { var maxValueLength = 25000; var params = []; // Unescape '+' characters that are used to encode a space. // See section 2.2.in RFC 3986: http://www.ietf.org/rfc/rfc3986.txt text = text.replace(/\+/g, " "); var args = text.split("&"); for (var i = 0; i < args.length; ++i) { try { var parts = args[i].split("="); if (parts.length == 2) { if (parts[1].length > maxValueLength) parts[1] = this.$STR("LargeData"); params.push({name: decodeURIComponent(parts[0]), value: [decodeURIComponent(parts[1])]}); } else params.push({name: decodeURIComponent(parts[0]), value: [""]}); } catch (e) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("parseURLEncodedText EXCEPTION ", e); FBTrace.sysout("parseURLEncodedText EXCEPTION URI", args[i]); } } } params.sort(function(a, b) { return a.name <= b.name ? -1 : 1; }); return params; }; this.reEncodeURL = function(file, text) { var lines = text.split("\n"); var params = this.parseURLEncodedText(lines[lines.length-1]); var args = []; for (var i = 0; i < params.length; ++i) args.push(encodeURIComponent(params[i].name)+"="+encodeURIComponent(params[i].value)); var url = file.href; url += (url.indexOf("?") == -1 ? "?" : "&") + args.join("&"); return url; }; this.getResource = function(aURL) { try { var channel=ioService.newChannel(aURL,null,null); var input=channel.open(); return FBL.readFromStream(input); } catch (e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.getResource FAILS for "+aURL, e); } }; this.parseJSONString = function(jsonString, originURL) { // See if this is a Prototype style *-secure request. var regex = new RegExp(/^\/\*-secure-([\s\S]*)\*\/\s*$/); var matches = regex.exec(jsonString); if (matches) { jsonString = matches[1]; if (jsonString[0] == "\\" && jsonString[1] == "n") jsonString = jsonString.substr(2); if (jsonString[jsonString.length-2] == "\\" && jsonString[jsonString.length-1] == "n") jsonString = jsonString.substr(0, jsonString.length-2); } if (jsonString.indexOf("&&&START&&&")) { regex = new RegExp(/&&&START&&& (.+) &&&END&&&/); matches = regex.exec(jsonString); if (matches) jsonString = matches[1]; } // throw on the extra parentheses jsonString = "(" + jsonString + ")"; ///var s = Components.utils.Sandbox(originURL); var jsonObject = null; try { ///jsonObject = Components.utils.evalInSandbox(jsonString, s); //jsonObject = Firebug.context.eval(jsonString); jsonObject = Firebug.context.evaluate(jsonString, null, null, function(){return null;}); } catch(e) { /*** if (e.message.indexOf("is not defined")) { var parts = e.message.split(" "); s[parts[0]] = function(str){ return str; }; try { jsonObject = Components.utils.evalInSandbox(jsonString, s); } catch(ex) { if (FBTrace.DBG_ERRORS || FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.parseJSON EXCEPTION", e); return null; } } else {/**/ if (FBTrace.DBG_ERRORS || FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.parseJSON EXCEPTION", e); return null; ///} } return jsonObject; }; // ************************************************************************************************ this.objectToString = function(object) { try { return object+""; } catch (exc) { return null; } }; // ************************************************************************************************ // Input Caret Position this.setSelectionRange = function(input, start, length) { if (input.createTextRange) { var range = input.createTextRange(); range.moveStart("character", start); range.moveEnd("character", length - input.value.length); range.select(); } else if (input.setSelectionRange) { input.setSelectionRange(start, length); input.focus(); } }; // ************************************************************************************************ // Input Selection Start / Caret Position this.getInputSelectionStart = function(input) { if (document.selection) { var range = input.ownerDocument.selection.createRange(); var text = range.text; //console.log("range", range.text); // if there is a selection, find the start position if (text) { return input.value.indexOf(text); } // if there is no selection, find the caret position else { range.moveStart("character", -input.value.length); return range.text.length; } } else if (typeof input.selectionStart != "undefined") return input.selectionStart; return 0; }; // ************************************************************************************************ // Opera Tab Fix function onOperaTabBlur(e) { if (this.lastKey == 9) this.focus(); }; function onOperaTabKeyDown(e) { this.lastKey = e.keyCode; }; function onOperaTabFocus(e) { this.lastKey = null; }; this.fixOperaTabKey = function(el) { el.onfocus = onOperaTabFocus; el.onblur = onOperaTabBlur; el.onkeydown = onOperaTabKeyDown; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.Property = function(object, name) { this.object = object; this.name = name; this.getObject = function() { return object[name]; }; }; this.ErrorCopy = function(message) { this.message = message; }; function EventCopy(event) { // Because event objects are destroyed arbitrarily by Gecko, we must make a copy of them to // represent them long term in the inspector. for (var name in event) { try { this[name] = event[name]; } catch (exc) { } } } this.EventCopy = EventCopy; // ************************************************************************************************ // Type Checking var toString = Object.prototype.toString; var reFunction = /^\s*function(\s+[\w_$][\w\d_$]*)?\s*\(/; this.isArray = function(object) { return toString.call(object) === '[object Array]'; }; this.isFunction = function(object) { if (!object) return false; try { // FIXME: xxxpedro this is failing in IE for the global "external" object return toString.call(object) === "[object Function]" || this.isIE && typeof object != "string" && reFunction.test(""+object); } catch (E) { FBTrace.sysout("Lib.isFunction() failed for ", object); return false; } }; // ************************************************************************************************ // Instance Checking this.instanceOf = function(object, className) { if (!object || typeof object != "object") return false; // Try to use the native instanceof operator. We can only use it when we know // exactly the window where the object is located at if (object.ownerDocument) { // find the correct window of the object var win = object.ownerDocument.defaultView || object.ownerDocument.parentWindow; // if the class is accessible in the window, uses the native instanceof operator // if the instanceof evaluates to "true" we can assume it is a instance, but if it // evaluates to "false" we must continue with the duck type detection below because // the native object may be extended, thus breaking the instanceof result // See Issue 3524: Firebug Lite Style Panel doesn't work if the native Element is extended if (className in win && object instanceof win[className]) return true; } // If the object doesn't have the ownerDocument property, we'll try to look at // the current context's window else { // TODO: xxxpedro context // Since we're not using yet a Firebug.context, we'll just use the top window // (browser) as a reference var win = Firebug.browser.window; if (className in win) return object instanceof win[className]; } // get the duck type model from the cache var cache = instanceCheckMap[className]; if (!cache) return false; // starts the hacky duck type detection for(var n in cache) { var obj = cache[n]; var type = typeof obj; obj = type == "object" ? obj : [obj]; for(var name in obj) { // avoid problems with extended native objects // See Issue 3524: Firebug Lite Style Panel doesn't work if the native Element is extended if (!obj.hasOwnProperty(name)) continue; var value = obj[name]; if( n == "property" && !(value in object) || n == "method" && !this.isFunction(object[value]) || n == "value" && (""+object[name]).toLowerCase() != (""+value).toLowerCase() ) return false; } } return true; }; var instanceCheckMap = { // DuckTypeCheck: // { // property: ["window", "document"], // method: "setTimeout", // value: {nodeType: 1} // }, Window: { property: ["window", "document"], method: "setTimeout" }, Document: { property: ["body", "cookie"], method: "getElementById" }, Node: { property: "ownerDocument", method: "appendChild" }, Element: { property: "tagName", value: {nodeType: 1} }, Location: { property: ["hostname", "protocol"], method: "assign" }, HTMLImageElement: { property: "useMap", value: { nodeType: 1, tagName: "img" } }, HTMLAnchorElement: { property: "hreflang", value: { nodeType: 1, tagName: "a" } }, HTMLInputElement: { property: "form", value: { nodeType: 1, tagName: "input" } }, HTMLButtonElement: { // ? }, HTMLFormElement: { method: "submit", value: { nodeType: 1, tagName: "form" } }, HTMLBodyElement: { }, HTMLHtmlElement: { }, CSSStyleRule: { property: ["selectorText", "style"] } }; // ************************************************************************************************ // DOM Constants /* Problems: - IE does not have window.Node, window.Element, etc - for (var name in Node.prototype) return nothing on FF */ var domMemberMap2 = {}; var domMemberMap2Sandbox = null; var getDomMemberMap2 = function(name) { if (!domMemberMap2Sandbox) { var doc = Firebug.chrome.document; var frame = doc.createElement("iframe"); frame.id = "FirebugSandbox"; frame.style.display = "none"; frame.src = "about:blank"; doc.body.appendChild(frame); domMemberMap2Sandbox = frame.window || frame.contentWindow; } var props = []; //var object = domMemberMap2Sandbox[name]; //object = object.prototype || object; var object = null; if (name == "Window") object = domMemberMap2Sandbox.window; else if (name == "Document") object = domMemberMap2Sandbox.document; else if (name == "HTMLScriptElement") object = domMemberMap2Sandbox.document.createElement("script"); else if (name == "HTMLAnchorElement") object = domMemberMap2Sandbox.document.createElement("a"); else if (name.indexOf("Element") != -1) { object = domMemberMap2Sandbox.document.createElement("div"); } if (object) { //object = object.prototype || object; //props = 'addEventListener,document,location,navigator,window'.split(','); for (var n in object) props.push(n); } /**/ return props; return extendArray(props, domMemberMap[name]); }; // xxxpedro experimental get DOM members this.getDOMMembers = function(object) { if (!domMemberCache) { FBL.domMemberCache = domMemberCache = {}; for (var name in domMemberMap) { var builtins = getDomMemberMap2(name); var cache = domMemberCache[name] = {}; /* if (name.indexOf("Element") != -1) { this.append(cache, this.getDOMMembers("Node")); this.append(cache, this.getDOMMembers("Element")); } /**/ for (var i = 0; i < builtins.length; ++i) cache[builtins[i]] = i; } } try { if (this.instanceOf(object, "Window")) { return domMemberCache.Window; } else if (this.instanceOf(object, "Document") || this.instanceOf(object, "XMLDocument")) { return domMemberCache.Document; } else if (this.instanceOf(object, "Location")) { return domMemberCache.Location; } else if (this.instanceOf(object, "HTMLImageElement")) { return domMemberCache.HTMLImageElement; } else if (this.instanceOf(object, "HTMLAnchorElement")) { return domMemberCache.HTMLAnchorElement; } else if (this.instanceOf(object, "HTMLInputElement")) { return domMemberCache.HTMLInputElement; } else if (this.instanceOf(object, "HTMLButtonElement")) { return domMemberCache.HTMLButtonElement; } else if (this.instanceOf(object, "HTMLFormElement")) { return domMemberCache.HTMLFormElement; } else if (this.instanceOf(object, "HTMLBodyElement")) { return domMemberCache.HTMLBodyElement; } else if (this.instanceOf(object, "HTMLHtmlElement")) { return domMemberCache.HTMLHtmlElement; } else if (this.instanceOf(object, "HTMLScriptElement")) { return domMemberCache.HTMLScriptElement; } else if (this.instanceOf(object, "HTMLTableElement")) { return domMemberCache.HTMLTableElement; } else if (this.instanceOf(object, "HTMLTableRowElement")) { return domMemberCache.HTMLTableRowElement; } else if (this.instanceOf(object, "HTMLTableCellElement")) { return domMemberCache.HTMLTableCellElement; } else if (this.instanceOf(object, "HTMLIFrameElement")) { return domMemberCache.HTMLIFrameElement; } else if (this.instanceOf(object, "SVGSVGElement")) { return domMemberCache.SVGSVGElement; } else if (this.instanceOf(object, "SVGElement")) { return domMemberCache.SVGElement; } else if (this.instanceOf(object, "Element")) { return domMemberCache.Element; } else if (this.instanceOf(object, "Text") || this.instanceOf(object, "CDATASection")) { return domMemberCache.Text; } else if (this.instanceOf(object, "Attr")) { return domMemberCache.Attr; } else if (this.instanceOf(object, "Node")) { return domMemberCache.Node; } else if (this.instanceOf(object, "Event") || this.instanceOf(object, "EventCopy")) { return domMemberCache.Event; } else return {}; } catch(E) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("lib.getDOMMembers FAILED ", E); return {}; } }; /* this.getDOMMembers = function(object) { if (!domMemberCache) { domMemberCache = {}; for (var name in domMemberMap) { var builtins = domMemberMap[name]; var cache = domMemberCache[name] = {}; for (var i = 0; i < builtins.length; ++i) cache[builtins[i]] = i; } } try { if (this.instanceOf(object, "Window")) { return domMemberCache.Window; } else if (object instanceof Document || object instanceof XMLDocument) { return domMemberCache.Document; } else if (object instanceof Location) { return domMemberCache.Location; } else if (object instanceof HTMLImageElement) { return domMemberCache.HTMLImageElement; } else if (object instanceof HTMLAnchorElement) { return domMemberCache.HTMLAnchorElement; } else if (object instanceof HTMLInputElement) { return domMemberCache.HTMLInputElement; } else if (object instanceof HTMLButtonElement) { return domMemberCache.HTMLButtonElement; } else if (object instanceof HTMLFormElement) { return domMemberCache.HTMLFormElement; } else if (object instanceof HTMLBodyElement) { return domMemberCache.HTMLBodyElement; } else if (object instanceof HTMLHtmlElement) { return domMemberCache.HTMLHtmlElement; } else if (object instanceof HTMLScriptElement) { return domMemberCache.HTMLScriptElement; } else if (object instanceof HTMLTableElement) { return domMemberCache.HTMLTableElement; } else if (object instanceof HTMLTableRowElement) { return domMemberCache.HTMLTableRowElement; } else if (object instanceof HTMLTableCellElement) { return domMemberCache.HTMLTableCellElement; } else if (object instanceof HTMLIFrameElement) { return domMemberCache.HTMLIFrameElement; } else if (object instanceof SVGSVGElement) { return domMemberCache.SVGSVGElement; } else if (object instanceof SVGElement) { return domMemberCache.SVGElement; } else if (object instanceof Element) { return domMemberCache.Element; } else if (object instanceof Text || object instanceof CDATASection) { return domMemberCache.Text; } else if (object instanceof Attr) { return domMemberCache.Attr; } else if (object instanceof Node) { return domMemberCache.Node; } else if (object instanceof Event || object instanceof EventCopy) { return domMemberCache.Event; } else return {}; } catch(E) { return {}; } }; /**/ this.isDOMMember = function(object, propName) { var members = this.getDOMMembers(object); return members && propName in members; }; var domMemberCache = null; var domMemberMap = {}; domMemberMap.Window = [ "document", "frameElement", "innerWidth", "innerHeight", "outerWidth", "outerHeight", "screenX", "screenY", "pageXOffset", "pageYOffset", "scrollX", "scrollY", "scrollMaxX", "scrollMaxY", "status", "defaultStatus", "parent", "opener", "top", "window", "content", "self", "location", "history", "frames", "navigator", "screen", "menubar", "toolbar", "locationbar", "personalbar", "statusbar", "directories", "scrollbars", "fullScreen", "netscape", "java", "console", "Components", "controllers", "closed", "crypto", "pkcs11", "name", "property", "length", "sessionStorage", "globalStorage", "setTimeout", "setInterval", "clearTimeout", "clearInterval", "addEventListener", "removeEventListener", "dispatchEvent", "getComputedStyle", "captureEvents", "releaseEvents", "routeEvent", "enableExternalCapture", "disableExternalCapture", "moveTo", "moveBy", "resizeTo", "resizeBy", "scroll", "scrollTo", "scrollBy", "scrollByLines", "scrollByPages", "sizeToContent", "setResizable", "getSelection", "open", "openDialog", "close", "alert", "confirm", "prompt", "dump", "focus", "blur", "find", "back", "forward", "home", "stop", "print", "atob", "btoa", "updateCommands", "XPCNativeWrapper", "GeckoActiveXObject", "applicationCache" // FF3 ]; domMemberMap.Location = [ "href", "protocol", "host", "hostname", "port", "pathname", "search", "hash", "assign", "reload", "replace" ]; domMemberMap.Node = [ "id", "className", "nodeType", "tagName", "nodeName", "localName", "prefix", "namespaceURI", "nodeValue", "ownerDocument", "parentNode", "offsetParent", "nextSibling", "previousSibling", "firstChild", "lastChild", "childNodes", "attributes", "dir", "baseURI", "textContent", "innerHTML", "addEventListener", "removeEventListener", "dispatchEvent", "cloneNode", "appendChild", "insertBefore", "replaceChild", "removeChild", "compareDocumentPosition", "hasAttributes", "hasChildNodes", "lookupNamespaceURI", "lookupPrefix", "normalize", "isDefaultNamespace", "isEqualNode", "isSameNode", "isSupported", "getFeature", "getUserData", "setUserData" ]; domMemberMap.Document = extendArray(domMemberMap.Node, [ "documentElement", "body", "title", "location", "referrer", "cookie", "contentType", "lastModified", "characterSet", "inputEncoding", "xmlEncoding", "xmlStandalone", "xmlVersion", "strictErrorChecking", "documentURI", "URL", "defaultView", "doctype", "implementation", "styleSheets", "images", "links", "forms", "anchors", "embeds", "plugins", "applets", "width", "height", "designMode", "compatMode", "async", "preferredStylesheetSet", "alinkColor", "linkColor", "vlinkColor", "bgColor", "fgColor", "domain", "addEventListener", "removeEventListener", "dispatchEvent", "captureEvents", "releaseEvents", "routeEvent", "clear", "open", "close", "execCommand", "execCommandShowHelp", "getElementsByName", "getSelection", "queryCommandEnabled", "queryCommandIndeterm", "queryCommandState", "queryCommandSupported", "queryCommandText", "queryCommandValue", "write", "writeln", "adoptNode", "appendChild", "removeChild", "renameNode", "cloneNode", "compareDocumentPosition", "createAttribute", "createAttributeNS", "createCDATASection", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEntityReference", "createEvent", "createExpression", "createNSResolver", "createNodeIterator", "createProcessingInstruction", "createRange", "createTextNode", "createTreeWalker", "domConfig", "evaluate", "evaluateFIXptr", "evaluateXPointer", "getAnonymousElementByAttribute", "getAnonymousNodes", "addBinding", "removeBinding", "getBindingParent", "getBoxObjectFor", "setBoxObjectFor", "getElementById", "getElementsByTagName", "getElementsByTagNameNS", "hasAttributes", "hasChildNodes", "importNode", "insertBefore", "isDefaultNamespace", "isEqualNode", "isSameNode", "isSupported", "load", "loadBindingDocument", "lookupNamespaceURI", "lookupPrefix", "normalize", "normalizeDocument", "getFeature", "getUserData", "setUserData" ]); domMemberMap.Element = extendArray(domMemberMap.Node, [ "clientWidth", "clientHeight", "offsetLeft", "offsetTop", "offsetWidth", "offsetHeight", "scrollLeft", "scrollTop", "scrollWidth", "scrollHeight", "style", "tabIndex", "title", "lang", "align", "spellcheck", "addEventListener", "removeEventListener", "dispatchEvent", "focus", "blur", "cloneNode", "appendChild", "insertBefore", "replaceChild", "removeChild", "compareDocumentPosition", "getElementsByTagName", "getElementsByTagNameNS", "getAttribute", "getAttributeNS", "getAttributeNode", "getAttributeNodeNS", "setAttribute", "setAttributeNS", "setAttributeNode", "setAttributeNodeNS", "removeAttribute", "removeAttributeNS", "removeAttributeNode", "hasAttribute", "hasAttributeNS", "hasAttributes", "hasChildNodes", "lookupNamespaceURI", "lookupPrefix", "normalize", "isDefaultNamespace", "isEqualNode", "isSameNode", "isSupported", "getFeature", "getUserData", "setUserData" ]); domMemberMap.SVGElement = extendArray(domMemberMap.Element, [ "x", "y", "width", "height", "rx", "ry", "transform", "href", "ownerSVGElement", "viewportElement", "farthestViewportElement", "nearestViewportElement", "getBBox", "getCTM", "getScreenCTM", "getTransformToElement", "getPresentationAttribute", "preserveAspectRatio" ]); domMemberMap.SVGSVGElement = extendArray(domMemberMap.Element, [ "x", "y", "width", "height", "rx", "ry", "transform", "viewBox", "viewport", "currentView", "useCurrentView", "pixelUnitToMillimeterX", "pixelUnitToMillimeterY", "screenPixelToMillimeterX", "screenPixelToMillimeterY", "currentScale", "currentTranslate", "zoomAndPan", "ownerSVGElement", "viewportElement", "farthestViewportElement", "nearestViewportElement", "contentScriptType", "contentStyleType", "getBBox", "getCTM", "getScreenCTM", "getTransformToElement", "getEnclosureList", "getIntersectionList", "getViewboxToViewportTransform", "getPresentationAttribute", "getElementById", "checkEnclosure", "checkIntersection", "createSVGAngle", "createSVGLength", "createSVGMatrix", "createSVGNumber", "createSVGPoint", "createSVGRect", "createSVGString", "createSVGTransform", "createSVGTransformFromMatrix", "deSelectAll", "preserveAspectRatio", "forceRedraw", "suspendRedraw", "unsuspendRedraw", "unsuspendRedrawAll", "getCurrentTime", "setCurrentTime", "animationsPaused", "pauseAnimations", "unpauseAnimations" ]); domMemberMap.HTMLImageElement = extendArray(domMemberMap.Element, [ "src", "naturalWidth", "naturalHeight", "width", "height", "x", "y", "name", "alt", "longDesc", "lowsrc", "border", "complete", "hspace", "vspace", "isMap", "useMap" ]); domMemberMap.HTMLAnchorElement = extendArray(domMemberMap.Element, [ "name", "target", "accessKey", "href", "protocol", "host", "hostname", "port", "pathname", "search", "hash", "hreflang", "coords", "shape", "text", "type", "rel", "rev", "charset" ]); domMemberMap.HTMLIFrameElement = extendArray(domMemberMap.Element, [ "contentDocument", "contentWindow", "frameBorder", "height", "longDesc", "marginHeight", "marginWidth", "name", "scrolling", "src", "width" ]); domMemberMap.HTMLTableElement = extendArray(domMemberMap.Element, [ "bgColor", "border", "caption", "cellPadding", "cellSpacing", "frame", "rows", "rules", "summary", "tBodies", "tFoot", "tHead", "width", "createCaption", "createTFoot", "createTHead", "deleteCaption", "deleteRow", "deleteTFoot", "deleteTHead", "insertRow" ]); domMemberMap.HTMLTableRowElement = extendArray(domMemberMap.Element, [ "bgColor", "cells", "ch", "chOff", "rowIndex", "sectionRowIndex", "vAlign", "deleteCell", "insertCell" ]); domMemberMap.HTMLTableCellElement = extendArray(domMemberMap.Element, [ "abbr", "axis", "bgColor", "cellIndex", "ch", "chOff", "colSpan", "headers", "height", "noWrap", "rowSpan", "scope", "vAlign", "width" ]); domMemberMap.HTMLScriptElement = extendArray(domMemberMap.Element, [ "src" ]); domMemberMap.HTMLButtonElement = extendArray(domMemberMap.Element, [ "accessKey", "disabled", "form", "name", "type", "value", "click" ]); domMemberMap.HTMLInputElement = extendArray(domMemberMap.Element, [ "type", "value", "checked", "accept", "accessKey", "alt", "controllers", "defaultChecked", "defaultValue", "disabled", "form", "maxLength", "name", "readOnly", "selectionEnd", "selectionStart", "size", "src", "textLength", "useMap", "click", "select", "setSelectionRange" ]); domMemberMap.HTMLFormElement = extendArray(domMemberMap.Element, [ "acceptCharset", "action", "author", "elements", "encoding", "enctype", "entry_id", "length", "method", "name", "post", "target", "text", "url", "reset", "submit" ]); domMemberMap.HTMLBodyElement = extendArray(domMemberMap.Element, [ "aLink", "background", "bgColor", "link", "text", "vLink" ]); domMemberMap.HTMLHtmlElement = extendArray(domMemberMap.Element, [ "version" ]); domMemberMap.Text = extendArray(domMemberMap.Node, [ "data", "length", "appendData", "deleteData", "insertData", "replaceData", "splitText", "substringData" ]); domMemberMap.Attr = extendArray(domMemberMap.Node, [ "name", "value", "specified", "ownerElement" ]); domMemberMap.Event = [ "type", "target", "currentTarget", "originalTarget", "explicitOriginalTarget", "relatedTarget", "rangeParent", "rangeOffset", "view", "keyCode", "charCode", "screenX", "screenY", "clientX", "clientY", "layerX", "layerY", "pageX", "pageY", "detail", "button", "which", "ctrlKey", "shiftKey", "altKey", "metaKey", "eventPhase", "timeStamp", "bubbles", "cancelable", "cancelBubble", "isTrusted", "isChar", "getPreventDefault", "initEvent", "initMouseEvent", "initKeyEvent", "initUIEvent", "preventBubble", "preventCapture", "preventDefault", "stopPropagation" ]; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.domConstantMap = { "ELEMENT_NODE": 1, "ATTRIBUTE_NODE": 1, "TEXT_NODE": 1, "CDATA_SECTION_NODE": 1, "ENTITY_REFERENCE_NODE": 1, "ENTITY_NODE": 1, "PROCESSING_INSTRUCTION_NODE": 1, "COMMENT_NODE": 1, "DOCUMENT_NODE": 1, "DOCUMENT_TYPE_NODE": 1, "DOCUMENT_FRAGMENT_NODE": 1, "NOTATION_NODE": 1, "DOCUMENT_POSITION_DISCONNECTED": 1, "DOCUMENT_POSITION_PRECEDING": 1, "DOCUMENT_POSITION_FOLLOWING": 1, "DOCUMENT_POSITION_CONTAINS": 1, "DOCUMENT_POSITION_CONTAINED_BY": 1, "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC": 1, "UNKNOWN_RULE": 1, "STYLE_RULE": 1, "CHARSET_RULE": 1, "IMPORT_RULE": 1, "MEDIA_RULE": 1, "FONT_FACE_RULE": 1, "PAGE_RULE": 1, "CAPTURING_PHASE": 1, "AT_TARGET": 1, "BUBBLING_PHASE": 1, "SCROLL_PAGE_UP": 1, "SCROLL_PAGE_DOWN": 1, "MOUSEUP": 1, "MOUSEDOWN": 1, "MOUSEOVER": 1, "MOUSEOUT": 1, "MOUSEMOVE": 1, "MOUSEDRAG": 1, "CLICK": 1, "DBLCLICK": 1, "KEYDOWN": 1, "KEYUP": 1, "KEYPRESS": 1, "DRAGDROP": 1, "FOCUS": 1, "BLUR": 1, "SELECT": 1, "CHANGE": 1, "RESET": 1, "SUBMIT": 1, "SCROLL": 1, "LOAD": 1, "UNLOAD": 1, "XFER_DONE": 1, "ABORT": 1, "ERROR": 1, "LOCATE": 1, "MOVE": 1, "RESIZE": 1, "FORWARD": 1, "HELP": 1, "BACK": 1, "TEXT": 1, "ALT_MASK": 1, "CONTROL_MASK": 1, "SHIFT_MASK": 1, "META_MASK": 1, "DOM_VK_TAB": 1, "DOM_VK_PAGE_UP": 1, "DOM_VK_PAGE_DOWN": 1, "DOM_VK_UP": 1, "DOM_VK_DOWN": 1, "DOM_VK_LEFT": 1, "DOM_VK_RIGHT": 1, "DOM_VK_CANCEL": 1, "DOM_VK_HELP": 1, "DOM_VK_BACK_SPACE": 1, "DOM_VK_CLEAR": 1, "DOM_VK_RETURN": 1, "DOM_VK_ENTER": 1, "DOM_VK_SHIFT": 1, "DOM_VK_CONTROL": 1, "DOM_VK_ALT": 1, "DOM_VK_PAUSE": 1, "DOM_VK_CAPS_LOCK": 1, "DOM_VK_ESCAPE": 1, "DOM_VK_SPACE": 1, "DOM_VK_END": 1, "DOM_VK_HOME": 1, "DOM_VK_PRINTSCREEN": 1, "DOM_VK_INSERT": 1, "DOM_VK_DELETE": 1, "DOM_VK_0": 1, "DOM_VK_1": 1, "DOM_VK_2": 1, "DOM_VK_3": 1, "DOM_VK_4": 1, "DOM_VK_5": 1, "DOM_VK_6": 1, "DOM_VK_7": 1, "DOM_VK_8": 1, "DOM_VK_9": 1, "DOM_VK_SEMICOLON": 1, "DOM_VK_EQUALS": 1, "DOM_VK_A": 1, "DOM_VK_B": 1, "DOM_VK_C": 1, "DOM_VK_D": 1, "DOM_VK_E": 1, "DOM_VK_F": 1, "DOM_VK_G": 1, "DOM_VK_H": 1, "DOM_VK_I": 1, "DOM_VK_J": 1, "DOM_VK_K": 1, "DOM_VK_L": 1, "DOM_VK_M": 1, "DOM_VK_N": 1, "DOM_VK_O": 1, "DOM_VK_P": 1, "DOM_VK_Q": 1, "DOM_VK_R": 1, "DOM_VK_S": 1, "DOM_VK_T": 1, "DOM_VK_U": 1, "DOM_VK_V": 1, "DOM_VK_W": 1, "DOM_VK_X": 1, "DOM_VK_Y": 1, "DOM_VK_Z": 1, "DOM_VK_CONTEXT_MENU": 1, "DOM_VK_NUMPAD0": 1, "DOM_VK_NUMPAD1": 1, "DOM_VK_NUMPAD2": 1, "DOM_VK_NUMPAD3": 1, "DOM_VK_NUMPAD4": 1, "DOM_VK_NUMPAD5": 1, "DOM_VK_NUMPAD6": 1, "DOM_VK_NUMPAD7": 1, "DOM_VK_NUMPAD8": 1, "DOM_VK_NUMPAD9": 1, "DOM_VK_MULTIPLY": 1, "DOM_VK_ADD": 1, "DOM_VK_SEPARATOR": 1, "DOM_VK_SUBTRACT": 1, "DOM_VK_DECIMAL": 1, "DOM_VK_DIVIDE": 1, "DOM_VK_F1": 1, "DOM_VK_F2": 1, "DOM_VK_F3": 1, "DOM_VK_F4": 1, "DOM_VK_F5": 1, "DOM_VK_F6": 1, "DOM_VK_F7": 1, "DOM_VK_F8": 1, "DOM_VK_F9": 1, "DOM_VK_F10": 1, "DOM_VK_F11": 1, "DOM_VK_F12": 1, "DOM_VK_F13": 1, "DOM_VK_F14": 1, "DOM_VK_F15": 1, "DOM_VK_F16": 1, "DOM_VK_F17": 1, "DOM_VK_F18": 1, "DOM_VK_F19": 1, "DOM_VK_F20": 1, "DOM_VK_F21": 1, "DOM_VK_F22": 1, "DOM_VK_F23": 1, "DOM_VK_F24": 1, "DOM_VK_NUM_LOCK": 1, "DOM_VK_SCROLL_LOCK": 1, "DOM_VK_COMMA": 1, "DOM_VK_PERIOD": 1, "DOM_VK_SLASH": 1, "DOM_VK_BACK_QUOTE": 1, "DOM_VK_OPEN_BRACKET": 1, "DOM_VK_BACK_SLASH": 1, "DOM_VK_CLOSE_BRACKET": 1, "DOM_VK_QUOTE": 1, "DOM_VK_META": 1, "SVG_ZOOMANDPAN_DISABLE": 1, "SVG_ZOOMANDPAN_MAGNIFY": 1, "SVG_ZOOMANDPAN_UNKNOWN": 1 }; this.cssInfo = { "background": ["bgRepeat", "bgAttachment", "bgPosition", "color", "systemColor", "none"], "background-attachment": ["bgAttachment"], "background-color": ["color", "systemColor"], "background-image": ["none"], "background-position": ["bgPosition"], "background-repeat": ["bgRepeat"], "border": ["borderStyle", "thickness", "color", "systemColor", "none"], "border-top": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-right": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-bottom": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-left": ["borderStyle", "borderCollapse", "color", "systemColor", "none"], "border-collapse": ["borderCollapse"], "border-color": ["color", "systemColor"], "border-top-color": ["color", "systemColor"], "border-right-color": ["color", "systemColor"], "border-bottom-color": ["color", "systemColor"], "border-left-color": ["color", "systemColor"], "border-spacing": [], "border-style": ["borderStyle"], "border-top-style": ["borderStyle"], "border-right-style": ["borderStyle"], "border-bottom-style": ["borderStyle"], "border-left-style": ["borderStyle"], "border-width": ["thickness"], "border-top-width": ["thickness"], "border-right-width": ["thickness"], "border-bottom-width": ["thickness"], "border-left-width": ["thickness"], "bottom": ["auto"], "caption-side": ["captionSide"], "clear": ["clear", "none"], "clip": ["auto"], "color": ["color", "systemColor"], "content": ["content"], "counter-increment": ["none"], "counter-reset": ["none"], "cursor": ["cursor", "none"], "direction": ["direction"], "display": ["display", "none"], "empty-cells": [], "float": ["float", "none"], "font": ["fontStyle", "fontVariant", "fontWeight", "fontFamily"], "font-family": ["fontFamily"], "font-size": ["fontSize"], "font-size-adjust": [], "font-stretch": [], "font-style": ["fontStyle"], "font-variant": ["fontVariant"], "font-weight": ["fontWeight"], "height": ["auto"], "left": ["auto"], "letter-spacing": [], "line-height": [], "list-style": ["listStyleType", "listStylePosition", "none"], "list-style-image": ["none"], "list-style-position": ["listStylePosition"], "list-style-type": ["listStyleType", "none"], "margin": [], "margin-top": [], "margin-right": [], "margin-bottom": [], "margin-left": [], "marker-offset": ["auto"], "min-height": ["none"], "max-height": ["none"], "min-width": ["none"], "max-width": ["none"], "outline": ["borderStyle", "color", "systemColor", "none"], "outline-color": ["color", "systemColor"], "outline-style": ["borderStyle"], "outline-width": [], "overflow": ["overflow", "auto"], "overflow-x": ["overflow", "auto"], "overflow-y": ["overflow", "auto"], "padding": [], "padding-top": [], "padding-right": [], "padding-bottom": [], "padding-left": [], "position": ["position"], "quotes": ["none"], "right": ["auto"], "table-layout": ["tableLayout", "auto"], "text-align": ["textAlign"], "text-decoration": ["textDecoration", "none"], "text-indent": [], "text-shadow": [], "text-transform": ["textTransform", "none"], "top": ["auto"], "unicode-bidi": [], "vertical-align": ["verticalAlign"], "white-space": ["whiteSpace"], "width": ["auto"], "word-spacing": [], "z-index": [], "-moz-appearance": ["mozAppearance"], "-moz-border-radius": [], "-moz-border-radius-bottomleft": [], "-moz-border-radius-bottomright": [], "-moz-border-radius-topleft": [], "-moz-border-radius-topright": [], "-moz-border-top-colors": ["color", "systemColor"], "-moz-border-right-colors": ["color", "systemColor"], "-moz-border-bottom-colors": ["color", "systemColor"], "-moz-border-left-colors": ["color", "systemColor"], "-moz-box-align": ["mozBoxAlign"], "-moz-box-direction": ["mozBoxDirection"], "-moz-box-flex": [], "-moz-box-ordinal-group": [], "-moz-box-orient": ["mozBoxOrient"], "-moz-box-pack": ["mozBoxPack"], "-moz-box-sizing": ["mozBoxSizing"], "-moz-opacity": [], "-moz-user-focus": ["userFocus", "none"], "-moz-user-input": ["userInput"], "-moz-user-modify": [], "-moz-user-select": ["userSelect", "none"], "-moz-background-clip": [], "-moz-background-inline-policy": [], "-moz-background-origin": [], "-moz-binding": [], "-moz-column-count": [], "-moz-column-gap": [], "-moz-column-width": [], "-moz-image-region": [] }; this.inheritedStyleNames = { "border-collapse": 1, "border-spacing": 1, "border-style": 1, "caption-side": 1, "color": 1, "cursor": 1, "direction": 1, "empty-cells": 1, "font": 1, "font-family": 1, "font-size-adjust": 1, "font-size": 1, "font-style": 1, "font-variant": 1, "font-weight": 1, "letter-spacing": 1, "line-height": 1, "list-style": 1, "list-style-image": 1, "list-style-position": 1, "list-style-type": 1, "quotes": 1, "text-align": 1, "text-decoration": 1, "text-indent": 1, "text-shadow": 1, "text-transform": 1, "white-space": 1, "word-spacing": 1 }; this.cssKeywords = { "appearance": [ "button", "button-small", "checkbox", "checkbox-container", "checkbox-small", "dialog", "listbox", "menuitem", "menulist", "menulist-button", "menulist-textfield", "menupopup", "progressbar", "radio", "radio-container", "radio-small", "resizer", "scrollbar", "scrollbarbutton-down", "scrollbarbutton-left", "scrollbarbutton-right", "scrollbarbutton-up", "scrollbartrack-horizontal", "scrollbartrack-vertical", "separator", "statusbar", "tab", "tab-left-edge", "tabpanels", "textfield", "toolbar", "toolbarbutton", "toolbox", "tooltip", "treeheadercell", "treeheadersortarrow", "treeitem", "treetwisty", "treetwistyopen", "treeview", "window" ], "systemColor": [ "ActiveBorder", "ActiveCaption", "AppWorkspace", "Background", "ButtonFace", "ButtonHighlight", "ButtonShadow", "ButtonText", "CaptionText", "GrayText", "Highlight", "HighlightText", "InactiveBorder", "InactiveCaption", "InactiveCaptionText", "InfoBackground", "InfoText", "Menu", "MenuText", "Scrollbar", "ThreeDDarkShadow", "ThreeDFace", "ThreeDHighlight", "ThreeDLightShadow", "ThreeDShadow", "Window", "WindowFrame", "WindowText", "-moz-field", "-moz-fieldtext", "-moz-workspace", "-moz-visitedhyperlinktext", "-moz-use-text-color" ], "color": [ "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DarkSkyBlue", "DimGray", "DodgerBlue", "Feldspar", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "VioletRed", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen", "transparent", "invert" ], "auto": [ "auto" ], "none": [ "none" ], "captionSide": [ "top", "bottom", "left", "right" ], "clear": [ "left", "right", "both" ], "cursor": [ "auto", "cell", "context-menu", "crosshair", "default", "help", "pointer", "progress", "move", "e-resize", "all-scroll", "ne-resize", "nw-resize", "n-resize", "se-resize", "sw-resize", "s-resize", "w-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize", "col-resize", "row-resize", "text", "vertical-text", "wait", "alias", "copy", "move", "no-drop", "not-allowed", "-moz-alias", "-moz-cell", "-moz-copy", "-moz-grab", "-moz-grabbing", "-moz-contextmenu", "-moz-zoom-in", "-moz-zoom-out", "-moz-spinning" ], "direction": [ "ltr", "rtl" ], "bgAttachment": [ "scroll", "fixed" ], "bgPosition": [ "top", "center", "bottom", "left", "right" ], "bgRepeat": [ "repeat", "repeat-x", "repeat-y", "no-repeat" ], "borderStyle": [ "hidden", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset", "-moz-bg-inset", "-moz-bg-outset", "-moz-bg-solid" ], "borderCollapse": [ "collapse", "separate" ], "overflow": [ "visible", "hidden", "scroll", "-moz-scrollbars-horizontal", "-moz-scrollbars-none", "-moz-scrollbars-vertical" ], "listStyleType": [ "disc", "circle", "square", "decimal", "decimal-leading-zero", "lower-roman", "upper-roman", "lower-greek", "lower-alpha", "lower-latin", "upper-alpha", "upper-latin", "hebrew", "armenian", "georgian", "cjk-ideographic", "hiragana", "katakana", "hiragana-iroha", "katakana-iroha", "inherit" ], "listStylePosition": [ "inside", "outside" ], "content": [ "open-quote", "close-quote", "no-open-quote", "no-close-quote", "inherit" ], "fontStyle": [ "normal", "italic", "oblique", "inherit" ], "fontVariant": [ "normal", "small-caps", "inherit" ], "fontWeight": [ "normal", "bold", "bolder", "lighter", "inherit" ], "fontSize": [ "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large", "smaller", "larger" ], "fontFamily": [ "Arial", "Comic Sans MS", "Georgia", "Tahoma", "Verdana", "Times New Roman", "Trebuchet MS", "Lucida Grande", "Helvetica", "serif", "sans-serif", "cursive", "fantasy", "monospace", "caption", "icon", "menu", "message-box", "small-caption", "status-bar", "inherit" ], "display": [ "block", "inline", "inline-block", "list-item", "marker", "run-in", "compact", "table", "inline-table", "table-row-group", "table-column", "table-column-group", "table-header-group", "table-footer-group", "table-row", "table-cell", "table-caption", "-moz-box", "-moz-compact", "-moz-deck", "-moz-grid", "-moz-grid-group", "-moz-grid-line", "-moz-groupbox", "-moz-inline-block", "-moz-inline-box", "-moz-inline-grid", "-moz-inline-stack", "-moz-inline-table", "-moz-marker", "-moz-popup", "-moz-runin", "-moz-stack" ], "position": [ "static", "relative", "absolute", "fixed", "inherit" ], "float": [ "left", "right" ], "textAlign": [ "left", "right", "center", "justify" ], "tableLayout": [ "fixed" ], "textDecoration": [ "underline", "overline", "line-through", "blink" ], "textTransform": [ "capitalize", "lowercase", "uppercase", "inherit" ], "unicodeBidi": [ "normal", "embed", "bidi-override" ], "whiteSpace": [ "normal", "pre", "nowrap" ], "verticalAlign": [ "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom", "inherit" ], "thickness": [ "thin", "medium", "thick" ], "userFocus": [ "ignore", "normal" ], "userInput": [ "disabled", "enabled" ], "userSelect": [ "normal" ], "mozBoxSizing": [ "content-box", "padding-box", "border-box" ], "mozBoxAlign": [ "start", "center", "end", "baseline", "stretch" ], "mozBoxDirection": [ "normal", "reverse" ], "mozBoxOrient": [ "horizontal", "vertical" ], "mozBoxPack": [ "start", "center", "end" ] }; this.nonEditableTags = { "HTML": 1, "HEAD": 1, "html": 1, "head": 1 }; this.innerEditableTags = { "BODY": 1, "body": 1 }; this.selfClosingTags = { // End tags for void elements are forbidden http://wiki.whatwg.org/wiki/HTML_vs._XHTML "meta": 1, "link": 1, "area": 1, "base": 1, "col": 1, "input": 1, "img": 1, "br": 1, "hr": 1, "param":1, "embed":1 }; var invisibleTags = this.invisibleTags = { "HTML": 1, "HEAD": 1, "TITLE": 1, "META": 1, "LINK": 1, "STYLE": 1, "SCRIPT": 1, "NOSCRIPT": 1, "BR": 1, "PARAM": 1, "COL": 1, "html": 1, "head": 1, "title": 1, "meta": 1, "link": 1, "style": 1, "script": 1, "noscript": 1, "br": 1, "param": 1, "col": 1 /* "window": 1, "browser": 1, "frame": 1, "tabbrowser": 1, "WINDOW": 1, "BROWSER": 1, "FRAME": 1, "TABBROWSER": 1, */ }; if (typeof KeyEvent == "undefined") { this.KeyEvent = { DOM_VK_CANCEL: 3, DOM_VK_HELP: 6, DOM_VK_BACK_SPACE: 8, DOM_VK_TAB: 9, DOM_VK_CLEAR: 12, DOM_VK_RETURN: 13, DOM_VK_ENTER: 14, DOM_VK_SHIFT: 16, DOM_VK_CONTROL: 17, DOM_VK_ALT: 18, DOM_VK_PAUSE: 19, DOM_VK_CAPS_LOCK: 20, DOM_VK_ESCAPE: 27, DOM_VK_SPACE: 32, DOM_VK_PAGE_UP: 33, DOM_VK_PAGE_DOWN: 34, DOM_VK_END: 35, DOM_VK_HOME: 36, DOM_VK_LEFT: 37, DOM_VK_UP: 38, DOM_VK_RIGHT: 39, DOM_VK_DOWN: 40, DOM_VK_PRINTSCREEN: 44, DOM_VK_INSERT: 45, DOM_VK_DELETE: 46, DOM_VK_0: 48, DOM_VK_1: 49, DOM_VK_2: 50, DOM_VK_3: 51, DOM_VK_4: 52, DOM_VK_5: 53, DOM_VK_6: 54, DOM_VK_7: 55, DOM_VK_8: 56, DOM_VK_9: 57, DOM_VK_SEMICOLON: 59, DOM_VK_EQUALS: 61, DOM_VK_A: 65, DOM_VK_B: 66, DOM_VK_C: 67, DOM_VK_D: 68, DOM_VK_E: 69, DOM_VK_F: 70, DOM_VK_G: 71, DOM_VK_H: 72, DOM_VK_I: 73, DOM_VK_J: 74, DOM_VK_K: 75, DOM_VK_L: 76, DOM_VK_M: 77, DOM_VK_N: 78, DOM_VK_O: 79, DOM_VK_P: 80, DOM_VK_Q: 81, DOM_VK_R: 82, DOM_VK_S: 83, DOM_VK_T: 84, DOM_VK_U: 85, DOM_VK_V: 86, DOM_VK_W: 87, DOM_VK_X: 88, DOM_VK_Y: 89, DOM_VK_Z: 90, DOM_VK_CONTEXT_MENU: 93, DOM_VK_NUMPAD0: 96, DOM_VK_NUMPAD1: 97, DOM_VK_NUMPAD2: 98, DOM_VK_NUMPAD3: 99, DOM_VK_NUMPAD4: 100, DOM_VK_NUMPAD5: 101, DOM_VK_NUMPAD6: 102, DOM_VK_NUMPAD7: 103, DOM_VK_NUMPAD8: 104, DOM_VK_NUMPAD9: 105, DOM_VK_MULTIPLY: 106, DOM_VK_ADD: 107, DOM_VK_SEPARATOR: 108, DOM_VK_SUBTRACT: 109, DOM_VK_DECIMAL: 110, DOM_VK_DIVIDE: 111, DOM_VK_F1: 112, DOM_VK_F2: 113, DOM_VK_F3: 114, DOM_VK_F4: 115, DOM_VK_F5: 116, DOM_VK_F6: 117, DOM_VK_F7: 118, DOM_VK_F8: 119, DOM_VK_F9: 120, DOM_VK_F10: 121, DOM_VK_F11: 122, DOM_VK_F12: 123, DOM_VK_F13: 124, DOM_VK_F14: 125, DOM_VK_F15: 126, DOM_VK_F16: 127, DOM_VK_F17: 128, DOM_VK_F18: 129, DOM_VK_F19: 130, DOM_VK_F20: 131, DOM_VK_F21: 132, DOM_VK_F22: 133, DOM_VK_F23: 134, DOM_VK_F24: 135, DOM_VK_NUM_LOCK: 144, DOM_VK_SCROLL_LOCK: 145, DOM_VK_COMMA: 188, DOM_VK_PERIOD: 190, DOM_VK_SLASH: 191, DOM_VK_BACK_QUOTE: 192, DOM_VK_OPEN_BRACKET: 219, DOM_VK_BACK_SLASH: 220, DOM_VK_CLOSE_BRACKET: 221, DOM_VK_QUOTE: 222, DOM_VK_META: 224 }; } // ************************************************************************************************ // Ajax /** * @namespace */ this.Ajax = { requests: [], transport: null, states: ["Uninitialized","Loading","Loaded","Interactive","Complete"], initialize: function() { this.transport = FBL.getNativeXHRObject(); }, getXHRObject: function() { var xhrObj = false; try { xhrObj = new XMLHttpRequest(); } catch(e) { var progid = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ]; for ( var i=0; i < progid.length; ++i ) { try { xhrObj = new ActiveXObject(progid[i]); } catch(e) { continue; } break; } } finally { return xhrObj; } }, /** * Create a AJAX request. * * @name request * @param {Object} options request options * @param {String} options.url URL to be requested * @param {String} options.type Request type ("get" ou "post"). Default is "get". * @param {Boolean} options.async Asynchronous flag. Default is "true". * @param {String} options.dataType Data type ("text", "html", "xml" or "json"). Default is "text". * @param {String} options.contentType Content-type of the data being sent. Default is "application/x-www-form-urlencoded". * @param {Function} options.onLoading onLoading callback * @param {Function} options.onLoaded onLoaded callback * @param {Function} options.onInteractive onInteractive callback * @param {Function} options.onComplete onComplete callback * @param {Function} options.onUpdate onUpdate callback * @param {Function} options.onSuccess onSuccess callback * @param {Function} options.onFailure onFailure callback */ request: function(options) { // process options var o = FBL.extend( { // default values type: "get", async: true, dataType: "text", contentType: "application/x-www-form-urlencoded" }, options || {} ); this.requests.push(o); var s = this.getState(); if (s == "Uninitialized" || s == "Complete" || s == "Loaded") this.sendRequest(); }, serialize: function(data) { var r = [""], rl = 0; if (data) { if (typeof data == "string") r[rl++] = data; else if (data.innerHTML && data.elements) { for (var i=0,el,l=(el=data.elements).length; i < l; i++) if (el[i].name) { r[rl++] = encodeURIComponent(el[i].name); r[rl++] = "="; r[rl++] = encodeURIComponent(el[i].value); r[rl++] = "&"; } } else for(var param in data) { r[rl++] = encodeURIComponent(param); r[rl++] = "="; r[rl++] = encodeURIComponent(data[param]); r[rl++] = "&"; } } return r.join("").replace(/&$/, ""); }, sendRequest: function() { var t = FBL.Ajax.transport, r = FBL.Ajax.requests.shift(), data; // open XHR object t.open(r.type, r.url, r.async); //setRequestHeaders(); // indicates that it is a XHR request to the server t.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // if data is being sent, sets the appropriate content-type if (data = FBL.Ajax.serialize(r.data)) t.setRequestHeader("Content-Type", r.contentType); /** @ignore */ // onreadystatechange handler t.onreadystatechange = function() { FBL.Ajax.onStateChange(r); }; // send the request t.send(data); }, /** * Handles the state change */ onStateChange: function(options) { var fn, o = options, t = this.transport; var state = this.getState(t); if (fn = o["on" + state]) fn(this.getResponse(o), o); if (state == "Complete") { var success = t.status == 200, response = this.getResponse(o); if (fn = o["onUpdate"]) fn(response, o); if (fn = o["on" + (success ? "Success" : "Failure")]) fn(response, o); t.onreadystatechange = FBL.emptyFn; if (this.requests.length > 0) setTimeout(this.sendRequest, 10); } }, /** * gets the appropriate response value according the type */ getResponse: function(options) { var t = this.transport, type = options.dataType; if (t.status != 200) return t.statusText; else if (type == "text") return t.responseText; else if (type == "html") return t.responseText; else if (type == "xml") return t.responseXML; else if (type == "json") return eval("(" + t.responseText + ")"); }, /** * returns the current state of the XHR object */ getState: function() { return this.states[this.transport.readyState]; } }; // ************************************************************************************************ // Cookie, from http://www.quirksmode.org/js/cookies.html this.createCookie = function(name,value,days) { if ('cookie' in document) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } }; this.readCookie = function (name) { if ('cookie' in document) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } } return null; }; this.removeCookie = function(name) { this.createCookie(name, "", -1); }; // ************************************************************************************************ // http://www.mister-pixel.com/#Content__state=is_that_simple var fixIE6BackgroundImageCache = function(doc) { doc = doc || document; try { doc.execCommand("BackgroundImageCache", false, true); } catch(E) { } }; // ************************************************************************************************ // calculatePixelsPerInch var resetStyle = "margin:0; padding:0; border:0; position:absolute; overflow:hidden; display:block;"; var calculatePixelsPerInch = function calculatePixelsPerInch(doc, body) { var inch = FBL.createGlobalElement("div"); inch.style.cssText = resetStyle + "width:1in; height:1in; position:absolute; top:-1234px; left:-1234px;"; body.appendChild(inch); FBL.pixelsPerInch = { x: inch.offsetWidth, y: inch.offsetHeight }; body.removeChild(inch); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.SourceLink = function(url, line, type, object, instance) { this.href = url; this.instance = instance; this.line = line; this.type = type; this.object = object; }; this.SourceLink.prototype = { toString: function() { return this.href; }, toJSON: function() // until 3.1... { return "{\"href\":\""+this.href+"\", "+ (this.line?("\"line\":"+this.line+","):"")+ (this.type?(" \"type\":\""+this.type+"\","):"")+ "}"; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.SourceText = function(lines, owner) { this.lines = lines; this.owner = owner; }; this.SourceText.getLineAsHTML = function(lineNo) { return escapeForSourceLine(this.lines[lineNo-1]); }; // ************************************************************************************************ }).apply(FBL); /* See license.txt for terms of usage */ FBL.ns( /** @scope s_i18n */ function() { with (FBL) { // ************************************************************************************************ // TODO: xxxpedro localization var oSTR = { "NoMembersWarning": "There are no properties to show for this object.", "EmptyStyleSheet": "There are no rules in this stylesheet.", "EmptyElementCSS": "This element has no style rules.", "AccessRestricted": "Access to restricted URI denied.", "net.label.Parameters": "Parameters", "net.label.Source": "Source", "URLParameters": "Params", "EditStyle": "Edit Element Style...", "NewRule": "New Rule...", "NewProp": "New Property...", "EditProp": 'Edit "%s"', "DeleteProp": 'Delete "%s"', "DisableProp": 'Disable "%s"' }; // ************************************************************************************************ FBL.$STR = function(name) { return oSTR.hasOwnProperty(name) ? oSTR[name] : name; }; FBL.$STRF = function(name, args) { if (!oSTR.hasOwnProperty(name)) return name; var format = oSTR[name]; var objIndex = 0; var parts = parseFormat(format); var trialIndex = objIndex; var objects = args; for (var i= 0; i < parts.length; i++) { var part = parts[i]; if (part && typeof(part) == "object") { if (++trialIndex > objects.length) // then too few parameters for format, assume unformatted. { format = ""; objIndex = -1; parts.length = 0; break; } } } var result = []; for (var i = 0; i < parts.length; ++i) { var part = parts[i]; if (part && typeof(part) == "object") { result.push(""+args.shift()); } else result.push(part); } return result.join(""); }; // ************************************************************************************************ var parseFormat = function parseFormat(format) { var parts = []; if (format.length <= 0) return parts; var reg = /((^%|.%)(\d+)?(\.)([a-zA-Z]))|((^%|.%)([a-zA-Z]))/; for (var m = reg.exec(format); m; m = reg.exec(format)) { if (m[0].substr(0, 2) == "%%") { parts.push(format.substr(0, m.index)); parts.push(m[0].substr(1)); } else { var type = m[8] ? m[8] : m[5]; var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0); var rep = null; switch (type) { case "s": rep = FirebugReps.Text; break; case "f": case "i": case "d": rep = FirebugReps.Number; break; case "o": rep = null; break; } parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1)); parts.push({rep: rep, precision: precision, type: ("%" + type)}); } format = format.substr(m.index+m[0].length); } parts.push(format); return parts; }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /** @scope s_firebug */ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Internals var modules = []; var panelTypes = []; var panelTypeMap = {}; var reps = []; var parentPanelMap = {}; // ************************************************************************************************ // Firebug /** * @namespace describe Firebug * @exports FBL.Firebug as Firebug */ FBL.Firebug = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * version: "Firebug Lite 1.4.0", revision: "$Revision$", // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * modules: modules, panelTypes: panelTypes, panelTypeMap: panelTypeMap, reps: reps, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Initialization initialize: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.initialize", "initializing application"); Firebug.browser = new Context(Env.browser); Firebug.context = Firebug.browser; Firebug.loadPrefs(); Firebug.context.persistedState.isOpen = false; // Document must be cached before chrome initialization cacheDocument(); if (Firebug.Inspector && Firebug.Inspector.create) Firebug.Inspector.create(); if (FBL.CssAnalyzer && FBL.CssAnalyzer.processAllStyleSheets) FBL.CssAnalyzer.processAllStyleSheets(Firebug.browser.document); FirebugChrome.initialize(); dispatch(modules, "initialize", []); if (Firebug.disableResourceFetching) Firebug.Console.logFormatted(["Some Firebug Lite features are not working because " + "resource fetching is disabled. To enabled it set the Firebug Lite option " + "\"disableResourceFetching\" to \"false\". More info at " + "http://getfirebug.com/firebuglite#Options"], Firebug.context, "warn"); if (Env.onLoad) { var onLoad = Env.onLoad; delete Env.onLoad; setTimeout(onLoad, 200); } }, shutdown: function() { if (Firebug.saveCookies) Firebug.savePrefs(); if (Firebug.Inspector) Firebug.Inspector.destroy(); dispatch(modules, "shutdown", []); var chromeMap = FirebugChrome.chromeMap; for (var name in chromeMap) { if (chromeMap.hasOwnProperty(name)) { try { chromeMap[name].destroy(); } catch(E) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("chrome.destroy() failed to: " + name); } } } Firebug.Lite.Cache.Element.clear(); Firebug.Lite.Cache.StyleSheet.clear(); Firebug.browser = null; Firebug.context = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Registration registerModule: function() { modules.push.apply(modules, arguments); if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.registerModule"); }, registerPanel: function() { panelTypes.push.apply(panelTypes, arguments); for (var i = 0, panelType; panelType = arguments[i]; ++i) { panelTypeMap[panelType.prototype.name] = arguments[i]; if (panelType.prototype.parentPanel) parentPanelMap[panelType.prototype.parentPanel] = 1; } if (FBTrace.DBG_INITIALIZE) for (var i = 0; i < arguments.length; ++i) FBTrace.sysout("Firebug.registerPanel", arguments[i].prototype.name); }, registerRep: function() { reps.push.apply(reps, arguments); }, unregisterRep: function() { for (var i = 0; i < arguments.length; ++i) remove(reps, arguments[i]); }, setDefaultReps: function(funcRep, rep) { FBL.defaultRep = rep; FBL.defaultFuncRep = funcRep; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Reps getRep: function(object) { var type = typeof object; if (isIE && isFunction(object)) type = "function"; for (var i = 0; i < reps.length; ++i) { var rep = reps[i]; try { if (rep.supportsObject(object, type)) { if (FBTrace.DBG_DOM) FBTrace.sysout("getRep type: "+type+" object: "+object, rep); return rep; } } catch (exc) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("firebug.getRep FAILS: ", exc.message || exc); FBTrace.sysout("firebug.getRep reps["+i+"/"+reps.length+"]: Rep="+reps[i].className); // TODO: xxxpedro add trace to FBTrace logs like in Firebug //firebug.trace(); } } } return (type == 'function') ? defaultFuncRep : defaultRep; }, getRepObject: function(node) { var target = null; for (var child = node; child; child = child.parentNode) { if (hasClass(child, "repTarget")) target = child; if (child.repObject) { if (!target && hasClass(child, "repIgnore")) break; else return child.repObject; } } }, getRepNode: function(node) { for (var child = node; child; child = child.parentNode) { if (child.repObject) return child; } }, getElementByRepObject: function(element, object) { for (var child = element.firstChild; child; child = child.nextSibling) { if (child.repObject == object) return child; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Preferences getPref: function(name) { return Firebug[name]; }, setPref: function(name, value) { Firebug[name] = value; Firebug.savePrefs(); }, setPrefs: function(prefs) { for (var name in prefs) { if (prefs.hasOwnProperty(name)) Firebug[name] = prefs[name]; } Firebug.savePrefs(); }, restorePrefs: function() { var Options = Env.DefaultOptions; for (var name in Options) { Firebug[name] = Options[name]; } }, loadPrefs: function() { this.restorePrefs(); var prefs = Store.get("FirebugLite") || {}; var options = prefs.options; var persistedState = prefs.persistedState || FBL.defaultPersistedState; for (var name in options) { if (options.hasOwnProperty(name)) Firebug[name] = options[name]; } if (Firebug.context && persistedState) Firebug.context.persistedState = persistedState; }, savePrefs: function() { var prefs = { options: {} }; var EnvOptions = Env.Options; var options = prefs.options; for (var name in EnvOptions) { if (EnvOptions.hasOwnProperty(name)) { options[name] = Firebug[name]; } } var persistedState = Firebug.context.persistedState; if (!persistedState) { persistedState = Firebug.context.persistedState = FBL.defaultPersistedState; } prefs.persistedState = persistedState; Store.set("FirebugLite", prefs); }, erasePrefs: function() { Store.remove("FirebugLite"); this.restorePrefs(); } }; Firebug.restorePrefs(); // xxxpedro should we remove this? window.Firebug = FBL.Firebug; if (!Env.Options.enablePersistent || Env.Options.enablePersistent && Env.isChromeContext || Env.isDebugMode) Env.browser.window.Firebug = FBL.Firebug; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Other methods FBL.cacheDocument = function cacheDocument() { var ElementCache = Firebug.Lite.Cache.Element; var els = Firebug.browser.document.getElementsByTagName("*"); for (var i=0, l=els.length, el; i<l; i++) { el = els[i]; ElementCache(el); } }; // ************************************************************************************************ /** * @class * * Support for listeners registration. This object also extended by Firebug.Module so, * all modules supports listening automatically. Notice that array of listeners * is created for each intance of a module within initialize method. Thus all derived * module classes must ensure that Firebug.Module.initialize method is called for the * super class. */ Firebug.Listener = function() { // The array is created when the first listeners is added. // It can't be created here since derived objects would share // the same array. this.fbListeners = null; }; Firebug.Listener.prototype = { addListener: function(listener) { if (!this.fbListeners) this.fbListeners = []; // delay the creation until the objects are created so 'this' causes new array for each module this.fbListeners.push(listener); }, removeListener: function(listener) { remove(this.fbListeners, listener); // if this.fbListeners is null, remove is being called with no add } }; // ************************************************************************************************ // ************************************************************************************************ // Module /** * @module Base class for all modules. Every derived module object must be registered using * <code>Firebug.registerModule</code> method. There is always one instance of a module object * per browser window. * @extends Firebug.Listener */ Firebug.Module = extend(new Firebug.Listener(), /** @extend Firebug.Module */ { /** * Called when the window is opened. */ initialize: function() { }, /** * Called when the window is closed. */ shutdown: function() { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Called when a new context is created but before the page is loaded. */ initContext: function(context) { }, /** * Called after a context is detached to a separate window; */ reattachContext: function(browser, context) { }, /** * Called when a context is destroyed. Module may store info on persistedState for reloaded pages. */ destroyContext: function(context, persistedState) { }, // Called when a FF tab is create or activated (user changes FF tab) // Called after context is created or with context == null (to abort?) showContext: function(browser, context) { }, /** * Called after a context's page gets DOMContentLoaded */ loadedContext: function(context) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * showPanel: function(browser, panel) { }, showSidePanel: function(browser, panel) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateOption: function(name, value) { }, getObjectByURL: function(context, url) { } }); // ************************************************************************************************ // Panel /** * @panel Base class for all panels. Every derived panel must define a constructor and * register with "Firebug.registerPanel" method. An instance of the panel * object is created by the framework for each browser tab where Firebug is activated. */ Firebug.Panel = { name: "HelloWorld", title: "Hello World!", parentPanel: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * options: { hasCommandLine: false, hasStatusBar: false, hasToolButtons: false, // Pre-rendered panels are those included in the skin file (firebug.html) isPreRendered: false, innerHTMLSync: false /* // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // To be used by external extensions panelHTML: "", panelCSS: "", toolButtonsHTML: "" /**/ }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * tabNode: null, panelNode: null, sidePanelNode: null, statusBarNode: null, toolButtonsNode: null, panelBarNode: null, sidePanelBarBoxNode: null, sidePanelBarNode: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * sidePanelBar: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * searchable: false, editable: true, order: 2147483647, statusSeparator: "<", create: function(context, doc) { this.hasSidePanel = parentPanelMap.hasOwnProperty(this.name); this.panelBarNode = $("fbPanelBar1"); this.sidePanelBarBoxNode = $("fbPanelBar2"); if (this.hasSidePanel) { this.sidePanelBar = extend({}, PanelBar); this.sidePanelBar.create(this); } var options = this.options = extend(Firebug.Panel.options, this.options); var panelId = "fb" + this.name; if (options.isPreRendered) { this.panelNode = $(panelId); this.tabNode = $(panelId + "Tab"); this.tabNode.style.display = "block"; if (options.hasToolButtons) { this.toolButtonsNode = $(panelId + "Buttons"); } if (options.hasStatusBar) { this.statusBarBox = $("fbStatusBarBox"); this.statusBarNode = $(panelId + "StatusBar"); } } else { var containerSufix = this.parentPanel ? "2" : "1"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Create Panel var panelNode = this.panelNode = createElement("div", { id: panelId, className: "fbPanel" }); $("fbPanel" + containerSufix).appendChild(panelNode); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Create Panel Tab var tabHTML = '<span class="fbTabL"></span><span class="fbTabText">' + this.title + '</span><span class="fbTabR"></span>'; var tabNode = this.tabNode = createElement("a", { id: panelId + "Tab", className: "fbTab fbHover", innerHTML: tabHTML }); if (isIE6) { tabNode.href = "javascript:void(0)"; } var panelBarNode = this.parentPanel ? Firebug.chrome.getPanel(this.parentPanel).sidePanelBarNode : this.panelBarNode; panelBarNode.appendChild(tabNode); tabNode.style.display = "block"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create ToolButtons if (options.hasToolButtons) { this.toolButtonsNode = createElement("span", { id: panelId + "Buttons", className: "fbToolbarButtons" }); $("fbToolbarButtons").appendChild(this.toolButtonsNode); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create StatusBar if (options.hasStatusBar) { this.statusBarBox = $("fbStatusBarBox"); this.statusBarNode = createElement("span", { id: panelId + "StatusBar", className: "fbToolbarButtons fbStatusBar" }); this.statusBarBox.appendChild(this.statusBarNode); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create SidePanel } this.containerNode = this.panelNode.parentNode; if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.create", this.name); // xxxpedro contextMenu this.onContextMenu = bind(this.onContextMenu, this); /* this.context = context; this.document = doc; this.panelNode = doc.createElement("div"); this.panelNode.ownerPanel = this; setClass(this.panelNode, "panelNode panelNode-"+this.name+" contextUID="+context.uid); doc.body.appendChild(this.panelNode); if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("firebug.initialize panelNode for "+this.name+"\n"); this.initializeNode(this.panelNode); /**/ }, destroy: function(state) // Panel may store info on state { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.destroy", this.name); if (this.hasSidePanel) { this.sidePanelBar.destroy(); this.sidePanelBar = null; } this.options = null; this.name = null; this.parentPanel = null; this.tabNode = null; this.panelNode = null; this.containerNode = null; this.toolButtonsNode = null; this.statusBarBox = null; this.statusBarNode = null; //if (this.panelNode) // delete this.panelNode.ownerPanel; //this.destroyNode(); }, initialize: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.initialize", this.name); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (this.hasSidePanel) { this.sidePanelBar.initialize(); } var options = this.options = extend(Firebug.Panel.options, this.options); var panelId = "fb" + this.name; this.panelNode = $(panelId); this.tabNode = $(panelId + "Tab"); this.tabNode.style.display = "block"; if (options.hasStatusBar) { this.statusBarBox = $("fbStatusBarBox"); this.statusBarNode = $(panelId + "StatusBar"); } if (options.hasToolButtons) { this.toolButtonsNode = $(panelId + "Buttons"); } this.containerNode = this.panelNode.parentNode; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // restore persistent state this.containerNode.scrollTop = this.lastScrollTop; // xxxpedro contextMenu addEvent(this.containerNode, "contextmenu", this.onContextMenu); /// TODO: xxxpedro infoTip Hack Firebug.chrome.currentPanel = Firebug.chrome.selectedPanel && Firebug.chrome.selectedPanel.sidePanelBar ? Firebug.chrome.selectedPanel.sidePanelBar.selectedPanel : Firebug.chrome.selectedPanel; Firebug.showInfoTips = true; if (Firebug.InfoTip) Firebug.InfoTip.initializeBrowser(Firebug.chrome); }, shutdown: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.Panel.shutdown", this.name); /// TODO: xxxpedro infoTip Hack if (Firebug.InfoTip) Firebug.InfoTip.uninitializeBrowser(Firebug.chrome); if (Firebug.chrome.largeCommandLineVisible) Firebug.chrome.hideLargeCommandLine(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (this.hasSidePanel) { // TODO: xxxpedro firebug1.3a6 // new PanelBar mechanism will need to call shutdown to hide the panels (so it // doesn't appears in other panel's sidePanelBar. Therefore, we need to implement // a "remember selected panel" feature in the sidePanelBar //this.sidePanelBar.shutdown(); } // store persistent state this.lastScrollTop = this.containerNode.scrollTop; // xxxpedro contextMenu removeEvent(this.containerNode, "contextmenu", this.onContextMenu); }, detach: function(oldChrome, newChrome) { if (oldChrome && oldChrome.selectedPanel && oldChrome.selectedPanel.name == this.name) this.lastScrollTop = oldChrome.selectedPanel.containerNode.scrollTop; }, reattach: function(doc) { if (this.options.innerHTMLSync) this.synchronizeUI(); }, synchronizeUI: function() { this.containerNode.scrollTop = this.lastScrollTop || 0; }, show: function(state) { var options = this.options; if (options.hasStatusBar) { this.statusBarBox.style.display = "inline"; this.statusBarNode.style.display = "inline"; } if (options.hasToolButtons) { this.toolButtonsNode.style.display = "inline"; } this.panelNode.style.display = "block"; this.visible = true; if (!this.parentPanel) Firebug.chrome.layout(this); }, hide: function(state) { var options = this.options; if (options.hasStatusBar) { this.statusBarBox.style.display = "none"; this.statusBarNode.style.display = "none"; } if (options.hasToolButtons) { this.toolButtonsNode.style.display = "none"; } this.panelNode.style.display = "none"; this.visible = false; }, watchWindow: function(win) { }, unwatchWindow: function(win) { }, updateOption: function(name, value) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Toolbar helpers */ showToolbarButtons: function(buttonsId, show) { try { if (!this.context.browser) // XXXjjb this is bug. Somehow the panel context is not FirebugContext. { if (FBTrace.DBG_ERRORS) FBTrace.sysout("firebug.Panel showToolbarButtons this.context has no browser, this:", this); return; } var buttons = this.context.browser.chrome.$(buttonsId); if (buttons) collapse(buttons, show ? "false" : "true"); } catch (exc) { if (FBTrace.DBG_ERRORS) { FBTrace.dumpProperties("firebug.Panel showToolbarButtons FAILS", exc); if (!this.context.browser)FBTrace.dumpStack("firebug.Panel showToolbarButtons no browser"); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * Returns a number indicating the view's ability to inspect the object. * * Zero means not supported, and higher numbers indicate specificity. */ supportsObject: function(object) { return 0; }, hasObject: function(object) // beyond type testing, is this object selectable? { return false; }, select: function(object, forceUpdate) { if (!object) object = this.getDefaultSelection(this.context); if(FBTrace.DBG_PANELS) FBTrace.sysout("firebug.select "+this.name+" forceUpdate: "+forceUpdate+" "+object+((object==this.selection)?"==":"!=")+this.selection); if (forceUpdate || object != this.selection) { this.selection = object; this.updateSelection(object); // TODO: xxxpedro // XXXjoe This is kind of cheating, but, feh. //Firebug.chrome.onPanelSelect(object, this); //if (uiListeners.length > 0) // dispatch(uiListeners, "onPanelSelect", [object, this]); // TODO: make Firebug.chrome a uiListener } }, updateSelection: function(object) { }, markChange: function(skipSelf) { if (this.dependents) { if (skipSelf) { for (var i = 0; i < this.dependents.length; ++i) { var panelName = this.dependents[i]; if (panelName != this.name) this.context.invalidatePanels(panelName); } } else this.context.invalidatePanels.apply(this.context, this.dependents); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * startInspecting: function() { }, stopInspecting: function(object, cancelled) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * search: function(text, reverse) { }, /** * Retrieves the search options that this modules supports. * This is used by the search UI to present the proper options. */ getSearchOptionsMenuItems: function() { return [ Firebug.Search.searchOptionMenu("search.Case Sensitive", "searchCaseSensitive") ]; }, /** * Navigates to the next document whose match parameter returns true. */ navigateToNextDocument: function(match, reverse) { // This is an approximation of the UI that is displayed by the location // selector. This should be close enough, although it may be better // to simply generate the sorted list within the module, rather than // sorting within the UI. var self = this; function compare(a, b) { var locA = self.getObjectDescription(a); var locB = self.getObjectDescription(b); if(locA.path > locB.path) return 1; if(locA.path < locB.path) return -1; if(locA.name > locB.name) return 1; if(locA.name < locB.name) return -1; return 0; } var allLocs = this.getLocationList().sort(compare); for (var curPos = 0; curPos < allLocs.length && allLocs[curPos] != this.location; curPos++); function transformIndex(index) { if (reverse) { // For the reverse case we need to implement wrap around. var intermediate = curPos - index - 1; return (intermediate < 0 ? allLocs.length : 0) + intermediate; } else { return (curPos + index + 1) % allLocs.length; } }; for (var next = 0; next < allLocs.length - 1; next++) { var object = allLocs[transformIndex(next)]; if (match(object)) { this.navigate(object); return object; } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Called when "Options" clicked. Return array of // {label: 'name', nol10n: true, type: "checkbox", checked: <value>, command:function to set <value>} getOptionsMenuItems: function() { return null; }, /* * Called by chrome.onContextMenu to build the context menu when this panel has focus. * See also FirebugRep for a similar function also called by onContextMenu * Extensions may monkey patch and chain off this call * @param object: the 'realObject', a model value, eg a DOM property * @param target: the HTML element clicked on. * @return an array of menu items. */ getContextMenuItems: function(object, target) { return []; }, getBreakOnMenuItems: function() { return []; }, getEditor: function(target, value) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getDefaultSelection: function() { return null; }, browseObject: function(object) { }, getPopupObject: function(target) { return Firebug.getRepObject(target); }, getTooltipObject: function(target) { return Firebug.getRepObject(target); }, showInfoTip: function(infoTip, x, y) { }, getObjectPath: function(object) { return null; }, // An array of objects that can be passed to getObjectLocation. // The list of things a panel can show, eg sourceFiles. // Only shown if panel.location defined and supportsObject true getLocationList: function() { return null; }, getDefaultLocation: function() { return null; }, getObjectLocation: function(object) { return ""; }, // Text for the location list menu eg script panel source file list // return.path: group/category label, return.name: item label getObjectDescription: function(object) { var url = this.getObjectLocation(object); return FBL.splitURLBase(url); }, /* * UI signal that a tab needs attention, eg Script panel is currently stopped on a breakpoint * @param: show boolean, true turns on. */ highlight: function(show) { var tab = this.getTab(); if (!tab) return; if (show) tab.setAttribute("highlight", "true"); else tab.removeAttribute("highlight"); }, getTab: function() { var chrome = Firebug.chrome; var tab = chrome.$("fbPanelBar2").getTab(this.name); if (!tab) tab = chrome.$("fbPanelBar1").getTab(this.name); return tab; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Support for Break On Next /** * Called by the framework when the user clicks on the Break On Next button. * @param {Boolean} armed Set to true if the Break On Next feature is * to be armed for action and set to false if the Break On Next should be disarmed. * If 'armed' is true, then the next call to shouldBreakOnNext should be |true|. */ breakOnNext: function(armed) { }, /** * Called when a panel is selected/displayed. The method should return true * if the Break On Next feature is currently armed for this panel. */ shouldBreakOnNext: function() { return false; }, /** * Returns labels for Break On Next tooltip (one for enabled and one for disabled state). * @param {Boolean} enabled Set to true if the Break On Next feature is * currently activated for this panel. */ getBreakOnNextTooltip: function(enabled) { return null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // xxxpedro contextMenu onContextMenu: function(event) { if (!this.getContextMenuItems) return; cancelEvent(event, true); var target = event.target || event.srcElement; var menu = this.getContextMenuItems(this.selection, target); if (!menu) return; var contextMenu = new Menu( { id: "fbPanelContextMenu", items: menu }); contextMenu.show(event.clientX, event.clientY); return true; /* // TODO: xxxpedro move code to somewhere. code to get cross-browser // window to screen coordinates var box = Firebug.browser.getElementPosition(Firebug.chrome.node); var screenY = 0; // Firefox if (typeof window.mozInnerScreenY != "undefined") { screenY = window.mozInnerScreenY; } // Chrome else if (typeof window.innerHeight != "undefined") { screenY = window.outerHeight - window.innerHeight; } // IE else if (typeof window.screenTop != "undefined") { screenY = window.screenTop; } contextMenu.show(event.screenX-box.left, event.screenY-screenY-box.top); /**/ } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * MeasureBox * To get pixels size.width and size.height: * <ul><li> this.startMeasuring(view); </li> * <li> var size = this.measureText(lineNoCharsSpacer); </li> * <li> this.stopMeasuring(); </li> * </ul> * * @namespace */ Firebug.MeasureBox = { startMeasuring: function(target) { if (!this.measureBox) { this.measureBox = target.ownerDocument.createElement("span"); this.measureBox.className = "measureBox"; } copyTextStyles(target, this.measureBox); target.ownerDocument.body.appendChild(this.measureBox); }, getMeasuringElement: function() { return this.measureBox; }, measureText: function(value) { this.measureBox.innerHTML = value ? escapeForSourceLine(value) : "m"; return {width: this.measureBox.offsetWidth, height: this.measureBox.offsetHeight-1}; }, measureInputText: function(value) { value = value ? escapeForTextNode(value) : "m"; if (!Firebug.showTextNodesWithWhitespace) value = value.replace(/\t/g,'mmmmmm').replace(/\ /g,'m'); this.measureBox.innerHTML = value; return {width: this.measureBox.offsetWidth, height: this.measureBox.offsetHeight-1}; }, getBox: function(target) { var style = this.measureBox.ownerDocument.defaultView.getComputedStyle(this.measureBox, ""); var box = getBoxFromStyles(style, this.measureBox); return box; }, stopMeasuring: function() { this.measureBox.parentNode.removeChild(this.measureBox); } }; // ************************************************************************************************ if (FBL.domplate) Firebug.Rep = domplate( { className: "", inspectable: true, supportsObject: function(object, type) { return false; }, inspectObject: function(object, context) { Firebug.chrome.select(object); }, browseObject: function(object, context) { }, persistObject: function(object, context) { }, getRealObject: function(object, context) { return object; }, getTitle: function(object) { var label = safeToString(object); var re = /\[object (.*?)\]/; var m = re.exec(label); ///return m ? m[1] : label; // if the label is in the "[object TYPE]" format return its type if (m) { return m[1]; } // if it is IE we need to handle some special cases else if ( // safeToString() fails to recognize some objects in IE isIE && // safeToString() returns "[object]" for some objects like window.Image (label == "[object]" || // safeToString() returns undefined for some objects like window.clientInformation typeof object == "object" && typeof label == "undefined") ) { return "Object"; } else { return label; } }, getTooltip: function(object) { return null; }, getContextMenuItems: function(object, target, context) { return []; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Convenience for domplates STR: function(name) { return $STR(name); }, cropString: function(text) { return cropString(text); }, cropMultipleLines: function(text, limit) { return cropMultipleLines(text, limit); }, toLowerCase: function(text) { return text ? text.toLowerCase() : text; }, plural: function(n) { return n == 1 ? "" : "s"; } }); // ************************************************************************************************ // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /** @scope s_gui */ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Controller /**@namespace*/ FBL.Controller = { controllers: null, controllerContext: null, initialize: function(context) { this.controllers = []; this.controllerContext = context || Firebug.chrome; }, shutdown: function() { this.removeControllers(); //this.controllers = null; //this.controllerContext = null; }, addController: function() { for (var i=0, arg; arg=arguments[i]; i++) { // If the first argument is a string, make a selector query // within the controller node context if (typeof arg[0] == "string") { arg[0] = $$(arg[0], this.controllerContext); } // bind the handler to the proper context var handler = arg[2]; arg[2] = bind(handler, this); // save the original handler as an extra-argument, so we can // look for it later, when removing a particular controller arg[3] = handler; this.controllers.push(arg); addEvent.apply(this, arg); } }, removeController: function() { for (var i=0, arg; arg=arguments[i]; i++) { for (var j=0, c; c=this.controllers[j]; j++) { if (arg[0] == c[0] && arg[1] == c[1] && arg[2] == c[3]) removeEvent.apply(this, c); } } }, removeControllers: function() { for (var i=0, c; c=this.controllers[i]; i++) { removeEvent.apply(this, c); } } }; // ************************************************************************************************ // PanelBar /**@namespace*/ FBL.PanelBar = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * panelMap: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * selectedPanel: null, parentPanelName: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * create: function(ownerPanel) { this.panelMap = {}; this.ownerPanel = ownerPanel; if (ownerPanel) { ownerPanel.sidePanelBarNode = createElement("span"); ownerPanel.sidePanelBarNode.style.display = "none"; ownerPanel.sidePanelBarBoxNode.appendChild(ownerPanel.sidePanelBarNode); } var panels = Firebug.panelTypes; for (var i=0, p; p=panels[i]; i++) { if ( // normal Panel of the Chrome's PanelBar !ownerPanel && !p.prototype.parentPanel || // Child Panel of the current Panel's SidePanelBar ownerPanel && p.prototype.parentPanel && ownerPanel.name == p.prototype.parentPanel) { this.addPanel(p.prototype.name); } } }, destroy: function() { PanelBar.shutdown.call(this); for (var name in this.panelMap) { this.removePanel(name); var panel = this.panelMap[name]; panel.destroy(); this.panelMap[name] = null; delete this.panelMap[name]; } this.panelMap = null; this.ownerPanel = null; }, initialize: function() { if (this.ownerPanel) this.ownerPanel.sidePanelBarNode.style.display = "inline"; for(var name in this.panelMap) { (function(self, name){ // tab click handler var onTabClick = function onTabClick() { self.selectPanel(name); return false; }; Firebug.chrome.addController([self.panelMap[name].tabNode, "mousedown", onTabClick]); })(this, name); } }, shutdown: function() { var selectedPanel = this.selectedPanel; if (selectedPanel) { removeClass(selectedPanel.tabNode, "fbSelectedTab"); selectedPanel.hide(); selectedPanel.shutdown(); } if (this.ownerPanel) this.ownerPanel.sidePanelBarNode.style.display = "none"; this.selectedPanel = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * addPanel: function(panelName, parentPanel) { var PanelType = Firebug.panelTypeMap[panelName]; var panel = this.panelMap[panelName] = new PanelType(); panel.create(); }, removePanel: function(panelName) { var panel = this.panelMap[panelName]; if (panel.hasOwnProperty(panelName)) panel.destroy(); }, selectPanel: function(panelName) { var selectedPanel = this.selectedPanel; var panel = this.panelMap[panelName]; if (panel && selectedPanel != panel) { if (selectedPanel) { removeClass(selectedPanel.tabNode, "fbSelectedTab"); selectedPanel.shutdown(); selectedPanel.hide(); } if (!panel.parentPanel) Firebug.context.persistedState.selectedPanelName = panelName; this.selectedPanel = panel; setClass(panel.tabNode, "fbSelectedTab"); panel.show(); panel.initialize(); } }, getPanel: function(panelName) { var panel = this.panelMap[panelName]; return panel; } }; //************************************************************************************************ // Button /** * options.element * options.caption * options.title * * options.owner * options.className * options.pressedClassName * * options.onPress * options.onUnpress * options.onClick * * @class * @extends FBL.Controller * */ FBL.Button = function(options) { options = options || {}; append(this, options); this.state = "unpressed"; this.display = "unpressed"; if (this.element) { this.container = this.element.parentNode; } else { this.shouldDestroy = true; this.container = this.owner.getPanel().toolButtonsNode; this.element = createElement("a", { className: this.baseClassName + " " + this.className + " fbHover", innerHTML: this.caption }); if (this.title) this.element.title = this.title; this.container.appendChild(this.element); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button.prototype = extend(Controller, /**@extend FBL.Button.prototype*/ { type: "normal", caption: "caption", title: null, className: "", // custom class baseClassName: "fbButton", // control class pressedClassName: "fbBtnPressed", // control pressed class element: null, container: null, owner: null, state: null, display: null, destroy: function() { this.shutdown(); // only remove if it is a dynamically generated button (not pre-rendered) if (this.shouldDestroy) this.container.removeChild(this.element); this.element = null; this.container = null; this.owner = null; }, initialize: function() { Controller.initialize.apply(this); var element = this.element; this.addController([element, "mousedown", this.handlePress]); if (this.type == "normal") this.addController( [element, "mouseup", this.handleUnpress], [element, "mouseout", this.handleUnpress], [element, "click", this.handleClick] ); }, shutdown: function() { Controller.shutdown.apply(this); }, restore: function() { this.changeState("unpressed"); }, changeState: function(state) { this.state = state; this.changeDisplay(state); }, changeDisplay: function(display) { if (display != this.display) { if (display == "pressed") { setClass(this.element, this.pressedClassName); } else if (display == "unpressed") { removeClass(this.element, this.pressedClassName); } this.display = display; } }, handlePress: function(event) { cancelEvent(event, true); if (this.type == "normal") { this.changeDisplay("pressed"); this.beforeClick = true; } else if (this.type == "toggle") { if (this.state == "pressed") { this.changeState("unpressed"); if (this.onUnpress) this.onUnpress.apply(this.owner, arguments); } else { this.changeState("pressed"); if (this.onPress) this.onPress.apply(this.owner, arguments); } if (this.onClick) this.onClick.apply(this.owner, arguments); } return false; }, handleUnpress: function(event) { cancelEvent(event, true); if (this.beforeClick) this.changeDisplay("unpressed"); return false; }, handleClick: function(event) { cancelEvent(event, true); if (this.type == "normal") { if (this.onClick) this.onClick.apply(this.owner); this.changeState("unpressed"); } this.beforeClick = false; return false; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * @class * @extends FBL.Button */ FBL.IconButton = function() { Button.apply(this, arguments); }; IconButton.prototype = extend(Button.prototype, /**@extend FBL.IconButton.prototype*/ { baseClassName: "fbIconButton", pressedClassName: "fbIconPressed" }); //************************************************************************************************ // Menu var menuItemProps = {"class": "$item.className", type: "$item.type", value: "$item.value", _command: "$item.command"}; if (isIE6) menuItemProps.href = "javascript:void(0)"; // Allow GUI to be loaded even when Domplate module is not installed. if (FBL.domplate) var MenuPlate = domplate(Firebug.Rep, { tag: DIV({"class": "fbMenu fbShadow"}, DIV({"class": "fbMenuContent fbShadowContent"}, FOR("item", "$object.items|memberIterator", TAG("$item.tag", {item: "$item"}) ) ) ), itemTag: A(menuItemProps, "$item.label" ), checkBoxTag: A(extend(menuItemProps, {checked : "$item.checked"}), "$item.label" ), radioButtonTag: A(extend(menuItemProps, {selected : "$item.selected"}), "$item.label" ), groupTag: A(extend(menuItemProps, {child: "$item.child"}), "$item.label" ), shortcutTag: A(menuItemProps, "$item.label", SPAN({"class": "fbMenuShortcutKey"}, "$item.key" ) ), separatorTag: SPAN({"class": "fbMenuSeparator"}), memberIterator: function(items) { var result = []; for (var i=0, length=items.length; i<length; i++) { var item = items[i]; // separator representation if (typeof item == "string" && item.indexOf("-") == 0) { result.push({tag: this.separatorTag}); continue; } item = extend(item, {}); item.type = item.type || ""; item.value = item.value || ""; var type = item.type; // default item representation item.tag = this.itemTag; var className = item.className || ""; className += "fbMenuOption fbHover "; // specific representations if (type == "checkbox") { className += "fbMenuCheckBox "; item.tag = this.checkBoxTag; } else if (type == "radiobutton") { className += "fbMenuRadioButton "; item.tag = this.radioButtonTag; } else if (type == "group") { className += "fbMenuGroup "; item.tag = this.groupTag; } else if (type == "shortcut") { className += "fbMenuShortcut "; item.tag = this.shortcutTag; } if (item.checked) className += "fbMenuChecked "; else if (item.selected) className += "fbMenuRadioSelected "; if (item.disabled) className += "fbMenuDisabled "; item.className = className; item.label = $STR(item.label); result.push(item); } return result; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** * options * options.element * options.id * options.items * * item.label * item.className * item.type * item.value * item.disabled * item.checked * item.selected * item.command * item.child * * * @class * @extends FBL.Controller * */ FBL.Menu = function(options) { // if element is not pre-rendered, we must render it now if (!options.element) { if (options.getItems) options.items = options.getItems(); options.element = MenuPlate.tag.append( {object: options}, getElementByClass(Firebug.chrome.document, "fbBody"), MenuPlate ); } // extend itself with the provided options append(this, options); if (typeof this.element == "string") { this.id = this.element; this.element = $(this.id); } else if (this.id) { this.element.id = this.id; } this.element.firebugIgnore = true; this.elementStyle = this.element.style; this.isVisible = false; this.handleMouseDown = bind(this.handleMouseDown, this); this.handleMouseOver = bind(this.handleMouseOver, this); this.handleMouseOut = bind(this.handleMouseOut, this); this.handleWindowMouseDown = bind(this.handleWindowMouseDown, this); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var menuMap = {}; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Menu.prototype = extend(Controller, /**@extend FBL.Menu.prototype*/ { destroy: function() { //if (this.element) console.log("destroy", this.element.id); this.hide(); // if it is a childMenu, remove its reference from the parentMenu if (this.parentMenu) this.parentMenu.childMenu = null; // remove the element from the document this.element.parentNode.removeChild(this.element); // clear references this.element = null; this.elementStyle = null; this.parentMenu = null; this.parentTarget = null; }, initialize: function() { Controller.initialize.call(this); this.addController( [this.element, "mousedown", this.handleMouseDown], [this.element, "mouseover", this.handleMouseOver] ); }, shutdown: function() { Controller.shutdown.call(this); }, show: function(x, y) { this.initialize(); if (this.isVisible) return; //console.log("show", this.element.id); x = x || 0; y = y || 0; if (this.parentMenu) { var oldChildMenu = this.parentMenu.childMenu; if (oldChildMenu && oldChildMenu != this) { oldChildMenu.destroy(); } this.parentMenu.childMenu = this; } else addEvent(Firebug.chrome.document, "mousedown", this.handleWindowMouseDown); this.elementStyle.display = "block"; this.elementStyle.visibility = "hidden"; var size = Firebug.chrome.getSize(); x = Math.min(x, size.width - this.element.clientWidth - 10); x = Math.max(x, 0); y = Math.min(y, size.height - this.element.clientHeight - 10); y = Math.max(y, 0); this.elementStyle.left = x + "px"; this.elementStyle.top = y + "px"; this.elementStyle.visibility = "visible"; this.isVisible = true; if (isFunction(this.onShow)) this.onShow.apply(this, arguments); }, hide: function() { this.clearHideTimeout(); this.clearShowChildTimeout(); if (!this.isVisible) return; //console.log("hide", this.element.id); this.elementStyle.display = "none"; if(this.childMenu) { this.childMenu.destroy(); this.childMenu = null; } if(this.parentTarget) removeClass(this.parentTarget, "fbMenuGroupSelected"); this.isVisible = false; this.shutdown(); if (isFunction(this.onHide)) this.onHide.apply(this, arguments); }, showChildMenu: function(target) { var id = target.getAttribute("child"); var parent = this; var target = target; this.showChildTimeout = Firebug.chrome.window.setTimeout(function(){ //if (!parent.isVisible) return; var box = Firebug.chrome.getElementBox(target); var childMenuObject = menuMap.hasOwnProperty(id) ? menuMap[id] : {element: $(id)}; var childMenu = new Menu(extend(childMenuObject, { parentMenu: parent, parentTarget: target })); var offsetLeft = isIE6 ? -1 : -6; // IE6 problem with fixed position childMenu.show(box.left + box.width + offsetLeft, box.top -6); setClass(target, "fbMenuGroupSelected"); },350); }, clearHideTimeout: function() { if (this.hideTimeout) { Firebug.chrome.window.clearTimeout(this.hideTimeout); delete this.hideTimeout; } }, clearShowChildTimeout: function() { if(this.showChildTimeout) { Firebug.chrome.window.clearTimeout(this.showChildTimeout); this.showChildTimeout = null; } }, handleMouseDown: function(event) { cancelEvent(event, true); var topParent = this; while (topParent.parentMenu) topParent = topParent.parentMenu; var target = event.target || event.srcElement; target = getAncestorByClass(target, "fbMenuOption"); if(!target || hasClass(target, "fbMenuGroup")) return false; if (target && !hasClass(target, "fbMenuDisabled")) { var type = target.getAttribute("type"); if (type == "checkbox") { var checked = target.getAttribute("checked"); var value = target.getAttribute("value"); var wasChecked = hasClass(target, "fbMenuChecked"); if (wasChecked) { removeClass(target, "fbMenuChecked"); target.setAttribute("checked", ""); } else { setClass(target, "fbMenuChecked"); target.setAttribute("checked", "true"); } if (isFunction(this.onCheck)) this.onCheck.call(this, target, value, !wasChecked); } if (type == "radiobutton") { var selectedRadios = getElementsByClass(target.parentNode, "fbMenuRadioSelected"); var group = target.getAttribute("group"); for (var i = 0, length = selectedRadios.length; i < length; i++) { radio = selectedRadios[i]; if (radio.getAttribute("group") == group) { removeClass(radio, "fbMenuRadioSelected"); radio.setAttribute("selected", ""); } } setClass(target, "fbMenuRadioSelected"); target.setAttribute("selected", "true"); } var handler = null; // target.command can be a function or a string. var cmd = target.command; // If it is a function it will be used as the handler if (isFunction(cmd)) handler = cmd; // If it is a string it the property of the current menu object // will be used as the handler else if (typeof cmd == "string") handler = this[cmd]; var closeMenu = true; if (handler) closeMenu = handler.call(this, target) !== false; if (closeMenu) topParent.hide(); } return false; }, handleWindowMouseDown: function(event) { //console.log("handleWindowMouseDown"); var target = event.target || event.srcElement; target = getAncestorByClass(target, "fbMenu"); if (!target) { removeEvent(Firebug.chrome.document, "mousedown", this.handleWindowMouseDown); this.hide(); } }, handleMouseOver: function(event) { //console.log("handleMouseOver", this.element.id); this.clearHideTimeout(); this.clearShowChildTimeout(); var target = event.target || event.srcElement; target = getAncestorByClass(target, "fbMenuOption"); if(!target) return; var childMenu = this.childMenu; if(childMenu) { removeClass(childMenu.parentTarget, "fbMenuGroupSelected"); if (childMenu.parentTarget != target && childMenu.isVisible) { childMenu.clearHideTimeout(); childMenu.hideTimeout = Firebug.chrome.window.setTimeout(function(){ childMenu.destroy(); },300); } } if(hasClass(target, "fbMenuGroup")) { this.showChildMenu(target); } } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * append(Menu, /**@extend FBL.Menu*/ { register: function(object) { menuMap[object.id] = object; }, check: function(element) { setClass(element, "fbMenuChecked"); element.setAttribute("checked", "true"); }, uncheck: function(element) { removeClass(element, "fbMenuChecked"); element.setAttribute("checked", ""); }, disable: function(element) { setClass(element, "fbMenuDisabled"); }, enable: function(element) { removeClass(element, "fbMenuDisabled"); } }); //************************************************************************************************ // Status Bar /**@class*/ function StatusBar(){}; StatusBar.prototype = extend(Controller, { }); // ************************************************************************************************ // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /**@scope s_context*/ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var refreshDelay = 300; // Opera and some versions of webkit returns the wrong value of document.elementFromPoint() // function, without taking into account the scroll position. Safari 4 (webkit/531.21.8) // still have this issue. Google Chrome 4 (webkit/532.5) does not. So, we're assuming this // issue was fixed in the 532 version var shouldFixElementFromPoint = isOpera || isSafari && browserVersion < "532"; var evalError = "___firebug_evaluation_error___"; var pixelsPerInch; var resetStyle = "margin:0; padding:0; border:0; position:absolute; overflow:hidden; display:block;"; var offscreenStyle = resetStyle + "top:-1234px; left:-1234px;"; // ************************************************************************************************ // Context /** @class */ FBL.Context = function(win) { this.window = win.window; this.document = win.document; this.browser = Env.browser; // Some windows in IE, like iframe, doesn't have the eval() method if (isIE && !this.window.eval) { // But after executing the following line the method magically appears! this.window.execScript("null"); // Just to make sure the "magic" really happened if (!this.window.eval) throw new Error("Firebug Error: eval() method not found in this window"); } // Create a new "black-box" eval() method that runs in the global namespace // of the context window, without exposing the local variables declared // by the function that calls it this.eval = this.window.eval("new Function('" + "try{ return window.eval.apply(window,arguments) }catch(E){ E."+evalError+"=true; return E }" + "')"); }; FBL.Context.prototype = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // partial-port of Firebug tabContext.js browser: null, loaded: true, setTimeout: function(fn, delay) { var win = this.window; if (win.setTimeout == this.setTimeout) throw new Error("setTimeout recursion"); var timeout = win.setTimeout.apply ? // IE doesn't have apply method on setTimeout win.setTimeout.apply(win, arguments) : win.setTimeout(fn, delay); if (!this.timeouts) this.timeouts = {}; this.timeouts[timeout] = 1; return timeout; }, clearTimeout: function(timeout) { clearTimeout(timeout); if (this.timeouts) delete this.timeouts[timeout]; }, setInterval: function(fn, delay) { var win = this.window; var timeout = win.setInterval.apply ? // IE doesn't have apply method on setTimeout win.setInterval.apply(win, arguments) : win.setInterval(fn, delay); if (!this.intervals) this.intervals = {}; this.intervals[timeout] = 1; return timeout; }, clearInterval: function(timeout) { clearInterval(timeout); if (this.intervals) delete this.intervals[timeout]; }, invalidatePanels: function() { if (!this.invalidPanels) this.invalidPanels = {}; for (var i = 0; i < arguments.length; ++i) { var panelName = arguments[i]; // avoid error. need to create a better getPanel() function as explained below if (!Firebug.chrome || !Firebug.chrome.selectedPanel) return; //var panel = this.getPanel(panelName, true); //TODO: xxxpedro context how to get all panels using a single function? // the current workaround to make the invalidation works is invalidating // only sidePanels. There's also a problem with panel name (LowerCase in Firebug Lite) var panel = Firebug.chrome.selectedPanel.sidePanelBar ? Firebug.chrome.selectedPanel.sidePanelBar.getPanel(panelName, true) : null; if (panel && !panel.noRefresh) this.invalidPanels[panelName] = 1; } if (this.refreshTimeout) { this.clearTimeout(this.refreshTimeout); delete this.refreshTimeout; } this.refreshTimeout = this.setTimeout(bindFixed(function() { var invalids = []; for (var panelName in this.invalidPanels) { //var panel = this.getPanel(panelName, true); //TODO: xxxpedro context how to get all panels using a single function? // the current workaround to make the invalidation works is invalidating // only sidePanels. There's also a problem with panel name (LowerCase in Firebug Lite) var panel = Firebug.chrome.selectedPanel.sidePanelBar ? Firebug.chrome.selectedPanel.sidePanelBar.getPanel(panelName, true) : null; if (panel) { if (panel.visible && !panel.editing) panel.refresh(); else panel.needsRefresh = true; // If the panel is being edited, we'll keep trying to // refresh it until editing is done if (panel.editing) invalids.push(panelName); } } delete this.invalidPanels; delete this.refreshTimeout; // Keep looping until every tab is valid if (invalids.length) this.invalidatePanels.apply(this, invalids); }, this), refreshDelay); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Evalutation Method /** * Evaluates an expression in the current context window. * * @param {String} expr expression to be evaluated * * @param {String} context string indicating the global location * of the object that will be used as the * context. The context is referred in * the expression as the "this" keyword. * If no context is informed, the "window" * context is used. * * @param {String} api string indicating the global location * of the object that will be used as the * api of the evaluation. * * @param {Function} errorHandler(message) error handler to be called * if the evaluation fails. */ evaluate: function(expr, context, api, errorHandler) { // the default context is the "window" object. It can be any string that represents // a global accessible element as: "my.namespaced.object" context = context || "window"; var isObjectLiteral = trim(expr).indexOf("{") == 0, cmd, result; // if the context is the "window" object, we don't need a closure if (context == "window") { // If it is an object literal, then wrap the expression with parenthesis so we can // capture the return value if (isObjectLiteral) { cmd = api ? "with("+api+"){ ("+expr+") }" : "(" + expr + ")"; } else { cmd = api ? "with("+api+"){ "+expr+" }" : expr; } } else { cmd = api ? // with API and context, no return value "(function(arguments){ with(" + api + "){ " + expr + " } }).call(" + context + ",undefined)" : // with context only, no return value "(function(arguments){ " + expr + " }).call(" + context + ",undefined)"; } result = this.eval(cmd); if (result && result[evalError]) { var msg = result.name ? (result.name + ": ") : ""; msg += result.message || result; if (errorHandler) result = errorHandler(msg); else result = msg; } return result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Window Methods getWindowSize: function() { var width=0, height=0, el; if (typeof this.window.innerWidth == "number") { width = this.window.innerWidth; height = this.window.innerHeight; } else if ((el=this.document.documentElement) && (el.clientHeight || el.clientWidth)) { width = el.clientWidth; height = el.clientHeight; } else if ((el=this.document.body) && (el.clientHeight || el.clientWidth)) { width = el.clientWidth; height = el.clientHeight; } return {width: width, height: height}; }, getWindowScrollSize: function() { var width=0, height=0, el; // first try the document.documentElement scroll size if (!isIEQuiksMode && (el=this.document.documentElement) && (el.scrollHeight || el.scrollWidth)) { width = el.scrollWidth; height = el.scrollHeight; } // then we need to check if document.body has a bigger scroll size value // because sometimes depending on the browser and the page, the document.body // scroll size returns a smaller (and wrong) measure if ((el=this.document.body) && (el.scrollHeight || el.scrollWidth) && (el.scrollWidth > width || el.scrollHeight > height)) { width = el.scrollWidth; height = el.scrollHeight; } return {width: width, height: height}; }, getWindowScrollPosition: function() { var top=0, left=0, el; if(typeof this.window.pageYOffset == "number") { top = this.window.pageYOffset; left = this.window.pageXOffset; } else if((el=this.document.body) && (el.scrollTop || el.scrollLeft)) { top = el.scrollTop; left = el.scrollLeft; } else if((el=this.document.documentElement) && (el.scrollTop || el.scrollLeft)) { top = el.scrollTop; left = el.scrollLeft; } return {top:top, left:left}; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Element Methods getElementFromPoint: function(x, y) { if (shouldFixElementFromPoint) { var scroll = this.getWindowScrollPosition(); return this.document.elementFromPoint(x + scroll.left, y + scroll.top); } else return this.document.elementFromPoint(x, y); }, getElementPosition: function(el) { var left = 0; var top = 0; do { left += el.offsetLeft; top += el.offsetTop; } while (el = el.offsetParent); return {left:left, top:top}; }, getElementBox: function(el) { var result = {}; if (el.getBoundingClientRect) { var rect = el.getBoundingClientRect(); // fix IE problem with offset when not in fullscreen mode var offset = isIE ? this.document.body.clientTop || this.document.documentElement.clientTop: 0; var scroll = this.getWindowScrollPosition(); result.top = Math.round(rect.top - offset + scroll.top); result.left = Math.round(rect.left - offset + scroll.left); result.height = Math.round(rect.bottom - rect.top); result.width = Math.round(rect.right - rect.left); } else { var position = this.getElementPosition(el); result.top = position.top; result.left = position.left; result.height = el.offsetHeight; result.width = el.offsetWidth; } return result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Measurement Methods getMeasurement: function(el, name) { var result = {value: 0, unit: "px"}; var cssValue = this.getStyle(el, name); if (!cssValue) return result; if (cssValue.toLowerCase() == "auto") return result; var reMeasure = /(\d+\.?\d*)(.*)/; var m = cssValue.match(reMeasure); if (m) { result.value = m[1]-0; result.unit = m[2].toLowerCase(); } return result; }, getMeasurementInPixels: function(el, name) { if (!el) return null; var m = this.getMeasurement(el, name); var value = m.value; var unit = m.unit; if (unit == "px") return value; else if (unit == "pt") return this.pointsToPixels(name, value); else if (unit == "em") return this.emToPixels(el, value); else if (unit == "%") return this.percentToPixels(el, value); else if (unit == "ex") return this.exToPixels(el, value); // TODO: add other units. Maybe create a better general way // to calculate measurements in different units. }, getMeasurementBox1: function(el, name) { var sufixes = ["Top", "Left", "Bottom", "Right"]; var result = []; for(var i=0, sufix; sufix=sufixes[i]; i++) result[i] = Math.round(this.getMeasurementInPixels(el, name + sufix)); return {top:result[0], left:result[1], bottom:result[2], right:result[3]}; }, getMeasurementBox: function(el, name) { var result = []; var sufixes = name == "border" ? ["TopWidth", "LeftWidth", "BottomWidth", "RightWidth"] : ["Top", "Left", "Bottom", "Right"]; if (isIE) { var propName, cssValue; var autoMargin = null; for(var i=0, sufix; sufix=sufixes[i]; i++) { propName = name + sufix; cssValue = el.currentStyle[propName] || el.style[propName]; if (cssValue == "auto") { if (!autoMargin) autoMargin = this.getCSSAutoMarginBox(el); result[i] = autoMargin[sufix.toLowerCase()]; } else result[i] = this.getMeasurementInPixels(el, propName); } } else { for(var i=0, sufix; sufix=sufixes[i]; i++) result[i] = this.getMeasurementInPixels(el, name + sufix); } return {top:result[0], left:result[1], bottom:result[2], right:result[3]}; }, getCSSAutoMarginBox: function(el) { if (isIE && " meta title input script link a ".indexOf(" "+el.nodeName.toLowerCase()+" ") != -1) return {top:0, left:0, bottom:0, right:0}; /**/ if (isIE && " h1 h2 h3 h4 h5 h6 h7 ul p ".indexOf(" "+el.nodeName.toLowerCase()+" ") == -1) return {top:0, left:0, bottom:0, right:0}; /**/ var offsetTop = 0; if (false && isIEStantandMode) { var scrollSize = Firebug.browser.getWindowScrollSize(); offsetTop = scrollSize.height; } var box = this.document.createElement("div"); //box.style.cssText = "margin:0; padding:1px; border: 0; position:static; overflow:hidden; visibility: hidden;"; box.style.cssText = "margin:0; padding:1px; border: 0; visibility: hidden;"; var clone = el.cloneNode(false); var text = this.document.createTextNode("&nbsp;"); clone.appendChild(text); box.appendChild(clone); this.document.body.appendChild(box); var marginTop = clone.offsetTop - box.offsetTop - 1; var marginBottom = box.offsetHeight - clone.offsetHeight - 2 - marginTop; var marginLeft = clone.offsetLeft - box.offsetLeft - 1; var marginRight = box.offsetWidth - clone.offsetWidth - 2 - marginLeft; this.document.body.removeChild(box); return {top:marginTop+offsetTop, left:marginLeft, bottom:marginBottom-offsetTop, right:marginRight}; }, getFontSizeInPixels: function(el) { var size = this.getMeasurement(el, "fontSize"); if (size.unit == "px") return size.value; // get font size, the dirty way var computeDirtyFontSize = function(el, calibration) { var div = this.document.createElement("div"); var divStyle = offscreenStyle; if (calibration) divStyle += " font-size:"+calibration+"px;"; div.style.cssText = divStyle; div.innerHTML = "A"; el.appendChild(div); var value = div.offsetHeight; el.removeChild(div); return value; }; /* var calibrationBase = 200; var calibrationValue = computeDirtyFontSize(el, calibrationBase); var rate = calibrationBase / calibrationValue; /**/ // the "dirty technique" fails in some environments, so we're using a static value // based in some tests. var rate = 200 / 225; var value = computeDirtyFontSize(el); return value * rate; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Unit Funtions pointsToPixels: function(name, value, returnFloat) { var axis = /Top$|Bottom$/.test(name) ? "y" : "x"; var result = value * pixelsPerInch[axis] / 72; return returnFloat ? result : Math.round(result); }, emToPixels: function(el, value) { if (!el) return null; var fontSize = this.getFontSizeInPixels(el); return Math.round(value * fontSize); }, exToPixels: function(el, value) { if (!el) return null; // get ex value, the dirty way var div = this.document.createElement("div"); div.style.cssText = offscreenStyle + "width:"+value + "ex;"; el.appendChild(div); var value = div.offsetWidth; el.removeChild(div); return value; }, percentToPixels: function(el, value) { if (!el) return null; // get % value, the dirty way var div = this.document.createElement("div"); div.style.cssText = offscreenStyle + "width:"+value + "%;"; el.appendChild(div); var value = div.offsetWidth; el.removeChild(div); return value; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getStyle: isIE ? function(el, name) { return el.currentStyle[name] || el.style[name] || undefined; } : function(el, name) { return this.document.defaultView.getComputedStyle(el,null)[name] || el.style[name] || undefined; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns( /**@scope ns-chrome*/ function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Window Options var WindowDefaultOptions = { type: "frame", id: "FirebugUI" //height: 350 // obsolete }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Instantiated objects commandLine, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Interface Elements Cache fbTop, fbContent, fbContentStyle, fbBottom, fbBtnInspect, fbToolbar, fbPanelBox1, fbPanelBox1Style, fbPanelBox2, fbPanelBox2Style, fbPanelBar2Box, fbPanelBar2BoxStyle, fbHSplitter, fbVSplitter, fbVSplitterStyle, fbPanel1, fbPanel1Style, fbPanel2, fbPanel2Style, fbConsole, fbConsoleStyle, fbHTML, fbCommandLine, fbLargeCommandLine, fbLargeCommandButtons, //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Cached size values topHeight, topPartialHeight, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * chromeRedrawSkipRate = isIE ? 75 : isOpera ? 80 : 75, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * lastSelectedPanelName, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * focusCommandLineState = 0, lastFocusedPanelName, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * lastHSplitterMouseMove = 0, onHSplitterMouseMoveBuffer = null, onHSplitterMouseMoveTimer = null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * lastVSplitterMouseMove = 0; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ************************************************************************************************ // FirebugChrome FBL.defaultPersistedState = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * isOpen: false, height: 300, sidePanelWidth: 350, selectedPanelName: "Console", selectedHTMLElementId: null, htmlSelectionStack: [] // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * }; /**@namespace*/ FBL.FirebugChrome = { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //isOpen: false, //height: 300, //sidePanelWidth: 350, //selectedPanelName: "Console", //selectedHTMLElementId: null, chromeMap: {}, htmlSelectionStack: [], // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * create: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FirebugChrome.create", "creating chrome window"); createChromeWindow(); }, initialize: function() { if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("FirebugChrome.initialize", "initializing chrome window"); if (Env.chrome.type == "frame" || Env.chrome.type == "div") ChromeMini.create(Env.chrome); var chrome = Firebug.chrome = new Chrome(Env.chrome); FirebugChrome.chromeMap[chrome.type] = chrome; addGlobalEvent("keydown", onGlobalKeyDown); if (Env.Options.enablePersistent && chrome.type == "popup") { // TODO: xxxpedro persist - revise chrome synchronization when in persistent mode var frame = FirebugChrome.chromeMap.frame; if (frame) frame.close(); //chrome.reattach(frame, chrome); //TODO: xxxpedro persist synchronize? chrome.initialize(); } }, clone: function(FBChrome) { for (var name in FBChrome) { var prop = FBChrome[name]; if (FBChrome.hasOwnProperty(name) && !isFunction(prop)) { this[name] = prop; } } } }; // ************************************************************************************************ // Chrome Window Creation var createChromeWindow = function(options) { options = extend(WindowDefaultOptions, options || {}); //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Locals var browserWin = Env.browser.window; var browserContext = new Context(browserWin); var prefs = Store.get("FirebugLite"); var persistedState = prefs && prefs.persistedState || defaultPersistedState; var chrome = {}, context = options.context || Env.browser, type = chrome.type = Env.Options.enablePersistent ? "popup" : options.type, isChromeFrame = type == "frame", useLocalSkin = Env.useLocalSkin, url = useLocalSkin ? Env.Location.skin : "about:blank", // document.body not available in XML+XSL documents in Firefox body = context.document.getElementsByTagName("body")[0], formatNode = function(node) { if (!Env.isDebugMode) { node.firebugIgnore = true; } var browserWinSize = browserContext.getWindowSize(); var height = persistedState.height || 300; height = Math.min(browserWinSize.height, height); height = Math.max(200, height); node.style.border = "0"; node.style.visibility = "hidden"; node.style.zIndex = "2147483647"; // MAX z-index = 2147483647 node.style.position = noFixedPosition ? "absolute" : "fixed"; node.style.width = "100%"; // "102%"; IE auto margin bug node.style.left = "0"; node.style.bottom = noFixedPosition ? "-1px" : "0"; node.style.height = height + "px"; // avoid flickering during chrome rendering //if (isFirefox) // node.style.display = "none"; }, createChromeDiv = function() { //Firebug.Console.warn("Firebug Lite GUI is working in 'windowless mode'. It may behave slower and receive interferences from the page in which it is installed."); var node = chrome.node = createGlobalElement("div"), style = createGlobalElement("style"), css = FirebugChrome.Skin.CSS /* .replace(/;/g, " !important;") .replace(/!important\s!important/g, "!important") .replace(/display\s*:\s*(\w+)\s*!important;/g, "display:$1;")*/, // reset some styles to minimize interference from the main page's style rules = ".fbBody *{margin:0;padding:0;font-size:11px;line-height:13px;color:inherit;}" + // load the chrome styles css + // adjust some remaining styles ".fbBody #fbHSplitter{position:absolute !important;} .fbBody #fbHTML span{line-height:14px;} .fbBody .lineNo div{line-height:inherit !important;}"; /* if (isIE) { // IE7 CSS bug (FbChrome table bigger than its parent div) rules += ".fbBody table.fbChrome{position: static !important;}"; }/**/ style.type = "text/css"; if (style.styleSheet) style.styleSheet.cssText = rules; else style.appendChild(context.document.createTextNode(rules)); document.getElementsByTagName("head")[0].appendChild(style); node.className = "fbBody"; node.style.overflow = "hidden"; node.innerHTML = getChromeDivTemplate(); if (isIE) { // IE7 CSS bug (FbChrome table bigger than its parent div) setTimeout(function(){ node.firstChild.style.height = "1px"; node.firstChild.style.position = "static"; },0); /**/ } formatNode(node); body.appendChild(node); chrome.window = window; chrome.document = document; onChromeLoad(chrome); }; //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * try { //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create the Chrome as a "div" (windowless mode) if (type == "div") { createChromeDiv(); return; } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // cretate the Chrome as an "iframe" else if (isChromeFrame) { // Create the Chrome Frame var node = chrome.node = createGlobalElement("iframe"); node.setAttribute("src", url); node.setAttribute("frameBorder", "0"); formatNode(node); body.appendChild(node); // must set the id after appending to the document, otherwise will cause an // strange error in IE, making the iframe load the page in which the bookmarklet // was created (like getfirebug.com), before loading the injected UI HTML, // generating an "Access Denied" error. node.id = options.id; } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create the Chrome as a "popup" else { var height = persistedState.popupHeight || 300; var browserWinSize = browserContext.getWindowSize(); var browserWinLeft = typeof browserWin.screenX == "number" ? browserWin.screenX : browserWin.screenLeft; var popupLeft = typeof persistedState.popupLeft == "number" ? persistedState.popupLeft : browserWinLeft; var browserWinTop = typeof browserWin.screenY == "number" ? browserWin.screenY : browserWin.screenTop; var popupTop = typeof persistedState.popupTop == "number" ? persistedState.popupTop : Math.max( 0, Math.min( browserWinTop + browserWinSize.height - height, // Google Chrome bug screen.availHeight - height - 61 ) ); var popupWidth = typeof persistedState.popupWidth == "number" ? persistedState.popupWidth : Math.max( 0, Math.min( browserWinSize.width, // Opera opens popup in a new tab if it's too big! screen.availWidth-10 ) ); var popupHeight = typeof persistedState.popupHeight == "number" ? persistedState.popupHeight : 300; var options = [ "true,top=", popupTop, ",left=", popupLeft, ",height=", popupHeight, ",width=", popupWidth, ",resizable" ].join(""), node = chrome.node = context.window.open( url, "popup", options ); if (node) { try { node.focus(); } catch(E) { alert("Firebug Error: Firebug popup was blocked."); return; } } else { alert("Firebug Error: Firebug popup was blocked."); return; } } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Inject the interface HTML if it is not using the local skin if (!useLocalSkin) { var tpl = getChromeTemplate(!isChromeFrame), doc = isChromeFrame ? node.contentWindow.document : node.document; doc.write(tpl); doc.close(); } //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Wait the Window to be loaded var win, waitDelay = useLocalSkin ? isChromeFrame ? 200 : 300 : 100, waitForWindow = function() { if ( // Frame loaded... OR isChromeFrame && (win=node.contentWindow) && node.contentWindow.document.getElementById("fbCommandLine") || // Popup loaded !isChromeFrame && (win=node.window) && node.document && node.document.getElementById("fbCommandLine") ) { chrome.window = win.window; chrome.document = win.document; // Prevent getting the wrong chrome height in FF when opening a popup setTimeout(function(){ onChromeLoad(chrome); }, useLocalSkin ? 200 : 0); } else setTimeout(waitForWindow, waitDelay); }; waitForWindow(); } catch(e) { var msg = e.message || e; if (/access/i.test(msg)) { // Firebug Lite could not create a window for its Graphical User Interface due to // a access restriction. This happens in some pages, when loading via bookmarklet. // In such cases, the only way is to load the GUI in a "windowless mode". if (isChromeFrame) body.removeChild(node); else if(type == "popup") node.close(); // Load the GUI in a "windowless mode" createChromeDiv(); } else { alert("Firebug Error: Firebug GUI could not be created."); } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var onChromeLoad = function onChromeLoad(chrome) { Env.chrome = chrome; if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Chrome onChromeLoad", "chrome window loaded"); if (Env.Options.enablePersistent) { // TODO: xxxpedro persist - make better chrome synchronization when in persistent mode Env.FirebugChrome = FirebugChrome; chrome.window.Firebug = chrome.window.Firebug || {}; chrome.window.Firebug.SharedEnv = Env; if (Env.isDevelopmentMode) { Env.browser.window.FBDev.loadChromeApplication(chrome); } else { var doc = chrome.document; var script = doc.createElement("script"); script.src = Env.Location.app + "#remote,persist"; doc.getElementsByTagName("head")[0].appendChild(script); } } else { if (chrome.type == "frame" || chrome.type == "div") { // initialize the chrome application setTimeout(function(){ FBL.Firebug.initialize(); },0); } else if (chrome.type == "popup") { var oldChrome = FirebugChrome.chromeMap.frame; var newChrome = new Chrome(chrome); // TODO: xxxpedro sync detach reattach attach dispatch(newChrome.panelMap, "detach", [oldChrome, newChrome]); newChrome.reattach(oldChrome, newChrome); } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var getChromeDivTemplate = function() { return FirebugChrome.Skin.HTML; }; var getChromeTemplate = function(isPopup) { var tpl = FirebugChrome.Skin; var r = [], i = -1; r[++i] = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/DTD/strict.dtd">'; r[++i] = '<html><head><title>'; r[++i] = Firebug.version; /* r[++i] = '</title><link href="'; r[++i] = Env.Location.skinDir + 'firebug.css'; r[++i] = '" rel="stylesheet" type="text/css" />'; /**/ r[++i] = '</title><style>html,body{margin:0;padding:0;overflow:hidden;}'; r[++i] = tpl.CSS; r[++i] = '</style>'; /**/ r[++i] = '</head><body class="fbBody' + (isPopup ? ' FirebugPopup' : '') + '">'; r[++i] = tpl.HTML; r[++i] = '</body></html>'; return r.join(""); }; // ************************************************************************************************ // Chrome Class /**@class*/ var Chrome = function Chrome(chrome) { var type = chrome.type; var Base = type == "frame" || type == "div" ? ChromeFrameBase : ChromePopupBase; append(this, Base); // inherit from base class (ChromeFrameBase or ChromePopupBase) append(this, chrome); // inherit chrome window properties append(this, new Context(chrome.window)); // inherit from Context class FirebugChrome.chromeMap[type] = this; Firebug.chrome = this; Env.chrome = chrome.window; this.commandLineVisible = false; this.sidePanelVisible = false; this.create(); return this; }; // ************************************************************************************************ // ChromeBase /** * @namespace * @extends FBL.Controller * @extends FBL.PanelBar **/ var ChromeBase = {}; append(ChromeBase, Controller); append(ChromeBase, PanelBar); append(ChromeBase, /**@extend ns-chrome-ChromeBase*/ { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // inherited properties // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // inherited from createChrome function node: null, type: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // inherited from Context.prototype document: null, window: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value properties sidePanelVisible: false, commandLineVisible: false, largeCommandLineVisible: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // object properties inspectButton: null, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * create: function() { PanelBar.create.call(this); if (Firebug.Inspector) this.inspectButton = new Button({ type: "toggle", element: $("fbChrome_btInspect"), owner: Firebug.Inspector, onPress: Firebug.Inspector.startInspecting, onUnpress: Firebug.Inspector.stopInspecting }); }, destroy: function() { if(Firebug.Inspector) this.inspectButton.destroy(); PanelBar.destroy.call(this); this.shutdown(); }, testMenu: function() { var firebugMenu = new Menu( { id: "fbFirebugMenu", items: [ { label: "Open Firebug", type: "shortcut", key: isFirefox ? "Shift+F12" : "F12", checked: true, command: "toggleChrome" }, { label: "Open Firebug in New Window", type: "shortcut", key: isFirefox ? "Ctrl+Shift+F12" : "Ctrl+F12", command: "openPopup" }, { label: "Inspect Element", type: "shortcut", key: "Ctrl+Shift+C", command: "toggleInspect" }, { label: "Command Line", type: "shortcut", key: "Ctrl+Shift+L", command: "focusCommandLine" }, "-", { label: "Options", type: "group", child: "fbFirebugOptionsMenu" }, "-", { label: "Firebug Lite Website...", command: "visitWebsite" }, { label: "Discussion Group...", command: "visitDiscussionGroup" }, { label: "Issue Tracker...", command: "visitIssueTracker" } ], onHide: function() { iconButton.restore(); }, toggleChrome: function() { Firebug.chrome.toggle(); }, openPopup: function() { Firebug.chrome.toggle(true, true); }, toggleInspect: function() { Firebug.Inspector.toggleInspect(); }, focusCommandLine: function() { Firebug.chrome.focusCommandLine(); }, visitWebsite: function() { this.visit("http://getfirebug.com/lite.html"); }, visitDiscussionGroup: function() { this.visit("http://groups.google.com/group/firebug"); }, visitIssueTracker: function() { this.visit("http://code.google.com/p/fbug/issues/list"); }, visit: function(url) { window.open(url); } }); /**@private*/ var firebugOptionsMenu = { id: "fbFirebugOptionsMenu", getItems: function() { var cookiesDisabled = !Firebug.saveCookies; return [ { label: "Start Opened", type: "checkbox", value: "startOpened", checked: Firebug.startOpened, disabled: cookiesDisabled }, { label: "Start in New Window", type: "checkbox", value: "startInNewWindow", checked: Firebug.startInNewWindow, disabled: cookiesDisabled }, { label: "Show Icon When Hidden", type: "checkbox", value: "showIconWhenHidden", checked: Firebug.showIconWhenHidden, disabled: cookiesDisabled }, { label: "Override Console Object", type: "checkbox", value: "overrideConsole", checked: Firebug.overrideConsole, disabled: cookiesDisabled }, { label: "Ignore Firebug Elements", type: "checkbox", value: "ignoreFirebugElements", checked: Firebug.ignoreFirebugElements, disabled: cookiesDisabled }, { label: "Disable When Firebug Active", type: "checkbox", value: "disableWhenFirebugActive", checked: Firebug.disableWhenFirebugActive, disabled: cookiesDisabled }, { label: "Disable XHR Listener", type: "checkbox", value: "disableXHRListener", checked: Firebug.disableXHRListener, disabled: cookiesDisabled }, { label: "Disable Resource Fetching", type: "checkbox", value: "disableResourceFetching", checked: Firebug.disableResourceFetching, disabled: cookiesDisabled }, { label: "Enable Trace Mode", type: "checkbox", value: "enableTrace", checked: Firebug.enableTrace, disabled: cookiesDisabled }, { label: "Enable Persistent Mode (experimental)", type: "checkbox", value: "enablePersistent", checked: Firebug.enablePersistent, disabled: cookiesDisabled }, "-", { label: "Reset All Firebug Options", command: "restorePrefs", disabled: cookiesDisabled } ]; }, onCheck: function(target, value, checked) { Firebug.setPref(value, checked); }, restorePrefs: function(target) { Firebug.erasePrefs(); if (target) this.updateMenu(target); }, updateMenu: function(target) { var options = getElementsByClass(target.parentNode, "fbMenuOption"); var firstOption = options[0]; var enabled = Firebug.saveCookies; if (enabled) Menu.check(firstOption); else Menu.uncheck(firstOption); if (enabled) Menu.check(options[0]); else Menu.uncheck(options[0]); for (var i = 1, length = options.length; i < length; i++) { var option = options[i]; var value = option.getAttribute("value"); var pref = Firebug[value]; if (pref) Menu.check(option); else Menu.uncheck(option); if (enabled) Menu.enable(option); else Menu.disable(option); } } }; Menu.register(firebugOptionsMenu); var menu = firebugMenu; var testMenuClick = function(event) { //console.log("testMenuClick"); cancelEvent(event, true); var target = event.target || event.srcElement; if (menu.isVisible) menu.hide(); else { var offsetLeft = isIE6 ? 1 : -4, // IE6 problem with fixed position chrome = Firebug.chrome, box = chrome.getElementBox(target), offset = chrome.type == "div" ? chrome.getElementPosition(chrome.node) : {top: 0, left: 0}; menu.show( box.left + offsetLeft - offset.left, box.top + box.height -5 - offset.top ); } return false; }; var iconButton = new IconButton({ type: "toggle", element: $("fbFirebugButton"), onClick: testMenuClick }); iconButton.initialize(); //addEvent($("fbToolbarIcon"), "click", testMenuClick); }, initialize: function() { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (Env.bookmarkletOutdated) Firebug.Console.logFormatted([ "A new bookmarklet version is available. " + "Please visit http://getfirebug.com/firebuglite#Install and update it." ], Firebug.context, "warn"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (Firebug.Console) Firebug.Console.flush(); if (Firebug.Trace) FBTrace.flush(Firebug.Trace); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.chrome.initialize", "initializing chrome application"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize inherited classes Controller.initialize.call(this); PanelBar.initialize.call(this); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // create the interface elements cache fbTop = $("fbTop"); fbContent = $("fbContent"); fbContentStyle = fbContent.style; fbBottom = $("fbBottom"); fbBtnInspect = $("fbBtnInspect"); fbToolbar = $("fbToolbar"); fbPanelBox1 = $("fbPanelBox1"); fbPanelBox1Style = fbPanelBox1.style; fbPanelBox2 = $("fbPanelBox2"); fbPanelBox2Style = fbPanelBox2.style; fbPanelBar2Box = $("fbPanelBar2Box"); fbPanelBar2BoxStyle = fbPanelBar2Box.style; fbHSplitter = $("fbHSplitter"); fbVSplitter = $("fbVSplitter"); fbVSplitterStyle = fbVSplitter.style; fbPanel1 = $("fbPanel1"); fbPanel1Style = fbPanel1.style; fbPanel2 = $("fbPanel2"); fbPanel2Style = fbPanel2.style; fbConsole = $("fbConsole"); fbConsoleStyle = fbConsole.style; fbHTML = $("fbHTML"); fbCommandLine = $("fbCommandLine"); fbLargeCommandLine = $("fbLargeCommandLine"); fbLargeCommandButtons = $("fbLargeCommandButtons"); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // static values cache topHeight = fbTop.offsetHeight; topPartialHeight = fbToolbar.offsetHeight; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * disableTextSelection($("fbToolbar")); disableTextSelection($("fbPanelBarBox")); disableTextSelection($("fbPanelBar1")); disableTextSelection($("fbPanelBar2")); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Add the "javascript:void(0)" href attributes used to make the hover effect in IE6 if (isIE6 && Firebug.Selector) { // TODO: xxxpedro change to getElementsByClass var as = $$(".fbHover"); for (var i=0, a; a=as[i]; i++) { a.setAttribute("href", "javascript:void(0)"); } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // initialize all panels /* var panelMap = Firebug.panelTypes; for (var i=0, p; p=panelMap[i]; i++) { if (!p.parentPanel) { this.addPanel(p.prototype.name); } } /**/ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ if(Firebug.Inspector) this.inspectButton.initialize(); // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ this.addController( [$("fbLargeCommandLineIcon"), "click", this.showLargeCommandLine] ); // ************************************************************************************************ // Select the first registered panel // TODO: BUG IE7 var self = this; setTimeout(function(){ self.selectPanel(Firebug.context.persistedState.selectedPanelName); if (Firebug.context.persistedState.selectedPanelName == "Console" && Firebug.CommandLine) Firebug.chrome.focusCommandLine(); },0); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //this.draw(); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var onPanelMouseDown = function onPanelMouseDown(event) { //console.log("onPanelMouseDown", event.target || event.srcElement, event); var target = event.target || event.srcElement; if (FBL.isLeftClick(event)) { var editable = FBL.getAncestorByClass(target, "editable"); // if an editable element has been clicked then start editing if (editable) { Firebug.Editor.startEditing(editable); FBL.cancelEvent(event); } // if any other element has been clicked then stop editing else { if (!hasClass(target, "textEditorInner")) Firebug.Editor.stopEditing(); } } else if (FBL.isMiddleClick(event) && Firebug.getRepNode(target)) { // Prevent auto-scroll when middle-clicking a rep object FBL.cancelEvent(event); } }; Firebug.getElementPanel = function(element) { var panelNode = getAncestorByClass(element, "fbPanel"); var id = panelNode.id.substr(2); var panel = Firebug.chrome.panelMap[id]; if (!panel) { if (Firebug.chrome.selectedPanel.sidePanelBar) panel = Firebug.chrome.selectedPanel.sidePanelBar.panelMap[id]; } return panel; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // TODO: xxxpedro port to Firebug // Improved window key code event listener. Only one "keydown" event will be attached // to the window, and the onKeyCodeListen() function will delegate which listeners // should be called according to the event.keyCode fired. var onKeyCodeListenersMap = []; var onKeyCodeListen = function(event) { for (var keyCode in onKeyCodeListenersMap) { var listeners = onKeyCodeListenersMap[keyCode]; for (var i = 0, listener; listener = listeners[i]; i++) { var filter = listener.filter || FBL.noKeyModifiers; if (event.keyCode == keyCode && (!filter || filter(event))) { listener.listener(); FBL.cancelEvent(event, true); return false; } } } }; addEvent(Firebug.chrome.document, "keydown", onKeyCodeListen); /** * @name keyCodeListen * @memberOf FBL.FirebugChrome */ Firebug.chrome.keyCodeListen = function(key, filter, listener, capture) { var keyCode = KeyEvent["DOM_VK_"+key]; if (!onKeyCodeListenersMap[keyCode]) onKeyCodeListenersMap[keyCode] = []; onKeyCodeListenersMap[keyCode].push({ filter: filter, listener: listener }); return keyCode; }; /** * @name keyIgnore * @memberOf FBL.FirebugChrome */ Firebug.chrome.keyIgnore = function(keyCode) { onKeyCodeListenersMap[keyCode] = null; delete onKeyCodeListenersMap[keyCode]; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /**/ // move to shutdown //removeEvent(Firebug.chrome.document, "keydown", listener[0]); /* Firebug.chrome.keyCodeListen = function(key, filter, listener, capture) { if (!filter) filter = FBL.noKeyModifiers; var keyCode = KeyEvent["DOM_VK_"+key]; var fn = function fn(event) { if (event.keyCode == keyCode && (!filter || filter(event))) { listener(); FBL.cancelEvent(event, true); return false; } } addEvent(Firebug.chrome.document, "keydown", fn); return [fn, capture]; }; Firebug.chrome.keyIgnore = function(listener) { removeEvent(Firebug.chrome.document, "keydown", listener[0]); }; /**/ this.addController( [fbPanel1, "mousedown", onPanelMouseDown], [fbPanel2, "mousedown", onPanelMouseDown] ); /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // menus can be used without domplate if (FBL.domplate) this.testMenu(); /**/ //test XHR /* setTimeout(function(){ FBL.Ajax.request({url: "../content/firebug/boot.js"}); FBL.Ajax.request({url: "../content/firebug/boot.js.invalid"}); },1000); /**/ }, shutdown: function() { // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ if(Firebug.Inspector) this.inspectButton.shutdown(); // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // remove disableTextSelection event handlers restoreTextSelection($("fbToolbar")); restoreTextSelection($("fbPanelBarBox")); restoreTextSelection($("fbPanelBar1")); restoreTextSelection($("fbPanelBar2")); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // shutdown inherited classes Controller.shutdown.call(this); PanelBar.shutdown.call(this); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Remove the interface elements cache (this must happen after calling // the shutdown method of all dependent components to avoid errors) fbTop = null; fbContent = null; fbContentStyle = null; fbBottom = null; fbBtnInspect = null; fbToolbar = null; fbPanelBox1 = null; fbPanelBox1Style = null; fbPanelBox2 = null; fbPanelBox2Style = null; fbPanelBar2Box = null; fbPanelBar2BoxStyle = null; fbHSplitter = null; fbVSplitter = null; fbVSplitterStyle = null; fbPanel1 = null; fbPanel1Style = null; fbPanel2 = null; fbConsole = null; fbConsoleStyle = null; fbHTML = null; fbCommandLine = null; fbLargeCommandLine = null; fbLargeCommandButtons = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // static values cache topHeight = null; topPartialHeight = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * toggle: function(forceOpen, popup) { if(popup) { this.detach(); } else { if (isOpera && Firebug.chrome.type == "popup" && Firebug.chrome.node.closed) { var frame = FirebugChrome.chromeMap.frame; frame.reattach(); FirebugChrome.chromeMap.popup = null; frame.open(); return; } // If the context is a popup, ignores the toggle process if (Firebug.chrome.type == "popup") return; var shouldOpen = forceOpen || !Firebug.context.persistedState.isOpen; if(shouldOpen) this.open(); else this.close(); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * detach: function() { if(!FirebugChrome.chromeMap.popup) { this.close(); createChromeWindow({type: "popup"}); } }, reattach: function(oldChrome, newChrome) { Firebug.browser.window.Firebug = Firebug; // chrome synchronization var newPanelMap = newChrome.panelMap; var oldPanelMap = oldChrome.panelMap; var panel; for(var name in newPanelMap) { // TODO: xxxpedro innerHTML panel = newPanelMap[name]; if (panel.options.innerHTMLSync) panel.panelNode.innerHTML = oldPanelMap[name].panelNode.innerHTML; } Firebug.chrome = newChrome; // TODO: xxxpedro sync detach reattach attach //dispatch(Firebug.chrome.panelMap, "detach", [oldChrome, newChrome]); if (newChrome.type == "popup") { newChrome.initialize(); //dispatch(Firebug.modules, "initialize", []); } else { // TODO: xxxpedro only needed in persistent // should use FirebugChrome.clone, but popup FBChrome // isn't acessible Firebug.context.persistedState.selectedPanelName = oldChrome.selectedPanel.name; } dispatch(newPanelMap, "reattach", [oldChrome, newChrome]); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * draw: function() { var size = this.getSize(); // Height related values var commandLineHeight = Firebug.chrome.commandLineVisible ? fbCommandLine.offsetHeight : 0, y = Math.max(size.height /* chrome height */, topHeight), heightValue = Math.max(y - topHeight - commandLineHeight /* fixed height */, 0), height = heightValue + "px", // Width related values sideWidthValue = Firebug.chrome.sidePanelVisible ? Firebug.context.persistedState.sidePanelWidth : 0, width = Math.max(size.width /* chrome width */ - sideWidthValue, 0) + "px"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Height related rendering fbPanelBox1Style.height = height; fbPanel1Style.height = height; if (isIE || isOpera) { // Fix IE and Opera problems with auto resizing the verticall splitter fbVSplitterStyle.height = Math.max(y - topPartialHeight - commandLineHeight, 0) + "px"; } //xxxpedro FF2 only? /* else if (isFirefox) { // Fix Firefox problem with table rows with 100% height (fit height) fbContentStyle.maxHeight = Math.max(y - fixedHeight, 0)+ "px"; }/**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Width related rendering fbPanelBox1Style.width = width; fbPanel1Style.width = width; // SidePanel rendering if (Firebug.chrome.sidePanelVisible) { sideWidthValue = Math.max(sideWidthValue - 6, 0); var sideWidth = sideWidthValue + "px"; fbPanelBox2Style.width = sideWidth; fbVSplitterStyle.right = sideWidth; if (Firebug.chrome.largeCommandLineVisible) { fbLargeCommandLine = $("fbLargeCommandLine"); fbLargeCommandLine.style.height = heightValue - 4 + "px"; fbLargeCommandLine.style.width = sideWidthValue - 2 + "px"; fbLargeCommandButtons = $("fbLargeCommandButtons"); fbLargeCommandButtons.style.width = sideWidth; } else { fbPanel2Style.height = height; fbPanel2Style.width = sideWidth; fbPanelBar2BoxStyle.width = sideWidth; } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getSize: function() { return this.type == "div" ? { height: this.node.offsetHeight, width: this.node.offsetWidth } : this.getWindowSize(); }, resize: function() { var self = this; // avoid partial resize when maximizing window setTimeout(function(){ self.draw(); if (noFixedPosition && (self.type == "frame" || self.type == "div")) self.fixIEPosition(); }, 0); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * layout: function(panel) { if (FBTrace.DBG_CHROME) FBTrace.sysout("Chrome.layout", ""); var options = panel.options; changeCommandLineVisibility(options.hasCommandLine); changeSidePanelVisibility(panel.hasSidePanel); Firebug.chrome.draw(); }, showLargeCommandLine: function(hideToggleIcon) { var chrome = Firebug.chrome; if (!chrome.largeCommandLineVisible) { chrome.largeCommandLineVisible = true; if (chrome.selectedPanel.options.hasCommandLine) { if (Firebug.CommandLine) Firebug.CommandLine.blur(); changeCommandLineVisibility(false); } changeSidePanelVisibility(true); fbLargeCommandLine.style.display = "block"; fbLargeCommandButtons.style.display = "block"; fbPanel2Style.display = "none"; fbPanelBar2BoxStyle.display = "none"; chrome.draw(); fbLargeCommandLine.focus(); if (Firebug.CommandLine) Firebug.CommandLine.setMultiLine(true); } }, hideLargeCommandLine: function() { if (Firebug.chrome.largeCommandLineVisible) { Firebug.chrome.largeCommandLineVisible = false; if (Firebug.CommandLine) Firebug.CommandLine.setMultiLine(false); fbLargeCommandLine.blur(); fbPanel2Style.display = "block"; fbPanelBar2BoxStyle.display = "block"; fbLargeCommandLine.style.display = "none"; fbLargeCommandButtons.style.display = "none"; changeSidePanelVisibility(false); if (Firebug.chrome.selectedPanel.options.hasCommandLine) changeCommandLineVisibility(true); Firebug.chrome.draw(); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * focusCommandLine: function() { var selectedPanelName = this.selectedPanel.name, panelToSelect; if (focusCommandLineState == 0 || selectedPanelName != "Console") { focusCommandLineState = 0; lastFocusedPanelName = selectedPanelName; panelToSelect = "Console"; } if (focusCommandLineState == 1) { panelToSelect = lastFocusedPanelName; } this.selectPanel(panelToSelect); try { if (Firebug.CommandLine) { if (panelToSelect == "Console") Firebug.CommandLine.focus(); else Firebug.CommandLine.blur(); } } catch(e) { //TODO: xxxpedro trace error } focusCommandLineState = ++focusCommandLineState % 2; } }); // ************************************************************************************************ // ChromeFrameBase /** * @namespace * @extends ns-chrome-ChromeBase */ var ChromeFrameBase = extend(ChromeBase, /**@extend ns-chrome-ChromeFrameBase*/ { create: function() { ChromeBase.create.call(this); // restore display for the anti-flicker trick if (isFirefox) this.node.style.display = "block"; if (Env.Options.startInNewWindow) { this.close(); this.toggle(true, true); return; } if (Env.Options.startOpened) this.open(); else this.close(); }, destroy: function() { var size = Firebug.chrome.getWindowSize(); Firebug.context.persistedState.height = size.height; if (Firebug.saveCookies) Firebug.savePrefs(); removeGlobalEvent("keydown", onGlobalKeyDown); ChromeBase.destroy.call(this); this.document = null; delete this.document; this.window = null; delete this.window; this.node.parentNode.removeChild(this.node); this.node = null; delete this.node; }, initialize: function() { //FBTrace.sysout("Frame", "initialize();") ChromeBase.initialize.call(this); this.addController( [Firebug.browser.window, "resize", this.resize], [$("fbWindow_btClose"), "click", this.close], [$("fbWindow_btDetach"), "click", this.detach], [$("fbWindow_btDeactivate"), "click", this.deactivate] ); if (!Env.Options.enablePersistent) this.addController([Firebug.browser.window, "unload", Firebug.shutdown]); if (noFixedPosition) { this.addController( [Firebug.browser.window, "scroll", this.fixIEPosition] ); } fbVSplitter.onmousedown = onVSplitterMouseDown; fbHSplitter.onmousedown = onHSplitterMouseDown; this.isInitialized = true; }, shutdown: function() { fbVSplitter.onmousedown = null; fbHSplitter.onmousedown = null; ChromeBase.shutdown.apply(this); this.isInitialized = false; }, reattach: function() { var frame = FirebugChrome.chromeMap.frame; ChromeBase.reattach(FirebugChrome.chromeMap.popup, this); }, open: function() { if (!Firebug.context.persistedState.isOpen) { Firebug.context.persistedState.isOpen = true; if (Env.isChromeExtension) localStorage.setItem("Firebug", "1,1"); var node = this.node; node.style.visibility = "hidden"; // Avoid flickering if (Firebug.showIconWhenHidden) { if (ChromeMini.isInitialized) { ChromeMini.shutdown(); } } else node.style.display = "block"; var main = $("fbChrome"); // IE6 throws an error when setting this property! why? //main.style.display = "table"; main.style.display = ""; var self = this; /// TODO: xxxpedro FOUC node.style.visibility = "visible"; setTimeout(function(){ ///node.style.visibility = "visible"; //dispatch(Firebug.modules, "initialize", []); self.initialize(); if (noFixedPosition) self.fixIEPosition(); self.draw(); }, 10); } }, close: function() { if (Firebug.context.persistedState.isOpen) { if (this.isInitialized) { //dispatch(Firebug.modules, "shutdown", []); this.shutdown(); } Firebug.context.persistedState.isOpen = false; if (Env.isChromeExtension) localStorage.setItem("Firebug", "1,0"); var node = this.node; if (Firebug.showIconWhenHidden) { node.style.visibility = "hidden"; // Avoid flickering // TODO: xxxpedro - persist IE fixed? var main = $("fbChrome", FirebugChrome.chromeMap.frame.document); main.style.display = "none"; ChromeMini.initialize(); node.style.visibility = "visible"; } else node.style.display = "none"; } }, deactivate: function() { // if it is running as a Chrome extension, dispatch a message to the extension signaling // that Firebug should be deactivated for the current tab if (Env.isChromeExtension) { localStorage.removeItem("Firebug"); Firebug.GoogleChrome.dispatch("FB_deactivate"); // xxxpedro problem here regarding Chrome extension. We can't deactivate the whole // app, otherwise it won't be able to be reactivated without reloading the page. // but we need to stop listening global keys, otherwise the key activation won't work. Firebug.chrome.close(); } else { Firebug.shutdown(); } }, fixIEPosition: function() { // fix IE problem with offset when not in fullscreen mode var doc = this.document; var offset = isIE ? doc.body.clientTop || doc.documentElement.clientTop: 0; var size = Firebug.browser.getWindowSize(); var scroll = Firebug.browser.getWindowScrollPosition(); var maxHeight = size.height; var height = this.node.offsetHeight; var bodyStyle = doc.body.currentStyle; this.node.style.top = maxHeight - height + scroll.top + "px"; if ((this.type == "frame" || this.type == "div") && (bodyStyle.marginLeft || bodyStyle.marginRight)) { this.node.style.width = size.width + "px"; } if (fbVSplitterStyle) fbVSplitterStyle.right = Firebug.context.persistedState.sidePanelWidth + "px"; this.draw(); } }); // ************************************************************************************************ // ChromeMini /** * @namespace * @extends FBL.Controller */ var ChromeMini = extend(Controller, /**@extend ns-chrome-ChromeMini*/ { create: function(chrome) { append(this, chrome); this.type = "mini"; }, initialize: function() { Controller.initialize.apply(this); var doc = FirebugChrome.chromeMap.frame.document; var mini = $("fbMiniChrome", doc); mini.style.display = "block"; var miniIcon = $("fbMiniIcon", doc); var width = miniIcon.offsetWidth + 10; miniIcon.title = "Open " + Firebug.version; var errors = $("fbMiniErrors", doc); if (errors.offsetWidth) width += errors.offsetWidth + 10; var node = this.node; node.style.height = "27px"; node.style.width = width + "px"; node.style.left = ""; node.style.right = 0; if (this.node.nodeName.toLowerCase() == "iframe") { node.setAttribute("allowTransparency", "true"); this.document.body.style.backgroundColor = "transparent"; } else node.style.background = "transparent"; if (noFixedPosition) this.fixIEPosition(); this.addController( [$("fbMiniIcon", doc), "click", onMiniIconClick] ); if (noFixedPosition) { this.addController( [Firebug.browser.window, "scroll", this.fixIEPosition] ); } this.isInitialized = true; }, shutdown: function() { var node = this.node; node.style.height = Firebug.context.persistedState.height + "px"; node.style.width = "100%"; node.style.left = 0; node.style.right = ""; if (this.node.nodeName.toLowerCase() == "iframe") { node.setAttribute("allowTransparency", "false"); this.document.body.style.backgroundColor = "#fff"; } else node.style.background = "#fff"; if (noFixedPosition) this.fixIEPosition(); var doc = FirebugChrome.chromeMap.frame.document; var mini = $("fbMiniChrome", doc); mini.style.display = "none"; Controller.shutdown.apply(this); this.isInitialized = false; }, draw: function() { }, fixIEPosition: ChromeFrameBase.fixIEPosition }); // ************************************************************************************************ // ChromePopupBase /** * @namespace * @extends ns-chrome-ChromeBase */ var ChromePopupBase = extend(ChromeBase, /**@extend ns-chrome-ChromePopupBase*/ { initialize: function() { setClass(this.document.body, "FirebugPopup"); ChromeBase.initialize.call(this); this.addController( [Firebug.chrome.window, "resize", this.resize], [Firebug.chrome.window, "unload", this.destroy] //[Firebug.chrome.window, "beforeunload", this.destroy] ); if (Env.Options.enablePersistent) { this.persist = bind(this.persist, this); addEvent(Firebug.browser.window, "unload", this.persist); } else this.addController( [Firebug.browser.window, "unload", this.close] ); fbVSplitter.onmousedown = onVSplitterMouseDown; }, destroy: function() { var chromeWin = Firebug.chrome.window; var left = chromeWin.screenX || chromeWin.screenLeft; var top = chromeWin.screenY || chromeWin.screenTop; var size = Firebug.chrome.getWindowSize(); Firebug.context.persistedState.popupTop = top; Firebug.context.persistedState.popupLeft = left; Firebug.context.persistedState.popupWidth = size.width; Firebug.context.persistedState.popupHeight = size.height; if (Firebug.saveCookies) Firebug.savePrefs(); // TODO: xxxpedro sync detach reattach attach var frame = FirebugChrome.chromeMap.frame; if(frame) { dispatch(frame.panelMap, "detach", [this, frame]); frame.reattach(this, frame); } if (Env.Options.enablePersistent) { removeEvent(Firebug.browser.window, "unload", this.persist); } ChromeBase.destroy.apply(this); FirebugChrome.chromeMap.popup = null; this.node.close(); }, persist: function() { persistTimeStart = new Date().getTime(); removeEvent(Firebug.browser.window, "unload", this.persist); Firebug.Inspector.destroy(); Firebug.browser.window.FirebugOldBrowser = true; var persistTimeStart = new Date().getTime(); var waitMainWindow = function() { var doc, head; try { if (window.opener && !window.opener.FirebugOldBrowser && (doc = window.opener.document)/* && doc.documentElement && (head = doc.documentElement.firstChild)*/) { try { // exposes the FBL to the global namespace when in debug mode if (Env.isDebugMode) { window.FBL = FBL; } window.Firebug = Firebug; window.opener.Firebug = Firebug; Env.browser = window.opener; Firebug.browser = Firebug.context = new Context(Env.browser); Firebug.loadPrefs(); registerConsole(); // the delay time should be calculated right after registering the // console, once right after the console registration, call log messages // will be properly handled var persistDelay = new Date().getTime() - persistTimeStart; var chrome = Firebug.chrome; addEvent(Firebug.browser.window, "unload", chrome.persist); FBL.cacheDocument(); Firebug.Inspector.create(); Firebug.Console.logFormatted( ["Firebug could not capture console calls during " + persistDelay + "ms"], Firebug.context, "info" ); setTimeout(function(){ var htmlPanel = chrome.getPanel("HTML"); htmlPanel.createUI(); },50); } catch(pE) { alert("persist error: " + (pE.message || pE)); } } else { window.setTimeout(waitMainWindow, 0); } } catch (E) { window.close(); } }; waitMainWindow(); }, close: function() { this.destroy(); } }); //************************************************************************************************ // UI helpers var changeCommandLineVisibility = function changeCommandLineVisibility(visibility) { var last = Firebug.chrome.commandLineVisible; var visible = Firebug.chrome.commandLineVisible = typeof visibility == "boolean" ? visibility : !Firebug.chrome.commandLineVisible; if (visible != last) { if (visible) { fbBottom.className = ""; if (Firebug.CommandLine) Firebug.CommandLine.activate(); } else { if (Firebug.CommandLine) Firebug.CommandLine.deactivate(); fbBottom.className = "hide"; } } }; var changeSidePanelVisibility = function changeSidePanelVisibility(visibility) { var last = Firebug.chrome.sidePanelVisible; Firebug.chrome.sidePanelVisible = typeof visibility == "boolean" ? visibility : !Firebug.chrome.sidePanelVisible; if (Firebug.chrome.sidePanelVisible != last) { fbPanelBox2.className = Firebug.chrome.sidePanelVisible ? "" : "hide"; fbPanelBar2Box.className = Firebug.chrome.sidePanelVisible ? "" : "hide"; } }; // ************************************************************************************************ // F12 Handler var onGlobalKeyDown = function onGlobalKeyDown(event) { var keyCode = event.keyCode; var shiftKey = event.shiftKey; var ctrlKey = event.ctrlKey; if (keyCode == 123 /* F12 */ && (!isFirefox && !shiftKey || shiftKey && isFirefox)) { Firebug.chrome.toggle(false, ctrlKey); cancelEvent(event, true); // TODO: xxxpedro replace with a better solution. we're doing this // to allow reactivating with the F12 key after being deactivated if (Env.isChromeExtension) { Firebug.GoogleChrome.dispatch("FB_enableIcon"); } } else if (keyCode == 67 /* C */ && ctrlKey && shiftKey) { Firebug.Inspector.toggleInspect(); cancelEvent(event, true); } else if (keyCode == 76 /* L */ && ctrlKey && shiftKey) { Firebug.chrome.focusCommandLine(); cancelEvent(event, true); } }; var onMiniIconClick = function onMiniIconClick(event) { Firebug.chrome.toggle(false, event.ctrlKey); cancelEvent(event, true); }; // ************************************************************************************************ // Horizontal Splitter Handling var onHSplitterMouseDown = function onHSplitterMouseDown(event) { addGlobalEvent("mousemove", onHSplitterMouseMove); addGlobalEvent("mouseup", onHSplitterMouseUp); if (isIE) addEvent(Firebug.browser.document.documentElement, "mouseleave", onHSplitterMouseUp); fbHSplitter.className = "fbOnMovingHSplitter"; return false; }; var onHSplitterMouseMove = function onHSplitterMouseMove(event) { cancelEvent(event, true); var clientY = event.clientY; var win = isIE ? event.srcElement.ownerDocument.parentWindow : event.target.defaultView || event.target.ownerDocument && event.target.ownerDocument.defaultView; if (!win) return; if (win != win.parent) { var frameElement = win.frameElement; if (frameElement) { var framePos = Firebug.browser.getElementPosition(frameElement).top; clientY += framePos; if (frameElement.style.position != "fixed") clientY -= Firebug.browser.getWindowScrollPosition().top; } } if (isOpera && isQuiksMode && win.frameElement.id == "FirebugUI") { clientY = Firebug.browser.getWindowSize().height - win.frameElement.offsetHeight + clientY; } /* console.log( typeof win.FBL != "undefined" ? "no-Chrome" : "Chrome", //win.frameElement.id, event.target, clientY );/**/ onHSplitterMouseMoveBuffer = clientY; // buffer if (new Date().getTime() - lastHSplitterMouseMove > chromeRedrawSkipRate) // frame skipping { lastHSplitterMouseMove = new Date().getTime(); handleHSplitterMouseMove(); } else if (!onHSplitterMouseMoveTimer) onHSplitterMouseMoveTimer = setTimeout(handleHSplitterMouseMove, chromeRedrawSkipRate); // improving the resizing performance by canceling the mouse event. // canceling events will prevent the page to receive such events, which would imply // in more processing being expended. cancelEvent(event, true); return false; }; var handleHSplitterMouseMove = function() { if (onHSplitterMouseMoveTimer) { clearTimeout(onHSplitterMouseMoveTimer); onHSplitterMouseMoveTimer = null; } var clientY = onHSplitterMouseMoveBuffer; var windowSize = Firebug.browser.getWindowSize(); var scrollSize = Firebug.browser.getWindowScrollSize(); // compute chrome fixed size (top bar and command line) var commandLineHeight = Firebug.chrome.commandLineVisible ? fbCommandLine.offsetHeight : 0; var fixedHeight = topHeight + commandLineHeight; var chromeNode = Firebug.chrome.node; var scrollbarSize = !isIE && (scrollSize.width > windowSize.width) ? 17 : 0; //var height = !isOpera ? chromeNode.offsetTop + chromeNode.clientHeight : windowSize.height; var height = windowSize.height; // compute the min and max size of the chrome var chromeHeight = Math.max(height - clientY + 5 - scrollbarSize, fixedHeight); chromeHeight = Math.min(chromeHeight, windowSize.height - scrollbarSize); Firebug.context.persistedState.height = chromeHeight; chromeNode.style.height = chromeHeight + "px"; if (noFixedPosition) Firebug.chrome.fixIEPosition(); Firebug.chrome.draw(); }; var onHSplitterMouseUp = function onHSplitterMouseUp(event) { removeGlobalEvent("mousemove", onHSplitterMouseMove); removeGlobalEvent("mouseup", onHSplitterMouseUp); if (isIE) removeEvent(Firebug.browser.document.documentElement, "mouseleave", onHSplitterMouseUp); fbHSplitter.className = ""; Firebug.chrome.draw(); // avoid text selection in IE when returning to the document // after the mouse leaves the document during the resizing return false; }; // ************************************************************************************************ // Vertical Splitter Handling var onVSplitterMouseDown = function onVSplitterMouseDown(event) { addGlobalEvent("mousemove", onVSplitterMouseMove); addGlobalEvent("mouseup", onVSplitterMouseUp); return false; }; var onVSplitterMouseMove = function onVSplitterMouseMove(event) { if (new Date().getTime() - lastVSplitterMouseMove > chromeRedrawSkipRate) // frame skipping { var target = event.target || event.srcElement; if (target && target.ownerDocument) // avoid error when cursor reaches out of the chrome { var clientX = event.clientX; var win = document.all ? event.srcElement.ownerDocument.parentWindow : event.target.ownerDocument.defaultView; if (win != win.parent) clientX += win.frameElement ? win.frameElement.offsetLeft : 0; var size = Firebug.chrome.getSize(); var x = Math.max(size.width - clientX + 3, 6); Firebug.context.persistedState.sidePanelWidth = x; Firebug.chrome.draw(); } lastVSplitterMouseMove = new Date().getTime(); } cancelEvent(event, true); return false; }; var onVSplitterMouseUp = function onVSplitterMouseUp(event) { removeGlobalEvent("mousemove", onVSplitterMouseMove); removeGlobalEvent("mouseup", onVSplitterMouseUp); Firebug.chrome.draw(); }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite = { }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Cache = { ID: "firebug-" + new Date().getTime() }; // ************************************************************************************************ /** * TODO: if a cached element is cloned, the expando property will be cloned too in IE * which will result in a bug. Firebug Lite will think the new cloned node is the old * one. * * TODO: Investigate a possibility of cache validation, to be customized by each * kind of cache. For ElementCache it should validate if the element still is * inserted at the DOM. */ var cacheUID = 0; var createCache = function() { var map = {}; var data = {}; var CID = Firebug.Lite.Cache.ID; // better detection var supportsDeleteExpando = !document.all; var cacheFunction = function(element) { return cacheAPI.set(element); }; var cacheAPI = { get: function(key) { return map.hasOwnProperty(key) ? map[key] : null; }, set: function(element) { var id = getValidatedKey(element); if (!id) { id = ++cacheUID; element[CID] = id; } if (!map.hasOwnProperty(id)) { map[id] = element; data[id] = {}; } return id; }, unset: function(element) { var id = getValidatedKey(element); if (!id) return; if (supportsDeleteExpando) { delete element[CID]; } else if (element.removeAttribute) { element.removeAttribute(CID); } delete map[id]; delete data[id]; }, key: function(element) { return getValidatedKey(element); }, has: function(element) { var id = getValidatedKey(element); return id && map.hasOwnProperty(id); }, each: function(callback) { for (var key in map) { if (map.hasOwnProperty(key)) { callback(key, map[key]); } } }, data: function(element, name, value) { // set data if (value) { if (!name) return null; var id = cacheAPI.set(element); return data[id][name] = value; } // get data else { var id = cacheAPI.key(element); return data.hasOwnProperty(id) && data[id].hasOwnProperty(name) ? data[id][name] : null; } }, clear: function() { for (var id in map) { var element = map[id]; cacheAPI.unset(element); } } }; var getValidatedKey = function(element) { var id = element[CID]; // If a cached element is cloned in IE, the expando property CID will be also // cloned (differently than other browsers) resulting in a bug: Firebug Lite // will think the new cloned node is the old one. To prevent this problem we're // checking if the cached element matches the given element. if ( !supportsDeleteExpando && // the problem happens when supportsDeleteExpando is false id && // the element has the expando property map.hasOwnProperty(id) && // there is a cached element with the same id map[id] != element // but it is a different element than the current one ) { // remove the problematic property element.removeAttribute(CID); id = null; } return id; }; FBL.append(cacheFunction, cacheAPI); return cacheFunction; }; // ************************************************************************************************ // TODO: xxxpedro : check if we need really this on FBL scope Firebug.Lite.Cache.StyleSheet = createCache(); Firebug.Lite.Cache.Element = createCache(); // TODO: xxxpedro Firebug.Lite.Cache.Event = createCache(); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ var sourceMap = {}; // ************************************************************************************************ Firebug.Lite.Proxy = { // jsonp callbacks _callbacks: {}, /** * Load a resource, either locally (directly) or externally (via proxy) using * synchronous XHR calls. Loading external resources requires the proxy plugin to * be installed and configured (see /plugin/proxy/proxy.php). */ load: function(url) { var resourceDomain = getDomain(url); var isLocalResource = // empty domain means local URL !resourceDomain || // same domain means local too resourceDomain == Firebug.context.window.location.host; // TODO: xxxpedro context return isLocalResource ? fetchResource(url) : fetchProxyResource(url); }, /** * Load a resource using JSONP technique. */ loadJSONP: function(url, callback) { var script = createGlobalElement("script"), doc = Firebug.context.document, uid = "" + new Date().getTime(), callbackName = "callback=Firebug.Lite.Proxy._callbacks." + uid, jsonpURL = url.indexOf("?") != -1 ? url + "&" + callbackName : url + "?" + callbackName; Firebug.Lite.Proxy._callbacks[uid] = function(data) { if (callback) callback(data); script.parentNode.removeChild(script); delete Firebug.Lite.Proxy._callbacks[uid]; }; script.src = jsonpURL; if (doc.documentElement) doc.documentElement.appendChild(script); }, /** * Load a resource using YQL (not reliable). */ YQL: function(url, callback) { var yql = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) + "%22&format=xml"; this.loadJSONP(yql, function(data) { var source = data.results[0]; // clean up YQL bogus elements var match = /<body>\s+<p>([\s\S]+)<\/p>\s+<\/body>$/.exec(source); if (match) source = match[1]; console.log(source); }); } }; // ************************************************************************************************ Firebug.Lite.Proxy.fetchResourceDisabledMessage = "/* Firebug Lite resource fetching is disabled.\n" + "To enabled it set the Firebug Lite option \"disableResourceFetching\" to \"false\".\n" + "More info at http://getfirebug.com/firebuglite#Options */"; var fetchResource = function(url) { if (Firebug.disableResourceFetching) { var source = sourceMap[url] = Firebug.Lite.Proxy.fetchResourceDisabledMessage; return source; } if (sourceMap.hasOwnProperty(url)) return sourceMap[url]; // Getting the native XHR object so our calls won't be logged in the Console Panel var xhr = FBL.getNativeXHRObject(); xhr.open("get", url, false); xhr.send(); var source = sourceMap[url] = xhr.responseText; return source; }; var fetchProxyResource = function(url) { if (sourceMap.hasOwnProperty(url)) return sourceMap[url]; var proxyURL = Env.Location.baseDir + "plugin/proxy/proxy.php?url=" + encodeURIComponent(url); var response = fetchResource(proxyURL); try { var data = eval("(" + response + ")"); } catch(E) { return "ERROR: Firebug Lite Proxy plugin returned an invalid response."; } var source = data ? data.contents : ""; return source; }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Style = { }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Script = function(window) { this.fileName = null; this.isValid = null; this.baseLineNumber = null; this.lineExtent = null; this.tag = null; this.functionName = null; this.functionSource = null; }; Firebug.Lite.Script.prototype = { isLineExecutable: function(){}, pcToLine: function(){}, lineToPc: function(){}, toString: function() { return "Firebug.Lite.Script"; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ Firebug.Lite.Browser = function(window) { this.contentWindow = window; this.contentDocument = window.document; this.currentURI = { spec: window.location.href }; }; Firebug.Lite.Browser.prototype = { toString: function() { return "Firebug.Lite.Browser"; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ /* http://www.JSON.org/json2.js 2010-03-20 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. // ************************************************************************************************ var JSON = window.JSON || {}; // ************************************************************************************************ (function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } // ************************************************************************************************ // registration FBL.JSON = JSON; // ************************************************************************************************ }()); /* See license.txt for terms of usage */ (function(){ // ************************************************************************************************ /* Copyright (c) 2010-2011 Marcus Westin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var store = (function(){ var api = {}, win = window, doc = win.document, localStorageName = 'localStorage', globalStorageName = 'globalStorage', namespace = '__firebug__storejs__', storage api.disabled = false api.set = function(key, value) {} api.get = function(key) {} api.remove = function(key) {} api.clear = function() {} api.transact = function(key, transactionFn) { var val = api.get(key) if (typeof val == 'undefined') { val = {} } transactionFn(val) api.set(key, val) } api.serialize = function(value) { return JSON.stringify(value) } api.deserialize = function(value) { if (typeof value != 'string') { return undefined } return JSON.parse(value) } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } function isGlobalStorageNameSupported() { try { return (globalStorageName in win && win[globalStorageName] && win[globalStorageName][win.location.hostname]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] api.set = function(key, val) { storage.setItem(key, api.serialize(val)) } api.get = function(key) { return api.deserialize(storage.getItem(key)) } api.remove = function(key) { storage.removeItem(key) } api.clear = function() { storage.clear() } } else if (isGlobalStorageNameSupported()) { storage = win[globalStorageName][win.location.hostname] api.set = function(key, val) { storage[key] = api.serialize(val) } api.get = function(key) { return api.deserialize(storage[key] && storage[key].value) } api.remove = function(key) { delete storage[key] } api.clear = function() { for (var key in storage ) { delete storage[key] } } } else if (doc.documentElement.addBehavior) { var storage = doc.createElement('div') function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx // TODO: xxxpedro doc.body is not always available so we must use doc.documentElement. // We need to make sure this change won't affect the behavior of this library. doc.documentElement.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(api, args) doc.documentElement.removeChild(storage) return result } } api.set = withIEStorage(function(storage, key, val) { storage.setAttribute(key, api.serialize(val)) storage.save(localStorageName) }) api.get = withIEStorage(function(storage, key) { return api.deserialize(storage.getAttribute(key)) }) api.remove = withIEStorage(function(storage, key) { storage.removeAttribute(key) storage.save(localStorageName) }) api.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr = attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) } try { api.set(namespace, namespace) if (api.get(namespace) != namespace) { api.disabled = true } api.remove(namespace) } catch(e) { api.disabled = true } return api })(); if (typeof module != 'undefined') { module.exports = store } // ************************************************************************************************ // registration FBL.Store = store; // ************************************************************************************************ })(); /* See license.txt for terms of usage */ FBL.ns( /**@scope s_selector*/ function() { with (FBL) { // ************************************************************************************************ /* * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); /** * @name Firebug.Selector * @namespace */ /** * @exports Sizzle as Firebug.Selector */ var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) selector += parts.shift(); set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { throw "Syntax error, unrecognized expression: " + (cur || selector); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.match[ type ].exec( expr )) != null ) { var filter = Expr.filter[ type ], found, item; anyFound = false; if ( curLoop == result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr == old ) { if ( anyFound == null ) { throw "Syntax error, unrecognized expression: " + expr; } else { break; } } old = expr; } return curLoop; }; /**#@+ @ignore */ var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part, isXML){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag && !isXML ) { part = part.toUpperCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part, isXML){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = isXML ? part : part.toUpperCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( !/\W/.test(part) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = isXML ? part : part.toUpperCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context, isXML){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) { if ( !inplace ) result.push( elem ); } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ for ( var i = 0; curLoop[i] === false; i++ ){} return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); }, CHILD: function(match){ if ( match[1] == "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 == i; }, eq: function(elem, i, match){ return match[3] - 0 == i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) return false; } if ( type == 'first') return true; node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) return false; } return true; case 'nth': var first = match[2], last = match[3]; if ( first == 1 && last == 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first == 0 ) { return diff == 0; } else { return ( diff % first == 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value != check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source ); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. try { Array.prototype.slice.call( document.documentElement.childNodes, 0 ); // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return 0; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return 0; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return 0; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date).getTime(); form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly var root = document.documentElement; root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( !!document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); root = form = null; // release memory in IE })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; } div = null; // release memory in IE })(); if ( document.querySelectorAll ) (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) if ( div.getElementsByClassName("e").length === 0 ) return; // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) return; Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ){ elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { var sibDir = dir == "previousSibling" && !isXML; for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { if ( sibDir && elem.nodeType === 1 ) { elem.sizcache = doneName; elem.sizset = i; } elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ return a.compareDocumentPosition(b) & 16; } : function(a, b){ return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML"; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE Firebug.Selector = Sizzle; /**#@-*/ // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Inspector Module var ElementCache = Firebug.Lite.Cache.Element; var inspectorTS, inspectorTimer, isInspecting; Firebug.Inspector = { create: function() { offlineFragment = Env.browser.document.createDocumentFragment(); createBoxModelInspector(); createOutlineInspector(); }, destroy: function() { destroyBoxModelInspector(); destroyOutlineInspector(); offlineFragment = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Inspect functions toggleInspect: function() { if (isInspecting) { this.stopInspecting(); } else { Firebug.chrome.inspectButton.changeState("pressed"); this.startInspecting(); } }, startInspecting: function() { isInspecting = true; Firebug.chrome.selectPanel("HTML"); createInspectorFrame(); var size = Firebug.browser.getWindowScrollSize(); fbInspectFrame.style.width = size.width + "px"; fbInspectFrame.style.height = size.height + "px"; //addEvent(Firebug.browser.document.documentElement, "mousemove", Firebug.Inspector.onInspectingBody); addEvent(fbInspectFrame, "mousemove", Firebug.Inspector.onInspecting); addEvent(fbInspectFrame, "mousedown", Firebug.Inspector.onInspectingClick); }, stopInspecting: function() { isInspecting = false; if (outlineVisible) this.hideOutline(); removeEvent(fbInspectFrame, "mousemove", Firebug.Inspector.onInspecting); removeEvent(fbInspectFrame, "mousedown", Firebug.Inspector.onInspectingClick); destroyInspectorFrame(); Firebug.chrome.inspectButton.restore(); if (Firebug.chrome.type == "popup") Firebug.chrome.node.focus(); }, onInspectingClick: function(e) { fbInspectFrame.style.display = "none"; var targ = Firebug.browser.getElementFromPoint(e.clientX, e.clientY); fbInspectFrame.style.display = "block"; // Avoid inspecting the outline, and the FirebugUI var id = targ.id; if (id && /^fbOutline\w$/.test(id)) return; if (id == "FirebugUI") return; // Avoid looking at text nodes in Opera while (targ.nodeType != 1) targ = targ.parentNode; //Firebug.Console.log(targ); Firebug.Inspector.stopInspecting(); }, onInspecting: function(e) { if (new Date().getTime() - lastInspecting > 30) { fbInspectFrame.style.display = "none"; var targ = Firebug.browser.getElementFromPoint(e.clientX, e.clientY); fbInspectFrame.style.display = "block"; // Avoid inspecting the outline, and the FirebugUI var id = targ.id; if (id && /^fbOutline\w$/.test(id)) return; if (id == "FirebugUI") return; // Avoid looking at text nodes in Opera while (targ.nodeType != 1) targ = targ.parentNode; if (targ.nodeName.toLowerCase() == "body") return; //Firebug.Console.log(e.clientX, e.clientY, targ); Firebug.Inspector.drawOutline(targ); if (ElementCache(targ)) { var target = ""+ElementCache.key(targ); var lazySelect = function() { inspectorTS = new Date().getTime(); if (Firebug.HTML) Firebug.HTML.selectTreeNode(""+ElementCache.key(targ)); }; if (inspectorTimer) { clearTimeout(inspectorTimer); inspectorTimer = null; } if (new Date().getTime() - inspectorTS > 200) setTimeout(lazySelect, 0); else inspectorTimer = setTimeout(lazySelect, 300); } lastInspecting = new Date().getTime(); } }, // TODO: xxxpedro remove this? onInspectingBody: function(e) { if (new Date().getTime() - lastInspecting > 30) { var targ = e.target; // Avoid inspecting the outline, and the FirebugUI var id = targ.id; if (id && /^fbOutline\w$/.test(id)) return; if (id == "FirebugUI") return; // Avoid looking at text nodes in Opera while (targ.nodeType != 1) targ = targ.parentNode; if (targ.nodeName.toLowerCase() == "body") return; //Firebug.Console.log(e.clientX, e.clientY, targ); Firebug.Inspector.drawOutline(targ); if (ElementCache.has(targ)) FBL.Firebug.HTML.selectTreeNode(""+ElementCache.key(targ)); lastInspecting = new Date().getTime(); } }, /** * * llttttttrr * llttttttrr * ll rr * ll rr * llbbbbbbrr * llbbbbbbrr */ drawOutline: function(el) { var border = 2; var scrollbarSize = 17; var windowSize = Firebug.browser.getWindowSize(); var scrollSize = Firebug.browser.getWindowScrollSize(); var scrollPosition = Firebug.browser.getWindowScrollPosition(); var box = Firebug.browser.getElementBox(el); var top = box.top; var left = box.left; var height = box.height; var width = box.width; var freeHorizontalSpace = scrollPosition.left + windowSize.width - left - width - (!isIE && scrollSize.height > windowSize.height ? // is *vertical* scrollbar visible scrollbarSize : 0); var freeVerticalSpace = scrollPosition.top + windowSize.height - top - height - (!isIE && scrollSize.width > windowSize.width ? // is *horizontal* scrollbar visible scrollbarSize : 0); var numVerticalBorders = freeVerticalSpace > 0 ? 2 : 1; var o = outlineElements; var style; style = o.fbOutlineT.style; style.top = top-border + "px"; style.left = left + "px"; style.height = border + "px"; // TODO: on initialize() style.width = width + "px"; style = o.fbOutlineL.style; style.top = top-border + "px"; style.left = left-border + "px"; style.height = height+ numVerticalBorders*border + "px"; style.width = border + "px"; // TODO: on initialize() style = o.fbOutlineB.style; if (freeVerticalSpace > 0) { style.top = top+height + "px"; style.left = left + "px"; style.width = width + "px"; //style.height = border + "px"; // TODO: on initialize() or worst case? } else { style.top = -2*border + "px"; style.left = -2*border + "px"; style.width = border + "px"; //style.height = border + "px"; } style = o.fbOutlineR.style; if (freeHorizontalSpace > 0) { style.top = top-border + "px"; style.left = left+width + "px"; style.height = height + numVerticalBorders*border + "px"; style.width = (freeHorizontalSpace < border ? freeHorizontalSpace : border) + "px"; } else { style.top = -2*border + "px"; style.left = -2*border + "px"; style.height = border + "px"; style.width = border + "px"; } if (!outlineVisible) this.showOutline(); }, hideOutline: function() { if (!outlineVisible) return; for (var name in outline) offlineFragment.appendChild(outlineElements[name]); outlineVisible = false; }, showOutline: function() { if (outlineVisible) return; if (boxModelVisible) this.hideBoxModel(); for (var name in outline) Firebug.browser.document.getElementsByTagName("body")[0].appendChild(outlineElements[name]); outlineVisible = true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Box Model drawBoxModel: function(el) { // avoid error when the element is not attached a document if (!el || !el.parentNode) return; var box = Firebug.browser.getElementBox(el); var windowSize = Firebug.browser.getWindowSize(); var scrollPosition = Firebug.browser.getWindowScrollPosition(); // element may be occluded by the chrome, when in frame mode var offsetHeight = Firebug.chrome.type == "frame" ? Firebug.context.persistedState.height : 0; // if element box is not inside the viewport, don't draw the box model if (box.top > scrollPosition.top + windowSize.height - offsetHeight || box.left > scrollPosition.left + windowSize.width || scrollPosition.top > box.top + box.height || scrollPosition.left > box.left + box.width ) return; var top = box.top; var left = box.left; var height = box.height; var width = box.width; var margin = Firebug.browser.getMeasurementBox(el, "margin"); var padding = Firebug.browser.getMeasurementBox(el, "padding"); var border = Firebug.browser.getMeasurementBox(el, "border"); boxModelStyle.top = top - margin.top + "px"; boxModelStyle.left = left - margin.left + "px"; boxModelStyle.height = height + margin.top + margin.bottom + "px"; boxModelStyle.width = width + margin.left + margin.right + "px"; boxBorderStyle.top = margin.top + "px"; boxBorderStyle.left = margin.left + "px"; boxBorderStyle.height = height + "px"; boxBorderStyle.width = width + "px"; boxPaddingStyle.top = margin.top + border.top + "px"; boxPaddingStyle.left = margin.left + border.left + "px"; boxPaddingStyle.height = height - border.top - border.bottom + "px"; boxPaddingStyle.width = width - border.left - border.right + "px"; boxContentStyle.top = margin.top + border.top + padding.top + "px"; boxContentStyle.left = margin.left + border.left + padding.left + "px"; boxContentStyle.height = height - border.top - padding.top - padding.bottom - border.bottom + "px"; boxContentStyle.width = width - border.left - padding.left - padding.right - border.right + "px"; if (!boxModelVisible) this.showBoxModel(); }, hideBoxModel: function() { if (!boxModelVisible) return; offlineFragment.appendChild(boxModel); boxModelVisible = false; }, showBoxModel: function() { if (boxModelVisible) return; if (outlineVisible) this.hideOutline(); Firebug.browser.document.getElementsByTagName("body")[0].appendChild(boxModel); boxModelVisible = true; } }; // ************************************************************************************************ // Inspector Internals // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Shared variables // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Internal variables var offlineFragment = null; var boxModelVisible = false; var boxModel, boxModelStyle, boxMargin, boxMarginStyle, boxBorder, boxBorderStyle, boxPadding, boxPaddingStyle, boxContent, boxContentStyle; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var resetStyle = "margin:0; padding:0; border:0; position:absolute; overflow:hidden; display:block;"; var offscreenStyle = resetStyle + "top:-1234px; left:-1234px;"; var inspectStyle = resetStyle + "z-index: 2147483500;"; var inspectFrameStyle = resetStyle + "z-index: 2147483550; top:0; left:0; background:url(" + Env.Location.skinDir + "pixel_transparent.gif);"; //if (Env.Options.enableTrace) inspectFrameStyle = resetStyle + "z-index: 2147483550; top: 0; left: 0; background: #ff0; opacity: 0.05; _filter: alpha(opacity=5);"; var inspectModelOpacity = isIE ? "filter:alpha(opacity=80);" : "opacity:0.8;"; var inspectModelStyle = inspectStyle + inspectModelOpacity; var inspectMarginStyle = inspectStyle + "background: #EDFF64; height:100%; width:100%;"; var inspectBorderStyle = inspectStyle + "background: #666;"; var inspectPaddingStyle = inspectStyle + "background: SlateBlue;"; var inspectContentStyle = inspectStyle + "background: SkyBlue;"; var outlineStyle = { fbHorizontalLine: "background: #3875D7;height: 2px;", fbVerticalLine: "background: #3875D7;width: 2px;" }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var lastInspecting = 0; var fbInspectFrame = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var outlineVisible = false; var outlineElements = {}; var outline = { "fbOutlineT": "fbHorizontalLine", "fbOutlineL": "fbVerticalLine", "fbOutlineB": "fbHorizontalLine", "fbOutlineR": "fbVerticalLine" }; var getInspectingTarget = function() { }; // ************************************************************************************************ // Section var createInspectorFrame = function createInspectorFrame() { fbInspectFrame = createGlobalElement("div"); fbInspectFrame.id = "fbInspectFrame"; fbInspectFrame.firebugIgnore = true; fbInspectFrame.style.cssText = inspectFrameStyle; Firebug.browser.document.getElementsByTagName("body")[0].appendChild(fbInspectFrame); }; var destroyInspectorFrame = function destroyInspectorFrame() { if (fbInspectFrame) { Firebug.browser.document.getElementsByTagName("body")[0].removeChild(fbInspectFrame); fbInspectFrame = null; } }; var createOutlineInspector = function createOutlineInspector() { for (var name in outline) { var el = outlineElements[name] = createGlobalElement("div"); el.id = name; el.firebugIgnore = true; el.style.cssText = inspectStyle + outlineStyle[outline[name]]; offlineFragment.appendChild(el); } }; var destroyOutlineInspector = function destroyOutlineInspector() { for (var name in outline) { var el = outlineElements[name]; el.parentNode.removeChild(el); } }; var createBoxModelInspector = function createBoxModelInspector() { boxModel = createGlobalElement("div"); boxModel.id = "fbBoxModel"; boxModel.firebugIgnore = true; boxModelStyle = boxModel.style; boxModelStyle.cssText = inspectModelStyle; boxMargin = createGlobalElement("div"); boxMargin.id = "fbBoxMargin"; boxMarginStyle = boxMargin.style; boxMarginStyle.cssText = inspectMarginStyle; boxModel.appendChild(boxMargin); boxBorder = createGlobalElement("div"); boxBorder.id = "fbBoxBorder"; boxBorderStyle = boxBorder.style; boxBorderStyle.cssText = inspectBorderStyle; boxModel.appendChild(boxBorder); boxPadding = createGlobalElement("div"); boxPadding.id = "fbBoxPadding"; boxPaddingStyle = boxPadding.style; boxPaddingStyle.cssText = inspectPaddingStyle; boxModel.appendChild(boxPadding); boxContent = createGlobalElement("div"); boxContent.id = "fbBoxContent"; boxContentStyle = boxContent.style; boxContentStyle.cssText = inspectContentStyle; boxModel.appendChild(boxContent); offlineFragment.appendChild(boxModel); }; var destroyBoxModelInspector = function destroyBoxModelInspector() { boxModel.parentNode.removeChild(boxModel); }; // ************************************************************************************************ // Section // ************************************************************************************************ }}); // Problems in IE // FIXED - eval return // FIXED - addEventListener problem in IE // FIXED doc.createRange? // // class reserved word // test all honza examples in IE6 and IE7 /* See license.txt for terms of usage */ ( /** @scope s_domplate */ function() { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** @class */ FBL.DomplateTag = function DomplateTag(tagName) { this.tagName = tagName; }; /** * @class * @extends FBL.DomplateTag */ FBL.DomplateEmbed = function DomplateEmbed() { }; /** * @class * @extends FBL.DomplateTag */ FBL.DomplateLoop = function DomplateLoop() { }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var DomplateTag = FBL.DomplateTag; var DomplateEmbed = FBL.DomplateEmbed; var DomplateLoop = FBL.DomplateLoop; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var womb = null; FBL.domplate = function() { var lastSubject; for (var i = 0; i < arguments.length; ++i) lastSubject = lastSubject ? copyObject(lastSubject, arguments[i]) : arguments[i]; for (var name in lastSubject) { var val = lastSubject[name]; if (isTag(val)) val.tag.subject = lastSubject; } return lastSubject; }; var domplate = FBL.domplate; FBL.domplate.context = function(context, fn) { var lastContext = domplate.lastContext; domplate.topContext = context; fn.apply(context); domplate.topContext = lastContext; }; FBL.TAG = function() { var embed = new DomplateEmbed(); return embed.merge(arguments); }; FBL.FOR = function() { var loop = new DomplateLoop(); return loop.merge(arguments); }; FBL.DomplateTag.prototype = { merge: function(args, oldTag) { if (oldTag) this.tagName = oldTag.tagName; this.context = oldTag ? oldTag.context : null; this.subject = oldTag ? oldTag.subject : null; this.attrs = oldTag ? copyObject(oldTag.attrs) : {}; this.classes = oldTag ? copyObject(oldTag.classes) : {}; this.props = oldTag ? copyObject(oldTag.props) : null; this.listeners = oldTag ? copyArray(oldTag.listeners) : null; this.children = oldTag ? copyArray(oldTag.children) : []; this.vars = oldTag ? copyArray(oldTag.vars) : []; var attrs = args.length ? args[0] : null; var hasAttrs = typeof(attrs) == "object" && !isTag(attrs); this.children = []; if (domplate.topContext) this.context = domplate.topContext; if (args.length) parseChildren(args, hasAttrs ? 1 : 0, this.vars, this.children); if (hasAttrs) this.parseAttrs(attrs); return creator(this, DomplateTag); }, parseAttrs: function(args) { for (var name in args) { var val = parseValue(args[name]); readPartNames(val, this.vars); if (name.indexOf("on") == 0) { var eventName = name.substr(2); if (!this.listeners) this.listeners = []; this.listeners.push(eventName, val); } else if (name.indexOf("_") == 0) { var propName = name.substr(1); if (!this.props) this.props = {}; this.props[propName] = val; } else if (name.indexOf("$") == 0) { var className = name.substr(1); if (!this.classes) this.classes = {}; this.classes[className] = val; } else { if (name == "class" && this.attrs.hasOwnProperty(name) ) this.attrs[name] += " " + val; else this.attrs[name] = val; } } }, compile: function() { if (this.renderMarkup) return; this.compileMarkup(); this.compileDOM(); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate renderMarkup: ", this.renderMarkup); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate renderDOM:", this.renderDOM); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate domArgs:", this.domArgs); }, compileMarkup: function() { this.markupArgs = []; var topBlock = [], topOuts = [], blocks = [], info = {args: this.markupArgs, argIndex: 0}; this.generateMarkup(topBlock, topOuts, blocks, info); this.addCode(topBlock, topOuts, blocks); var fnBlock = ['r=(function (__code__, __context__, __in__, __out__']; for (var i = 0; i < info.argIndex; ++i) fnBlock.push(', s', i); fnBlock.push(') {'); if (this.subject) fnBlock.push('with (this) {'); if (this.context) fnBlock.push('with (__context__) {'); fnBlock.push('with (__in__) {'); fnBlock.push.apply(fnBlock, blocks); if (this.subject) fnBlock.push('}'); if (this.context) fnBlock.push('}'); fnBlock.push('}})'); function __link__(tag, code, outputs, args) { if (!tag || !tag.tag) return; tag.tag.compile(); var tagOutputs = []; var markupArgs = [code, tag.tag.context, args, tagOutputs]; markupArgs.push.apply(markupArgs, tag.tag.markupArgs); tag.tag.renderMarkup.apply(tag.tag.subject, markupArgs); outputs.push(tag); outputs.push(tagOutputs); } function __escape__(value) { function replaceChars(ch) { switch (ch) { case "<": return "&lt;"; case ">": return "&gt;"; case "&": return "&amp;"; case "'": return "&#39;"; case '"': return "&quot;"; } return "?"; }; return String(value).replace(/[<>&"']/g, replaceChars); } function __loop__(iter, outputs, fn) { var iterOuts = []; outputs.push(iterOuts); if (iter instanceof Array) iter = new ArrayIterator(iter); try { while (1) { var value = iter.next(); var itemOuts = [0,0]; iterOuts.push(itemOuts); fn.apply(this, [value, itemOuts]); } } catch (exc) { if (exc != StopIteration) throw exc; } } var js = fnBlock.join(""); var r = null; eval(js); this.renderMarkup = r; }, getVarNames: function(args) { if (this.vars) args.push.apply(args, this.vars); for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (isTag(child)) child.tag.getVarNames(args); else if (child instanceof Parts) { for (var i = 0; i < child.parts.length; ++i) { if (child.parts[i] instanceof Variable) { var name = child.parts[i].name; var names = name.split("."); args.push(names[0]); } } } } }, generateMarkup: function(topBlock, topOuts, blocks, info) { topBlock.push(',"<', this.tagName, '"'); for (var name in this.attrs) { if (name != "class") { var val = this.attrs[name]; topBlock.push(', " ', name, '=\\""'); addParts(val, ',', topBlock, info, true); topBlock.push(', "\\""'); } } if (this.listeners) { for (var i = 0; i < this.listeners.length; i += 2) readPartNames(this.listeners[i+1], topOuts); } if (this.props) { for (var name in this.props) readPartNames(this.props[name], topOuts); } if ( this.attrs.hasOwnProperty("class") || this.classes) { topBlock.push(', " class=\\""'); if (this.attrs.hasOwnProperty("class")) addParts(this.attrs["class"], ',', topBlock, info, true); topBlock.push(', " "'); for (var name in this.classes) { topBlock.push(', ('); addParts(this.classes[name], '', topBlock, info); topBlock.push(' ? "', name, '" + " " : "")'); } topBlock.push(', "\\""'); } topBlock.push(',">"'); this.generateChildMarkup(topBlock, topOuts, blocks, info); topBlock.push(',"</', this.tagName, '>"'); }, generateChildMarkup: function(topBlock, topOuts, blocks, info) { for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (isTag(child)) child.tag.generateMarkup(topBlock, topOuts, blocks, info); else addParts(child, ',', topBlock, info, true); } }, addCode: function(topBlock, topOuts, blocks) { if (topBlock.length) blocks.push('__code__.push(""', topBlock.join(""), ');'); if (topOuts.length) blocks.push('__out__.push(', topOuts.join(","), ');'); topBlock.splice(0, topBlock.length); topOuts.splice(0, topOuts.length); }, addLocals: function(blocks) { var varNames = []; this.getVarNames(varNames); var map = {}; for (var i = 0; i < varNames.length; ++i) { var name = varNames[i]; if ( map.hasOwnProperty(name) ) continue; map[name] = 1; var names = name.split("."); blocks.push('var ', names[0] + ' = ' + '__in__.' + names[0] + ';'); } }, compileDOM: function() { var path = []; var blocks = []; this.domArgs = []; path.embedIndex = 0; path.loopIndex = 0; path.staticIndex = 0; path.renderIndex = 0; var nodeCount = this.generateDOM(path, blocks, this.domArgs); var fnBlock = ['r=(function (root, context, o']; for (var i = 0; i < path.staticIndex; ++i) fnBlock.push(', ', 's'+i); for (var i = 0; i < path.renderIndex; ++i) fnBlock.push(', ', 'd'+i); fnBlock.push(') {'); for (var i = 0; i < path.loopIndex; ++i) fnBlock.push('var l', i, ' = 0;'); for (var i = 0; i < path.embedIndex; ++i) fnBlock.push('var e', i, ' = 0;'); if (this.subject) fnBlock.push('with (this) {'); if (this.context) fnBlock.push('with (context) {'); fnBlock.push(blocks.join("")); if (this.subject) fnBlock.push('}'); if (this.context) fnBlock.push('}'); fnBlock.push('return ', nodeCount, ';'); fnBlock.push('})'); function __bind__(object, fn) { return function(event) { return fn.apply(object, [event]); }; } function __link__(node, tag, args) { if (!tag || !tag.tag) return; tag.tag.compile(); var domArgs = [node, tag.tag.context, 0]; domArgs.push.apply(domArgs, tag.tag.domArgs); domArgs.push.apply(domArgs, args); //if (FBTrace.DBG_DOM) FBTrace.dumpProperties("domplate__link__ domArgs:", domArgs); return tag.tag.renderDOM.apply(tag.tag.subject, domArgs); } var self = this; function __loop__(iter, fn) { var nodeCount = 0; for (var i = 0; i < iter.length; ++i) { iter[i][0] = i; iter[i][1] = nodeCount; nodeCount += fn.apply(this, iter[i]); //if (FBTrace.DBG_DOM) FBTrace.sysout("nodeCount", nodeCount); } return nodeCount; } function __path__(parent, offset) { //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate __path__ offset: "+ offset+"\n"); var root = parent; for (var i = 2; i < arguments.length; ++i) { var index = arguments[i]; if (i == 3) index += offset; if (index == -1) parent = parent.parentNode; else parent = parent.childNodes[index]; } //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate: "+arguments[2]+", root: "+ root+", parent: "+ parent+"\n"); return parent; } var js = fnBlock.join(""); //if (FBTrace.DBG_DOM) FBTrace.sysout(js.replace(/(\;|\{)/g, "$1\n")); var r = null; eval(js); this.renderDOM = r; }, generateDOM: function(path, blocks, args) { if (this.listeners || this.props) this.generateNodePath(path, blocks); if (this.listeners) { for (var i = 0; i < this.listeners.length; i += 2) { var val = this.listeners[i+1]; var arg = generateArg(val, path, args); //blocks.push('node.addEventListener("', this.listeners[i], '", __bind__(this, ', arg, '), false);'); blocks.push('addEvent(node, "', this.listeners[i], '", __bind__(this, ', arg, '), false);'); } } if (this.props) { for (var name in this.props) { var val = this.props[name]; var arg = generateArg(val, path, args); blocks.push('node.', name, ' = ', arg, ';'); } } this.generateChildDOM(path, blocks, args); return 1; }, generateNodePath: function(path, blocks) { blocks.push("var node = __path__(root, o"); for (var i = 0; i < path.length; ++i) blocks.push(",", path[i]); blocks.push(");"); }, generateChildDOM: function(path, blocks, args) { path.push(0); for (var i = 0; i < this.children.length; ++i) { var child = this.children[i]; if (isTag(child)) path[path.length-1] += '+' + child.tag.generateDOM(path, blocks, args); else path[path.length-1] += '+1'; } path.pop(); } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * FBL.DomplateEmbed.prototype = copyObject(FBL.DomplateTag.prototype, /** @lends FBL.DomplateEmbed.prototype */ { merge: function(args, oldTag) { this.value = oldTag ? oldTag.value : parseValue(args[0]); this.attrs = oldTag ? oldTag.attrs : {}; this.vars = oldTag ? copyArray(oldTag.vars) : []; var attrs = args[1]; for (var name in attrs) { var val = parseValue(attrs[name]); this.attrs[name] = val; readPartNames(val, this.vars); } return creator(this, DomplateEmbed); }, getVarNames: function(names) { if (this.value instanceof Parts) names.push(this.value.parts[0].name); if (this.vars) names.push.apply(names, this.vars); }, generateMarkup: function(topBlock, topOuts, blocks, info) { this.addCode(topBlock, topOuts, blocks); blocks.push('__link__('); addParts(this.value, '', blocks, info); blocks.push(', __code__, __out__, {'); var lastName = null; for (var name in this.attrs) { if (lastName) blocks.push(','); lastName = name; var val = this.attrs[name]; blocks.push('"', name, '":'); addParts(val, '', blocks, info); } blocks.push('});'); //this.generateChildMarkup(topBlock, topOuts, blocks, info); }, generateDOM: function(path, blocks, args) { var embedName = 'e'+path.embedIndex++; this.generateNodePath(path, blocks); var valueName = 'd' + path.renderIndex++; var argsName = 'd' + path.renderIndex++; blocks.push(embedName + ' = __link__(node, ', valueName, ', ', argsName, ');'); return embedName; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * FBL.DomplateLoop.prototype = copyObject(FBL.DomplateTag.prototype, /** @lends FBL.DomplateLoop.prototype */ { merge: function(args, oldTag) { this.varName = oldTag ? oldTag.varName : args[0]; this.iter = oldTag ? oldTag.iter : parseValue(args[1]); this.vars = []; this.children = oldTag ? copyArray(oldTag.children) : []; var offset = Math.min(args.length, 2); parseChildren(args, offset, this.vars, this.children); return creator(this, DomplateLoop); }, getVarNames: function(names) { if (this.iter instanceof Parts) names.push(this.iter.parts[0].name); DomplateTag.prototype.getVarNames.apply(this, [names]); }, generateMarkup: function(topBlock, topOuts, blocks, info) { this.addCode(topBlock, topOuts, blocks); var iterName; if (this.iter instanceof Parts) { var part = this.iter.parts[0]; iterName = part.name; if (part.format) { for (var i = 0; i < part.format.length; ++i) iterName = part.format[i] + "(" + iterName + ")"; } } else iterName = this.iter; blocks.push('__loop__.apply(this, [', iterName, ', __out__, function(', this.varName, ', __out__) {'); this.generateChildMarkup(topBlock, topOuts, blocks, info); this.addCode(topBlock, topOuts, blocks); blocks.push('}]);'); }, generateDOM: function(path, blocks, args) { var iterName = 'd'+path.renderIndex++; var counterName = 'i'+path.loopIndex; var loopName = 'l'+path.loopIndex++; if (!path.length) path.push(-1, 0); var preIndex = path.renderIndex; path.renderIndex = 0; var nodeCount = 0; var subBlocks = []; var basePath = path[path.length-1]; for (var i = 0; i < this.children.length; ++i) { path[path.length-1] = basePath+'+'+loopName+'+'+nodeCount; var child = this.children[i]; if (isTag(child)) nodeCount += '+' + child.tag.generateDOM(path, subBlocks, args); else nodeCount += '+1'; } path[path.length-1] = basePath+'+'+loopName; blocks.push(loopName,' = __loop__.apply(this, [', iterName, ', function(', counterName,',',loopName); for (var i = 0; i < path.renderIndex; ++i) blocks.push(',d'+i); blocks.push(') {'); blocks.push(subBlocks.join("")); blocks.push('return ', nodeCount, ';'); blocks.push('}]);'); path.renderIndex = preIndex; return loopName; } }); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** @class */ function Variable(name, format) { this.name = name; this.format = format; } /** @class */ function Parts(parts) { this.parts = parts; } // ************************************************************************************************ function parseParts(str) { var re = /\$([_A-Za-z][_A-Za-z0-9.|]*)/g; var index = 0; var parts = []; var m; while (m = re.exec(str)) { var pre = str.substr(index, (re.lastIndex-m[0].length)-index); if (pre) parts.push(pre); var expr = m[1].split("|"); parts.push(new Variable(expr[0], expr.slice(1))); index = re.lastIndex; } if (!index) return str; var post = str.substr(index); if (post) parts.push(post); return new Parts(parts); } function parseValue(val) { return typeof(val) == 'string' ? parseParts(val) : val; } function parseChildren(args, offset, vars, children) { for (var i = offset; i < args.length; ++i) { var val = parseValue(args[i]); children.push(val); readPartNames(val, vars); } } function readPartNames(val, vars) { if (val instanceof Parts) { for (var i = 0; i < val.parts.length; ++i) { var part = val.parts[i]; if (part instanceof Variable) vars.push(part.name); } } } function generateArg(val, path, args) { if (val instanceof Parts) { var vals = []; for (var i = 0; i < val.parts.length; ++i) { var part = val.parts[i]; if (part instanceof Variable) { var varName = 'd'+path.renderIndex++; if (part.format) { for (var j = 0; j < part.format.length; ++j) varName = part.format[j] + '(' + varName + ')'; } vals.push(varName); } else vals.push('"'+part.replace(/"/g, '\\"')+'"'); } return vals.join('+'); } else { args.push(val); return 's' + path.staticIndex++; } } function addParts(val, delim, block, info, escapeIt) { var vals = []; if (val instanceof Parts) { for (var i = 0; i < val.parts.length; ++i) { var part = val.parts[i]; if (part instanceof Variable) { var partName = part.name; if (part.format) { for (var j = 0; j < part.format.length; ++j) partName = part.format[j] + "(" + partName + ")"; } if (escapeIt) vals.push("__escape__(" + partName + ")"); else vals.push(partName); } else vals.push('"'+ part + '"'); } } else if (isTag(val)) { info.args.push(val); vals.push('s'+info.argIndex++); } else vals.push('"'+ val + '"'); var parts = vals.join(delim); if (parts) block.push(delim, parts); } function isTag(obj) { return (typeof(obj) == "function" || obj instanceof Function) && !!obj.tag; } function creator(tag, cons) { var fn = new Function( "var tag = arguments.callee.tag;" + "var cons = arguments.callee.cons;" + "var newTag = new cons();" + "return newTag.merge(arguments, tag);"); fn.tag = tag; fn.cons = cons; extend(fn, Renderer); return fn; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * function copyArray(oldArray) { var ary = []; if (oldArray) for (var i = 0; i < oldArray.length; ++i) ary.push(oldArray[i]); return ary; } function copyObject(l, r) { var m = {}; extend(m, l); extend(m, r); return m; } function extend(l, r) { for (var n in r) l[n] = r[n]; } function addEvent(object, name, handler) { if (document.all) object.attachEvent("on"+name, handler); else object.addEventListener(name, handler, false); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /** @class */ function ArrayIterator(array) { var index = -1; this.next = function() { if (++index >= array.length) throw StopIteration; return array[index]; }; } /** @class */ function StopIteration() {} FBL.$break = function() { throw StopIteration; }; // ************************************************************************************************ /** @namespace */ var Renderer = { renderHTML: function(args, outputs, self) { var code = []; var markupArgs = [code, this.tag.context, args, outputs]; markupArgs.push.apply(markupArgs, this.tag.markupArgs); this.tag.renderMarkup.apply(self ? self : this.tag.subject, markupArgs); return code.join(""); }, insertRows: function(args, before, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); var doc = before.ownerDocument; var div = doc.createElement("div"); div.innerHTML = "<table><tbody>"+html+"</tbody></table>"; var tbody = div.firstChild.firstChild; var parent = before.tagName == "TR" ? before.parentNode : before; var after = before.tagName == "TR" ? before.nextSibling : null; var firstRow = tbody.firstChild, lastRow; while (tbody.firstChild) { lastRow = tbody.firstChild; if (after) parent.insertBefore(lastRow, after); else parent.appendChild(lastRow); } var offset = 0; if (before.tagName == "TR") { var node = firstRow.parentNode.firstChild; for (; node && node != firstRow; node = node.nextSibling) ++offset; } var domArgs = [firstRow, this.tag.context, offset]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return [firstRow, lastRow]; }, insertBefore: function(args, before, self) { return this.insertNode(args, before.ownerDocument, before, false, self); }, insertAfter: function(args, after, self) { return this.insertNode(args, after.ownerDocument, after, true, self); }, insertNode: function(args, doc, element, isAfter, self) { if (!args) args = {}; this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); //if (FBTrace.DBG_DOM) // FBTrace.sysout("domplate.insertNode html: "+html+"\n"); var doc = element.ownerDocument; if (!womb || womb.ownerDocument != doc) womb = doc.createElement("div"); womb.innerHTML = html; var root = womb.firstChild; if (isAfter) { while (womb.firstChild) if (element.nextSibling) element.parentNode.insertBefore(womb.firstChild, element.nextSibling); else element.parentNode.appendChild(womb.firstChild); } else { while (womb.lastChild) element.parentNode.insertBefore(womb.lastChild, element); } var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); //if (FBTrace.DBG_DOM) // FBTrace.sysout("domplate.insertNode domArgs:", domArgs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return root; }, /**/ /* insertAfter: function(args, before, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); var doc = before.ownerDocument; if (!womb || womb.ownerDocument != doc) womb = doc.createElement("div"); womb.innerHTML = html; var root = womb.firstChild; while (womb.firstChild) if (before.nextSibling) before.parentNode.insertBefore(womb.firstChild, before.nextSibling); else before.parentNode.appendChild(womb.firstChild); var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); this.tag.renderDOM.apply(self ? self : (this.tag.subject ? this.tag.subject : null), domArgs); return root; }, /**/ replace: function(args, parent, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); var root; if (parent.nodeType == 1) { parent.innerHTML = html; root = parent.firstChild; } else { if (!parent || parent.nodeType != 9) parent = document; if (!womb || womb.ownerDocument != parent) womb = parent.createElement("div"); womb.innerHTML = html; root = womb.firstChild; //womb.removeChild(root); } var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return root; }, append: function(args, parent, self) { this.tag.compile(); var outputs = []; var html = this.renderHTML(args, outputs, self); //if (FBTrace.DBG_DOM) FBTrace.sysout("domplate.append html: "+html+"\n"); if (!womb || womb.ownerDocument != parent.ownerDocument) womb = parent.ownerDocument.createElement("div"); womb.innerHTML = html; // TODO: xxxpedro domplate port to Firebug var root = womb.firstChild; while (womb.firstChild) parent.appendChild(womb.firstChild); // clearing element reference to avoid reference error in IE8 when switching contexts womb = null; var domArgs = [root, this.tag.context, 0]; domArgs.push.apply(domArgs, this.tag.domArgs); domArgs.push.apply(domArgs, outputs); //if (FBTrace.DBG_DOM) FBTrace.dumpProperties("domplate append domArgs:", domArgs); this.tag.renderDOM.apply(self ? self : this.tag.subject, domArgs); return root; } }; // ************************************************************************************************ function defineTags() { for (var i = 0; i < arguments.length; ++i) { var tagName = arguments[i]; var fn = new Function("var newTag = new arguments.callee.DomplateTag('"+tagName+"'); return newTag.merge(arguments);"); fn.DomplateTag = DomplateTag; var fnName = tagName.toUpperCase(); FBL[fnName] = fn; } } defineTags( "a", "button", "br", "canvas", "code", "col", "colgroup", "div", "fieldset", "form", "h1", "h2", "h3", "hr", "img", "input", "label", "legend", "li", "ol", "optgroup", "option", "p", "pre", "select", "span", "strong", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "tr", "tt", "ul", "iframe" ); })(); /* See license.txt for terms of usage */ var FirebugReps = FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Common Tags var OBJECTBOX = this.OBJECTBOX = SPAN({"class": "objectBox objectBox-$className"}); var OBJECTBLOCK = this.OBJECTBLOCK = DIV({"class": "objectBox objectBox-$className"}); var OBJECTLINK = this.OBJECTLINK = isIE6 ? // IE6 object link representation A({ "class": "objectLink objectLink-$className a11yFocus", href: "javascript:void(0)", // workaround to show XPath (a better approach would use the tooltip on mouseover, // so the XPath information would be calculated dynamically, but we need to create // a tooltip class/wrapper around Menu or InfoTip) title: "$object|FBL.getElementXPath", _repObject: "$object" }) : // Other browsers A({ "class": "objectLink objectLink-$className a11yFocus", // workaround to show XPath (a better approach would use the tooltip on mouseover, // so the XPath information would be calculated dynamically, but we need to create // a tooltip class/wrapper around Menu or InfoTip) title: "$object|FBL.getElementXPath", _repObject: "$object" }); // ************************************************************************************************ this.Undefined = domplate(Firebug.Rep, { tag: OBJECTBOX("undefined"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "undefined", supportsObject: function(object, type) { return type == "undefined"; } }); // ************************************************************************************************ this.Null = domplate(Firebug.Rep, { tag: OBJECTBOX("null"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "null", supportsObject: function(object, type) { return object == null; } }); // ************************************************************************************************ this.Nada = domplate(Firebug.Rep, { tag: SPAN(""), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "nada" }); // ************************************************************************************************ this.Number = domplate(Firebug.Rep, { tag: OBJECTBOX("$object"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "number", supportsObject: function(object, type) { return type == "boolean" || type == "number"; } }); // ************************************************************************************************ this.String = domplate(Firebug.Rep, { tag: OBJECTBOX("&quot;$object&quot;"), shortTag: OBJECTBOX("&quot;$object|cropString&quot;"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "string", supportsObject: function(object, type) { return type == "string"; } }); // ************************************************************************************************ this.Text = domplate(Firebug.Rep, { tag: OBJECTBOX("$object"), shortTag: OBJECTBOX("$object|cropString"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "text" }); // ************************************************************************************************ this.Caption = domplate(Firebug.Rep, { tag: SPAN({"class": "caption"}, "$object") }); // ************************************************************************************************ this.Warning = domplate(Firebug.Rep, { tag: DIV({"class": "warning focusRow", role : 'listitem'}, "$object|STR") }); // ************************************************************************************************ this.Func = domplate(Firebug.Rep, { tag: OBJECTLINK("$object|summarizeFunction"), summarizeFunction: function(fn) { var fnRegex = /function ([^(]+\([^)]*\)) \{/; var fnText = safeToString(fn); var m = fnRegex.exec(fnText); return m ? m[1] : "function()"; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copySource: function(fn) { copyToClipboard(safeToString(fn)); }, monitor: function(fn, script, monitored) { if (monitored) Firebug.Debugger.unmonitorScript(fn, script, "monitor"); else Firebug.Debugger.monitorScript(fn, script, "monitor"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "function", supportsObject: function(object, type) { return isFunction(object); }, inspectObject: function(fn, context) { var sourceLink = findSourceForFunction(fn, context); if (sourceLink) Firebug.chrome.select(sourceLink); if (FBTrace.DBG_FUNCTION_NAME) FBTrace.sysout("reps.function.inspectObject selected sourceLink is ", sourceLink); }, getTooltip: function(fn, context) { var script = findScriptForFunctionInContext(context, fn); if (script) return $STRF("Line", [normalizeURL(script.fileName), script.baseLineNumber]); else if (fn.toString) return fn.toString(); }, getTitle: function(fn, context) { var name = fn.name ? fn.name : "function"; return name + "()"; }, getContextMenuItems: function(fn, target, context, script) { if (!script) script = findScriptForFunctionInContext(context, fn); if (!script) return; var scriptInfo = getSourceFileAndLineByScript(context, script); var monitored = scriptInfo ? fbs.isMonitored(scriptInfo.sourceFile.href, scriptInfo.lineNo) : false; var name = script ? getFunctionName(script, context) : fn.name; return [ {label: "CopySource", command: bindFixed(this.copySource, this, fn) }, "-", {label: $STRF("ShowCallsInConsole", [name]), nol10n: true, type: "checkbox", checked: monitored, command: bindFixed(this.monitor, this, fn, script, monitored) } ]; } }); // ************************************************************************************************ /* this.jsdScript = domplate(Firebug.Rep, { copySource: function(script) { var fn = script.functionObject.getWrappedValue(); return FirebugReps.Func.copySource(fn); }, monitor: function(fn, script, monitored) { fn = script.functionObject.getWrappedValue(); return FirebugReps.Func.monitor(fn, script, monitored); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "jsdScript", inspectable: false, supportsObject: function(object, type) { return object instanceof jsdIScript; }, inspectObject: function(script, context) { var sourceLink = getSourceLinkForScript(script, context); if (sourceLink) Firebug.chrome.select(sourceLink); }, getRealObject: function(script, context) { return script; }, getTooltip: function(script) { return $STRF("jsdIScript", [script.tag]); }, getTitle: function(script, context) { var fn = script.functionObject.getWrappedValue(); return FirebugReps.Func.getTitle(fn, context); }, getContextMenuItems: function(script, target, context) { var fn = script.functionObject.getWrappedValue(); var scriptInfo = getSourceFileAndLineByScript(context, script); var monitored = scriptInfo ? fbs.isMonitored(scriptInfo.sourceFile.href, scriptInfo.lineNo) : false; var name = getFunctionName(script, context); return [ {label: "CopySource", command: bindFixed(this.copySource, this, script) }, "-", {label: $STRF("ShowCallsInConsole", [name]), nol10n: true, type: "checkbox", checked: monitored, command: bindFixed(this.monitor, this, fn, script, monitored) } ]; } }); /**/ //************************************************************************************************ this.Obj = domplate(Firebug.Rep, { tag: OBJECTLINK( SPAN({"class": "objectTitle"}, "$object|getTitle "), SPAN({"class": "objectProps"}, SPAN({"class": "objectLeftBrace", role: "presentation"}, "{"), FOR("prop", "$object|propIterator", SPAN({"class": "objectPropName", role: "presentation"}, "$prop.name"), SPAN({"class": "objectEqual", role: "presentation"}, "$prop.equal"), TAG("$prop.tag", {object: "$prop.object"}), SPAN({"class": "objectComma", role: "presentation"}, "$prop.delim") ), SPAN({"class": "objectRightBrace"}, "}") ) ), propNumberTag: SPAN({"class": "objectProp-number"}, "$object"), propStringTag: SPAN({"class": "objectProp-string"}, "&quot;$object&quot;"), propObjectTag: SPAN({"class": "objectProp-object"}, "$object"), propIterator: function (object) { ///Firebug.ObjectShortIteratorMax; var maxLength = 55; // default max length for long representation if (!object) return []; var props = []; var length = 0; var numProperties = 0; var numPropertiesShown = 0; var maxLengthReached = false; var lib = this; var propRepsMap = { "boolean": this.propNumberTag, "number": this.propNumberTag, "string": this.propStringTag, "object": this.propObjectTag }; try { var title = Firebug.Rep.getTitle(object); length += title.length; for (var name in object) { var value; try { value = object[name]; } catch (exc) { continue; } var type = typeof(value); if (type == "boolean" || type == "number" || (type == "string" && value) || (type == "object" && value && value.toString)) { var tag = propRepsMap[type]; var value = (type == "object") ? Firebug.getRep(value).getTitle(value) : value + ""; length += name.length + value.length + 4; if (length <= maxLength) { props.push({ tag: tag, name: name, object: value, equal: "=", delim: ", " }); numPropertiesShown++; } else maxLengthReached = true; } numProperties++; if (maxLengthReached && numProperties > numPropertiesShown) break; } if (numProperties > numPropertiesShown) { props.push({ object: "...", //xxxHonza localization tag: FirebugReps.Caption.tag, name: "", equal:"", delim:"" }); } else if (props.length > 0) { props[props.length-1].delim = ''; } } catch (exc) { // Sometimes we get exceptions when trying to read from certain objects, like // StorageList, but don't let that gum up the works // XXXjjb also History.previous fails because object is a web-page object which does not have // permission to read the history } return props; }, fb_1_6_propIterator: function (object, max) { max = max || 3; if (!object) return []; var props = []; var len = 0, count = 0; try { for (var name in object) { var value; try { value = object[name]; } catch (exc) { continue; } var t = typeof(value); if (t == "boolean" || t == "number" || (t == "string" && value) || (t == "object" && value && value.toString)) { var rep = Firebug.getRep(value); var tag = rep.shortTag || rep.tag; if (t == "object") { value = rep.getTitle(value); tag = rep.titleTag; } count++; if (count <= max) props.push({tag: tag, name: name, object: value, equal: "=", delim: ", "}); else break; } } if (count > max) { props[Math.max(1,max-1)] = { object: "more...", //xxxHonza localization tag: FirebugReps.Caption.tag, name: "", equal:"", delim:"" }; } else if (props.length > 0) { props[props.length-1].delim = ''; } } catch (exc) { // Sometimes we get exceptions when trying to read from certain objects, like // StorageList, but don't let that gum up the works // XXXjjb also History.previous fails because object is a web-page object which does not have // permission to read the history } return props; }, /* propIterator: function (object) { if (!object) return []; var props = []; var len = 0; try { for (var name in object) { var val; try { val = object[name]; } catch (exc) { continue; } var t = typeof val; if (t == "boolean" || t == "number" || (t == "string" && val) || (t == "object" && !isFunction(val) && val && val.toString)) { var title = (t == "object") ? Firebug.getRep(val).getTitle(val) : val+""; len += name.length + title.length + 1; if (len < 50) props.push({name: name, value: title}); else break; } } } catch (exc) { // Sometimes we get exceptions when trying to read from certain objects, like // StorageList, but don't let that gum up the works // XXXjjb also History.previous fails because object is a web-page object which does not have // permission to read the history } return props; }, /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object, type) { return true; } }); // ************************************************************************************************ this.Arr = domplate(Firebug.Rep, { tag: OBJECTBOX({_repObject: "$object"}, SPAN({"class": "arrayLeftBracket", role : "presentation"}, "["), FOR("item", "$object|arrayIterator", TAG("$item.tag", {object: "$item.object"}), SPAN({"class": "arrayComma", role : "presentation"}, "$item.delim") ), SPAN({"class": "arrayRightBracket", role : "presentation"}, "]") ), shortTag: OBJECTBOX({_repObject: "$object"}, SPAN({"class": "arrayLeftBracket", role : "presentation"}, "["), FOR("item", "$object|shortArrayIterator", TAG("$item.tag", {object: "$item.object"}), SPAN({"class": "arrayComma", role : "presentation"}, "$item.delim") ), // TODO: xxxpedro - confirm this on Firebug //FOR("prop", "$object|shortPropIterator", // " $prop.name=", // SPAN({"class": "objectPropValue"}, "$prop.value|cropString") //), SPAN({"class": "arrayRightBracket"}, "]") ), arrayIterator: function(array) { var items = []; for (var i = 0; i < array.length; ++i) { var value = array[i]; var rep = Firebug.getRep(value); var tag = rep.shortTag ? rep.shortTag : rep.tag; var delim = (i == array.length-1 ? "" : ", "); items.push({object: value, tag: tag, delim: delim}); } return items; }, shortArrayIterator: function(array) { var items = []; for (var i = 0; i < array.length && i < 3; ++i) { var value = array[i]; var rep = Firebug.getRep(value); var tag = rep.shortTag ? rep.shortTag : rep.tag; var delim = (i == array.length-1 ? "" : ", "); items.push({object: value, tag: tag, delim: delim}); } if (array.length > 3) items.push({object: (array.length-3) + " more...", tag: FirebugReps.Caption.tag, delim: ""}); return items; }, shortPropIterator: this.Obj.propIterator, getItemIndex: function(child) { var arrayIndex = 0; for (child = child.previousSibling; child; child = child.previousSibling) { if (child.repObject) ++arrayIndex; } return arrayIndex; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "array", supportsObject: function(object) { return this.isArray(object); }, // http://code.google.com/p/fbug/issues/detail?id=874 // BEGIN Yahoo BSD Source (modified here) YAHOO.lang.isArray, YUI 2.2.2 June 2007 isArray: function(obj) { try { if (!obj) return false; else if (isIE && !isFunction(obj) && typeof obj == "object" && isFinite(obj.length) && obj.nodeType != 8) return true; else if (isFinite(obj.length) && isFunction(obj.splice)) return true; else if (isFinite(obj.length) && isFunction(obj.callee)) // arguments return true; else if (instanceOf(obj, "HTMLCollection")) return true; else if (instanceOf(obj, "NodeList")) return true; else return false; } catch(exc) { if (FBTrace.DBG_ERRORS) { FBTrace.sysout("isArray FAILS:", exc); /* Something weird: without the try/catch, OOM, with no exception?? */ FBTrace.sysout("isArray Fails on obj", obj); } } return false; }, // END Yahoo BSD SOURCE See license below. getTitle: function(object, context) { return "[" + object.length + "]"; } }); // ************************************************************************************************ this.Property = domplate(Firebug.Rep, { supportsObject: function(object) { return object instanceof Property; }, getRealObject: function(prop, context) { return prop.object[prop.name]; }, getTitle: function(prop, context) { return prop.name; } }); // ************************************************************************************************ this.NetFile = domplate(this.Obj, { supportsObject: function(object) { return object instanceof Firebug.NetFile; }, browseObject: function(file, context) { openNewTab(file.href); return true; }, getRealObject: function(file, context) { return null; } }); // ************************************************************************************************ this.Except = domplate(Firebug.Rep, { tag: OBJECTBOX({_repObject: "$object"}, "$object.message"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "exception", supportsObject: function(object) { return object instanceof ErrorCopy; } }); // ************************************************************************************************ this.Element = domplate(Firebug.Rep, { tag: OBJECTLINK( "&lt;", SPAN({"class": "nodeTag"}, "$object.nodeName|toLowerCase"), FOR("attr", "$object|attrIterator", "&nbsp;$attr.nodeName=&quot;", SPAN({"class": "nodeValue"}, "$attr.nodeValue"), "&quot;" ), "&gt;" ), shortTag: OBJECTLINK( SPAN({"class": "$object|getVisible"}, SPAN({"class": "selectorTag"}, "$object|getSelectorTag"), SPAN({"class": "selectorId"}, "$object|getSelectorId"), SPAN({"class": "selectorClass"}, "$object|getSelectorClass"), SPAN({"class": "selectorValue"}, "$object|getValue") ) ), getVisible: function(elt) { return isVisible(elt) ? "" : "selectorHidden"; }, getSelectorTag: function(elt) { return elt.nodeName.toLowerCase(); }, getSelectorId: function(elt) { return elt.id ? "#" + elt.id : ""; }, getSelectorClass: function(elt) { return elt.className ? "." + elt.className.split(" ")[0] : ""; }, getValue: function(elt) { // TODO: xxxpedro return ""; var value; if (elt instanceof HTMLImageElement) value = getFileName(elt.src); else if (elt instanceof HTMLAnchorElement) value = getFileName(elt.href); else if (elt instanceof HTMLInputElement) value = elt.value; else if (elt instanceof HTMLFormElement) value = getFileName(elt.action); else if (elt instanceof HTMLScriptElement) value = getFileName(elt.src); return value ? " " + cropString(value, 20) : ""; }, attrIterator: function(elt) { var attrs = []; var idAttr, classAttr; if (elt.attributes) { for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; // we must check if the attribute is specified otherwise IE will show them if (!attr.specified || attr.nodeName && attr.nodeName.indexOf("firebug-") != -1) continue; else if (attr.nodeName == "id") idAttr = attr; else if (attr.nodeName == "class") classAttr = attr; else if (attr.nodeName == "style") attrs.push({ nodeName: attr.nodeName, nodeValue: attr.nodeValue || // IE won't recognize the attr.nodeValue of <style> nodes ... // and will return CSS property names in upper case, so we need to convert them elt.style.cssText.replace(/([^\s]+)\s*:/g, function(m,g){return g.toLowerCase()+":"}) }); else attrs.push(attr); } } if (classAttr) attrs.splice(0, 0, classAttr); if (idAttr) attrs.splice(0, 0, idAttr); return attrs; }, shortAttrIterator: function(elt) { var attrs = []; if (elt.attributes) { for (var i = 0; i < elt.attributes.length; ++i) { var attr = elt.attributes[i]; if (attr.nodeName == "id" || attr.nodeName == "class") attrs.push(attr); } } return attrs; }, getHidden: function(elt) { return isVisible(elt) ? "" : "nodeHidden"; }, getXPath: function(elt) { return getElementTreeXPath(elt); }, // TODO: xxxpedro remove this? getNodeText: function(element) { var text = element.textContent; if (Firebug.showFullTextNodes) return text; else return cropString(text, 50); }, /**/ getNodeTextGroups: function(element) { var text = element.textContent; if (!Firebug.showFullTextNodes) { text=cropString(text,50); } var escapeGroups=[]; if (Firebug.showTextNodesWithWhitespace) escapeGroups.push({ 'group': 'whitespace', 'class': 'nodeWhiteSpace', 'extra': { '\t': '_Tab', '\n': '_Para', ' ' : '_Space' } }); if (Firebug.showTextNodesWithEntities) escapeGroups.push({ 'group':'text', 'class':'nodeTextEntity', 'extra':{} }); if (escapeGroups.length) return escapeGroupsForEntities(text, escapeGroups); else return [{str:text,'class':'',extra:''}]; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyHTML: function(elt) { var html = getElementXML(elt); copyToClipboard(html); }, copyInnerHTML: function(elt) { copyToClipboard(elt.innerHTML); }, copyXPath: function(elt) { var xpath = getElementXPath(elt); copyToClipboard(xpath); }, persistor: function(context, xpath) { var elts = xpath ? getElementsByXPath(context.window.document, xpath) : null; return elts && elts.length ? elts[0] : null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "element", supportsObject: function(object) { //return object instanceof Element || object.nodeType == 1 && typeof object.nodeName == "string"; return instanceOf(object, "Element"); }, browseObject: function(elt, context) { var tag = elt.nodeName.toLowerCase(); if (tag == "script") openNewTab(elt.src); else if (tag == "link") openNewTab(elt.href); else if (tag == "a") openNewTab(elt.href); else if (tag == "img") openNewTab(elt.src); return true; }, persistObject: function(elt, context) { var xpath = getElementXPath(elt); return bind(this.persistor, top, xpath); }, getTitle: function(element, context) { return getElementCSSSelector(element); }, getTooltip: function(elt) { return this.getXPath(elt); }, getContextMenuItems: function(elt, target, context) { var monitored = areEventsMonitored(elt, null, context); return [ {label: "CopyHTML", command: bindFixed(this.copyHTML, this, elt) }, {label: "CopyInnerHTML", command: bindFixed(this.copyInnerHTML, this, elt) }, {label: "CopyXPath", command: bindFixed(this.copyXPath, this, elt) }, "-", {label: "ShowEventsInConsole", type: "checkbox", checked: monitored, command: bindFixed(toggleMonitorEvents, FBL, elt, null, monitored, context) }, "-", {label: "ScrollIntoView", command: bindFixed(elt.scrollIntoView, elt) } ]; } }); // ************************************************************************************************ this.TextNode = domplate(Firebug.Rep, { tag: OBJECTLINK( "&lt;", SPAN({"class": "nodeTag"}, "TextNode"), "&nbsp;textContent=&quot;", SPAN({"class": "nodeValue"}, "$object.textContent|cropString"), "&quot;", "&gt;" ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "textNode", supportsObject: function(object) { return object instanceof Text; } }); // ************************************************************************************************ this.Document = domplate(Firebug.Rep, { tag: OBJECTLINK("Document ", SPAN({"class": "objectPropValue"}, "$object|getLocation")), getLocation: function(doc) { return doc.location ? getFileName(doc.location.href) : ""; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { //return object instanceof Document || object instanceof XMLDocument; return instanceOf(object, "Document"); }, browseObject: function(doc, context) { openNewTab(doc.location.href); return true; }, persistObject: function(doc, context) { return this.persistor; }, persistor: function(context) { return context.window.document; }, getTitle: function(win, context) { return "document"; }, getTooltip: function(doc) { return doc.location.href; } }); // ************************************************************************************************ this.StyleSheet = domplate(Firebug.Rep, { tag: OBJECTLINK("StyleSheet ", SPAN({"class": "objectPropValue"}, "$object|getLocation")), getLocation: function(styleSheet) { return getFileName(styleSheet.href); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyURL: function(styleSheet) { copyToClipboard(styleSheet.href); }, openInTab: function(styleSheet) { openNewTab(styleSheet.href); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { //return object instanceof CSSStyleSheet; return instanceOf(object, "CSSStyleSheet"); }, browseObject: function(styleSheet, context) { openNewTab(styleSheet.href); return true; }, persistObject: function(styleSheet, context) { return bind(this.persistor, top, styleSheet.href); }, getTooltip: function(styleSheet) { return styleSheet.href; }, getContextMenuItems: function(styleSheet, target, context) { return [ {label: "CopyLocation", command: bindFixed(this.copyURL, this, styleSheet) }, "-", {label: "OpenInTab", command: bindFixed(this.openInTab, this, styleSheet) } ]; }, persistor: function(context, href) { return getStyleSheetByHref(href, context); } }); // ************************************************************************************************ this.Window = domplate(Firebug.Rep, { tag: OBJECTLINK("Window ", SPAN({"class": "objectPropValue"}, "$object|getLocation")), getLocation: function(win) { try { return (win && win.location && !win.closed) ? getFileName(win.location.href) : ""; } catch (exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("reps.Window window closed?"); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { return instanceOf(object, "Window"); }, browseObject: function(win, context) { openNewTab(win.location.href); return true; }, persistObject: function(win, context) { return this.persistor; }, persistor: function(context) { return context.window; }, getTitle: function(win, context) { return "window"; }, getTooltip: function(win) { if (win && !win.closed) return win.location.href; } }); // ************************************************************************************************ this.Event = domplate(Firebug.Rep, { tag: TAG("$copyEventTag", {object: "$object|copyEvent"}), copyEventTag: OBJECTLINK("$object|summarizeEvent"), summarizeEvent: function(event) { var info = [event.type, ' ']; var eventFamily = getEventFamily(event.type); if (eventFamily == "mouse") info.push("clientX=", event.clientX, ", clientY=", event.clientY); else if (eventFamily == "key") info.push("charCode=", event.charCode, ", keyCode=", event.keyCode); return info.join(""); }, copyEvent: function(event) { return new EventCopy(event); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "object", supportsObject: function(object) { //return object instanceof Event || object instanceof EventCopy; return instanceOf(object, "Event") || instanceOf(object, "EventCopy"); }, getTitle: function(event, context) { return "Event " + event.type; } }); // ************************************************************************************************ this.SourceLink = domplate(Firebug.Rep, { tag: OBJECTLINK({$collapsed: "$object|hideSourceLink"}, "$object|getSourceLinkTitle"), hideSourceLink: function(sourceLink) { return sourceLink ? sourceLink.href.indexOf("XPCSafeJSObjectWrapper") != -1 : true; }, getSourceLinkTitle: function(sourceLink) { if (!sourceLink) return ""; try { var fileName = getFileName(sourceLink.href); fileName = decodeURIComponent(fileName); fileName = cropString(fileName, 17); } catch(exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("reps.getSourceLinkTitle decodeURIComponent fails for \'"+fileName+"\': "+exc, exc); } return typeof sourceLink.line == "number" ? fileName + " (line " + sourceLink.line + ")" : fileName; // TODO: xxxpedro //return $STRF("Line", [fileName, sourceLink.line]); }, copyLink: function(sourceLink) { copyToClipboard(sourceLink.href); }, openInTab: function(sourceLink) { openNewTab(sourceLink.href); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "sourceLink", supportsObject: function(object) { return object instanceof SourceLink; }, getTooltip: function(sourceLink) { return decodeURI(sourceLink.href); }, inspectObject: function(sourceLink, context) { if (sourceLink.type == "js") { var scriptFile = getSourceFileByHref(sourceLink.href, context); if (scriptFile) return Firebug.chrome.select(sourceLink); } else if (sourceLink.type == "css") { // If an object is defined, treat it as the highest priority for // inspect actions if (sourceLink.object) { Firebug.chrome.select(sourceLink.object); return; } var stylesheet = getStyleSheetByHref(sourceLink.href, context); if (stylesheet) { var ownerNode = stylesheet.ownerNode; if (ownerNode) { Firebug.chrome.select(sourceLink, "html"); return; } var panel = context.getPanel("stylesheet"); if (panel && panel.getRuleByLine(stylesheet, sourceLink.line)) return Firebug.chrome.select(sourceLink); } } // Fallback is to just open the view-source window on the file viewSource(sourceLink.href, sourceLink.line); }, browseObject: function(sourceLink, context) { openNewTab(sourceLink.href); return true; }, getContextMenuItems: function(sourceLink, target, context) { return [ {label: "CopyLocation", command: bindFixed(this.copyLink, this, sourceLink) }, "-", {label: "OpenInTab", command: bindFixed(this.openInTab, this, sourceLink) } ]; } }); // ************************************************************************************************ this.SourceFile = domplate(this.SourceLink, { tag: OBJECTLINK({$collapsed: "$object|hideSourceLink"}, "$object|getSourceLinkTitle"), persistor: function(context, href) { return getSourceFileByHref(href, context); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "sourceFile", supportsObject: function(object) { return object instanceof SourceFile; }, persistObject: function(sourceFile) { return bind(this.persistor, top, sourceFile.href); }, browseObject: function(sourceLink, context) { }, getTooltip: function(sourceFile) { return sourceFile.href; } }); // ************************************************************************************************ this.StackFrame = domplate(Firebug.Rep, // XXXjjb Since the repObject is fn the stack does not have correct line numbers { tag: OBJECTBLOCK( A({"class": "objectLink objectLink-function focusRow a11yFocus", _repObject: "$object.fn"}, "$object|getCallName"), " ( ", FOR("arg", "$object|argIterator", TAG("$arg.tag", {object: "$arg.value"}), SPAN({"class": "arrayComma"}, "$arg.delim") ), " )", SPAN({"class": "objectLink-sourceLink objectLink"}, "$object|getSourceLinkTitle") ), getCallName: function(frame) { //TODO: xxxpedro reps StackFrame return frame.name || "anonymous"; //return getFunctionName(frame.script, frame.context); }, getSourceLinkTitle: function(frame) { //TODO: xxxpedro reps StackFrame var fileName = cropString(getFileName(frame.href), 20); return fileName + (frame.lineNo ? " (line " + frame.lineNo + ")" : ""); var fileName = cropString(getFileName(frame.href), 17); return $STRF("Line", [fileName, frame.lineNo]); }, argIterator: function(frame) { if (!frame.args) return []; var items = []; for (var i = 0; i < frame.args.length; ++i) { var arg = frame.args[i]; if (!arg) break; var rep = Firebug.getRep(arg.value); var tag = rep.shortTag ? rep.shortTag : rep.tag; var delim = (i == frame.args.length-1 ? "" : ", "); items.push({name: arg.name, value: arg.value, tag: tag, delim: delim}); } return items; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "stackFrame", supportsObject: function(object) { return object instanceof StackFrame; }, inspectObject: function(stackFrame, context) { var sourceLink = new SourceLink(stackFrame.href, stackFrame.lineNo, "js"); Firebug.chrome.select(sourceLink); }, getTooltip: function(stackFrame, context) { return $STRF("Line", [stackFrame.href, stackFrame.lineNo]); } }); // ************************************************************************************************ this.StackTrace = domplate(Firebug.Rep, { tag: FOR("frame", "$object.frames focusRow", TAG(this.StackFrame.tag, {object: "$frame"}) ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "stackTrace", supportsObject: function(object) { return object instanceof StackTrace; } }); // ************************************************************************************************ this.jsdStackFrame = domplate(Firebug.Rep, { inspectable: false, supportsObject: function(object) { return (object instanceof jsdIStackFrame) && (object.isValid); }, getTitle: function(frame, context) { if (!frame.isValid) return "(invalid frame)"; // XXXjjb avoid frame.script == null return getFunctionName(frame.script, context); }, getTooltip: function(frame, context) { if (!frame.isValid) return "(invalid frame)"; // XXXjjb avoid frame.script == null var sourceInfo = FBL.getSourceFileAndLineByScript(context, frame.script, frame); if (sourceInfo) return $STRF("Line", [sourceInfo.sourceFile.href, sourceInfo.lineNo]); else return $STRF("Line", [frame.script.fileName, frame.line]); }, getContextMenuItems: function(frame, target, context) { var fn = frame.script.functionObject.getWrappedValue(); return FirebugReps.Func.getContextMenuItems(fn, target, context, frame.script); } }); // ************************************************************************************************ this.ErrorMessage = domplate(Firebug.Rep, { tag: OBJECTBOX({ $hasTwisty: "$object|hasStackTrace", $hasBreakSwitch: "$object|hasBreakSwitch", $breakForError: "$object|hasErrorBreak", _repObject: "$object", _stackTrace: "$object|getLastErrorStackTrace", onclick: "$onToggleError"}, DIV({"class": "errorTitle a11yFocus", role : 'checkbox', 'aria-checked' : 'false'}, "$object.message|getMessage" ), DIV({"class": "errorTrace"}), DIV({"class": "errorSourceBox errorSource-$object|getSourceType"}, IMG({"class": "errorBreak a11yFocus", src:"blank.gif", role : 'checkbox', 'aria-checked':'false', title: "Break on this error"}), A({"class": "errorSource a11yFocus"}, "$object|getLine") ), TAG(this.SourceLink.tag, {object: "$object|getSourceLink"}) ), getLastErrorStackTrace: function(error) { return error.trace; }, hasStackTrace: function(error) { var url = error.href.toString(); var fromCommandLine = (url.indexOf("XPCSafeJSObjectWrapper") != -1); return !fromCommandLine && error.trace; }, hasBreakSwitch: function(error) { return error.href && error.lineNo > 0; }, hasErrorBreak: function(error) { return fbs.hasErrorBreakpoint(error.href, error.lineNo); }, getMessage: function(message) { var re = /\[Exception... "(.*?)" nsresult:/; var m = re.exec(message); return m ? m[1] : message; }, getLine: function(error) { if (error.category == "js") { if (error.source) return cropString(error.source, 80); else if (error.href && error.href.indexOf("XPCSafeJSObjectWrapper") == -1) return cropString(error.getSourceLine(), 80); } }, getSourceLink: function(error) { var ext = error.category == "css" ? "css" : "js"; return error.lineNo ? new SourceLink(error.href, error.lineNo, ext) : null; }, getSourceType: function(error) { // Errors occurring inside of HTML event handlers look like "foo.html (line 1)" // so let's try to skip those if (error.source) return "syntax"; else if (error.lineNo == 1 && getFileExtension(error.href) != "js") return "none"; else if (error.category == "css") return "none"; else if (!error.href || !error.lineNo) return "none"; else return "exec"; }, onToggleError: function(event) { var target = event.currentTarget; if (hasClass(event.target, "errorBreak")) { this.breakOnThisError(target.repObject); } else if (hasClass(event.target, "errorSource")) { var panel = Firebug.getElementPanel(event.target); this.inspectObject(target.repObject, panel.context); } else if (hasClass(event.target, "errorTitle")) { var traceBox = target.childNodes[1]; toggleClass(target, "opened"); event.target.setAttribute('aria-checked', hasClass(target, "opened")); if (hasClass(target, "opened")) { if (target.stackTrace) var node = FirebugReps.StackTrace.tag.append({object: target.stackTrace}, traceBox); if (Firebug.A11yModel.enabled) { var panel = Firebug.getElementPanel(event.target); dispatch([Firebug.A11yModel], "onLogRowContentCreated", [panel , traceBox]); } } else clearNode(traceBox); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyError: function(error) { var message = [ this.getMessage(error.message), error.href, "Line " + error.lineNo ]; copyToClipboard(message.join("\n")); }, breakOnThisError: function(error) { if (this.hasErrorBreak(error)) Firebug.Debugger.clearErrorBreakpoint(error.href, error.lineNo); else Firebug.Debugger.setErrorBreakpoint(error.href, error.lineNo); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "errorMessage", inspectable: false, supportsObject: function(object) { return object instanceof ErrorMessage; }, inspectObject: function(error, context) { var sourceLink = this.getSourceLink(error); FirebugReps.SourceLink.inspectObject(sourceLink, context); }, getContextMenuItems: function(error, target, context) { var breakOnThisError = this.hasErrorBreak(error); var items = [ {label: "CopyError", command: bindFixed(this.copyError, this, error) } ]; if (error.category == "css") { items.push( "-", {label: "BreakOnThisError", type: "checkbox", checked: breakOnThisError, command: bindFixed(this.breakOnThisError, this, error) }, optionMenu("BreakOnAllErrors", "breakOnErrors") ); } return items; } }); // ************************************************************************************************ this.Assert = domplate(Firebug.Rep, { tag: DIV( DIV({"class": "errorTitle"}), DIV({"class": "assertDescription"}) ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "assert", inspectObject: function(error, context) { var sourceLink = this.getSourceLink(error); Firebug.chrome.select(sourceLink); }, getContextMenuItems: function(error, target, context) { var breakOnThisError = this.hasErrorBreak(error); return [ {label: "CopyError", command: bindFixed(this.copyError, this, error) }, "-", {label: "BreakOnThisError", type: "checkbox", checked: breakOnThisError, command: bindFixed(this.breakOnThisError, this, error) }, {label: "BreakOnAllErrors", type: "checkbox", checked: Firebug.breakOnErrors, command: bindFixed(this.breakOnAllErrors, this, error) } ]; } }); // ************************************************************************************************ this.SourceText = domplate(Firebug.Rep, { tag: DIV( FOR("line", "$object|lineIterator", DIV({"class": "sourceRow", role : "presentation"}, SPAN({"class": "sourceLine", role : "presentation"}, "$line.lineNo"), SPAN({"class": "sourceRowText", role : "presentation"}, "$line.text") ) ) ), lineIterator: function(sourceText) { var maxLineNoChars = (sourceText.lines.length + "").length; var list = []; for (var i = 0; i < sourceText.lines.length; ++i) { // Make sure all line numbers are the same width (with a fixed-width font) var lineNo = (i+1) + ""; while (lineNo.length < maxLineNoChars) lineNo = " " + lineNo; list.push({lineNo: lineNo, text: sourceText.lines[i]}); } return list; }, getHTML: function(sourceText) { return getSourceLineRange(sourceText, 1, sourceText.lines.length); } }); //************************************************************************************************ this.nsIDOMHistory = domplate(Firebug.Rep, { tag:OBJECTBOX({onclick: "$showHistory"}, OBJECTLINK("$object|summarizeHistory") ), className: "nsIDOMHistory", summarizeHistory: function(history) { try { var items = history.length; return items + " history entries"; } catch(exc) { return "object does not support history (nsIDOMHistory)"; } }, showHistory: function(history) { try { var items = history.length; // if this throws, then unsupported Firebug.chrome.select(history); } catch (exc) { } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * supportsObject: function(object, type) { return (object instanceof Ci.nsIDOMHistory); } }); // ************************************************************************************************ this.ApplicationCache = domplate(Firebug.Rep, { tag:OBJECTBOX({onclick: "$showApplicationCache"}, OBJECTLINK("$object|summarizeCache") ), summarizeCache: function(applicationCache) { try { return applicationCache.length + " items in offline cache"; } catch(exc) { return "https://bugzilla.mozilla.org/show_bug.cgi?id=422264"; } }, showApplicationCache: function(event) { openNewTab("https://bugzilla.mozilla.org/show_bug.cgi?id=422264"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "applicationCache", supportsObject: function(object, type) { if (Ci.nsIDOMOfflineResourceList) return (object instanceof Ci.nsIDOMOfflineResourceList); } }); this.Storage = domplate(Firebug.Rep, { tag: OBJECTBOX({onclick: "$show"}, OBJECTLINK("$object|summarize")), summarize: function(storage) { return storage.length +" items in Storage"; }, show: function(storage) { openNewTab("http://dev.w3.org/html5/webstorage/#storage-0"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * className: "Storage", supportsObject: function(object, type) { return (object instanceof Storage); } }); // ************************************************************************************************ Firebug.registerRep( //this.nsIDOMHistory, // make this early to avoid exceptions this.Undefined, this.Null, this.Number, this.String, this.Window, //this.ApplicationCache, // must come before Arr (array) else exceptions. //this.ErrorMessage, this.Element, //this.TextNode, this.Document, this.StyleSheet, this.Event, //this.SourceLink, //this.SourceFile, //this.StackTrace, //this.StackFrame, //this.jsdStackFrame, //this.jsdScript, //this.NetFile, this.Property, this.Except, this.Arr ); Firebug.setDefaultReps(this.Func, this.Obj); }}); // ************************************************************************************************ /* * The following is http://developer.yahoo.com/yui/license.txt and applies to only code labeled "Yahoo BSD Source" * in only this file reps.js. John J. Barton June 2007. * Software License Agreement (BSD License) Copyright (c) 2006, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * / */ /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants var saveTimeout = 400; var pageAmount = 10; // ************************************************************************************************ // Globals var currentTarget = null; var currentGroup = null; var currentPanel = null; var currentEditor = null; var defaultEditor = null; var originalClassName = null; var originalValue = null; var defaultValue = null; var previousValue = null; var invalidEditor = false; var ignoreNextInput = false; // ************************************************************************************************ Firebug.Editor = extend(Firebug.Module, { supportsStopEvent: true, dispatchName: "editor", tabCharacter: " ", startEditing: function(target, value, editor) { this.stopEditing(); if (hasClass(target, "insertBefore") || hasClass(target, "insertAfter")) return; var panel = Firebug.getElementPanel(target); if (!panel.editable) return; if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.startEditing " + value, target); defaultValue = target.getAttribute("defaultValue"); if (value == undefined) { var textContent = isIE ? "innerText" : "textContent"; value = target[textContent]; if (value == defaultValue) value = ""; } originalValue = previousValue = value; invalidEditor = false; currentTarget = target; currentPanel = panel; currentGroup = getAncestorByClass(target, "editGroup"); currentPanel.editing = true; var panelEditor = currentPanel.getEditor(target, value); currentEditor = editor ? editor : panelEditor; if (!currentEditor) currentEditor = getDefaultEditor(currentPanel); var inlineParent = getInlineParent(target); var targetSize = getOffsetSize(inlineParent); setClass(panel.panelNode, "editing"); setClass(target, "editing"); if (currentGroup) setClass(currentGroup, "editing"); currentEditor.show(target, currentPanel, value, targetSize); //dispatch(this.fbListeners, "onBeginEditing", [currentPanel, currentEditor, target, value]); currentEditor.beginEditing(target, value); if (FBTrace.DBG_EDITOR) FBTrace.sysout("Editor start panel "+currentPanel.name); this.attachListeners(currentEditor, panel.context); }, stopEditing: function(cancel) { if (!currentTarget) return; if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.stopEditing cancel:" + cancel+" saveTimeout: "+this.saveTimeout); clearTimeout(this.saveTimeout); delete this.saveTimeout; this.detachListeners(currentEditor, currentPanel.context); removeClass(currentPanel.panelNode, "editing"); removeClass(currentTarget, "editing"); if (currentGroup) removeClass(currentGroup, "editing"); var value = currentEditor.getValue(); if (value == defaultValue) value = ""; var removeGroup = currentEditor.endEditing(currentTarget, value, cancel); try { if (cancel) { //dispatch([Firebug.A11yModel], 'onInlineEditorClose', [currentPanel, currentTarget, removeGroup && !originalValue]); if (value != originalValue) this.saveEditAndNotifyListeners(currentTarget, originalValue, previousValue); if (removeGroup && !originalValue && currentGroup) currentGroup.parentNode.removeChild(currentGroup); } else if (!value) { this.saveEditAndNotifyListeners(currentTarget, null, previousValue); if (removeGroup && currentGroup) currentGroup.parentNode.removeChild(currentGroup); } else this.save(value); } catch (exc) { //throw exc.message; //ERROR(exc); } currentEditor.hide(); currentPanel.editing = false; //dispatch(this.fbListeners, "onStopEdit", [currentPanel, currentEditor, currentTarget]); //if (FBTrace.DBG_EDITOR) // FBTrace.sysout("Editor stop panel "+currentPanel.name); currentTarget = null; currentGroup = null; currentPanel = null; currentEditor = null; originalValue = null; invalidEditor = false; return value; }, cancelEditing: function() { return this.stopEditing(true); }, update: function(saveNow) { if (this.saveTimeout) clearTimeout(this.saveTimeout); invalidEditor = true; currentEditor.layout(); if (saveNow) this.save(); else { var context = currentPanel.context; this.saveTimeout = context.setTimeout(bindFixed(this.save, this), saveTimeout); if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.update saveTimeout: "+this.saveTimeout); } }, save: function(value) { if (!invalidEditor) return; if (value == undefined) value = currentEditor.getValue(); if (FBTrace.DBG_EDITOR) FBTrace.sysout("editor.save saveTimeout: "+this.saveTimeout+" currentPanel: "+(currentPanel?currentPanel.name:"null")); try { this.saveEditAndNotifyListeners(currentTarget, value, previousValue); previousValue = value; invalidEditor = false; } catch (exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("editor.save FAILS "+exc, exc); } }, saveEditAndNotifyListeners: function(currentTarget, value, previousValue) { currentEditor.saveEdit(currentTarget, value, previousValue); //dispatch(this.fbListeners, "onSaveEdit", [currentPanel, currentEditor, currentTarget, value, previousValue]); }, setEditTarget: function(element) { if (!element) { dispatch([Firebug.A11yModel], 'onInlineEditorClose', [currentPanel, currentTarget, true]); this.stopEditing(); } else if (hasClass(element, "insertBefore")) this.insertRow(element, "before"); else if (hasClass(element, "insertAfter")) this.insertRow(element, "after"); else this.startEditing(element); }, tabNextEditor: function() { if (!currentTarget) return; var value = currentEditor.getValue(); var nextEditable = currentTarget; do { nextEditable = !value && currentGroup ? getNextOutsider(nextEditable, currentGroup) : getNextByClass(nextEditable, "editable"); } while (nextEditable && !nextEditable.offsetHeight); this.setEditTarget(nextEditable); }, tabPreviousEditor: function() { if (!currentTarget) return; var value = currentEditor.getValue(); var prevEditable = currentTarget; do { prevEditable = !value && currentGroup ? getPreviousOutsider(prevEditable, currentGroup) : getPreviousByClass(prevEditable, "editable"); } while (prevEditable && !prevEditable.offsetHeight); this.setEditTarget(prevEditable); }, insertRow: function(relative, insertWhere) { var group = relative || getAncestorByClass(currentTarget, "editGroup") || currentTarget; var value = this.stopEditing(); currentPanel = Firebug.getElementPanel(group); currentEditor = currentPanel.getEditor(group, value); if (!currentEditor) currentEditor = getDefaultEditor(currentPanel); currentGroup = currentEditor.insertNewRow(group, insertWhere); if (!currentGroup) return; var editable = hasClass(currentGroup, "editable") ? currentGroup : getNextByClass(currentGroup, "editable"); if (editable) this.setEditTarget(editable); }, insertRowForObject: function(relative) { var container = getAncestorByClass(relative, "insertInto"); if (container) { relative = getChildByClass(container, "insertBefore"); if (relative) this.insertRow(relative, "before"); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * attachListeners: function(editor, context) { var win = isIE ? currentTarget.ownerDocument.parentWindow : currentTarget.ownerDocument.defaultView; addEvent(win, "resize", this.onResize); addEvent(win, "blur", this.onBlur); var chrome = Firebug.chrome; this.listeners = [ chrome.keyCodeListen("ESCAPE", null, bind(this.cancelEditing, this)) ]; if (editor.arrowCompletion) { this.listeners.push( chrome.keyCodeListen("UP", null, bindFixed(editor.completeValue, editor, -1)), chrome.keyCodeListen("DOWN", null, bindFixed(editor.completeValue, editor, 1)), chrome.keyCodeListen("PAGE_UP", null, bindFixed(editor.completeValue, editor, -pageAmount)), chrome.keyCodeListen("PAGE_DOWN", null, bindFixed(editor.completeValue, editor, pageAmount)) ); } if (currentEditor.tabNavigation) { this.listeners.push( chrome.keyCodeListen("RETURN", null, bind(this.tabNextEditor, this)), chrome.keyCodeListen("RETURN", isControl, bind(this.insertRow, this, null, "after")), chrome.keyCodeListen("TAB", null, bind(this.tabNextEditor, this)), chrome.keyCodeListen("TAB", isShift, bind(this.tabPreviousEditor, this)) ); } else if (currentEditor.multiLine) { this.listeners.push( chrome.keyCodeListen("TAB", null, insertTab) ); } else { this.listeners.push( chrome.keyCodeListen("RETURN", null, bindFixed(this.stopEditing, this)) ); if (currentEditor.tabCompletion) { this.listeners.push( chrome.keyCodeListen("TAB", null, bind(editor.completeValue, editor, 1)), chrome.keyCodeListen("TAB", isShift, bind(editor.completeValue, editor, -1)) ); } } }, detachListeners: function(editor, context) { if (!this.listeners) return; var win = isIE ? currentTarget.ownerDocument.parentWindow : currentTarget.ownerDocument.defaultView; removeEvent(win, "resize", this.onResize); removeEvent(win, "blur", this.onBlur); var chrome = Firebug.chrome; if (chrome) { for (var i = 0; i < this.listeners.length; ++i) chrome.keyIgnore(this.listeners[i]); } delete this.listeners; }, onResize: function(event) { currentEditor.layout(true); }, onBlur: function(event) { if (currentEditor.enterOnBlur && isAncestor(event.target, currentEditor.box)) this.stopEditing(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module initialize: function() { Firebug.Module.initialize.apply(this, arguments); this.onResize = bindFixed(this.onResize, this); this.onBlur = bind(this.onBlur, this); }, disable: function() { this.stopEditing(); }, showContext: function(browser, context) { this.stopEditing(); }, showPanel: function(browser, panel) { this.stopEditing(); } }); // ************************************************************************************************ // BaseEditor Firebug.BaseEditor = extend(Firebug.MeasureBox, { getValue: function() { }, setValue: function(value) { }, show: function(target, panel, value, textSize, targetSize) { }, hide: function() { }, layout: function(forceAll) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Support for context menus within inline editors. getContextMenuItems: function(target) { var items = []; items.push({label: "Cut", commandID: "cmd_cut"}); items.push({label: "Copy", commandID: "cmd_copy"}); items.push({label: "Paste", commandID: "cmd_paste"}); return items; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Editor Module listeners will get "onBeginEditing" just before this call beginEditing: function(target, value) { }, // Editor Module listeners will get "onSaveEdit" just after this call saveEdit: function(target, value, previousValue) { }, endEditing: function(target, value, cancel) { // Remove empty groups by default return true; }, insertNewRow: function(target, insertWhere) { } }); // ************************************************************************************************ // InlineEditor // basic inline editor attributes var inlineEditorAttributes = { "class": "textEditorInner", type: "text", spellcheck: "false", onkeypress: "$onKeyPress", onoverflow: "$onOverflow", oncontextmenu: "$onContextMenu" }; // IE does not support the oninput event, so we're using the onkeydown to signalize // the relevant keyboard events, and the onpropertychange to actually handle the // input event, which should happen after the onkeydown event is fired and after the // value of the input is updated, but before the onkeyup and before the input (with the // new value) is rendered if (isIE) { inlineEditorAttributes.onpropertychange = "$onInput"; inlineEditorAttributes.onkeydown = "$onKeyDown"; } // for other browsers we use the oninput event else { inlineEditorAttributes.oninput = "$onInput"; } Firebug.InlineEditor = function(doc) { this.initializeInline(doc); }; Firebug.InlineEditor.prototype = domplate(Firebug.BaseEditor, { enterOnBlur: true, outerMargin: 8, shadowExpand: 7, tag: DIV({"class": "inlineEditor"}, DIV({"class": "textEditorTop1"}, DIV({"class": "textEditorTop2"}) ), DIV({"class": "textEditorInner1"}, DIV({"class": "textEditorInner2"}, INPUT( inlineEditorAttributes ) ) ), DIV({"class": "textEditorBottom1"}, DIV({"class": "textEditorBottom2"}) ) ), inputTag : INPUT({"class": "textEditorInner", type: "text", /*oninput: "$onInput",*/ onkeypress: "$onKeyPress", onoverflow: "$onOverflow"} ), expanderTag: IMG({"class": "inlineExpander", src: "blank.gif"}), initialize: function() { this.fixedWidth = false; this.completeAsYouType = true; this.tabNavigation = true; this.multiLine = false; this.tabCompletion = false; this.arrowCompletion = true; this.noWrap = true; this.numeric = false; }, destroy: function() { this.destroyInput(); }, initializeInline: function(doc) { if (FBTrace.DBG_EDITOR) FBTrace.sysout("Firebug.InlineEditor initializeInline()"); //this.box = this.tag.replace({}, doc, this); this.box = this.tag.append({}, doc.body, this); //this.input = this.box.childNodes[1].firstChild.firstChild; // XXXjjb childNode[1] required this.input = this.box.getElementsByTagName("input")[0]; if (isIElt8) { this.input.style.top = "-8px"; } this.expander = this.expanderTag.replace({}, doc, this); this.initialize(); }, destroyInput: function() { // XXXjoe Need to remove input/keypress handlers to avoid leaks }, getValue: function() { return this.input.value; }, setValue: function(value) { // It's only a one-line editor, so new lines shouldn't be allowed return this.input.value = stripNewLines(value); }, show: function(target, panel, value, targetSize) { //dispatch([Firebug.A11yModel], "onInlineEditorShow", [panel, this]); this.target = target; this.panel = panel; this.targetSize = targetSize; // TODO: xxxpedro editor //this.targetOffset = getClientOffset(target); // Some browsers (IE, Google Chrome and Safari) will have problem trying to get the // offset values of invisible elements, or empty elements. So, in order to get the // correct values, we temporary inject a character in the innerHTML of the empty element, // then we get the offset values, and next, we restore the original innerHTML value. var innerHTML = target.innerHTML; var isEmptyElement = !innerHTML; if (isEmptyElement) target.innerHTML = "."; // Get the position of the target element (that is about to be edited) this.targetOffset = { x: target.offsetLeft, y: target.offsetTop }; // Restore the original innerHTML value of the empty element if (isEmptyElement) target.innerHTML = innerHTML; this.originalClassName = this.box.className; var classNames = target.className.split(" "); for (var i = 0; i < classNames.length; ++i) setClass(this.box, "editor-" + classNames[i]); // Make the editor match the target's font style copyTextStyles(target, this.box); this.setValue(value); if (this.fixedWidth) this.updateLayout(true); else { this.startMeasuring(target); this.textSize = this.measureInputText(value); // Correct the height of the box to make the funky CSS drop-shadow line up var parent = this.input.parentNode; if (hasClass(parent, "textEditorInner2")) { var yDiff = this.textSize.height - this.shadowExpand; // IE6 height offset if (isIE6) yDiff -= 2; parent.style.height = yDiff + "px"; parent.parentNode.style.height = yDiff + "px"; } this.updateLayout(true); } this.getAutoCompleter().reset(); if (isIElt8) panel.panelNode.appendChild(this.box); else target.offsetParent.appendChild(this.box); //console.log(target); //this.input.select(); // it's called bellow, with setTimeout if (isIE) { // reset input style this.input.style.fontFamily = "Monospace"; this.input.style.fontSize = "11px"; } // Insert the "expander" to cover the target element with white space if (!this.fixedWidth) { copyBoxStyles(target, this.expander); target.parentNode.replaceChild(this.expander, target); collapse(target, true); this.expander.parentNode.insertBefore(target, this.expander); } //TODO: xxxpedro //scrollIntoCenterView(this.box, null, true); // Display the editor after change its size and position to avoid flickering this.box.style.display = "block"; // we need to call input.focus() and input.select() with a timeout, // otherwise it won't work on all browsers due to timing issues var self = this; setTimeout(function(){ self.input.focus(); self.input.select(); },0); }, hide: function() { this.box.className = this.originalClassName; if (!this.fixedWidth) { this.stopMeasuring(); collapse(this.target, false); if (this.expander.parentNode) this.expander.parentNode.removeChild(this.expander); } if (this.box.parentNode) { ///setSelectionRange(this.input, 0, 0); this.input.blur(); this.box.parentNode.removeChild(this.box); } delete this.target; delete this.panel; }, layout: function(forceAll) { if (!this.fixedWidth) this.textSize = this.measureInputText(this.input.value); if (forceAll) this.targetOffset = getClientOffset(this.expander); this.updateLayout(false, forceAll); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * beginEditing: function(target, value) { }, saveEdit: function(target, value, previousValue) { }, endEditing: function(target, value, cancel) { // Remove empty groups by default return true; }, insertNewRow: function(target, insertWhere) { }, advanceToNext: function(target, charCode) { return false; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getAutoCompleteRange: function(value, offset) { }, getAutoCompleteList: function(preExpr, expr, postExpr) { }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getAutoCompleter: function() { if (!this.autoCompleter) { this.autoCompleter = new Firebug.AutoCompleter(null, bind(this.getAutoCompleteRange, this), bind(this.getAutoCompleteList, this), true, false); } return this.autoCompleter; }, completeValue: function(amt) { //console.log("completeValue"); var selectRangeCallback = this.getAutoCompleter().complete(currentPanel.context, this.input, true, amt < 0); if (selectRangeCallback) { Firebug.Editor.update(true); // We need to select the editor text after calling update in Safari/Chrome, // otherwise the text won't be selected if (isSafari) setTimeout(selectRangeCallback,0); else selectRangeCallback(); } else this.incrementValue(amt); }, incrementValue: function(amt) { var value = this.input.value; // TODO: xxxpedro editor if (isIE) var start = getInputSelectionStart(this.input), end = start; else var start = this.input.selectionStart, end = this.input.selectionEnd; //debugger; var range = this.getAutoCompleteRange(value, start); if (!range || range.type != "int") range = {start: 0, end: value.length-1}; var expr = value.substr(range.start, range.end-range.start+1); preExpr = value.substr(0, range.start); postExpr = value.substr(range.end+1); // See if the value is an integer, and if so increment it var intValue = parseInt(expr); if (!!intValue || intValue == 0) { var m = /\d+/.exec(expr); var digitPost = expr.substr(m.index+m[0].length); var completion = intValue-amt; this.input.value = preExpr + completion + digitPost + postExpr; setSelectionRange(this.input, start, end); Firebug.Editor.update(true); return true; } else return false; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onKeyPress: function(event) { //console.log("onKeyPress", event); if (event.keyCode == 27 && !this.completeAsYouType) { var reverted = this.getAutoCompleter().revert(this.input); if (reverted) cancelEvent(event); } else if (event.charCode && this.advanceToNext(this.target, event.charCode)) { Firebug.Editor.tabNextEditor(); cancelEvent(event); } else { if (this.numeric && event.charCode && (event.charCode < 48 || event.charCode > 57) && event.charCode != 45 && event.charCode != 46) FBL.cancelEvent(event); else { // If the user backspaces, don't autocomplete after the upcoming input event this.ignoreNextInput = event.keyCode == 8; } } }, onOverflow: function() { this.updateLayout(false, false, 3); }, onKeyDown: function(event) { //console.log("onKeyDown", event.keyCode); if (event.keyCode > 46 || event.keyCode == 32 || event.keyCode == 8) { this.keyDownPressed = true; } }, onInput: function(event) { //debugger; // skip not relevant onpropertychange calls on IE if (isIE) { if (event.propertyName != "value" || !isVisible(this.input) || !this.keyDownPressed) return; this.keyDownPressed = false; } //console.log("onInput", event); //console.trace(); var selectRangeCallback; if (this.ignoreNextInput) { this.ignoreNextInput = false; this.getAutoCompleter().reset(); } else if (this.completeAsYouType) selectRangeCallback = this.getAutoCompleter().complete(currentPanel.context, this.input, false); else this.getAutoCompleter().reset(); Firebug.Editor.update(); if (selectRangeCallback) { // We need to select the editor text after calling update in Safari/Chrome, // otherwise the text won't be selected if (isSafari) setTimeout(selectRangeCallback,0); else selectRangeCallback(); } }, onContextMenu: function(event) { cancelEvent(event); var popup = $("fbInlineEditorPopup"); FBL.eraseNode(popup); var target = event.target || event.srcElement; var menu = this.getContextMenuItems(target); if (menu) { for (var i = 0; i < menu.length; ++i) FBL.createMenuItem(popup, menu[i]); } if (!popup.firstChild) return false; popup.openPopupAtScreen(event.screenX, event.screenY, true); return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateLayout: function(initial, forceAll, extraWidth) { if (this.fixedWidth) { this.box.style.left = (this.targetOffset.x) + "px"; this.box.style.top = (this.targetOffset.y) + "px"; var w = this.target.offsetWidth; var h = this.target.offsetHeight; this.input.style.width = w + "px"; this.input.style.height = (h-3) + "px"; } else { if (initial || forceAll) { this.box.style.left = this.targetOffset.x + "px"; this.box.style.top = this.targetOffset.y + "px"; } var approxTextWidth = this.textSize.width; var maxWidth = (currentPanel.panelNode.scrollWidth - this.targetOffset.x) - this.outerMargin; var wrapped = initial ? this.noWrap && this.targetSize.height > this.textSize.height+3 : this.noWrap && approxTextWidth > maxWidth; if (wrapped) { var style = isIE ? this.target.currentStyle : this.target.ownerDocument.defaultView.getComputedStyle(this.target, ""); targetMargin = parseInt(style.marginLeft) + parseInt(style.marginRight); // Make the width fit the remaining x-space from the offset to the far right approxTextWidth = maxWidth - targetMargin; this.input.style.width = "100%"; this.box.style.width = approxTextWidth + "px"; } else { // Make the input one character wider than the text value so that // typing does not ever cause the textbox to scroll var charWidth = this.measureInputText('m').width; // Sometimes we need to make the editor a little wider, specifically when // an overflow happens, otherwise it will scroll off some text on the left if (extraWidth) charWidth *= extraWidth; var inputWidth = approxTextWidth + charWidth; if (initial) { if (isIE) { // TODO: xxxpedro var xDiff = 13; this.box.style.width = (inputWidth + xDiff) + "px"; } else this.box.style.width = "auto"; } else { // TODO: xxxpedro var xDiff = isIE ? 13: this.box.scrollWidth - this.input.offsetWidth; this.box.style.width = (inputWidth + xDiff) + "px"; } this.input.style.width = inputWidth + "px"; } this.expander.style.width = approxTextWidth + "px"; this.expander.style.height = Math.max(this.textSize.height-3,0) + "px"; } if (forceAll) scrollIntoCenterView(this.box, null, true); } }); // ************************************************************************************************ // Autocompletion Firebug.AutoCompleter = function(getExprOffset, getRange, evaluator, selectMode, caseSensitive) { var candidates = null; var originalValue = null; var originalOffset = -1; var lastExpr = null; var lastOffset = -1; var exprOffset = 0; var lastIndex = 0; var preParsed = null; var preExpr = null; var postExpr = null; this.revert = function(textBox) { if (originalOffset != -1) { textBox.value = originalValue; setSelectionRange(textBox, originalOffset, originalOffset); this.reset(); return true; } else { this.reset(); return false; } }; this.reset = function() { candidates = null; originalValue = null; originalOffset = -1; lastExpr = null; lastOffset = 0; exprOffset = 0; }; this.complete = function(context, textBox, cycle, reverse) { //console.log("complete", context, textBox, cycle, reverse); // TODO: xxxpedro important port to firebug (variable leak) //var value = lastValue = textBox.value; var value = textBox.value; //var offset = textBox.selectionStart; var offset = getInputSelectionStart(textBox); // The result of selectionStart() in Safari/Chrome is 1 unit less than the result // in Firefox. Therefore, we need to manually adjust the value here. if (isSafari && !cycle && offset >= 0) offset++; if (!selectMode && originalOffset != -1) offset = originalOffset; if (!candidates || !cycle || offset != lastOffset) { originalOffset = offset; originalValue = value; // Find the part of the string that will be parsed var parseStart = getExprOffset ? getExprOffset(value, offset, context) : 0; preParsed = value.substr(0, parseStart); var parsed = value.substr(parseStart); // Find the part of the string that is being completed var range = getRange ? getRange(parsed, offset-parseStart, context) : null; if (!range) range = {start: 0, end: parsed.length-1 }; var expr = parsed.substr(range.start, range.end-range.start+1); preExpr = parsed.substr(0, range.start); postExpr = parsed.substr(range.end+1); exprOffset = parseStart + range.start; if (!cycle) { if (!expr) return; else if (lastExpr && lastExpr.indexOf(expr) != 0) { candidates = null; } else if (lastExpr && lastExpr.length >= expr.length) { candidates = null; lastExpr = expr; return; } } lastExpr = expr; lastOffset = offset; var searchExpr; // Check if the cursor is at the very right edge of the expression, or // somewhere in the middle of it if (expr && offset != parseStart+range.end+1) { if (cycle) { // We are in the middle of the expression, but we can // complete by cycling to the next item in the values // list after the expression offset = range.start; searchExpr = expr; expr = ""; } else { // We can't complete unless we are at the ridge edge return; } } var values = evaluator(preExpr, expr, postExpr, context); if (!values) return; if (expr) { // Filter the list of values to those which begin with expr. We // will then go on to complete the first value in the resulting list candidates = []; if (caseSensitive) { for (var i = 0; i < values.length; ++i) { var name = values[i]; if (name.indexOf && name.indexOf(expr) == 0) candidates.push(name); } } else { var lowerExpr = caseSensitive ? expr : expr.toLowerCase(); for (var i = 0; i < values.length; ++i) { var name = values[i]; if (name.indexOf && name.toLowerCase().indexOf(lowerExpr) == 0) candidates.push(name); } } lastIndex = reverse ? candidates.length-1 : 0; } else if (searchExpr) { var searchIndex = -1; // Find the first instance of searchExpr in the values list. We // will then complete the string that is found if (caseSensitive) { searchIndex = values.indexOf(expr); } else { var lowerExpr = searchExpr.toLowerCase(); for (var i = 0; i < values.length; ++i) { var name = values[i]; if (name && name.toLowerCase().indexOf(lowerExpr) == 0) { searchIndex = i; break; } } } // Nothing found, so there's nothing to complete to if (searchIndex == -1) return this.reset(); expr = searchExpr; candidates = cloneArray(values); lastIndex = searchIndex; } else { expr = ""; candidates = []; for (var i = 0; i < values.length; ++i) { if (values[i].substr) candidates.push(values[i]); } lastIndex = -1; } } if (cycle) { expr = lastExpr; lastIndex += reverse ? -1 : 1; } if (!candidates.length) return; if (lastIndex >= candidates.length) lastIndex = 0; else if (lastIndex < 0) lastIndex = candidates.length-1; var completion = candidates[lastIndex]; var preCompletion = expr.substr(0, offset-exprOffset); var postCompletion = completion.substr(offset-exprOffset); textBox.value = preParsed + preExpr + preCompletion + postCompletion + postExpr; var offsetEnd = preParsed.length + preExpr.length + completion.length; // TODO: xxxpedro remove the following commented code, if the lib.setSelectionRange() // is working well. /* if (textBox.setSelectionRange) { // we must select the range with a timeout, otherwise the text won't // be properly selected (because after this function executes, the editor's // input will be resized to fit the whole text) setTimeout(function(){ if (selectMode) textBox.setSelectionRange(offset, offsetEnd); else textBox.setSelectionRange(offsetEnd, offsetEnd); },0); } /**/ // we must select the range with a timeout, otherwise the text won't // be properly selected (because after this function executes, the editor's // input will be resized to fit the whole text) /* setTimeout(function(){ if (selectMode) setSelectionRange(textBox, offset, offsetEnd); else setSelectionRange(textBox, offsetEnd, offsetEnd); },0); return true; /**/ // The editor text should be selected only after calling the editor.update() // in Safari/Chrome, otherwise the text won't be selected. So, we're returning // a function to be called later (in the proper time for all browsers). // // TODO: xxxpedro see if we can move the editor.update() calls to here, and avoid // returning a closure. the complete() function seems to be called only twice in // editor.js. See if this function is called anywhere else (like css.js for example). return function(){ //console.log("autocomplete ", textBox, offset, offsetEnd); if (selectMode) setSelectionRange(textBox, offset, offsetEnd); else setSelectionRange(textBox, offsetEnd, offsetEnd); }; /**/ }; }; // ************************************************************************************************ // Local Helpers var getDefaultEditor = function getDefaultEditor(panel) { if (!defaultEditor) { var doc = panel.document; defaultEditor = new Firebug.InlineEditor(doc); } return defaultEditor; } /** * An outsider is the first element matching the stepper element that * is not an child of group. Elements tagged with insertBefore or insertAfter * classes are also excluded from these results unless they are the sibling * of group, relative to group's parent editGroup. This allows for the proper insertion * rows when groups are nested. */ var getOutsider = function getOutsider(element, group, stepper) { var parentGroup = getAncestorByClass(group.parentNode, "editGroup"); var next; do { next = stepper(next || element); } while (isAncestor(next, group) || isGroupInsert(next, parentGroup)); return next; } var isGroupInsert = function isGroupInsert(next, group) { return (!group || isAncestor(next, group)) && (hasClass(next, "insertBefore") || hasClass(next, "insertAfter")); } var getNextOutsider = function getNextOutsider(element, group) { return getOutsider(element, group, bind(getNextByClass, FBL, "editable")); } var getPreviousOutsider = function getPreviousOutsider(element, group) { return getOutsider(element, group, bind(getPreviousByClass, FBL, "editable")); } var getInlineParent = function getInlineParent(element) { var lastInline = element; for (; element; element = element.parentNode) { //var s = element.ownerDocument.defaultView.getComputedStyle(element, ""); var s = isIE ? element.currentStyle : element.ownerDocument.defaultView.getComputedStyle(element, ""); if (s.display != "inline") return lastInline; else lastInline = element; } return null; } var insertTab = function insertTab() { insertTextIntoElement(currentEditor.input, Firebug.Editor.tabCharacter); } // ************************************************************************************************ Firebug.registerModule(Firebug.Editor); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ if (Env.Options.disableXHRListener) return; // ************************************************************************************************ // XHRSpy var XHRSpy = function() { this.requestHeaders = []; this.responseHeaders = []; }; XHRSpy.prototype = { method: null, url: null, async: null, xhrRequest: null, href: null, loaded: false, logRow: null, responseText: null, requestHeaders: null, responseHeaders: null, sourceLink: null, // {href:"file.html", line: 22} getURL: function() { return this.href; } }; // ************************************************************************************************ // XMLHttpRequestWrapper var XMLHttpRequestWrapper = function(activeXObject) { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper internal variables var xhrRequest = typeof activeXObject != "undefined" ? activeXObject : new _XMLHttpRequest(), spy = new XHRSpy(), self = this, reqType, reqUrl, reqStartTS; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper internal methods var updateSelfPropertiesIgnore = { abort: 1, channel: 1, getAllResponseHeaders: 1, getInterface: 1, getResponseHeader: 1, mozBackgroundRequest: 1, multipart: 1, onreadystatechange: 1, open: 1, send: 1, setRequestHeader: 1 }; var updateSelfProperties = function() { if (supportsXHRIterator) { for (var propName in xhrRequest) { if (propName in updateSelfPropertiesIgnore) continue; try { var propValue = xhrRequest[propName]; if (propValue && !isFunction(propValue)) self[propName] = propValue; } catch(E) { //console.log(propName, E.message); } } } else { // will fail to read these xhrRequest properties if the request is not completed if (xhrRequest.readyState == 4) { self.status = xhrRequest.status; self.statusText = xhrRequest.statusText; self.responseText = xhrRequest.responseText; self.responseXML = xhrRequest.responseXML; } } }; var updateXHRPropertiesIgnore = { channel: 1, onreadystatechange: 1, readyState: 1, responseBody: 1, responseText: 1, responseXML: 1, status: 1, statusText: 1, upload: 1 }; var updateXHRProperties = function() { for (var propName in self) { if (propName in updateXHRPropertiesIgnore) continue; try { var propValue = self[propName]; if (propValue && !xhrRequest[propName]) { xhrRequest[propName] = propValue; } } catch(E) { //console.log(propName, E.message); } } }; var logXHR = function() { var row = Firebug.Console.log(spy, null, "spy", Firebug.Spy.XHR); if (row) { setClass(row, "loading"); spy.logRow = row; } }; var finishXHR = function() { var duration = new Date().getTime() - reqStartTS; var success = xhrRequest.status == 200; var responseHeadersText = xhrRequest.getAllResponseHeaders(); var responses = responseHeadersText ? responseHeadersText.split(/[\n\r]/) : []; var reHeader = /^(\S+):\s*(.*)/; for (var i=0, l=responses.length; i<l; i++) { var text = responses[i]; var match = text.match(reHeader); if (match) { var name = match[1]; var value = match[2]; // update the spy mimeType property so we can detect when to show // custom response viewers (such as HTML, XML or JSON viewer) if (name == "Content-Type") spy.mimeType = value; /* if (name == "Last Modified") { if (!spy.cacheEntry) spy.cacheEntry = []; spy.cacheEntry.push({ name: [name], value: [value] }); } /**/ spy.responseHeaders.push({ name: [name], value: [value] }); } } with({ row: spy.logRow, status: xhrRequest.status == 0 ? // if xhrRequest.status == 0 then accessing xhrRequest.statusText // will cause an error, so we must handle this case (Issue 3504) "" : xhrRequest.status + " " + xhrRequest.statusText, time: duration, success: success }) { setTimeout(function(){ spy.responseText = xhrRequest.responseText; // update row information to avoid "ethernal spinning gif" bug in IE row = row || spy.logRow; // if chrome document is not loaded, there will be no row yet, so just ignore if (!row) return; // update the XHR representation data handleRequestStatus(success, status, time); },200); } spy.loaded = true; /* // commented because they are being updated by the updateSelfProperties() function self.status = xhrRequest.status; self.statusText = xhrRequest.statusText; self.responseText = xhrRequest.responseText; self.responseXML = xhrRequest.responseXML; /**/ updateSelfProperties(); }; var handleStateChange = function() { //Firebug.Console.log(["onreadystatechange", xhrRequest.readyState, xhrRequest.readyState == 4 && xhrRequest.status]); self.readyState = xhrRequest.readyState; if (xhrRequest.readyState == 4) { finishXHR(); xhrRequest.onreadystatechange = function(){}; } //Firebug.Console.log(spy.url + ": " + xhrRequest.readyState); self.onreadystatechange(); }; // update the XHR representation data var handleRequestStatus = function(success, status, time) { var row = spy.logRow; FBL.removeClass(row, "loading"); if (!success) FBL.setClass(row, "error"); var item = FBL.$$(".spyStatus", row)[0]; item.innerHTML = status; if (time) { var item = FBL.$$(".spyTime", row)[0]; item.innerHTML = time + "ms"; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper public properties and handlers this.readyState = 0; this.onreadystatechange = function(){}; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // XMLHttpRequestWrapper public methods this.open = function(method, url, async, user, password) { //Firebug.Console.log("xhrRequest open"); updateSelfProperties(); if (spy.loaded) spy = new XHRSpy(); spy.method = method; spy.url = url; spy.async = async; spy.href = url; spy.xhrRequest = xhrRequest; spy.urlParams = parseURLParamsArray(url); try { // xhrRequest.open.apply may not be available in IE if (supportsApply) xhrRequest.open.apply(xhrRequest, arguments); else xhrRequest.open(method, url, async, user, password); } catch(e) { } xhrRequest.onreadystatechange = handleStateChange; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.send = function(data) { //Firebug.Console.log("xhrRequest send"); spy.data = data; reqStartTS = new Date().getTime(); updateXHRProperties(); try { xhrRequest.send(data); } catch(e) { // TODO: xxxpedro XHR throws or not? //throw e; } finally { logXHR(); if (!spy.async) { self.readyState = xhrRequest.readyState; // sometimes an error happens when calling finishXHR() // Issue 3422: Firebug Lite breaks Google Instant Search try { finishXHR(); } catch(E) { } } } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.setRequestHeader = function(header, value) { spy.requestHeaders.push({name: [header], value: [value]}); return xhrRequest.setRequestHeader(header, value); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.abort = function() { xhrRequest.abort(); updateSelfProperties(); handleRequestStatus(false, "Aborted"); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.getResponseHeader = function(header) { return xhrRequest.getResponseHeader(header); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * this.getAllResponseHeaders = function() { return xhrRequest.getAllResponseHeaders(); }; /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Clone XHR object // xhrRequest.open.apply not available in IE and will throw an error in // IE6 by simply reading xhrRequest.open so we must sniff it var supportsApply = !isIE6 && xhrRequest && xhrRequest.open && typeof xhrRequest.open.apply != "undefined"; var numberOfXHRProperties = 0; for (var propName in xhrRequest) { numberOfXHRProperties++; if (propName in updateSelfPropertiesIgnore) continue; try { var propValue = xhrRequest[propName]; if (isFunction(propValue)) { if (typeof self[propName] == "undefined") { this[propName] = (function(name, xhr){ return supportsApply ? // if the browser supports apply function() { return xhr[name].apply(xhr, arguments); } : function(a,b,c,d,e) { return xhr[name](a,b,c,d,e); }; })(propName, xhrRequest); } } else this[propName] = propValue; } catch(E) { //console.log(propName, E.message); } } // IE6 does not support for (var prop in XHR) var supportsXHRIterator = numberOfXHRProperties > 0; /**/ return this; }; // ************************************************************************************************ // ActiveXObject Wrapper (IE6 only) var _ActiveXObject; var isIE6 = /msie 6/i.test(navigator.appVersion); if (isIE6) { _ActiveXObject = window.ActiveXObject; var xhrObjects = " MSXML2.XMLHTTP.5.0 MSXML2.XMLHTTP.4.0 MSXML2.XMLHTTP.3.0 MSXML2.XMLHTTP Microsoft.XMLHTTP "; window.ActiveXObject = function(name) { var error = null; try { var activeXObject = new _ActiveXObject(name); } catch(e) { error = e; } finally { if (!error) { if (xhrObjects.indexOf(" " + name + " ") != -1) return new XMLHttpRequestWrapper(activeXObject); else return activeXObject; } else throw error.message; } }; } // ************************************************************************************************ // Register the XMLHttpRequestWrapper for non-IE6 browsers if (!isIE6) { var _XMLHttpRequest = XMLHttpRequest; window.XMLHttpRequest = function() { return new XMLHttpRequestWrapper(); }; } //************************************************************************************************ FBL.getNativeXHRObject = function() { var xhrObj = false; try { xhrObj = new _XMLHttpRequest(); } catch(e) { var progid = [ "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ]; for ( var i=0; i < progid.length; ++i ) { try { xhrObj = new _ActiveXObject(progid[i]); } catch(e) { continue; } break; } } finally { return xhrObj; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var reIgnore = /about:|javascript:|resource:|chrome:|jar:/; var layoutInterval = 300; var indentWidth = 18; var cacheSession = null; var contexts = new Array(); var panelName = "net"; var maxQueueRequests = 500; //var panelBar1 = $("fbPanelBar1"); // chrome not available at startup var activeRequests = []; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var mimeExtensionMap = { "txt": "text/plain", "html": "text/html", "htm": "text/html", "xhtml": "text/html", "xml": "text/xml", "css": "text/css", "js": "application/x-javascript", "jss": "application/x-javascript", "jpg": "image/jpg", "jpeg": "image/jpeg", "gif": "image/gif", "png": "image/png", "bmp": "image/bmp", "swf": "application/x-shockwave-flash", "flv": "video/x-flv" }; var fileCategories = { "undefined": 1, "html": 1, "css": 1, "js": 1, "xhr": 1, "image": 1, "flash": 1, "txt": 1, "bin": 1 }; var textFileCategories = { "txt": 1, "html": 1, "xhr": 1, "css": 1, "js": 1 }; var binaryFileCategories = { "bin": 1, "flash": 1 }; var mimeCategoryMap = { "text/plain": "txt", "application/octet-stream": "bin", "text/html": "html", "text/xml": "html", "text/css": "css", "application/x-javascript": "js", "text/javascript": "js", "application/javascript" : "js", "image/jpeg": "image", "image/jpg": "image", "image/gif": "image", "image/png": "image", "image/bmp": "image", "application/x-shockwave-flash": "flash", "video/x-flv": "flash" }; var binaryCategoryMap = { "image": 1, "flash" : 1 }; // ************************************************************************************************ /** * @module Represents a module object for the Net panel. This object is derived * from <code>Firebug.ActivableModule</code> in order to support activation (enable/disable). * This allows to avoid (performance) expensive features if the functionality is not necessary * for the user. */ Firebug.NetMonitor = extend(Firebug.ActivableModule, { dispatchName: "netMonitor", clear: function(context) { // The user pressed a Clear button so, remove content of the panel... var panel = context.getPanel(panelName, true); if (panel) panel.clear(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module initialize: function() { return; this.panelName = panelName; Firebug.ActivableModule.initialize.apply(this, arguments); if (Firebug.TraceModule) Firebug.TraceModule.addListener(this.TraceListener); // HTTP observer must be registered now (and not in monitorContext, since if a // page is opened in a new tab the top document request would be missed otherwise. NetHttpObserver.registerObserver(); NetHttpActivityObserver.registerObserver(); Firebug.Debugger.addListener(this.DebuggerListener); }, shutdown: function() { return; prefs.removeObserver(Firebug.prefDomain, this, false); if (Firebug.TraceModule) Firebug.TraceModule.removeListener(this.TraceListener); NetHttpObserver.unregisterObserver(); NetHttpActivityObserver.unregisterObserver(); Firebug.Debugger.removeListener(this.DebuggerListener); } }); /** * @domplate Represents a template that is used to reneder detailed info about a request. * This template is rendered when a request is expanded. */ Firebug.NetMonitor.NetInfoBody = domplate(Firebug.Rep, new Firebug.Listener(), { tag: DIV({"class": "netInfoBody", _repObject: "$file"}, TAG("$infoTabs", {file: "$file"}), TAG("$infoBodies", {file: "$file"}) ), infoTabs: DIV({"class": "netInfoTabs focusRow subFocusRow", "role": "tablist"}, A({"class": "netInfoParamsTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Params", $collapsed: "$file|hideParams"}, $STR("URLParameters") ), A({"class": "netInfoHeadersTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Headers"}, $STR("Headers") ), A({"class": "netInfoPostTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Post", $collapsed: "$file|hidePost"}, $STR("Post") ), A({"class": "netInfoPutTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Put", $collapsed: "$file|hidePut"}, $STR("Put") ), A({"class": "netInfoResponseTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Response", $collapsed: "$file|hideResponse"}, $STR("Response") ), A({"class": "netInfoCacheTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Cache", $collapsed: "$file|hideCache"}, $STR("Cache") ), A({"class": "netInfoHtmlTab netInfoTab a11yFocus", onclick: "$onClickTab", "role": "tab", view: "Html", $collapsed: "$file|hideHtml"}, $STR("HTML") ) ), infoBodies: DIV({"class": "netInfoBodies outerFocusRow"}, TABLE({"class": "netInfoParamsText netInfoText netInfoParamsTable", "role": "tabpanel", cellpadding: 0, cellspacing: 0}, TBODY()), DIV({"class": "netInfoHeadersText netInfoText", "role": "tabpanel"}), DIV({"class": "netInfoPostText netInfoText", "role": "tabpanel"}), DIV({"class": "netInfoPutText netInfoText", "role": "tabpanel"}), PRE({"class": "netInfoResponseText netInfoText", "role": "tabpanel"}), DIV({"class": "netInfoCacheText netInfoText", "role": "tabpanel"}, TABLE({"class": "netInfoCacheTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("Cache")}) ) ), DIV({"class": "netInfoHtmlText netInfoText", "role": "tabpanel"}, IFRAME({"class": "netInfoHtmlPreview", "role": "document"}) ) ), headerDataTag: FOR("param", "$headers", TR({"role": "listitem"}, TD({"class": "netInfoParamName", "role": "presentation"}, TAG("$param|getNameTag", {param: "$param"}) ), TD({"class": "netInfoParamValue", "role": "list", "aria-label": "$param.name"}, FOR("line", "$param|getParamValueIterator", CODE({"class": "focusRow subFocusRow", "role": "listitem"}, "$line") ) ) ) ), customTab: A({"class": "netInfo$tabId\\Tab netInfoTab", onclick: "$onClickTab", view: "$tabId", "role": "tab"}, "$tabTitle" ), customBody: DIV({"class": "netInfo$tabId\\Text netInfoText", "role": "tabpanel"}), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * nameTag: SPAN("$param|getParamName"), nameWithTooltipTag: SPAN({title: "$param.name"}, "$param|getParamName"), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getNameTag: function(param) { return (this.getParamName(param) == param.name) ? this.nameTag : this.nameWithTooltipTag; }, getParamName: function(param) { var limit = 25; var name = param.name; if (name.length > limit) name = name.substr(0, limit) + "..."; return name; }, getParamTitle: function(param) { var limit = 25; var name = param.name; if (name.length > limit) return name; return ""; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * hideParams: function(file) { return !file.urlParams || !file.urlParams.length; }, hidePost: function(file) { return file.method.toUpperCase() != "POST"; }, hidePut: function(file) { return file.method.toUpperCase() != "PUT"; }, hideResponse: function(file) { return false; //return file.category in binaryFileCategories; }, hideCache: function(file) { return true; //xxxHonza: I don't see any reason why not to display the cache also info for images. return !file.cacheEntry; // || file.category=="image"; }, hideHtml: function(file) { return (file.mimeType != "text/html") && (file.mimeType != "application/xhtml+xml"); }, onClickTab: function(event) { this.selectTab(event.currentTarget || event.srcElement); }, getParamValueIterator: function(param) { // TODO: xxxpedro console2 return param.value; // This value is inserted into CODE element and so, make sure the HTML isn't escaped (1210). // This is why the second parameter is true. // The CODE (with style white-space:pre) element preserves whitespaces so they are // displayed the same, as they come from the server (1194). // In case of a long header values of post parameters the value must be wrapped (2105). return wrapText(param.value, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * appendTab: function(netInfoBox, tabId, tabTitle) { // Create new tab and body. var args = {tabId: tabId, tabTitle: tabTitle}; ///this.customTab.append(args, netInfoBox.getElementsByClassName("netInfoTabs").item(0)); ///this.customBody.append(args, netInfoBox.getElementsByClassName("netInfoBodies").item(0)); this.customTab.append(args, $$(".netInfoTabs", netInfoBox)[0]); this.customBody.append(args, $$(".netInfoBodies", netInfoBox)[0]); }, selectTabByName: function(netInfoBox, tabName) { var tab = getChildByClass(netInfoBox, "netInfoTabs", "netInfo"+tabName+"Tab"); if (tab) this.selectTab(tab); }, selectTab: function(tab) { var view = tab.getAttribute("view"); var netInfoBox = getAncestorByClass(tab, "netInfoBody"); var selectedTab = netInfoBox.selectedTab; if (selectedTab) { //netInfoBox.selectedText.removeAttribute("selected"); removeClass(netInfoBox.selectedText, "netInfoTextSelected"); removeClass(selectedTab, "netInfoTabSelected"); //selectedTab.removeAttribute("selected"); selectedTab.setAttribute("aria-selected", "false"); } var textBodyName = "netInfo" + view + "Text"; selectedTab = netInfoBox.selectedTab = tab; netInfoBox.selectedText = $$("."+textBodyName, netInfoBox)[0]; //netInfoBox.selectedText = netInfoBox.getElementsByClassName(textBodyName).item(0); //netInfoBox.selectedText.setAttribute("selected", "true"); setClass(netInfoBox.selectedText, "netInfoTextSelected"); setClass(selectedTab, "netInfoTabSelected"); selectedTab.setAttribute("selected", "true"); selectedTab.setAttribute("aria-selected", "true"); var file = Firebug.getRepObject(netInfoBox); //var context = Firebug.getElementPanel(netInfoBox).context; var context = Firebug.chrome; this.updateInfo(netInfoBox, file, context); }, updateInfo: function(netInfoBox, file, context) { if (FBTrace.DBG_NET) FBTrace.sysout("net.updateInfo; file", file); if (!netInfoBox) { if (FBTrace.DBG_NET || FBTrace.DBG_ERRORS) FBTrace.sysout("net.updateInfo; ERROR netInfo == null " + file.href, file); return; } var tab = netInfoBox.selectedTab; if (hasClass(tab, "netInfoParamsTab")) { if (file.urlParams && !netInfoBox.urlParamsPresented) { netInfoBox.urlParamsPresented = true; this.insertHeaderRows(netInfoBox, file.urlParams, "Params"); } } else if (hasClass(tab, "netInfoHeadersTab")) { var headersText = $$(".netInfoHeadersText", netInfoBox)[0]; //var headersText = netInfoBox.getElementsByClassName("netInfoHeadersText").item(0); if (file.responseHeaders && !netInfoBox.responseHeadersPresented) { netInfoBox.responseHeadersPresented = true; NetInfoHeaders.renderHeaders(headersText, file.responseHeaders, "ResponseHeaders"); } if (file.requestHeaders && !netInfoBox.requestHeadersPresented) { netInfoBox.requestHeadersPresented = true; NetInfoHeaders.renderHeaders(headersText, file.requestHeaders, "RequestHeaders"); } } else if (hasClass(tab, "netInfoPostTab")) { if (!netInfoBox.postPresented) { netInfoBox.postPresented = true; //var postText = netInfoBox.getElementsByClassName("netInfoPostText").item(0); var postText = $$(".netInfoPostText", netInfoBox)[0]; NetInfoPostData.render(context, postText, file); } } else if (hasClass(tab, "netInfoPutTab")) { if (!netInfoBox.putPresented) { netInfoBox.putPresented = true; //var putText = netInfoBox.getElementsByClassName("netInfoPutText").item(0); var putText = $$(".netInfoPutText", netInfoBox)[0]; NetInfoPostData.render(context, putText, file); } } else if (hasClass(tab, "netInfoResponseTab") && file.loaded && !netInfoBox.responsePresented) { ///var responseTextBox = netInfoBox.getElementsByClassName("netInfoResponseText").item(0); var responseTextBox = $$(".netInfoResponseText", netInfoBox)[0]; if (file.category == "image") { netInfoBox.responsePresented = true; var responseImage = netInfoBox.ownerDocument.createElement("img"); responseImage.src = file.href; clearNode(responseTextBox); responseTextBox.appendChild(responseImage, responseTextBox); } else ///if (!(binaryCategoryMap.hasOwnProperty(file.category))) { this.setResponseText(file, netInfoBox, responseTextBox, context); } } else if (hasClass(tab, "netInfoCacheTab") && file.loaded && !netInfoBox.cachePresented) { var responseTextBox = netInfoBox.getElementsByClassName("netInfoCacheText").item(0); if (file.cacheEntry) { netInfoBox.cachePresented = true; this.insertHeaderRows(netInfoBox, file.cacheEntry, "Cache"); } } else if (hasClass(tab, "netInfoHtmlTab") && file.loaded && !netInfoBox.htmlPresented) { netInfoBox.htmlPresented = true; var text = Utils.getResponseText(file, context); ///var iframe = netInfoBox.getElementsByClassName("netInfoHtmlPreview").item(0); var iframe = $$(".netInfoHtmlPreview", netInfoBox)[0]; ///iframe.contentWindow.document.body.innerHTML = text; // TODO: xxxpedro net - remove scripts var reScript = /<script(.|\s)*?\/script>/gi; text = text.replace(reScript, ""); iframe.contentWindow.document.write(text); iframe.contentWindow.document.close(); } // Notify listeners about update so, content of custom tabs can be updated. dispatch(NetInfoBody.fbListeners, "updateTabBody", [netInfoBox, file, context]); }, setResponseText: function(file, netInfoBox, responseTextBox, context) { //********************************************** //********************************************** //********************************************** netInfoBox.responsePresented = true; // line breaks somehow are different in IE // make this only once in the initialization? we don't have net panels and modules yet. if (isIE) responseTextBox.style.whiteSpace = "nowrap"; responseTextBox[ typeof responseTextBox.textContent != "undefined" ? "textContent" : "innerText" ] = file.responseText; return; //********************************************** //********************************************** //********************************************** // Get response text and make sure it doesn't exceed the max limit. var text = Utils.getResponseText(file, context); var limit = Firebug.netDisplayedResponseLimit + 15; var limitReached = text ? (text.length > limit) : false; if (limitReached) text = text.substr(0, limit) + "..."; // Insert the response into the UI. if (text) insertWrappedText(text, responseTextBox); else insertWrappedText("", responseTextBox); // Append a message informing the user that the response isn't fully displayed. if (limitReached) { var object = { text: $STR("net.responseSizeLimitMessage"), onClickLink: function() { var panel = context.getPanel("net", true); panel.openResponseInTab(file); } }; Firebug.NetMonitor.ResponseSizeLimit.append(object, responseTextBox); } netInfoBox.responsePresented = true; if (FBTrace.DBG_NET) FBTrace.sysout("net.setResponseText; response text updated"); }, insertHeaderRows: function(netInfoBox, headers, tableName, rowName) { if (!headers.length) return; var headersTable = $$(".netInfo"+tableName+"Table", netInfoBox)[0]; //var headersTable = netInfoBox.getElementsByClassName("netInfo"+tableName+"Table").item(0); var tbody = getChildByClass(headersTable, "netInfo" + rowName + "Body"); if (!tbody) tbody = headersTable.firstChild; var titleRow = getChildByClass(tbody, "netInfo" + rowName + "Title"); this.headerDataTag.insertRows({headers: headers}, titleRow ? titleRow : tbody); removeClass(titleRow, "collapsed"); } }); var NetInfoBody = Firebug.NetMonitor.NetInfoBody; // ************************************************************************************************ /** * @domplate Used within the Net panel to display raw source of request and response headers * as well as pretty-formatted summary of these headers. */ Firebug.NetMonitor.NetInfoHeaders = domplate(Firebug.Rep, //new Firebug.Listener(), { tag: DIV({"class": "netInfoHeadersTable", "role": "tabpanel"}, DIV({"class": "netInfoHeadersGroup netInfoResponseHeadersTitle"}, SPAN($STR("ResponseHeaders")), SPAN({"class": "netHeadersViewSource response collapsed", onclick: "$onViewSource", _sourceDisplayed: false, _rowName: "ResponseHeaders"}, $STR("net.headers.view source") ) ), TABLE({cellpadding: 0, cellspacing: 0}, TBODY({"class": "netInfoResponseHeadersBody", "role": "list", "aria-label": $STR("ResponseHeaders")}) ), DIV({"class": "netInfoHeadersGroup netInfoRequestHeadersTitle"}, SPAN($STR("RequestHeaders")), SPAN({"class": "netHeadersViewSource request collapsed", onclick: "$onViewSource", _sourceDisplayed: false, _rowName: "RequestHeaders"}, $STR("net.headers.view source") ) ), TABLE({cellpadding: 0, cellspacing: 0}, TBODY({"class": "netInfoRequestHeadersBody", "role": "list", "aria-label": $STR("RequestHeaders")}) ) ), sourceTag: TR({"role": "presentation"}, TD({colspan: 2, "role": "presentation"}, PRE({"class": "source"}) ) ), onViewSource: function(event) { var target = event.target; var requestHeaders = (target.rowName == "RequestHeaders"); var netInfoBox = getAncestorByClass(target, "netInfoBody"); var file = netInfoBox.repObject; if (target.sourceDisplayed) { var headers = requestHeaders ? file.requestHeaders : file.responseHeaders; this.insertHeaderRows(netInfoBox, headers, target.rowName); target.innerHTML = $STR("net.headers.view source"); } else { var source = requestHeaders ? file.requestHeadersText : file.responseHeadersText; this.insertSource(netInfoBox, source, target.rowName); target.innerHTML = $STR("net.headers.pretty print"); } target.sourceDisplayed = !target.sourceDisplayed; cancelEvent(event); }, insertSource: function(netInfoBox, source, rowName) { // This breaks copy to clipboard. //if (source) // source = source.replace(/\r\n/gm, "<span style='color:lightgray'>\\r\\n</span>\r\n"); ///var tbody = netInfoBox.getElementsByClassName("netInfo" + rowName + "Body").item(0); var tbody = $$(".netInfo" + rowName + "Body", netInfoBox)[0]; var node = this.sourceTag.replace({}, tbody); ///var sourceNode = node.getElementsByClassName("source").item(0); var sourceNode = $$(".source", node)[0]; sourceNode.innerHTML = source; }, insertHeaderRows: function(netInfoBox, headers, rowName) { var headersTable = $$(".netInfoHeadersTable", netInfoBox)[0]; var tbody = $$(".netInfo" + rowName + "Body", headersTable)[0]; //var headersTable = netInfoBox.getElementsByClassName("netInfoHeadersTable").item(0); //var tbody = headersTable.getElementsByClassName("netInfo" + rowName + "Body").item(0); clearNode(tbody); if (!headers.length) return; NetInfoBody.headerDataTag.insertRows({headers: headers}, tbody); var titleRow = getChildByClass(headersTable, "netInfo" + rowName + "Title"); removeClass(titleRow, "collapsed"); }, init: function(parent) { var rootNode = this.tag.append({}, parent); var netInfoBox = getAncestorByClass(parent, "netInfoBody"); var file = netInfoBox.repObject; var viewSource; viewSource = $$(".request", rootNode)[0]; //viewSource = rootNode.getElementsByClassName("netHeadersViewSource request").item(0); if (file.requestHeadersText) removeClass(viewSource, "collapsed"); viewSource = $$(".response", rootNode)[0]; //viewSource = rootNode.getElementsByClassName("netHeadersViewSource response").item(0); if (file.responseHeadersText) removeClass(viewSource, "collapsed"); }, renderHeaders: function(parent, headers, rowName) { if (!parent.firstChild) this.init(parent); this.insertHeaderRows(parent, headers, rowName); } }); var NetInfoHeaders = Firebug.NetMonitor.NetInfoHeaders; // ************************************************************************************************ /** * @domplate Represents posted data within request info (the info, which is visible when * a request entry is expanded. This template renders content of the Post tab. */ Firebug.NetMonitor.NetInfoPostData = domplate(Firebug.Rep, /*new Firebug.Listener(),*/ { // application/x-www-form-urlencoded paramsTable: TABLE({"class": "netInfoPostParamsTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("net.label.Parameters")}, TR({"class": "netInfoPostParamsTitle", "role": "presentation"}, TD({colspan: 3, "role": "presentation"}, DIV({"class": "netInfoPostParams"}, $STR("net.label.Parameters"), SPAN({"class": "netInfoPostContentType"}, "application/x-www-form-urlencoded" ) ) ) ) ) ), // multipart/form-data partsTable: TABLE({"class": "netInfoPostPartsTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("net.label.Parts")}, TR({"class": "netInfoPostPartsTitle", "role": "presentation"}, TD({colspan: 2, "role":"presentation" }, DIV({"class": "netInfoPostParams"}, $STR("net.label.Parts"), SPAN({"class": "netInfoPostContentType"}, "multipart/form-data" ) ) ) ) ) ), // application/json jsonTable: TABLE({"class": "netInfoPostJSONTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, ///TBODY({"role": "list", "aria-label": $STR("jsonviewer.tab.JSON")}, TBODY({"role": "list", "aria-label": $STR("JSON")}, TR({"class": "netInfoPostJSONTitle", "role": "presentation"}, TD({"role": "presentation" }, DIV({"class": "netInfoPostParams"}, ///$STR("jsonviewer.tab.JSON") $STR("JSON") ) ) ), TR( TD({"class": "netInfoPostJSONBody"}) ) ) ), // application/xml xmlTable: TABLE({"class": "netInfoPostXMLTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("xmlviewer.tab.XML")}, TR({"class": "netInfoPostXMLTitle", "role": "presentation"}, TD({"role": "presentation" }, DIV({"class": "netInfoPostParams"}, $STR("xmlviewer.tab.XML") ) ) ), TR( TD({"class": "netInfoPostXMLBody"}) ) ) ), sourceTable: TABLE({"class": "netInfoPostSourceTable", cellpadding: 0, cellspacing: 0, "role": "presentation"}, TBODY({"role": "list", "aria-label": $STR("net.label.Source")}, TR({"class": "netInfoPostSourceTitle", "role": "presentation"}, TD({colspan: 2, "role": "presentation"}, DIV({"class": "netInfoPostSource"}, $STR("net.label.Source") ) ) ) ) ), sourceBodyTag: TR({"role": "presentation"}, TD({colspan: 2, "role": "presentation"}, FOR("line", "$param|getParamValueIterator", CODE({"class":"focusRow subFocusRow" , "role": "listitem"},"$line") ) ) ), getParamValueIterator: function(param) { return NetInfoBody.getParamValueIterator(param); }, render: function(context, parentNode, file) { //debugger; var spy = getAncestorByClass(parentNode, "spyHead"); var spyObject = spy.repObject; var data = spyObject.data; ///var contentType = Utils.findHeader(file.requestHeaders, "content-type"); var contentType = file.mimeType; ///var text = Utils.getPostText(file, context, true); ///if (text == undefined) /// return; ///if (Utils.isURLEncodedRequest(file, context)) // fake Utils.isURLEncodedRequest identification if (contentType && contentType == "application/x-www-form-urlencoded" || data && data.indexOf("=") != -1) { ///var lines = text.split("\n"); ///var params = parseURLEncodedText(lines[lines.length-1]); var params = parseURLEncodedTextArray(data); if (params) this.insertParameters(parentNode, params); } ///if (Utils.isMultiPartRequest(file, context)) ///{ /// var data = this.parseMultiPartText(file, context); /// if (data) /// this.insertParts(parentNode, data); ///} // moved to the top ///var contentType = Utils.findHeader(file.requestHeaders, "content-type"); ///if (Firebug.JSONViewerModel.isJSON(contentType)) var jsonData = { responseText: data }; if (Firebug.JSONViewerModel.isJSON(contentType, data)) ///this.insertJSON(parentNode, file, context); this.insertJSON(parentNode, jsonData, context); ///if (Firebug.XMLViewerModel.isXML(contentType)) /// this.insertXML(parentNode, file, context); ///var postText = Utils.getPostText(file, context); ///postText = Utils.formatPostText(postText); var postText = data; if (postText) this.insertSource(parentNode, postText); }, insertParameters: function(parentNode, params) { if (!params || !params.length) return; var paramTable = this.paramsTable.append({object:{}}, parentNode); var row = $$(".netInfoPostParamsTitle", paramTable)[0]; //var paramTable = this.paramsTable.append(null, parentNode); //var row = paramTable.getElementsByClassName("netInfoPostParamsTitle").item(0); var tbody = paramTable.getElementsByTagName("tbody")[0]; NetInfoBody.headerDataTag.insertRows({headers: params}, row); }, insertParts: function(parentNode, data) { if (!data.params || !data.params.length) return; var partsTable = this.partsTable.append({object:{}}, parentNode); var row = $$(".netInfoPostPartsTitle", paramTable)[0]; //var partsTable = this.partsTable.append(null, parentNode); //var row = partsTable.getElementsByClassName("netInfoPostPartsTitle").item(0); NetInfoBody.headerDataTag.insertRows({headers: data.params}, row); }, insertJSON: function(parentNode, file, context) { ///var text = Utils.getPostText(file, context); var text = file.responseText; ///var data = parseJSONString(text, "http://" + file.request.originalURI.host); var data = parseJSONString(text); if (!data) return; ///var jsonTable = this.jsonTable.append(null, parentNode); var jsonTable = this.jsonTable.append({}, parentNode); ///var jsonBody = jsonTable.getElementsByClassName("netInfoPostJSONBody").item(0); var jsonBody = $$(".netInfoPostJSONBody", jsonTable)[0]; if (!this.toggles) this.toggles = {}; Firebug.DOMPanel.DirTable.tag.replace( {object: data, toggles: this.toggles}, jsonBody); }, insertXML: function(parentNode, file, context) { var text = Utils.getPostText(file, context); var jsonTable = this.xmlTable.append(null, parentNode); ///var jsonBody = jsonTable.getElementsByClassName("netInfoPostXMLBody").item(0); var jsonBody = $$(".netInfoPostXMLBody", jsonTable)[0]; Firebug.XMLViewerModel.insertXML(jsonBody, text); }, insertSource: function(parentNode, text) { var sourceTable = this.sourceTable.append({object:{}}, parentNode); var row = $$(".netInfoPostSourceTitle", sourceTable)[0]; //var sourceTable = this.sourceTable.append(null, parentNode); //var row = sourceTable.getElementsByClassName("netInfoPostSourceTitle").item(0); var param = {value: [text]}; this.sourceBodyTag.insertRows({param: param}, row); }, parseMultiPartText: function(file, context) { var text = Utils.getPostText(file, context); if (text == undefined) return null; FBTrace.sysout("net.parseMultiPartText; boundary: ", text); var boundary = text.match(/\s*boundary=\s*(.*)/)[1]; var divider = "\r\n\r\n"; var bodyStart = text.indexOf(divider); var body = text.substr(bodyStart + divider.length); var postData = {}; postData.mimeType = "multipart/form-data"; postData.params = []; var parts = body.split("--" + boundary); for (var i=0; i<parts.length; i++) { var part = parts[i].split(divider); if (part.length != 2) continue; var m = part[0].match(/\s*name=\"(.*)\"(;|$)/); postData.params.push({ name: (m && m.length > 1) ? m[1] : "", value: trim(part[1]) }); } return postData; } }); var NetInfoPostData = Firebug.NetMonitor.NetInfoPostData; // ************************************************************************************************ // TODO: xxxpedro net i18n var $STRP = function(a){return a;}; Firebug.NetMonitor.NetLimit = domplate(Firebug.Rep, { collapsed: true, tableTag: DIV( TABLE({width: "100%", cellpadding: 0, cellspacing: 0}, TBODY() ) ), limitTag: TR({"class": "netRow netLimitRow", $collapsed: "$isCollapsed"}, TD({"class": "netCol netLimitCol", colspan: 6}, TABLE({cellpadding: 0, cellspacing: 0}, TBODY( TR( TD( SPAN({"class": "netLimitLabel"}, $STRP("plural.Limit_Exceeded", [0]) ) ), TD({style: "width:100%"}), TD( BUTTON({"class": "netLimitButton", title: "$limitPrefsTitle", onclick: "$onPreferences"}, $STR("LimitPrefs") ) ), TD("&nbsp;") ) ) ) ) ), isCollapsed: function() { return this.collapsed; }, onPreferences: function(event) { openNewTab("about:config"); }, updateCounter: function(row) { removeClass(row, "collapsed"); // Update info within the limit row. var limitLabel = row.getElementsByClassName("netLimitLabel").item(0); limitLabel.firstChild.nodeValue = $STRP("plural.Limit_Exceeded", [row.limitInfo.totalCount]); }, createTable: function(parent, limitInfo) { var table = this.tableTag.replace({}, parent); var row = this.createRow(table.firstChild.firstChild, limitInfo); return [table, row]; }, createRow: function(parent, limitInfo) { var row = this.limitTag.insertRows(limitInfo, parent, this)[0]; row.limitInfo = limitInfo; return row; }, // nsIPrefObserver observe: function(subject, topic, data) { // We're observing preferences only. if (topic != "nsPref:changed") return; if (data.indexOf("net.logLimit") != -1) this.updateMaxLimit(); }, updateMaxLimit: function() { var value = Firebug.getPref(Firebug.prefDomain, "net.logLimit"); maxQueueRequests = value ? value : maxQueueRequests; } }); var NetLimit = Firebug.NetMonitor.NetLimit; // ************************************************************************************************ Firebug.NetMonitor.ResponseSizeLimit = domplate(Firebug.Rep, { tag: DIV({"class": "netInfoResponseSizeLimit"}, SPAN("$object.beforeLink"), A({"class": "objectLink", onclick: "$onClickLink"}, "$object.linkText" ), SPAN("$object.afterLink") ), reLink: /^(.*)<a>(.*)<\/a>(.*$)/, append: function(obj, parent) { var m = obj.text.match(this.reLink); return this.tag.append({onClickLink: obj.onClickLink, object: { beforeLink: m[1], linkText: m[2], afterLink: m[3] }}, parent, this); } }); // ************************************************************************************************ // ************************************************************************************************ Firebug.NetMonitor.Utils = { findHeader: function(headers, name) { if (!headers) return null; name = name.toLowerCase(); for (var i = 0; i < headers.length; ++i) { var headerName = headers[i].name.toLowerCase(); if (headerName == name) return headers[i].value; } }, formatPostText: function(text) { if (text instanceof XMLDocument) return getElementXML(text.documentElement); else return text; }, getPostText: function(file, context, noLimit) { if (!file.postText) { file.postText = readPostTextFromRequest(file.request, context); if (!file.postText && context) file.postText = readPostTextFromPage(file.href, context); } if (!file.postText) return file.postText; var limit = Firebug.netDisplayedPostBodyLimit; if (file.postText.length > limit && !noLimit) { return cropString(file.postText, limit, "\n\n... " + $STR("net.postDataSizeLimitMessage") + " ...\n\n"); } return file.postText; }, getResponseText: function(file, context) { // The response can be also empty string so, check agains "undefined". return (typeof(file.responseText) != "undefined")? file.responseText : context.sourceCache.loadText(file.href, file.method, file); }, isURLEncodedRequest: function(file, context) { var text = Utils.getPostText(file, context); if (text && text.toLowerCase().indexOf("content-type: application/x-www-form-urlencoded") == 0) return true; // The header value doesn't have to be always exactly "application/x-www-form-urlencoded", // there can be even charset specified. So, use indexOf rather than just "==". var headerValue = Utils.findHeader(file.requestHeaders, "content-type"); if (headerValue && headerValue.indexOf("application/x-www-form-urlencoded") == 0) return true; return false; }, isMultiPartRequest: function(file, context) { var text = Utils.getPostText(file, context); if (text && text.toLowerCase().indexOf("content-type: multipart/form-data") == 0) return true; return false; }, getMimeType: function(mimeType, uri) { if (!mimeType || !(mimeCategoryMap.hasOwnProperty(mimeType))) { var ext = getFileExtension(uri); if (!ext) return mimeType; else { var extMimeType = mimeExtensionMap[ext.toLowerCase()]; return extMimeType ? extMimeType : mimeType; } } else return mimeType; }, getDateFromSeconds: function(s) { var d = new Date(); d.setTime(s*1000); return d; }, getHttpHeaders: function(request, file) { try { var http = QI(request, Ci.nsIHttpChannel); file.status = request.responseStatus; // xxxHonza: is there any problem to do this in requestedFile method? file.method = http.requestMethod; file.urlParams = parseURLParams(file.href); file.mimeType = Utils.getMimeType(request.contentType, request.name); if (!file.responseHeaders && Firebug.collectHttpHeaders) { var requestHeaders = [], responseHeaders = []; http.visitRequestHeaders({ visitHeader: function(name, value) { requestHeaders.push({name: name, value: value}); } }); http.visitResponseHeaders({ visitHeader: function(name, value) { responseHeaders.push({name: name, value: value}); } }); file.requestHeaders = requestHeaders; file.responseHeaders = responseHeaders; } } catch (exc) { // An exception can be throwed e.g. when the request is aborted and // request.responseStatus is accessed. if (FBTrace.DBG_ERRORS) FBTrace.sysout("net.getHttpHeaders FAILS " + file.href, exc); } }, isXHR: function(request) { try { var callbacks = request.notificationCallbacks; var xhrRequest = callbacks ? callbacks.getInterface(Ci.nsIXMLHttpRequest) : null; if (FBTrace.DBG_NET) FBTrace.sysout("net.isXHR; " + (xhrRequest != null) + ", " + safeGetName(request)); return (xhrRequest != null); } catch (exc) { } return false; }, getFileCategory: function(file) { if (file.category) { if (FBTrace.DBG_NET) FBTrace.sysout("net.getFileCategory; current: " + file.category + " for: " + file.href, file); return file.category; } if (file.isXHR) { if (FBTrace.DBG_NET) FBTrace.sysout("net.getFileCategory; XHR for: " + file.href, file); return file.category = "xhr"; } if (!file.mimeType) { var ext = getFileExtension(file.href); if (ext) file.mimeType = mimeExtensionMap[ext.toLowerCase()]; } /*if (FBTrace.DBG_NET) FBTrace.sysout("net.getFileCategory; " + mimeCategoryMap[file.mimeType] + ", mimeType: " + file.mimeType + " for: " + file.href, file);*/ if (!file.mimeType) return ""; // Solve cases when charset is also specified, eg "text/html; charset=UTF-8". var mimeType = file.mimeType; if (mimeType) mimeType = mimeType.split(";")[0]; return (file.category = mimeCategoryMap[mimeType]); } }; var Utils = Firebug.NetMonitor.Utils; // ************************************************************************************************ //Firebug.registerRep(Firebug.NetMonitor.NetRequestTable); //Firebug.registerActivableModule(Firebug.NetMonitor); //Firebug.registerPanel(NetPanel); Firebug.registerModule(Firebug.NetMonitor); //Firebug.registerRep(Firebug.NetMonitor.BreakpointRep); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants //const Cc = Components.classes; //const Ci = Components.interfaces; // List of contexts with XHR spy attached. var contexts = []; // ************************************************************************************************ // Spy Module /** * @module Represents a XHR Spy module. The main purpose of the XHR Spy feature is to monitor * XHR activity of the current page and create appropriate log into the Console panel. * This feature can be controlled by an option <i>Show XMLHttpRequests</i> (from within the * console panel). * * The module is responsible for attaching/detaching a HTTP Observers when Firebug is * activated/deactivated for a site. */ Firebug.Spy = extend(Firebug.Module, /** @lends Firebug.Spy */ { dispatchName: "spy", initialize: function() { if (Firebug.TraceModule) Firebug.TraceModule.addListener(this.TraceListener); Firebug.Module.initialize.apply(this, arguments); }, shutdown: function() { Firebug.Module.shutdown.apply(this, arguments); if (Firebug.TraceModule) Firebug.TraceModule.removeListener(this.TraceListener); }, initContext: function(context) { context.spies = []; if (Firebug.showXMLHttpRequests && Firebug.Console.isAlwaysEnabled()) this.attachObserver(context, context.window); if (FBTrace.DBG_SPY) FBTrace.sysout("spy.initContext " + contexts.length + " ", context.getName()); }, destroyContext: function(context) { // For any spies that are in progress, remove our listeners so that they don't leak this.detachObserver(context, null); if (FBTrace.DBG_SPY && context.spies.length) FBTrace.sysout("spy.destroyContext; ERROR There are leaking Spies (" + context.spies.length + ") " + context.getName()); delete context.spies; if (FBTrace.DBG_SPY) FBTrace.sysout("spy.destroyContext " + contexts.length + " ", context.getName()); }, watchWindow: function(context, win) { if (Firebug.showXMLHttpRequests && Firebug.Console.isAlwaysEnabled()) this.attachObserver(context, win); }, unwatchWindow: function(context, win) { try { // This make sure that the existing context is properly removed from "contexts" array. this.detachObserver(context, win); } catch (ex) { // Get exceptions here sometimes, so let's just ignore them // since the window is going away anyhow ERROR(ex); } }, updateOption: function(name, value) { // XXXjjb Honza, if Console.isEnabled(context) false, then this can't be called, // but somehow seems not correct if (name == "showXMLHttpRequests") { var tach = value ? this.attachObserver : this.detachObserver; for (var i = 0; i < TabWatcher.contexts.length; ++i) { var context = TabWatcher.contexts[i]; iterateWindows(context.window, function(win) { tach.apply(this, [context, win]); }); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Attaching Spy to XHR requests. /** * Returns false if Spy should not be attached to XHRs executed by the specified window. */ skipSpy: function(win) { if (!win) return true; // Don't attach spy to chrome. var uri = safeGetWindowLocation(win); if (uri && (uri.indexOf("about:") == 0 || uri.indexOf("chrome:") == 0)) return true; }, attachObserver: function(context, win) { if (Firebug.Spy.skipSpy(win)) return; for (var i=0; i<contexts.length; ++i) { if ((contexts[i].context == context) && (contexts[i].win == win)) return; } // Register HTTP observers only once. if (contexts.length == 0) { httpObserver.addObserver(SpyHttpObserver, "firebug-http-event", false); SpyHttpActivityObserver.registerObserver(); } contexts.push({context: context, win: win}); if (FBTrace.DBG_SPY) FBTrace.sysout("spy.attachObserver (HTTP) " + contexts.length + " ", context.getName()); }, detachObserver: function(context, win) { for (var i=0; i<contexts.length; ++i) { if (contexts[i].context == context) { if (win && (contexts[i].win != win)) continue; contexts.splice(i, 1); // If no context is using spy, remvove the (only one) HTTP observer. if (contexts.length == 0) { httpObserver.removeObserver(SpyHttpObserver, "firebug-http-event"); SpyHttpActivityObserver.unregisterObserver(); } if (FBTrace.DBG_SPY) FBTrace.sysout("spy.detachObserver (HTTP) " + contexts.length + " ", context.getName()); return; } } }, /** * Return XHR object that is associated with specified request <i>nsIHttpChannel</i>. * Returns null if the request doesn't represent XHR. */ getXHR: function(request) { // Does also query-interface for nsIHttpChannel. if (!(request instanceof Ci.nsIHttpChannel)) return null; try { var callbacks = request.notificationCallbacks; return (callbacks ? callbacks.getInterface(Ci.nsIXMLHttpRequest) : null); } catch (exc) { if (exc.name == "NS_NOINTERFACE") { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.getXHR; Request is not nsIXMLHttpRequest: " + safeGetRequestName(request)); } } return null; } }); // ************************************************************************************************ /* function getSpyForXHR(request, xhrRequest, context, noCreate) { var spy = null; // Iterate all existing spy objects in this context and look for one that is // already created for this request. var length = context.spies.length; for (var i=0; i<length; i++) { spy = context.spies[i]; if (spy.request == request) return spy; } if (noCreate) return null; spy = new Firebug.Spy.XMLHttpRequestSpy(request, xhrRequest, context); context.spies.push(spy); var name = request.URI.asciiSpec; var origName = request.originalURI.asciiSpec; // Attach spy only to the original request. Notice that there can be more network requests // made by the same XHR if redirects are involved. if (name == origName) spy.attach(); if (FBTrace.DBG_SPY) FBTrace.sysout("spy.getSpyForXHR; New spy object created (" + (name == origName ? "new XHR" : "redirected XHR") + ") for: " + name, spy); return spy; } /**/ // ************************************************************************************************ /** * @class This class represents a Spy object that is attached to XHR. This object * registers various listeners into the XHR in order to monitor various events fired * during the request process (onLoad, onAbort, etc.) */ /* Firebug.Spy.XMLHttpRequestSpy = function(request, xhrRequest, context) { this.request = request; this.xhrRequest = xhrRequest; this.context = context; this.responseText = ""; // For compatibility with the Net templates. this.isXHR = true; // Support for activity-observer this.transactionStarted = false; this.transactionClosed = false; }; /**/ //Firebug.Spy.XMLHttpRequestSpy.prototype = /** @lends Firebug.Spy.XMLHttpRequestSpy */ /* { attach: function() { var spy = this; this.onReadyStateChange = function(event) { onHTTPSpyReadyStateChange(spy, event); }; this.onLoad = function() { onHTTPSpyLoad(spy); }; this.onError = function() { onHTTPSpyError(spy); }; this.onAbort = function() { onHTTPSpyAbort(spy); }; // xxxHonza: #502959 is still failing on Fx 3.5 // Use activity distributor to identify 3.6 if (SpyHttpActivityObserver.getActivityDistributor()) { this.onreadystatechange = this.xhrRequest.onreadystatechange; this.xhrRequest.onreadystatechange = this.onReadyStateChange; } this.xhrRequest.addEventListener("load", this.onLoad, false); this.xhrRequest.addEventListener("error", this.onError, false); this.xhrRequest.addEventListener("abort", this.onAbort, false); // xxxHonza: should be removed from FB 3.6 if (!SpyHttpActivityObserver.getActivityDistributor()) this.context.sourceCache.addListener(this); }, detach: function() { // Bubble out if already detached. if (!this.onLoad) return; // If the activity distributor is available, let's detach it when the XHR // transaction is closed. Since, in case of multipart XHRs the onLoad method // (readyState == 4) can be called mutliple times. // Keep in mind: // 1) It can happen that that the TRANSACTION_CLOSE event comes before // the onLoad (if the XHR is made as part of the page load) so, detach if // it's already closed. // 2) In case of immediate cache responses, the transaction doesn't have to // be started at all (or the activity observer is no available in Firefox 3.5). // So, also detach in this case. if (this.transactionStarted && !this.transactionClosed) return; if (FBTrace.DBG_SPY) FBTrace.sysout("spy.detach; " + this.href); // Remove itself from the list of active spies. remove(this.context.spies, this); if (this.onreadystatechange) this.xhrRequest.onreadystatechange = this.onreadystatechange; try { this.xhrRequest.removeEventListener("load", this.onLoad, false); } catch (e) {} try { this.xhrRequest.removeEventListener("error", this.onError, false); } catch (e) {} try { this.xhrRequest.removeEventListener("abort", this.onAbort, false); } catch (e) {} this.onreadystatechange = null; this.onLoad = null; this.onError = null; this.onAbort = null; // xxxHonza: shouuld be removed from FB 1.6 if (!SpyHttpActivityObserver.getActivityDistributor()) this.context.sourceCache.removeListener(this); }, getURL: function() { return this.xhrRequest.channel ? this.xhrRequest.channel.name : this.href; }, // Cache listener onStopRequest: function(context, request, responseText) { if (!responseText) return; if (request == this.request) this.responseText = responseText; }, }; /**/ // ************************************************************************************************ /* function onHTTPSpyReadyStateChange(spy, event) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyReadyStateChange " + spy.xhrRequest.readyState + " (multipart: " + spy.xhrRequest.multipart + ")"); // Remember just in case spy is detached (readyState == 4). var originalHandler = spy.onreadystatechange; // Force response text to be updated in the UI (in case the console entry // has been already expanded and the response tab selected). if (spy.logRow && spy.xhrRequest.readyState >= 3) { var netInfoBox = getChildByClass(spy.logRow, "spyHead", "netInfoBody"); if (netInfoBox) { netInfoBox.htmlPresented = false; netInfoBox.responsePresented = false; } } // If the request is loading update the end time. if (spy.xhrRequest.readyState == 3) { spy.responseTime = spy.endTime - spy.sendTime; updateTime(spy); } // Request loaded. Get all the info from the request now, just in case the // XHR would be aborted in the original onReadyStateChange handler. if (spy.xhrRequest.readyState == 4) { // Cumulate response so, multipart response content is properly displayed. if (SpyHttpActivityObserver.getActivityDistributor()) spy.responseText += spy.xhrRequest.responseText; else { // xxxHonza: remove from FB 1.6 if (!spy.responseText) spy.responseText = spy.xhrRequest.responseText; } // The XHR is loaded now (used also by the activity observer). spy.loaded = true; // Update UI. updateHttpSpyInfo(spy); // Notify Net pane about a request beeing loaded. // xxxHonza: I don't think this is necessary. var netProgress = spy.context.netProgress; if (netProgress) netProgress.post(netProgress.stopFile, [spy.request, spy.endTime, spy.postText, spy.responseText]); // Notify registered listeners about finish of the XHR. dispatch(Firebug.Spy.fbListeners, "onLoad", [spy.context, spy]); } // Pass the event to the original page handler. callPageHandler(spy, event, originalHandler); } function onHTTPSpyLoad(spy) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyLoad: " + spy.href, spy); // Detach must be done in onLoad (not in onreadystatechange) otherwise // onAbort would not be handled. spy.detach(); // xxxHonza: Still needed for Fx 3.5 (#502959) if (!SpyHttpActivityObserver.getActivityDistributor()) onHTTPSpyReadyStateChange(spy, null); } function onHTTPSpyError(spy) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyError; " + spy.href, spy); spy.detach(); spy.loaded = true; if (spy.logRow) { removeClass(spy.logRow, "loading"); setClass(spy.logRow, "error"); } } function onHTTPSpyAbort(spy) { if (FBTrace.DBG_SPY) FBTrace.sysout("spy.onHTTPSpyAbort: " + spy.href, spy); spy.detach(); spy.loaded = true; if (spy.logRow) { removeClass(spy.logRow, "loading"); setClass(spy.logRow, "error"); } spy.statusText = "Aborted"; updateLogRow(spy); // Notify Net pane about a request beeing aborted. // xxxHonza: the net panel shoud find out this itself. var netProgress = spy.context.netProgress; if (netProgress) netProgress.post(netProgress.abortFile, [spy.request, spy.endTime, spy.postText, spy.responseText]); } /**/ // ************************************************************************************************ /** * @domplate Represents a template for XHRs logged in the Console panel. The body of the * log (displayed when expanded) is rendered using {@link Firebug.NetMonitor.NetInfoBody}. */ Firebug.Spy.XHR = domplate(Firebug.Rep, /** @lends Firebug.Spy.XHR */ { tag: DIV({"class": "spyHead", _repObject: "$object"}, TABLE({"class": "spyHeadTable focusRow outerFocusRow", cellpadding: 0, cellspacing: 0, "role": "listitem", "aria-expanded": "false"}, TBODY({"role": "presentation"}, TR({"class": "spyRow"}, TD({"class": "spyTitleCol spyCol", onclick: "$onToggleBody"}, DIV({"class": "spyTitle"}, "$object|getCaption" ), DIV({"class": "spyFullTitle spyTitle"}, "$object|getFullUri" ) ), TD({"class": "spyCol"}, DIV({"class": "spyStatus"}, "$object|getStatus") ), TD({"class": "spyCol"}, SPAN({"class": "spyIcon"}) ), TD({"class": "spyCol"}, SPAN({"class": "spyTime"}) ), TD({"class": "spyCol"}, TAG(FirebugReps.SourceLink.tag, {object: "$object.sourceLink"}) ) ) ) ) ), getCaption: function(spy) { return spy.method.toUpperCase() + " " + cropString(spy.getURL(), 100); }, getFullUri: function(spy) { return spy.method.toUpperCase() + " " + spy.getURL(); }, getStatus: function(spy) { var text = ""; if (spy.statusCode) text += spy.statusCode + " "; if (spy.statusText) return text += spy.statusText; return text; }, onToggleBody: function(event) { var target = event.currentTarget || event.srcElement; var logRow = getAncestorByClass(target, "logRow-spy"); if (isLeftClick(event)) { toggleClass(logRow, "opened"); var spy = getChildByClass(logRow, "spyHead").repObject; var spyHeadTable = getAncestorByClass(target, "spyHeadTable"); if (hasClass(logRow, "opened")) { updateHttpSpyInfo(spy, logRow); if (spyHeadTable) spyHeadTable.setAttribute('aria-expanded', 'true'); } else { //var netInfoBox = getChildByClass(spy.logRow, "spyHead", "netInfoBody"); //dispatch(Firebug.NetMonitor.NetInfoBody.fbListeners, "destroyTabBody", [netInfoBox, spy]); //if (spyHeadTable) // spyHeadTable.setAttribute('aria-expanded', 'false'); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * copyURL: function(spy) { copyToClipboard(spy.getURL()); }, copyParams: function(spy) { var text = spy.postText; if (!text) return; var url = reEncodeURL(spy, text, true); copyToClipboard(url); }, copyResponse: function(spy) { copyToClipboard(spy.responseText); }, openInTab: function(spy) { openNewTab(spy.getURL(), spy.postText); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * supportsObject: function(object) { // TODO: xxxpedro spy xhr return false; return object instanceof Firebug.Spy.XMLHttpRequestSpy; }, browseObject: function(spy, context) { var url = spy.getURL(); openNewTab(url); return true; }, getRealObject: function(spy, context) { return spy.xhrRequest; }, getContextMenuItems: function(spy) { var items = [ {label: "CopyLocation", command: bindFixed(this.copyURL, this, spy) } ]; if (spy.postText) { items.push( {label: "CopyLocationParameters", command: bindFixed(this.copyParams, this, spy) } ); } items.push( {label: "CopyResponse", command: bindFixed(this.copyResponse, this, spy) }, "-", {label: "OpenInTab", command: bindFixed(this.openInTab, this, spy) } ); return items; } }); // ************************************************************************************************ function updateTime(spy) { var timeBox = spy.logRow.getElementsByClassName("spyTime").item(0); if (spy.responseTime) timeBox.textContent = " " + formatTime(spy.responseTime); } function updateLogRow(spy) { updateTime(spy); var statusBox = spy.logRow.getElementsByClassName("spyStatus").item(0); statusBox.textContent = Firebug.Spy.XHR.getStatus(spy); removeClass(spy.logRow, "loading"); setClass(spy.logRow, "loaded"); try { var errorRange = Math.floor(spy.xhrRequest.status/100); if (errorRange == 4 || errorRange == 5) setClass(spy.logRow, "error"); } catch (exc) { } } var updateHttpSpyInfo = function updateHttpSpyInfo(spy, logRow) { if (!spy.logRow && logRow) spy.logRow = logRow; if (!spy.logRow || !hasClass(spy.logRow, "opened")) return; if (!spy.params) //spy.params = parseURLParams(spy.href+""); spy.params = parseURLParams(spy.href+""); if (!spy.requestHeaders) spy.requestHeaders = getRequestHeaders(spy); if (!spy.responseHeaders && spy.loaded) spy.responseHeaders = getResponseHeaders(spy); var template = Firebug.NetMonitor.NetInfoBody; var netInfoBox = getChildByClass(spy.logRow, "spyHead", "netInfoBody"); if (!netInfoBox) { var head = getChildByClass(spy.logRow, "spyHead"); netInfoBox = template.tag.append({"file": spy}, head); dispatch(template.fbListeners, "initTabBody", [netInfoBox, spy]); template.selectTabByName(netInfoBox, "Response"); } else { template.updateInfo(netInfoBox, spy, spy.context); } }; // ************************************************************************************************ function getRequestHeaders(spy) { var headers = []; var channel = spy.xhrRequest.channel; if (channel instanceof Ci.nsIHttpChannel) { channel.visitRequestHeaders({ visitHeader: function(name, value) { headers.push({name: name, value: value}); } }); } return headers; } function getResponseHeaders(spy) { var headers = []; try { var channel = spy.xhrRequest.channel; if (channel instanceof Ci.nsIHttpChannel) { channel.visitResponseHeaders({ visitHeader: function(name, value) { headers.push({name: name, value: value}); } }); } } catch (exc) { if (FBTrace.DBG_SPY || FBTrace.DBG_ERRORS) FBTrace.sysout("spy.getResponseHeaders; EXCEPTION " + safeGetRequestName(spy.request), exc); } return headers; } // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.Spy); //Firebug.registerRep(Firebug.Spy.XHR); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // List of JSON content types. var contentTypes = { // TODO: create issue: jsonViewer will not try to evaluate the contents of the requested file // if the content-type is set to "text/plain" //"text/plain": 1, "text/javascript": 1, "text/x-javascript": 1, "text/json": 1, "text/x-json": 1, "application/json": 1, "application/x-json": 1, "application/javascript": 1, "application/x-javascript": 1, "application/json-rpc": 1 }; // ************************************************************************************************ // Model implementation Firebug.JSONViewerModel = extend(Firebug.Module, { dispatchName: "jsonViewer", initialize: function() { Firebug.NetMonitor.NetInfoBody.addListener(this); // Used by Firebug.DOMPanel.DirTable domplate. this.toggles = {}; }, shutdown: function() { Firebug.NetMonitor.NetInfoBody.removeListener(this); }, initTabBody: function(infoBox, file) { if (FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.initTabBody", infoBox); // Let listeners to parse the JSON. dispatch(this.fbListeners, "onParseJSON", [file]); // The JSON is still no there, try to parse most common cases. if (!file.jsonObject) { ///if (this.isJSON(safeGetContentType(file.request), file.responseText)) if (this.isJSON(file.mimeType, file.responseText)) file.jsonObject = this.parseJSON(file); } // The jsonObject is created so, the JSON tab can be displayed. if (file.jsonObject && hasProperties(file.jsonObject)) { Firebug.NetMonitor.NetInfoBody.appendTab(infoBox, "JSON", ///$STR("jsonviewer.tab.JSON")); $STR("JSON")); if (FBTrace.DBG_JSONVIEWER) FBTrace.sysout("jsonviewer.initTabBody; JSON object available " + (typeof(file.jsonObject) != "undefined"), file.jsonObject); } }, isJSON: function(contentType, data) { // Workaround for JSON responses without proper content type // Let's consider all responses starting with "{" as JSON. In the worst // case there will be an exception when parsing. This means that no-JSON // responses (and post data) (with "{") can be parsed unnecessarily, // which represents a little overhead, but this happens only if the request // is actually expanded by the user in the UI (Net & Console panels). ///var responseText = data ? trimLeft(data) : null; ///if (responseText && responseText.indexOf("{") == 0) /// return true; var responseText = data ? trim(data) : null; if (responseText && responseText.indexOf("{") == 0) return true; if (!contentType) return false; contentType = contentType.split(";")[0]; contentType = trim(contentType); return contentTypes[contentType]; }, // Update listener for TabView updateTabBody: function(infoBox, file, context) { var tab = infoBox.selectedTab; ///var tabBody = infoBox.getElementsByClassName("netInfoJSONText").item(0); var tabBody = $$(".netInfoJSONText", infoBox)[0]; if (!hasClass(tab, "netInfoJSONTab") || tabBody.updated) return; tabBody.updated = true; if (file.jsonObject) { Firebug.DOMPanel.DirTable.tag.replace( {object: file.jsonObject, toggles: this.toggles}, tabBody); } }, parseJSON: function(file) { var jsonString = new String(file.responseText); ///return parseJSONString(jsonString, "http://" + file.request.originalURI.host); return parseJSONString(jsonString); } }); // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.JSONViewerModel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants // List of XML related content types. var xmlContentTypes = [ "text/xml", "application/xml", "application/xhtml+xml", "application/rss+xml", "application/atom+xml",, "application/vnd.mozilla.maybe.feed", "application/rdf+xml", "application/vnd.mozilla.xul+xml" ]; // ************************************************************************************************ // Model implementation /** * @module Implements viewer for XML based network responses. In order to create a new * tab wihin network request detail, a listener is registered into * <code>Firebug.NetMonitor.NetInfoBody</code> object. */ Firebug.XMLViewerModel = extend(Firebug.Module, { dispatchName: "xmlViewer", initialize: function() { ///Firebug.ActivableModule.initialize.apply(this, arguments); Firebug.Module.initialize.apply(this, arguments); Firebug.NetMonitor.NetInfoBody.addListener(this); }, shutdown: function() { ///Firebug.ActivableModule.shutdown.apply(this, arguments); Firebug.Module.shutdown.apply(this, arguments); Firebug.NetMonitor.NetInfoBody.removeListener(this); }, /** * Check response's content-type and if it's a XML, create a new tab with XML preview. */ initTabBody: function(infoBox, file) { if (FBTrace.DBG_XMLVIEWER) FBTrace.sysout("xmlviewer.initTabBody", infoBox); // If the response is XML let's display a pretty preview. ///if (this.isXML(safeGetContentType(file.request))) if (this.isXML(file.mimeType, file.responseText)) { Firebug.NetMonitor.NetInfoBody.appendTab(infoBox, "XML", ///$STR("xmlviewer.tab.XML")); $STR("XML")); if (FBTrace.DBG_XMLVIEWER) FBTrace.sysout("xmlviewer.initTabBody; XML response available"); } }, isXML: function(contentType) { if (!contentType) return false; // Look if the response is XML based. for (var i=0; i<xmlContentTypes.length; i++) { if (contentType.indexOf(xmlContentTypes[i]) == 0) return true; } return false; }, /** * Parse XML response and render pretty printed preview. */ updateTabBody: function(infoBox, file, context) { var tab = infoBox.selectedTab; ///var tabBody = infoBox.getElementsByClassName("netInfoXMLText").item(0); var tabBody = $$(".netInfoXMLText", infoBox)[0]; if (!hasClass(tab, "netInfoXMLTab") || tabBody.updated) return; tabBody.updated = true; this.insertXML(tabBody, Firebug.NetMonitor.Utils.getResponseText(file, context)); }, insertXML: function(parentNode, text) { var xmlText = text.replace(/^\s*<?.+?>\s*/, ""); var div = parentNode.ownerDocument.createElement("div"); div.innerHTML = xmlText; var root = div.getElementsByTagName("*")[0]; /*** var parser = CCIN("@mozilla.org/xmlextras/domparser;1", "nsIDOMParser"); var doc = parser.parseFromString(text, "text/xml"); var root = doc.documentElement; // Error handling var nsURI = "http://www.mozilla.org/newlayout/xml/parsererror.xml"; if (root.namespaceURI == nsURI && root.nodeName == "parsererror") { this.ParseError.tag.replace({error: { message: root.firstChild.nodeValue, source: root.lastChild.textContent }}, parentNode); return; } /**/ if (FBTrace.DBG_XMLVIEWER) FBTrace.sysout("xmlviewer.updateTabBody; XML response parsed", doc); // Override getHidden in these templates. The parsed XML documen is // hidden, but we want to display it using 'visible' styling. /* var templates = [ Firebug.HTMLPanel.CompleteElement, Firebug.HTMLPanel.Element, Firebug.HTMLPanel.TextElement, Firebug.HTMLPanel.EmptyElement, Firebug.HTMLPanel.XEmptyElement, ]; var originals = []; for (var i=0; i<templates.length; i++) { originals[i] = templates[i].getHidden; templates[i].getHidden = function() { return ""; } } /**/ // Generate XML preview. ///Firebug.HTMLPanel.CompleteElement.tag.replace({object: doc.documentElement}, parentNode); // TODO: xxxpedro html3 ///Firebug.HTMLPanel.CompleteElement.tag.replace({object: root}, parentNode); var html = []; Firebug.Reps.appendNode(root, html); parentNode.innerHTML = html.join(""); /* for (var i=0; i<originals.length; i++) templates[i].getHidden = originals[i];/**/ } }); // ************************************************************************************************ // Domplate /** * @domplate Represents a template for displaying XML parser errors. Used by * <code>Firebug.XMLViewerModel</code>. */ Firebug.XMLViewerModel.ParseError = domplate(Firebug.Rep, { tag: DIV({"class": "xmlInfoError"}, DIV({"class": "xmlInfoErrorMsg"}, "$error.message"), PRE({"class": "xmlInfoErrorSource"}, "$error|getSource") ), getSource: function(error) { var parts = error.source.split("\n"); if (parts.length != 2) return error.source; var limit = 50; var column = parts[1].length; if (column >= limit) { parts[0] = "..." + parts[0].substr(column - limit); parts[1] = "..." + parts[1].substr(column - limit); } if (parts[0].length > 80) parts[0] = parts[0].substr(0, 80) + "..."; return parts.join("\n"); } }); // ************************************************************************************************ // Registration Firebug.registerModule(Firebug.XMLViewerModel); }}); /* See license.txt for terms of usage */ // next-generation Console Panel (will override consoje.js) FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Constants /* const Cc = Components.classes; const Ci = Components.interfaces; const nsIPrefBranch2 = Ci.nsIPrefBranch2; const PrefService = Cc["@mozilla.org/preferences-service;1"]; const prefs = PrefService.getService(nsIPrefBranch2); /**/ /* // new offline message handler o = {x:1,y:2}; r = Firebug.getRep(o); r.tag.tag.compile(); outputs = []; html = r.tag.renderHTML({object:o}, outputs); // finish rendering the template (the DOM part) target = $("build"); target.innerHTML = html; root = target.firstChild; domArgs = [root, r.tag.context, 0]; domArgs.push.apply(domArgs, r.tag.domArgs); domArgs.push.apply(domArgs, outputs); r.tag.tag.renderDOM.apply(self ? self : r.tag.subject, domArgs); */ var consoleQueue = []; var lastHighlightedObject; var FirebugContext = Env.browser; // ************************************************************************************************ var maxQueueRequests = 500; // ************************************************************************************************ Firebug.ConsoleBase = { log: function(object, context, className, rep, noThrottle, sourceLink) { //dispatch(this.fbListeners,"log",[context, object, className, sourceLink]); return this.logRow(appendObject, object, context, className, rep, sourceLink, noThrottle); }, logFormatted: function(objects, context, className, noThrottle, sourceLink) { //dispatch(this.fbListeners,"logFormatted",[context, objects, className, sourceLink]); return this.logRow(appendFormatted, objects, context, className, null, sourceLink, noThrottle); }, openGroup: function(objects, context, className, rep, noThrottle, sourceLink, noPush) { return this.logRow(appendOpenGroup, objects, context, className, rep, sourceLink, noThrottle); }, closeGroup: function(context, noThrottle) { return this.logRow(appendCloseGroup, null, context, null, null, null, noThrottle, true); }, logRow: function(appender, objects, context, className, rep, sourceLink, noThrottle, noRow) { // TODO: xxxpedro console console2 noThrottle = true; // xxxpedro forced because there is no TabContext yet if (!context) context = FirebugContext; if (FBTrace.DBG_ERRORS && !context) FBTrace.sysout("Console.logRow has no context, skipping objects", objects); if (!context) return; if (noThrottle || !context) { var panel = this.getPanel(context); if (panel) { var row = panel.append(appender, objects, className, rep, sourceLink, noRow); var container = panel.panelNode; // TODO: xxxpedro what is this? console console2 /* var template = Firebug.NetMonitor.NetLimit; while (container.childNodes.length > maxQueueRequests + 1) { clearDomplate(container.firstChild.nextSibling); container.removeChild(container.firstChild.nextSibling); panel.limit.limitInfo.totalCount++; template.updateCounter(panel.limit); } dispatch([Firebug.A11yModel], "onLogRowCreated", [panel , row]); /**/ return row; } else { consoleQueue.push([appender, objects, context, className, rep, sourceLink, noThrottle, noRow]); } } else { if (!context.throttle) { //FBTrace.sysout("console.logRow has not context.throttle! "); return; } var args = [appender, objects, context, className, rep, sourceLink, true, noRow]; context.throttle(this.logRow, this, args); } }, appendFormatted: function(args, row, context) { if (!context) context = FirebugContext; var panel = this.getPanel(context); panel.appendFormatted(args, row); }, clear: function(context) { if (!context) //context = FirebugContext; context = Firebug.context; /* if (context) Firebug.Errors.clear(context); /**/ var panel = this.getPanel(context, true); if (panel) { panel.clear(); } }, // Override to direct output to your panel getPanel: function(context, noCreate) { //return context.getPanel("console", noCreate); // TODO: xxxpedro console console2 return Firebug.chrome ? Firebug.chrome.getPanel("Console") : null; } }; // ************************************************************************************************ //TODO: xxxpedro //var ActivableConsole = extend(Firebug.ActivableModule, Firebug.ConsoleBase); var ActivableConsole = extend(Firebug.ConsoleBase, { isAlwaysEnabled: function() { return true; } }); Firebug.Console = Firebug.Console = extend(ActivableConsole, //Firebug.Console = extend(ActivableConsole, { dispatchName: "console", error: function() { Firebug.Console.logFormatted(arguments, Firebug.browser, "error"); }, flush: function() { dispatch(this.fbListeners,"flush",[]); for (var i=0, length=consoleQueue.length; i<length; i++) { var args = consoleQueue[i]; this.logRow.apply(this, args); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module showPanel: function(browser, panel) { }, getFirebugConsoleElement: function(context, win) { var element = win.document.getElementById("_firebugConsole"); if (!element) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("getFirebugConsoleElement forcing element"); var elementForcer = "(function(){var r=null; try { r = window._getFirebugConsoleElement();}catch(exc){r=exc;} return r;})();"; // we could just add the elements here if (context.stopped) Firebug.Console.injector.evaluateConsoleScript(context); // todo evaluate consoleForcer on stack else var r = Firebug.CommandLine.evaluateInWebPage(elementForcer, context, win); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("getFirebugConsoleElement forcing element result "+r, r); var element = win.document.getElementById("_firebugConsole"); if (!element) // elementForce fails { if (FBTrace.DBG_ERRORS) FBTrace.sysout("console.getFirebugConsoleElement: no _firebugConsole in win:", win); Firebug.Console.logFormatted(["Firebug cannot find _firebugConsole element", r, win], context, "error", true); } } return element; }, isReadyElsePreparing: function(context, win) // this is the only code that should call injector.attachIfNeeded { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.isReadyElsePreparing, win is " + (win?"an argument: ":"null, context.window: ") + (win?win.location:context.window.location), (win?win:context.window)); if (win) return this.injector.attachIfNeeded(context, win); else { var attached = true; for (var i = 0; i < context.windows.length; i++) attached = attached && this.injector.attachIfNeeded(context, context.windows[i]); // already in the list above attached = attached && this.injector.attachIfNeeded(context, context.window); if (context.windows.indexOf(context.window) == -1) FBTrace.sysout("isReadyElsePreparing ***************** context.window not in context.windows"); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.isReadyElsePreparing attached to "+context.windows.length+" and returns "+attached); return attached; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends ActivableModule initialize: function() { this.panelName = "console"; //TODO: xxxpedro //Firebug.ActivableModule.initialize.apply(this, arguments); //Firebug.Debugger.addListener(this); }, enable: function() { if (Firebug.Console.isAlwaysEnabled()) this.watchForErrors(); }, disable: function() { if (Firebug.Console.isAlwaysEnabled()) this.unwatchForErrors(); }, initContext: function(context, persistedState) { Firebug.ActivableModule.initContext.apply(this, arguments); context.consoleReloadWarning = true; // mark as need to warn. }, loadedContext: function(context) { for (var url in context.sourceFileMap) return; // if there are any sourceFiles, then do nothing // else we saw no JS, so the reload warning it not needed. this.clearReloadWarning(context); }, clearReloadWarning: function(context) // remove the warning about reloading. { if (context.consoleReloadWarning) { var panel = context.getPanel(this.panelName); panel.clearReloadWarning(); delete context.consoleReloadWarning; } }, togglePersist: function(context) { var panel = context.getPanel(this.panelName); panel.persistContent = panel.persistContent ? false : true; Firebug.chrome.setGlobalAttribute("cmd_togglePersistConsole", "checked", panel.persistContent); }, showContext: function(browser, context) { Firebug.chrome.setGlobalAttribute("cmd_clearConsole", "disabled", !context); Firebug.ActivableModule.showContext.apply(this, arguments); }, destroyContext: function(context, persistedState) { Firebug.Console.injector.detachConsole(context, context.window); // TODO iterate windows? }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onPanelEnable: function(panelName) { if (panelName != this.panelName) // we don't care about other panels return; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onPanelEnable**************"); this.watchForErrors(); Firebug.Debugger.addDependentModule(this); // we inject the console during JS compiles so we need jsd }, onPanelDisable: function(panelName) { if (panelName != this.panelName) // we don't care about other panels return; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onPanelDisable**************"); Firebug.Debugger.removeDependentModule(this); // we inject the console during JS compiles so we need jsd this.unwatchForErrors(); // Make sure possible errors coming from the page and displayed in the Firefox // status bar are removed. this.clear(); }, onSuspendFirebug: function() { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onSuspendFirebug\n"); if (Firebug.Console.isAlwaysEnabled()) this.unwatchForErrors(); }, onResumeFirebug: function() { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onResumeFirebug\n"); if (Firebug.Console.isAlwaysEnabled()) this.watchForErrors(); }, watchForErrors: function() { Firebug.Errors.checkEnabled(); $('fbStatusIcon').setAttribute("console", "on"); }, unwatchForErrors: function() { Firebug.Errors.checkEnabled(); $('fbStatusIcon').removeAttribute("console"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Firebug.Debugger listener onMonitorScript: function(context, frame) { Firebug.Console.log(frame, context); }, onFunctionCall: function(context, frame, depth, calling) { if (calling) Firebug.Console.openGroup([frame, "depth:"+depth], context); else Firebug.Console.closeGroup(context); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * logRow: function(appender, objects, context, className, rep, sourceLink, noThrottle, noRow) { if (!context) context = FirebugContext; if (FBTrace.DBG_WINDOWS && !context) FBTrace.sysout("Console.logRow: no context \n"); if (this.isAlwaysEnabled()) return Firebug.ConsoleBase.logRow.apply(this, arguments); } }); Firebug.ConsoleListener = { log: function(context, object, className, sourceLink) { }, logFormatted: function(context, objects, className, sourceLink) { } }; // ************************************************************************************************ Firebug.ConsolePanel = function () {} // XXjjb attach Firebug so this panel can be extended. //TODO: xxxpedro //Firebug.ConsolePanel.prototype = extend(Firebug.ActivablePanel, Firebug.ConsolePanel.prototype = extend(Firebug.Panel, { wasScrolledToBottom: false, messageCount: 0, lastLogTime: 0, groups: null, limit: null, append: function(appender, objects, className, rep, sourceLink, noRow) { var container = this.getTopContainer(); if (noRow) { appender.apply(this, [objects]); } else { // xxxHonza: Don't update the this.wasScrolledToBottom flag now. // At the beginning (when the first log is created) the isScrolledToBottom // always returns true. //if (this.panelNode.offsetHeight) // this.wasScrolledToBottom = isScrolledToBottom(this.panelNode); var row = this.createRow("logRow", className); appender.apply(this, [objects, row, rep]); if (sourceLink) FirebugReps.SourceLink.tag.append({object: sourceLink}, row); container.appendChild(row); this.filterLogRow(row, this.wasScrolledToBottom); if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); return row; } }, clear: function() { if (this.panelNode) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("ConsolePanel.clear"); clearNode(this.panelNode); this.insertLogLimit(this.context); } }, insertLogLimit: function() { // Create limit row. This row is the first in the list of entries // and initially hidden. It's displayed as soon as the number of // entries reaches the limit. var row = this.createRow("limitRow"); var limitInfo = { totalCount: 0, limitPrefsTitle: $STRF("LimitPrefsTitle", [Firebug.prefDomain+".console.logLimit"]) }; //TODO: xxxpedro console net limit!? return; var netLimitRep = Firebug.NetMonitor.NetLimit; var nodes = netLimitRep.createTable(row, limitInfo); this.limit = nodes[1]; var container = this.panelNode; container.insertBefore(nodes[0], container.firstChild); }, insertReloadWarning: function() { // put the message in, we will clear if the window console is injected. this.warningRow = this.append(appendObject, $STR("message.Reload to activate window console"), "info"); }, clearReloadWarning: function() { if (this.warningRow) { this.warningRow.parentNode.removeChild(this.warningRow); delete this.warningRow; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * appendObject: function(object, row, rep) { if (!rep) rep = Firebug.getRep(object); return rep.tag.append({object: object}, row); }, appendFormatted: function(objects, row, rep) { if (!objects || !objects.length) return; function logText(text, row) { var node = row.ownerDocument.createTextNode(text); row.appendChild(node); } var format = objects[0]; var objIndex = 0; if (typeof(format) != "string") { format = ""; objIndex = -1; } else // a string { if (objects.length === 1) // then we have only a string... { if (format.length < 1) { // ...and it has no characters. logText("(an empty string)", row); return; } } } var parts = parseFormat(format); var trialIndex = objIndex; for (var i= 0; i < parts.length; i++) { var part = parts[i]; if (part && typeof(part) == "object") { if (++trialIndex > objects.length) // then too few parameters for format, assume unformatted. { format = ""; objIndex = -1; parts.length = 0; break; } } } for (var i = 0; i < parts.length; ++i) { var part = parts[i]; if (part && typeof(part) == "object") { var object = objects[++objIndex]; if (typeof(object) != "undefined") this.appendObject(object, row, part.rep); else this.appendObject(part.type, row, FirebugReps.Text); } else FirebugReps.Text.tag.append({object: part}, row); } for (var i = objIndex+1; i < objects.length; ++i) { logText(" ", row); var object = objects[i]; if (typeof(object) == "string") FirebugReps.Text.tag.append({object: object}, row); else this.appendObject(object, row); } }, appendOpenGroup: function(objects, row, rep) { if (!this.groups) this.groups = []; setClass(row, "logGroup"); setClass(row, "opened"); var innerRow = this.createRow("logRow"); setClass(innerRow, "logGroupLabel"); if (rep) rep.tag.replace({"objects": objects}, innerRow); else this.appendFormatted(objects, innerRow, rep); row.appendChild(innerRow); //dispatch([Firebug.A11yModel], 'onLogRowCreated', [this, innerRow]); var groupBody = this.createRow("logGroupBody"); row.appendChild(groupBody); groupBody.setAttribute('role', 'group'); this.groups.push(groupBody); addEvent(innerRow, "mousedown", function(event) { if (isLeftClick(event)) { //console.log(event.currentTarget == event.target); var target = event.target || event.srcElement; target = getAncestorByClass(target, "logGroupLabel"); var groupRow = target.parentNode; if (hasClass(groupRow, "opened")) { removeClass(groupRow, "opened"); target.setAttribute('aria-expanded', 'false'); } else { setClass(groupRow, "opened"); target.setAttribute('aria-expanded', 'true'); } } }); }, appendCloseGroup: function(object, row, rep) { if (this.groups) this.groups.pop(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // TODO: xxxpedro console2 onMouseMove: function(event) { if (!Firebug.Inspector) return; var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink-element"); object = object ? object.repObject : null; if(object && instanceOf(object, "Element") && object.nodeType == 1) { if(object != lastHighlightedObject) { Firebug.Inspector.drawBoxModel(object); object = lastHighlightedObject; } } else Firebug.Inspector.hideBoxModel(); }, onMouseDown: function(event) { var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink"); var repObject = object ? object.repObject : null; if (!repObject) { return; } if (hasClass(object, "objectLink-object")) { Firebug.chrome.selectPanel("DOM"); Firebug.chrome.getPanel("DOM").select(repObject, true); } else if (hasClass(object, "objectLink-element")) { Firebug.chrome.selectPanel("HTML"); Firebug.chrome.getPanel("HTML").select(repObject, true); } /* if(object && instanceOf(object, "Element") && object.nodeType == 1) { if(object != lastHighlightedObject) { Firebug.Inspector.drawBoxModel(object); object = lastHighlightedObject; } } else Firebug.Inspector.hideBoxModel(); /**/ }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "Console", title: "Console", //searchable: true, //breakable: true, //editable: false, options: { hasCommandLine: true, hasToolButtons: true, isPreRendered: true }, create: function() { Firebug.Panel.create.apply(this, arguments); this.context = Firebug.browser.window; this.document = Firebug.chrome.document; this.onMouseMove = bind(this.onMouseMove, this); this.onMouseDown = bind(this.onMouseDown, this); this.clearButton = new Button({ element: $("fbConsole_btClear"), owner: Firebug.Console, onClick: Firebug.Console.clear }); }, initialize: function() { Firebug.Panel.initialize.apply(this, arguments); // loads persisted content //Firebug.ActivablePanel.initialize.apply(this, arguments); // loads persisted content if (!this.persistedContent && Firebug.Console.isAlwaysEnabled()) { this.insertLogLimit(this.context); // Initialize log limit and listen for changes. this.updateMaxLimit(); if (this.context.consoleReloadWarning) // we have not yet injected the console this.insertReloadWarning(); } //Firebug.Console.injector.install(Firebug.browser.window); addEvent(this.panelNode, "mouseover", this.onMouseMove); addEvent(this.panelNode, "mousedown", this.onMouseDown); this.clearButton.initialize(); //consolex.trace(); //TODO: xxxpedro remove this /* Firebug.Console.openGroup(["asd"], null, "group", null, false); Firebug.Console.log("asd"); Firebug.Console.log("asd"); Firebug.Console.log("asd"); /**/ //TODO: xxxpedro preferences prefs //prefs.addObserver(Firebug.prefDomain, this, false); }, initializeNode : function() { //dispatch([Firebug.A11yModel], 'onInitializeNode', [this]); if (FBTrace.DBG_CONSOLE) { this.onScroller = bind(this.onScroll, this); addEvent(this.panelNode, "scroll", this.onScroller); } this.onResizer = bind(this.onResize, this); this.resizeEventTarget = Firebug.chrome.$('fbContentBox'); addEvent(this.resizeEventTarget, "resize", this.onResizer); }, destroyNode : function() { //dispatch([Firebug.A11yModel], 'onDestroyNode', [this]); if (this.onScroller) removeEvent(this.panelNode, "scroll", this.onScroller); //removeEvent(this.resizeEventTarget, "resize", this.onResizer); }, shutdown: function() { //TODO: xxxpedro console console2 this.clearButton.shutdown(); removeEvent(this.panelNode, "mousemove", this.onMouseMove); removeEvent(this.panelNode, "mousedown", this.onMouseDown); this.destroyNode(); Firebug.Panel.shutdown.apply(this, arguments); //TODO: xxxpedro preferences prefs //prefs.removeObserver(Firebug.prefDomain, this, false); }, ishow: function(state) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.panel show; " + this.context.getName(), state); var enabled = Firebug.Console.isAlwaysEnabled(); if (enabled) { Firebug.Console.disabledPanelPage.hide(this); this.showCommandLine(true); this.showToolbarButtons("fbConsoleButtons", true); Firebug.chrome.setGlobalAttribute("cmd_togglePersistConsole", "checked", this.persistContent); if (state && state.wasScrolledToBottom) { this.wasScrolledToBottom = state.wasScrolledToBottom; delete state.wasScrolledToBottom; } if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.show ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", " + this.context.getName()); } else { this.hide(state); Firebug.Console.disabledPanelPage.show(this); } }, ihide: function(state) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.panel hide; " + this.context.getName(), state); this.showToolbarButtons("fbConsoleButtons", false); this.showCommandLine(false); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.hide ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", " + this.context.getName()); }, destroy: function(state) { if (this.panelNode.offsetHeight) this.wasScrolledToBottom = isScrolledToBottom(this.panelNode); if (state) state.wasScrolledToBottom = this.wasScrolledToBottom; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.destroy ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", " + this.context.getName()); }, shouldBreakOnNext: function() { // xxxHonza: shouldn't the breakOnErrors be context related? // xxxJJB, yes, but we can't support it because we can't yet tell // which window the error is on. return Firebug.getPref(Firebug.servicePrefDomain, "breakOnErrors"); }, getBreakOnNextTooltip: function(enabled) { return (enabled ? $STR("console.Disable Break On All Errors") : $STR("console.Break On All Errors")); }, enablePanel: function(module) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.ConsolePanel.enablePanel; " + this.context.getName()); Firebug.ActivablePanel.enablePanel.apply(this, arguments); this.showCommandLine(true); if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); }, disablePanel: function(module) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.ConsolePanel.disablePanel; " + this.context.getName()); Firebug.ActivablePanel.disablePanel.apply(this, arguments); this.showCommandLine(false); }, getOptionsMenuItems: function() { return [ optionMenu("ShowJavaScriptErrors", "showJSErrors"), optionMenu("ShowJavaScriptWarnings", "showJSWarnings"), optionMenu("ShowCSSErrors", "showCSSErrors"), optionMenu("ShowXMLErrors", "showXMLErrors"), optionMenu("ShowXMLHttpRequests", "showXMLHttpRequests"), optionMenu("ShowChromeErrors", "showChromeErrors"), optionMenu("ShowChromeMessages", "showChromeMessages"), optionMenu("ShowExternalErrors", "showExternalErrors"), optionMenu("ShowNetworkErrors", "showNetworkErrors"), this.getShowStackTraceMenuItem(), this.getStrictOptionMenuItem(), "-", optionMenu("LargeCommandLine", "largeCommandLine") ]; }, getShowStackTraceMenuItem: function() { var menuItem = serviceOptionMenu("ShowStackTrace", "showStackTrace"); if (FirebugContext && !Firebug.Debugger.isAlwaysEnabled()) menuItem.disabled = true; return menuItem; }, getStrictOptionMenuItem: function() { var strictDomain = "javascript.options"; var strictName = "strict"; var strictValue = prefs.getBoolPref(strictDomain+"."+strictName); return {label: "JavascriptOptionsStrict", type: "checkbox", checked: strictValue, command: bindFixed(Firebug.setPref, Firebug, strictDomain, strictName, !strictValue) }; }, getBreakOnMenuItems: function() { //xxxHonza: no BON options for now. /*return [ optionMenu("console.option.Persist Break On Error", "persistBreakOnError") ];*/ return []; }, search: function(text) { if (!text) return; // Make previously visible nodes invisible again if (this.matchSet) { for (var i in this.matchSet) removeClass(this.matchSet[i], "matched"); } this.matchSet = []; function findRow(node) { return getAncestorByClass(node, "logRow"); } var search = new TextSearch(this.panelNode, findRow); var logRow = search.find(text); if (!logRow) { dispatch([Firebug.A11yModel], 'onConsoleSearchMatchFound', [this, text, []]); return false; } for (; logRow; logRow = search.findNext()) { setClass(logRow, "matched"); this.matchSet.push(logRow); } dispatch([Firebug.A11yModel], 'onConsoleSearchMatchFound', [this, text, this.matchSet]); return true; }, breakOnNext: function(breaking) { Firebug.setPref(Firebug.servicePrefDomain, "breakOnErrors", breaking); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // private createRow: function(rowName, className) { var elt = this.document.createElement("div"); elt.className = rowName + (className ? " " + rowName + "-" + className : ""); return elt; }, getTopContainer: function() { if (this.groups && this.groups.length) return this.groups[this.groups.length-1]; else return this.panelNode; }, filterLogRow: function(logRow, scrolledToBottom) { if (this.searchText) { setClass(logRow, "matching"); setClass(logRow, "matched"); // Search after a delay because we must wait for a frame to be created for // the new logRow so that the finder will be able to locate it setTimeout(bindFixed(function() { if (this.searchFilter(this.searchText, logRow)) this.matchSet.push(logRow); else removeClass(logRow, "matched"); removeClass(logRow, "matching"); if (scrolledToBottom) scrollToBottom(this.panelNode); }, this), 100); } }, searchFilter: function(text, logRow) { var count = this.panelNode.childNodes.length; var searchRange = this.document.createRange(); searchRange.setStart(this.panelNode, 0); searchRange.setEnd(this.panelNode, count); var startPt = this.document.createRange(); startPt.setStartBefore(logRow); var endPt = this.document.createRange(); endPt.setStartAfter(logRow); return finder.Find(text, searchRange, startPt, endPt) != null; }, // nsIPrefObserver observe: function(subject, topic, data) { // We're observing preferences only. if (topic != "nsPref:changed") return; // xxxHonza check this out. var prefDomain = "Firebug.extension."; var prefName = data.substr(prefDomain.length); if (prefName == "console.logLimit") this.updateMaxLimit(); }, updateMaxLimit: function() { var value = 1000; //TODO: xxxpedro preferences log limit? //var value = Firebug.getPref(Firebug.prefDomain, "console.logLimit"); maxQueueRequests = value ? value : maxQueueRequests; }, showCommandLine: function(shouldShow) { //TODO: xxxpedro show command line important return; if (shouldShow) { collapse(Firebug.chrome.$("fbCommandBox"), false); Firebug.CommandLine.setMultiLine(Firebug.largeCommandLine, Firebug.chrome); } else { // Make sure that entire content of the Console panel is hidden when // the panel is disabled. Firebug.CommandLine.setMultiLine(false, Firebug.chrome, Firebug.largeCommandLine); collapse(Firebug.chrome.$("fbCommandBox"), true); } }, onScroll: function(event) { // Update the scroll position flag if the position changes. this.wasScrolledToBottom = FBL.isScrolledToBottom(this.panelNode); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onScroll ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", wasScrolledToBottom: " + this.context.getName(), event); }, onResize: function(event) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("console.onResize ------------------ wasScrolledToBottom: " + this.wasScrolledToBottom + ", offsetHeight: " + this.panelNode.offsetHeight + ", scrollTop: " + this.panelNode.scrollTop + ", scrollHeight: " + this.panelNode.scrollHeight + ", " + this.context.getName(), event); if (this.wasScrolledToBottom) scrollToBottom(this.panelNode); } }); // ************************************************************************************************ function parseFormat(format) { var parts = []; if (format.length <= 0) return parts; var reg = /((^%|.%)(\d+)?(\.)([a-zA-Z]))|((^%|.%)([a-zA-Z]))/; for (var m = reg.exec(format); m; m = reg.exec(format)) { if (m[0].substr(0, 2) == "%%") { parts.push(format.substr(0, m.index)); parts.push(m[0].substr(1)); } else { var type = m[8] ? m[8] : m[5]; var precision = m[3] ? parseInt(m[3]) : (m[4] == "." ? -1 : 0); var rep = null; switch (type) { case "s": rep = FirebugReps.Text; break; case "f": case "i": case "d": rep = FirebugReps.Number; break; case "o": rep = null; break; } parts.push(format.substr(0, m[0][0] == "%" ? m.index : m.index+1)); parts.push({rep: rep, precision: precision, type: ("%" + type)}); } format = format.substr(m.index+m[0].length); } parts.push(format); return parts; } // ************************************************************************************************ var appendObject = Firebug.ConsolePanel.prototype.appendObject; var appendFormatted = Firebug.ConsolePanel.prototype.appendFormatted; var appendOpenGroup = Firebug.ConsolePanel.prototype.appendOpenGroup; var appendCloseGroup = Firebug.ConsolePanel.prototype.appendCloseGroup; // ************************************************************************************************ //Firebug.registerActivableModule(Firebug.Console); Firebug.registerModule(Firebug.Console); Firebug.registerPanel(Firebug.ConsolePanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants //const Cc = Components.classes; //const Ci = Components.interfaces; var frameCounters = {}; var traceRecursion = 0; Firebug.Console.injector = { install: function(context) { var win = context.window; var consoleHandler = new FirebugConsoleHandler(context, win); var properties = [ "log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupCollapsed", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd", "clear", "open", "close" ]; var Handler = function(name) { var c = consoleHandler; var f = consoleHandler[name]; return function(){return f.apply(c,arguments);}; }; var installer = function(c) { for (var i=0, l=properties.length; i<l; i++) { var name = properties[i]; c[name] = new Handler(name); c.firebuglite = Firebug.version; } }; var sandbox; if (win.console) { if (Env.Options.overrideConsole) sandbox = new win.Function("arguments.callee.install(window.console={})"); else // if there's a console object and overrideConsole is false we should just quit return; } else { try { // try overriding the console object sandbox = new win.Function("arguments.callee.install(window.console={})"); } catch(E) { // if something goes wrong create the firebug object instead sandbox = new win.Function("arguments.callee.install(window.firebug={})"); } } sandbox.install = installer; sandbox(); }, isAttached: function(context, win) { if (win.wrappedJSObject) { var attached = (win.wrappedJSObject._getFirebugConsoleElement ? true : false); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.isAttached:"+attached+" to win.wrappedJSObject "+safeGetWindowLocation(win.wrappedJSObject)); return attached; } else { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.isAttached? to win "+win.location+" fnc:"+win._getFirebugConsoleElement); return (win._getFirebugConsoleElement ? true : false); } }, attachIfNeeded: function(context, win) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.attachIfNeeded has win "+(win? ((win.wrappedJSObject?"YES":"NO")+" wrappedJSObject"):"null") ); if (this.isAttached(context, win)) return true; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("Console.attachIfNeeded found isAttached false "); this.attachConsoleInjector(context, win); this.addConsoleListener(context, win); Firebug.Console.clearReloadWarning(context); var attached = this.isAttached(context, win); if (attached) dispatch(Firebug.Console.fbListeners, "onConsoleInjected", [context, win]); return attached; }, attachConsoleInjector: function(context, win) { var consoleInjection = this.getConsoleInjectionScript(); // Do it all here. if (FBTrace.DBG_CONSOLE) FBTrace.sysout("attachConsoleInjector evaluating in "+win.location, consoleInjection); Firebug.CommandLine.evaluateInWebPage(consoleInjection, context, win); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("attachConsoleInjector evaluation completed for "+win.location); }, getConsoleInjectionScript: function() { if (!this.consoleInjectionScript) { var script = ""; script += "window.__defineGetter__('console', function() {\n"; script += " return (window._firebug ? window._firebug : window.loadFirebugConsole()); })\n\n"; script += "window.loadFirebugConsole = function() {\n"; script += "window._firebug = new _FirebugConsole();"; if (FBTrace.DBG_CONSOLE) script += " window.dump('loadFirebugConsole '+window.location+'\\n');\n"; script += " return window._firebug };\n"; var theFirebugConsoleScript = getResource("chrome://firebug/content/consoleInjected.js"); script += theFirebugConsoleScript; this.consoleInjectionScript = script; } return this.consoleInjectionScript; }, forceConsoleCompilationInPage: function(context, win) { if (!win) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("no win in forceConsoleCompilationInPage!"); return; } var consoleForcer = "window.loadFirebugConsole();"; if (context.stopped) Firebug.Console.injector.evaluateConsoleScript(context); // todo evaluate consoleForcer on stack else Firebug.CommandLine.evaluateInWebPage(consoleForcer, context, win); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("forceConsoleCompilationInPage "+win.location, consoleForcer); }, evaluateConsoleScript: function(context) { var scriptSource = this.getConsoleInjectionScript(); // TODO XXXjjb this should be getConsoleInjectionScript Firebug.Debugger.evaluate(scriptSource, context); }, addConsoleListener: function(context, win) { if (!context.activeConsoleHandlers) // then we have not been this way before context.activeConsoleHandlers = []; else { // we've been this way before... for (var i=0; i<context.activeConsoleHandlers.length; i++) { if (context.activeConsoleHandlers[i].window == win) { context.activeConsoleHandlers[i].detach(); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector addConsoleListener removed handler("+context.activeConsoleHandlers[i].handler_name+") from _firebugConsole in : "+win.location+"\n"); context.activeConsoleHandlers.splice(i,1); } } } // We need the element to attach our event listener. var element = Firebug.Console.getFirebugConsoleElement(context, win); if (element) element.setAttribute("FirebugVersion", Firebug.version); // Initialize Firebug version. else return false; var handler = new FirebugConsoleHandler(context, win); handler.attachTo(element); context.activeConsoleHandlers.push(handler); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector addConsoleListener attached handler("+handler.handler_name+") to _firebugConsole in : "+win.location+"\n"); return true; }, detachConsole: function(context, win) { if (win && win.document) { var element = win.document.getElementById("_firebugConsole"); if (element) element.parentNode.removeChild(element); } } }; var total_handlers = 0; var FirebugConsoleHandler = function FirebugConsoleHandler(context, win) { this.window = win; this.attachTo = function(element) { this.element = element; // When raised on our injected element, callback to Firebug and append to console this.boundHandler = bind(this.handleEvent, this); this.element.addEventListener('firebugAppendConsole', this.boundHandler, true); // capturing }; this.detach = function() { this.element.removeEventListener('firebugAppendConsole', this.boundHandler, true); }; this.handler_name = ++total_handlers; this.handleEvent = function(event) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("FirebugConsoleHandler("+this.handler_name+") "+event.target.getAttribute("methodName")+", event", event); if (!Firebug.CommandLine.CommandHandler.handle(event, this, win)) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("FirebugConsoleHandler", this); var methodName = event.target.getAttribute("methodName"); Firebug.Console.log($STRF("console.MethodNotSupported", [methodName])); } }; this.firebuglite = Firebug.version; this.init = function() { var consoleElement = win.document.getElementById('_firebugConsole'); consoleElement.setAttribute("FirebugVersion", Firebug.version); }; this.log = function() { logFormatted(arguments, "log"); }; this.debug = function() { logFormatted(arguments, "debug", true); }; this.info = function() { logFormatted(arguments, "info", true); }; this.warn = function() { logFormatted(arguments, "warn", true); }; this.error = function() { //TODO: xxxpedro console error //if (arguments.length == 1) //{ // logAssert("error", arguments); // add more info based on stack trace //} //else //{ //Firebug.Errors.increaseCount(context); logFormatted(arguments, "error", true); // user already added info //} }; this.exception = function() { logAssert("error", arguments); }; this.assert = function(x) { if (!x) { var rest = []; for (var i = 1; i < arguments.length; i++) rest.push(arguments[i]); logAssert("assert", rest); } }; this.dir = function(o) { Firebug.Console.log(o, context, "dir", Firebug.DOMPanel.DirTable); }; this.dirxml = function(o) { ///if (o instanceof Window) if (instanceOf(o, "Window")) o = o.document.documentElement; ///else if (o instanceof Document) else if (instanceOf(o, "Document")) o = o.documentElement; Firebug.Console.log(o, context, "dirxml", Firebug.HTMLPanel.SoloElement); }; this.group = function() { //TODO: xxxpedro; //var sourceLink = getStackLink(); var sourceLink = null; Firebug.Console.openGroup(arguments, null, "group", null, false, sourceLink); }; this.groupEnd = function() { Firebug.Console.closeGroup(context); }; this.groupCollapsed = function() { var sourceLink = getStackLink(); // noThrottle true is probably ok, openGroups will likely be short strings. var row = Firebug.Console.openGroup(arguments, null, "group", null, true, sourceLink); removeClass(row, "opened"); }; this.profile = function(title) { logFormatted(["console.profile() not supported."], "warn", true); //Firebug.Profiler.startProfiling(context, title); }; this.profileEnd = function() { logFormatted(["console.profile() not supported."], "warn", true); //Firebug.Profiler.stopProfiling(context); }; this.count = function(key) { // TODO: xxxpedro console2: is there a better way to find a unique ID for the coun() call? var frameId = "0"; //var frameId = FBL.getStackFrameId(); if (frameId) { if (!frameCounters) frameCounters = {}; if (key != undefined) frameId += key; var frameCounter = frameCounters[frameId]; if (!frameCounter) { var logRow = logFormatted(["0"], null, true, true); frameCounter = {logRow: logRow, count: 1}; frameCounters[frameId] = frameCounter; } else ++frameCounter.count; var label = key == undefined ? frameCounter.count : key + " " + frameCounter.count; frameCounter.logRow.firstChild.firstChild.nodeValue = label; } }; this.trace = function() { var getFuncName = function getFuncName (f) { if (f.getName instanceof Function) { return f.getName(); } if (f.name) // in FireFox, Function objects have a name property... { return f.name; } var name = f.toString().match(/function\s*([_$\w\d]*)/)[1]; return name || "anonymous"; }; var wasVisited = function(fn) { for (var i=0, l=frames.length; i<l; i++) { if (frames[i].fn == fn) { return true; } } return false; }; traceRecursion++; if (traceRecursion > 1) { traceRecursion--; return; } var frames = []; for (var fn = arguments.callee.caller.caller; fn; fn = fn.caller) { if (wasVisited(fn)) break; var args = []; for (var i = 0, l = fn.arguments.length; i < l; ++i) { args.push({value: fn.arguments[i]}); } frames.push({fn: fn, name: getFuncName(fn), args: args}); } // **************************************************************************************** try { (0)(); } catch(e) { var result = e; var stack = result.stack || // Firefox / Google Chrome result.stacktrace || // Opera ""; stack = stack.replace(/\n\r|\r\n/g, "\n"); // normalize line breaks var items = stack.split(/[\n\r]/); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Google Chrome if (FBL.isSafari) { //var reChromeStackItem = /^\s+at\s+([^\(]+)\s\((.*)\)$/; //var reChromeStackItem = /^\s+at\s+(.*)((?:http|https|ftp|file):\/\/.*)$/; var reChromeStackItem = /^\s+at\s+(.*)((?:http|https|ftp|file):\/\/.*)$/; var reChromeStackItemName = /\s*\($/; var reChromeStackItemValue = /^(.+)\:(\d+\:\d+)\)?$/; var framePos = 0; for (var i=4, length=items.length; i<length; i++, framePos++) { var frame = frames[framePos]; var item = items[i]; var match = item.match(reChromeStackItem); //Firebug.Console.log("["+ framePos +"]--------------------------"); //Firebug.Console.log(item); //Firebug.Console.log("................"); if (match) { var name = match[1]; if (name) { name = name.replace(reChromeStackItemName, ""); frame.name = name; } //Firebug.Console.log("name: "+name); var value = match[2].match(reChromeStackItemValue); if (value) { frame.href = value[1]; frame.lineNo = value[2]; //Firebug.Console.log("url: "+value[1]); //Firebug.Console.log("line: "+value[2]); } //else // Firebug.Console.log(match[2]); } } } /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * else if (FBL.isFirefox) { // Firefox var reFirefoxStackItem = /^(.*)@(.*)$/; var reFirefoxStackItemValue = /^(.+)\:(\d+)$/; var framePos = 0; for (var i=2, length=items.length; i<length; i++, framePos++) { var frame = frames[framePos] || {}; var item = items[i]; var match = item.match(reFirefoxStackItem); if (match) { var name = match[1]; //Firebug.Console.logFormatted("name: "+name); var value = match[2].match(reFirefoxStackItemValue); if (value) { frame.href = value[1]; frame.lineNo = value[2]; //Firebug.Console.log("href: "+ value[1]); //Firebug.Console.log("line: " + value[2]); } //else // Firebug.Console.logFormatted([match[2]]); } } } /**/ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* else if (FBL.isOpera) { // Opera var reOperaStackItem = /^\s\s(?:\.\.\.\s\s)?Line\s(\d+)\sof\s(.+)$/; var reOperaStackItemValue = /^linked\sscript\s(.+)$/; for (var i=0, length=items.length; i<length; i+=2) { var item = items[i]; var match = item.match(reOperaStackItem); if (match) { //Firebug.Console.log(match[1]); var value = match[2].match(reOperaStackItemValue); if (value) { //Firebug.Console.log(value[1]); } //else // Firebug.Console.log(match[2]); //Firebug.Console.log("--------------------------"); } } } /**/ } //console.log(stack); //console.dir(frames); Firebug.Console.log({frames: frames}, context, "stackTrace", FirebugReps.StackTrace); traceRecursion--; }; this.trace_ok = function() { var getFuncName = function getFuncName (f) { if (f.getName instanceof Function) return f.getName(); if (f.name) // in FireFox, Function objects have a name property... return f.name; var name = f.toString().match(/function\s*([_$\w\d]*)/)[1]; return name || "anonymous"; }; var wasVisited = function(fn) { for (var i=0, l=frames.length; i<l; i++) { if (frames[i].fn == fn) return true; } return false; }; var frames = []; for (var fn = arguments.callee.caller; fn; fn = fn.caller) { if (wasVisited(fn)) break; var args = []; for (var i = 0, l = fn.arguments.length; i < l; ++i) { args.push({value: fn.arguments[i]}); } frames.push({fn: fn, name: getFuncName(fn), args: args}); } Firebug.Console.log({frames: frames}, context, "stackTrace", FirebugReps.StackTrace); }; this.clear = function() { Firebug.Console.clear(context); }; this.time = function(name, reset) { if (!name) return; var time = new Date().getTime(); if (!this.timeCounters) this.timeCounters = {}; var key = "KEY"+name.toString(); if (!reset && this.timeCounters[key]) return; this.timeCounters[key] = time; }; this.timeEnd = function(name) { var time = new Date().getTime(); if (!this.timeCounters) return; var key = "KEY"+name.toString(); var timeCounter = this.timeCounters[key]; if (timeCounter) { var diff = time - timeCounter; var label = name + ": " + diff + "ms"; this.info(label); delete this.timeCounters[key]; } return diff; }; // These functions are over-ridden by commandLine this.evaluated = function(result, context) { if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector.FirebugConsoleHandler evalutated default called", result); Firebug.Console.log(result, context); }; this.evaluateError = function(result, context) { Firebug.Console.log(result, context, "errorMessage"); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * function logFormatted(args, className, linkToSource, noThrottle) { var sourceLink = linkToSource ? getStackLink() : null; return Firebug.Console.logFormatted(args, context, className, noThrottle, sourceLink); } function logAssert(category, args) { Firebug.Errors.increaseCount(context); if (!args || !args.length || args.length == 0) var msg = [FBL.$STR("Assertion")]; else var msg = args[0]; if (Firebug.errorStackTrace) { var trace = Firebug.errorStackTrace; delete Firebug.errorStackTrace; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("logAssert trace from errorStackTrace", trace); } else if (msg.stack) { var trace = parseToStackTrace(msg.stack); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("logAssert trace from msg.stack", trace); } else { var trace = getJSDUserStack(); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("logAssert trace from getJSDUserStack", trace); } var errorObject = new FBL.ErrorMessage(msg, (msg.fileName?msg.fileName:win.location), (msg.lineNumber?msg.lineNumber:0), "", category, context, trace); if (trace && trace.frames && trace.frames[0]) errorObject.correctWithStackTrace(trace); errorObject.resetSource(); var objects = errorObject; if (args.length > 1) { objects = [errorObject]; for (var i = 1; i < args.length; i++) objects.push(args[i]); } var row = Firebug.Console.log(objects, context, "errorMessage", null, true); // noThrottle row.scrollIntoView(); } function getComponentsStackDump() { // Starting with our stack, walk back to the user-level code var frame = Components.stack; var userURL = win.location.href.toString(); if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector.getComponentsStackDump initial stack for userURL "+userURL, frame); // Drop frames until we get into user code. while (frame && FBL.isSystemURL(frame.filename) ) frame = frame.caller; // Drop two more frames, the injected console function and firebugAppendConsole() if (frame) frame = frame.caller; if (frame) frame = frame.caller; if (FBTrace.DBG_CONSOLE) FBTrace.sysout("consoleInjector.getComponentsStackDump final stack for userURL "+userURL, frame); return frame; } function getStackLink() { // TODO: xxxpedro console2 return; //return FBL.getFrameSourceLink(getComponentsStackDump()); } function getJSDUserStack() { var trace = FBL.getCurrentStackTrace(context); var frames = trace ? trace.frames : null; if (frames && (frames.length > 0) ) { var oldest = frames.length - 1; // 6 - 1 = 5 for (var i = 0; i < frames.length; i++) { if (frames[oldest - i].href.indexOf("chrome:") == 0) break; var fn = frames[oldest - i].fn + ""; if (fn && (fn.indexOf("_firebugEvalEvent") != -1) ) break; // command line } FBTrace.sysout("consoleInjector getJSDUserStack: "+frames.length+" oldest: "+oldest+" i: "+i+" i - oldest + 2: "+(i - oldest + 2), trace); trace.frames = trace.frames.slice(2 - i); // take the oldest frames, leave 2 behind they are injection code return trace; } else return "Firebug failed to get stack trace with any frames"; } }; // ************************************************************************************************ // Register console namespace FBL.registerConsole = function() { var win = Env.browser.window; Firebug.Console.injector.install(win); }; registerConsole(); }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var commandPrefix = ">>>"; var reOpenBracket = /[\[\(\{]/; var reCloseBracket = /[\]\)\}]/; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var commandHistory = []; var commandPointer = -1; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var isAutoCompleting = null; var autoCompletePrefix = null; var autoCompleteExpr = null; var autoCompleteBuffer = null; var autoCompletePosition = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var fbCommandLine = null; var fbLargeCommandLine = null; var fbLargeCommandButtons = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var _completion = { window: [ "console" ], document: [ "getElementById", "getElementsByTagName" ] }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var _stack = function(command) { Firebug.context.persistedState.commandHistory.push(command); Firebug.context.persistedState.commandPointer = Firebug.context.persistedState.commandHistory.length; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ************************************************************************************************ // CommandLine Firebug.CommandLine = extend(Firebug.Module, { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * element: null, isMultiLine: false, isActive: false, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * initialize: function(doc) { this.clear = bind(this.clear, this); this.enter = bind(this.enter, this); this.onError = bind(this.onError, this); this.onKeyDown = bind(this.onKeyDown, this); this.onMultiLineKeyDown = bind(this.onMultiLineKeyDown, this); addEvent(Firebug.browser.window, "error", this.onError); addEvent(Firebug.chrome.window, "error", this.onError); }, shutdown: function(doc) { this.deactivate(); removeEvent(Firebug.browser.window, "error", this.onError); removeEvent(Firebug.chrome.window, "error", this.onError); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * activate: function(multiLine, hideToggleIcon, onRun) { defineCommandLineAPI(); Firebug.context.persistedState.commandHistory = Firebug.context.persistedState.commandHistory || []; Firebug.context.persistedState.commandPointer = Firebug.context.persistedState.commandPointer || -1; if (this.isActive) { if (this.isMultiLine == multiLine) return; this.deactivate(); } fbCommandLine = $("fbCommandLine"); fbLargeCommandLine = $("fbLargeCommandLine"); fbLargeCommandButtons = $("fbLargeCommandButtons"); if (multiLine) { onRun = onRun || this.enter; this.isMultiLine = true; this.element = fbLargeCommandLine; addEvent(this.element, "keydown", this.onMultiLineKeyDown); addEvent($("fbSmallCommandLineIcon"), "click", Firebug.chrome.hideLargeCommandLine); this.runButton = new Button({ element: $("fbCommand_btRun"), owner: Firebug.CommandLine, onClick: onRun }); this.runButton.initialize(); this.clearButton = new Button({ element: $("fbCommand_btClear"), owner: Firebug.CommandLine, onClick: this.clear }); this.clearButton.initialize(); } else { this.isMultiLine = false; this.element = fbCommandLine; if (!fbCommandLine) return; addEvent(this.element, "keydown", this.onKeyDown); } //Firebug.Console.log("activate", this.element); if (isOpera) fixOperaTabKey(this.element); if(this.lastValue) this.element.value = this.lastValue; this.isActive = true; }, deactivate: function() { if (!this.isActive) return; //Firebug.Console.log("deactivate", this.element); this.isActive = false; this.lastValue = this.element.value; if (this.isMultiLine) { removeEvent(this.element, "keydown", this.onMultiLineKeyDown); removeEvent($("fbSmallCommandLineIcon"), "click", Firebug.chrome.hideLargeCommandLine); this.runButton.destroy(); this.clearButton.destroy(); } else { removeEvent(this.element, "keydown", this.onKeyDown); } this.element = null; delete this.element; fbCommandLine = null; fbLargeCommandLine = null; fbLargeCommandButtons = null; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * focus: function() { this.element.focus(); }, blur: function() { this.element.blur(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * clear: function() { this.element.value = ""; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * evaluate: function(expr) { // TODO: need to register the API in console.firebug.commandLineAPI var api = "Firebug.CommandLine.API"; var result = Firebug.context.evaluate(expr, "window", api, Firebug.Console.error); return result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * enter: function() { var command = this.element.value; if (!command) return; _stack(command); Firebug.Console.log(commandPrefix + " " + stripNewLines(command), Firebug.browser, "command", FirebugReps.Text); var result = this.evaluate(command); Firebug.Console.log(result); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * prevCommand: function() { if (Firebug.context.persistedState.commandPointer > 0 && Firebug.context.persistedState.commandHistory.length > 0) { this.element.value = Firebug.context.persistedState.commandHistory [--Firebug.context.persistedState.commandPointer]; } }, nextCommand: function() { var element = this.element; var limit = Firebug.context.persistedState.commandHistory.length -1; var i = Firebug.context.persistedState.commandPointer; if (i < limit) element.value = Firebug.context.persistedState.commandHistory [++Firebug.context.persistedState.commandPointer]; else if (i == limit) { ++Firebug.context.persistedState.commandPointer; element.value = ""; } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * autocomplete: function(reverse) { var element = this.element; var command = element.value; var offset = getExpressionOffset(command); var valBegin = offset ? command.substr(0, offset) : ""; var val = command.substr(offset); var buffer, obj, objName, commandBegin, result, prefix; // if it is the beginning of the completion if(!isAutoCompleting) { // group1 - command begin // group2 - base object // group3 - property prefix var reObj = /(.*[^_$\w\d\.])?((?:[_$\w][_$\w\d]*\.)*)([_$\w][_$\w\d]*)?$/; var r = reObj.exec(val); // parse command if (r[1] || r[2] || r[3]) { commandBegin = r[1] || ""; objName = r[2] || ""; prefix = r[3] || ""; } else if (val == "") { commandBegin = objName = prefix = ""; } else return; isAutoCompleting = true; // find base object if(objName == "") obj = window; else { objName = objName.replace(/\.$/, ""); var n = objName.split("."); var target = window, o; for (var i=0, ni; ni = n[i]; i++) { if (o = target[ni]) target = o; else { target = null; break; } } obj = target; } // map base object if(obj) { autoCompletePrefix = prefix; autoCompleteExpr = valBegin + commandBegin + (objName ? objName + "." : ""); autoCompletePosition = -1; buffer = autoCompleteBuffer = isIE ? _completion[objName || "window"] || [] : []; for(var p in obj) buffer.push(p); } // if it is the continuation of the last completion } else buffer = autoCompleteBuffer; if (buffer) { prefix = autoCompletePrefix; var diff = reverse ? -1 : 1; for(var i=autoCompletePosition+diff, l=buffer.length, bi; i>=0 && i<l; i+=diff) { bi = buffer[i]; if (bi.indexOf(prefix) == 0) { autoCompletePosition = i; result = bi; break; } } } if (result) element.value = autoCompleteExpr + result; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * setMultiLine: function(multiLine) { if (multiLine == this.isMultiLine) return; this.activate(multiLine); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onError: function(msg, href, lineNo) { href = href || ""; var lastSlash = href.lastIndexOf("/"); var fileName = lastSlash == -1 ? href : href.substr(lastSlash+1); var html = [ '<span class="errorMessage">', msg, '</span>', '<div class="objectBox-sourceLink">', fileName, ' (line ', lineNo, ')</div>' ]; // TODO: xxxpedro ajust to Console2 //Firebug.Console.writeRow(html, "error"); }, onKeyDown: function(e) { e = e || event; var code = e.keyCode; /*tab, shift, control, alt*/ if (code != 9 && code != 16 && code != 17 && code != 18) { isAutoCompleting = false; } if (code == 13 /* enter */) { this.enter(); this.clear(); } else if (code == 27 /* ESC */) { setTimeout(this.clear, 0); } else if (code == 38 /* up */) { this.prevCommand(); } else if (code == 40 /* down */) { this.nextCommand(); } else if (code == 9 /* tab */) { this.autocomplete(e.shiftKey); } else return; cancelEvent(e, true); return false; }, onMultiLineKeyDown: function(e) { e = e || event; var code = e.keyCode; if (code == 13 /* enter */ && e.ctrlKey) { this.enter(); } } }); Firebug.registerModule(Firebug.CommandLine); // ************************************************************************************************ // function getExpressionOffset(command) { // XXXjoe This is kind of a poor-man's JavaScript parser - trying // to find the start of the expression that the cursor is inside. // Not 100% fool proof, but hey... var bracketCount = 0; var start = command.length-1; for (; start >= 0; --start) { var c = command[start]; if ((c == "," || c == ";" || c == " ") && !bracketCount) break; if (reOpenBracket.test(c)) { if (bracketCount) --bracketCount; else break; } else if (reCloseBracket.test(c)) ++bracketCount; } return start + 1; } // ************************************************************************************************ // CommandLine API var CommandLineAPI = { $: function(id) { return Firebug.browser.document.getElementById(id); }, $$: function(selector, context) { context = context || Firebug.browser.document; return Firebug.Selector ? Firebug.Selector(selector, context) : Firebug.Console.error("Firebug.Selector module not loaded."); }, $0: null, $1: null, dir: function(o) { Firebug.Console.log(o, Firebug.context, "dir", Firebug.DOMPanel.DirTable); }, dirxml: function(o) { ///if (o instanceof Window) if (instanceOf(o, "Window")) o = o.document.documentElement; ///else if (o instanceof Document) else if (instanceOf(o, "Document")) o = o.documentElement; Firebug.Console.log(o, Firebug.context, "dirxml", Firebug.HTMLPanel.SoloElement); } }; // ************************************************************************************************ var defineCommandLineAPI = function defineCommandLineAPI() { Firebug.CommandLine.API = {}; for (var m in CommandLineAPI) if (!Env.browser.window[m]) Firebug.CommandLine.API[m] = CommandLineAPI[m]; var stack = FirebugChrome.htmlSelectionStack; if (stack) { Firebug.CommandLine.API.$0 = stack[0]; Firebug.CommandLine.API.$1 = stack[1]; } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var ElementCache = Firebug.Lite.Cache.Element; var cacheID = Firebug.Lite.Cache.ID; var ignoreHTMLProps = { // ignores the attributes injected by Sizzle, otherwise it will // be visible on IE (when enumerating element.attributes) sizcache: 1, sizset: 1 }; if (Firebug.ignoreFirebugElements) // ignores also the cache property injected by firebug ignoreHTMLProps[cacheID] = 1; // ************************************************************************************************ // HTML Module Firebug.HTML = extend(Firebug.Module, { appendTreeNode: function(nodeArray, html) { var reTrim = /^\s+|\s+$/g; if (!nodeArray.length) nodeArray = [nodeArray]; for (var n=0, node; node=nodeArray[n]; n++) { if (node.nodeType == 1) { if (Firebug.ignoreFirebugElements && node.firebugIgnore) continue; var uid = ElementCache(node); var child = node.childNodes; var childLength = child.length; var nodeName = node.nodeName.toLowerCase(); var nodeVisible = isVisible(node); var hasSingleTextChild = childLength == 1 && node.firstChild.nodeType == 3 && nodeName != "script" && nodeName != "style"; var nodeControl = !hasSingleTextChild && childLength > 0 ? ('<div class="nodeControl"></div>') : ''; // FIXME xxxpedro remove this //var isIE = false; if(isIE && nodeControl) html.push(nodeControl); if (typeof uid != 'undefined') html.push( '<div class="objectBox-element" ', 'id="', uid, '">', !isIE && nodeControl ? nodeControl: "", '<span ', cacheID, '="', uid, '" class="nodeBox', nodeVisible ? "" : " nodeHidden", '">&lt;<span class="nodeTag">', nodeName, '</span>' ); else html.push( '<div class="objectBox-element"><span class="nodeBox', nodeVisible ? "" : " nodeHidden", '">&lt;<span class="nodeTag">', nodeName, '</span>' ); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified || // Issue 4432: Firebug Lite: HTML is mixed-up with functions // The problem here is that expando properties added to DOM elements in // IE < 9 will behave like DOM attributes and so they'll show up when // looking at element.attributes list. isIE && (browserVersion-0<9) && typeof attr.nodeValue != "string" || Firebug.ignoreFirebugElements && ignoreHTMLProps.hasOwnProperty(attr.nodeName)) continue; var name = attr.nodeName.toLowerCase(); var value = name == "style" ? formatStyles(node.style.cssText) : attr.nodeValue; html.push('&nbsp;<span class="nodeName">', name, '</span>=&quot;<span class="nodeValue">', escapeHTML(value), '</span>&quot;'); } /* // source code nodes if (nodeName == 'script' || nodeName == 'style') { if(document.all){ var src = node.innerHTML+'\n'; }else { var src = '\n'+node.innerHTML+'\n'; } var match = src.match(/\n/g); var num = match ? match.length : 0; var s = [], sl = 0; for(var c=1; c<num; c++){ s[sl++] = '<div line="'+c+'">' + c + '</div>'; } html.push('&gt;</div><div class="nodeGroup"><div class="nodeChildren"><div class="lineNo">', s.join(''), '</div><pre class="nodeCode">', escapeHTML(src), '</pre>', '</div><div class="objectBox-element">&lt;/<span class="nodeTag">', nodeName, '</span>&gt;</div>', '</div>' ); }/**/ // Just a single text node child if (hasSingleTextChild) { var value = child[0].nodeValue.replace(reTrim, ''); if(value) { html.push( '&gt;<span class="nodeText">', escapeHTML(value), '</span>&lt;/<span class="nodeTag">', nodeName, '</span>&gt;</span></div>' ); } else html.push('/&gt;</span></div>'); // blank text, print as childless node } else if (childLength > 0) { html.push('&gt;</span></div>'); } else html.push('/&gt;</span></div>'); } else if (node.nodeType == 3) { if ( node.parentNode && ( node.parentNode.nodeName.toLowerCase() == "script" || node.parentNode.nodeName.toLowerCase() == "style" ) ) { var value = node.nodeValue.replace(reTrim, ''); if(isIE){ var src = value+'\n'; }else { var src = '\n'+value+'\n'; } var match = src.match(/\n/g); var num = match ? match.length : 0; var s = [], sl = 0; for(var c=1; c<num; c++){ s[sl++] = '<div line="'+c+'">' + c + '</div>'; } html.push('<div class="lineNo">', s.join(''), '</div><pre class="sourceCode">', escapeHTML(src), '</pre>' ); } else { var value = node.nodeValue.replace(reTrim, ''); if (value) html.push('<div class="nodeText">', escapeHTML(value),'</div>'); } } } }, appendTreeChildren: function(treeNode) { var doc = Firebug.chrome.document; var uid = treeNode.id; var parentNode = ElementCache.get(uid); if (parentNode.childNodes.length == 0) return; var treeNext = treeNode.nextSibling; var treeParent = treeNode.parentNode; // FIXME xxxpedro remove this //var isIE = false; var control = isIE ? treeNode.previousSibling : treeNode.firstChild; control.className = 'nodeControl nodeMaximized'; var html = []; var children = doc.createElement("div"); children.className = "nodeChildren"; this.appendTreeNode(parentNode.childNodes, html); children.innerHTML = html.join(""); treeParent.insertBefore(children, treeNext); var closeElement = doc.createElement("div"); closeElement.className = "objectBox-element"; closeElement.innerHTML = '&lt;/<span class="nodeTag">' + parentNode.nodeName.toLowerCase() + '&gt;</span>'; treeParent.insertBefore(closeElement, treeNext); }, removeTreeChildren: function(treeNode) { var children = treeNode.nextSibling; var closeTag = children.nextSibling; // FIXME xxxpedro remove this //var isIE = false; var control = isIE ? treeNode.previousSibling : treeNode.firstChild; control.className = 'nodeControl'; children.parentNode.removeChild(children); closeTag.parentNode.removeChild(closeTag); }, isTreeNodeVisible: function(id) { return $(id); }, select: function(el) { var id = el && ElementCache(el); if (id) this.selectTreeNode(id); }, selectTreeNode: function(id) { id = ""+id; var node, stack = []; while(id && !this.isTreeNodeVisible(id)) { stack.push(id); var node = ElementCache.get(id).parentNode; if (node) id = ElementCache(node); else break; } stack.push(id); while(stack.length > 0) { id = stack.pop(); node = $(id); if (stack.length > 0 && ElementCache.get(id).childNodes.length > 0) this.appendTreeChildren(node); } selectElement(node); // TODO: xxxpedro if (fbPanel1) fbPanel1.scrollTop = Math.round(node.offsetTop - fbPanel1.clientHeight/2); } }); Firebug.registerModule(Firebug.HTML); // ************************************************************************************************ // HTML Panel function HTMLPanel(){}; HTMLPanel.prototype = extend(Firebug.Panel, { name: "HTML", title: "HTML", options: { hasSidePanel: true, //hasToolButtons: true, isPreRendered: !Firebug.flexChromeEnabled /* FIXME xxxpedro chromenew */, innerHTMLSync: true }, create: function(){ Firebug.Panel.create.apply(this, arguments); this.panelNode.style.padding = "4px 3px 1px 15px"; this.panelNode.style.minWidth = "500px"; if (Env.Options.enablePersistent || Firebug.chrome.type != "popup") this.createUI(); if(this.sidePanelBar && !this.sidePanelBar.selectedPanel) { this.sidePanelBar.selectPanel("css"); } }, destroy: function() { selectedElement = null; fbPanel1 = null; selectedSidePanelTS = null; selectedSidePanelTimer = null; Firebug.Panel.destroy.apply(this, arguments); }, createUI: function() { var rootNode = Firebug.browser.document.documentElement; var html = []; Firebug.HTML.appendTreeNode(rootNode, html); this.panelNode.innerHTML = html.join(""); }, initialize: function() { Firebug.Panel.initialize.apply(this, arguments); addEvent(this.panelNode, 'click', Firebug.HTML.onTreeClick); fbPanel1 = $("fbPanel1"); if(!selectedElement) { Firebug.context.persistedState.selectedHTMLElementId = Firebug.context.persistedState.selectedHTMLElementId && ElementCache.get(Firebug.context.persistedState.selectedHTMLElementId) ? Firebug.context.persistedState.selectedHTMLElementId : ElementCache(Firebug.browser.document.body); Firebug.HTML.selectTreeNode(Firebug.context.persistedState.selectedHTMLElementId); } // TODO: xxxpedro addEvent(fbPanel1, 'mousemove', Firebug.HTML.onListMouseMove); addEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove); addEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove); }, shutdown: function() { // TODO: xxxpedro removeEvent(fbPanel1, 'mousemove', Firebug.HTML.onListMouseMove); removeEvent($("fbContent"), 'mouseout', Firebug.HTML.onListMouseMove); removeEvent(Firebug.chrome.node, 'mouseout', Firebug.HTML.onListMouseMove); removeEvent(this.panelNode, 'click', Firebug.HTML.onTreeClick); fbPanel1 = null; Firebug.Panel.shutdown.apply(this, arguments); }, reattach: function() { // TODO: panel reattach if(Firebug.context.persistedState.selectedHTMLElementId) Firebug.HTML.selectTreeNode(Firebug.context.persistedState.selectedHTMLElementId); }, updateSelection: function(object) { var id = ElementCache(object); if (id) { Firebug.HTML.selectTreeNode(id); } } }); Firebug.registerPanel(HTMLPanel); // ************************************************************************************************ var formatStyles = function(styles) { return isIE ? // IE return CSS property names in upper case, so we need to convert them styles.replace(/([^\s]+)\s*:/g, function(m,g){return g.toLowerCase()+":";}) : // other browsers are just fine styles; }; // ************************************************************************************************ var selectedElement = null; var fbPanel1 = null; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var selectedSidePanelTS, selectedSidePanelTimer; var selectElement= function selectElement(e) { if (e != selectedElement) { if (selectedElement) selectedElement.className = "objectBox-element"; e.className = e.className + " selectedElement"; if (FBL.isFirefox) e.style.MozBorderRadius = "2px"; else if (FBL.isSafari) e.style.WebkitBorderRadius = "2px"; e.style.borderRadius = "2px"; selectedElement = e; Firebug.context.persistedState.selectedHTMLElementId = e.id; var target = ElementCache.get(e.id); var sidePanelBar = Firebug.chrome.getPanel("HTML").sidePanelBar; var selectedSidePanel = sidePanelBar ? sidePanelBar.selectedPanel : null; var stack = FirebugChrome.htmlSelectionStack; stack.unshift(target); if (stack.length > 2) stack.pop(); var lazySelect = function() { selectedSidePanelTS = new Date().getTime(); if (selectedSidePanel) selectedSidePanel.select(target, true); }; if (selectedSidePanelTimer) { clearTimeout(selectedSidePanelTimer); selectedSidePanelTimer = null; } if (new Date().getTime() - selectedSidePanelTS > 100) setTimeout(lazySelect, 0); else selectedSidePanelTimer = setTimeout(lazySelect, 150); } }; // ************************************************************************************************ // *** TODO: REFACTOR ************************************************************************** // ************************************************************************************************ Firebug.HTML.onTreeClick = function (e) { e = e || event; var targ; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; if (targ.className.indexOf('nodeControl') != -1 || targ.className == 'nodeTag') { // FIXME xxxpedro remove this //var isIE = false; if(targ.className == 'nodeTag') { var control = isIE ? (targ.parentNode.previousSibling || targ) : (targ.parentNode.previousSibling || targ); selectElement(targ.parentNode.parentNode); if (control.className.indexOf('nodeControl') == -1) return; } else control = targ; FBL.cancelEvent(e); var treeNode = isIE ? control.nextSibling : control.parentNode; //FBL.Firebug.Console.log(treeNode); if (control.className.indexOf(' nodeMaximized') != -1) { FBL.Firebug.HTML.removeTreeChildren(treeNode); } else { FBL.Firebug.HTML.appendTreeChildren(treeNode); } } else if (targ.className == 'nodeValue' || targ.className == 'nodeName') { /* var input = FBL.Firebug.chrome.document.getElementById('treeInput'); input.style.display = "block"; input.style.left = targ.offsetLeft + 'px'; input.style.top = FBL.topHeight + targ.offsetTop - FBL.fbPanel1.scrollTop + 'px'; input.style.width = targ.offsetWidth + 6 + 'px'; input.value = targ.textContent || targ.innerText; input.focus(); /**/ } }; function onListMouseOut(e) { e = e || event || window; var targ; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; if (hasClass(targ, "fbPanel")) { FBL.Firebug.Inspector.hideBoxModel(); hoverElement = null; } }; var hoverElement = null; var hoverElementTS = 0; Firebug.HTML.onListMouseMove = function onListMouseMove(e) { try { e = e || event || window; var targ; if (e.target) targ = e.target; else if (e.srcElement) targ = e.srcElement; if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode; var found = false; while (targ && !found) { if (!/\snodeBox\s|\sobjectBox-selector\s/.test(" " + targ.className + " ")) targ = targ.parentNode; else found = true; } if (!targ) { FBL.Firebug.Inspector.hideBoxModel(); hoverElement = null; return; } /* if (typeof targ.attributes[cacheID] == 'undefined') return; var uid = targ.attributes[cacheID]; if (!uid) return; /**/ if (typeof targ.attributes[cacheID] == 'undefined') return; var uid = targ.attributes[cacheID]; if (!uid) return; var el = ElementCache.get(uid.value); var nodeName = el.nodeName.toLowerCase(); if (FBL.isIE && " meta title script link ".indexOf(" "+nodeName+" ") != -1) return; if (!/\snodeBox\s|\sobjectBox-selector\s/.test(" " + targ.className + " ")) return; if (el.id == "FirebugUI" || " html head body br script link iframe ".indexOf(" "+nodeName+" ") != -1) { FBL.Firebug.Inspector.hideBoxModel(); hoverElement = null; return; } if ((new Date().getTime() - hoverElementTS > 40) && hoverElement != el) { hoverElementTS = new Date().getTime(); hoverElement = el; FBL.Firebug.Inspector.drawBoxModel(el); } } catch(E) { } }; // ************************************************************************************************ Firebug.Reps = { appendText: function(object, html) { html.push(escapeHTML(objectToString(object))); }, appendNull: function(object, html) { html.push('<span class="objectBox-null">', escapeHTML(objectToString(object)), '</span>'); }, appendString: function(object, html) { html.push('<span class="objectBox-string">&quot;', escapeHTML(objectToString(object)), '&quot;</span>'); }, appendInteger: function(object, html) { html.push('<span class="objectBox-number">', escapeHTML(objectToString(object)), '</span>'); }, appendFloat: function(object, html) { html.push('<span class="objectBox-number">', escapeHTML(objectToString(object)), '</span>'); }, appendFunction: function(object, html) { var reName = /function ?(.*?)\(/; var m = reName.exec(objectToString(object)); var name = m && m[1] ? m[1] : "function"; html.push('<span class="objectBox-function">', escapeHTML(name), '()</span>'); }, appendObject: function(object, html) { /* var rep = Firebug.getRep(object); var outputs = []; rep.tag.tag.compile(); var str = rep.tag.renderHTML({object: object}, outputs); html.push(str); /**/ try { if (object == undefined) this.appendNull("undefined", html); else if (object == null) this.appendNull("null", html); else if (typeof object == "string") this.appendString(object, html); else if (typeof object == "number") this.appendInteger(object, html); else if (typeof object == "boolean") this.appendInteger(object, html); else if (typeof object == "function") this.appendFunction(object, html); else if (object.nodeType == 1) this.appendSelector(object, html); else if (typeof object == "object") { if (typeof object.length != "undefined") this.appendArray(object, html); else this.appendObjectFormatted(object, html); } else this.appendText(object, html); } catch (exc) { } /**/ }, appendObjectFormatted: function(object, html) { var text = objectToString(object); var reObject = /\[object (.*?)\]/; var m = reObject.exec(text); html.push('<span class="objectBox-object">', m ? m[1] : text, '</span>'); }, appendSelector: function(object, html) { var uid = ElementCache(object); var uidString = uid ? [cacheID, '="', uid, '"'].join("") : ""; html.push('<span class="objectBox-selector"', uidString, '>'); html.push('<span class="selectorTag">', escapeHTML(object.nodeName.toLowerCase()), '</span>'); if (object.id) html.push('<span class="selectorId">#', escapeHTML(object.id), '</span>'); if (object.className) html.push('<span class="selectorClass">.', escapeHTML(object.className), '</span>'); html.push('</span>'); }, appendNode: function(node, html) { if (node.nodeType == 1) { var uid = ElementCache(node); var uidString = uid ? [cacheID, '="', uid, '"'].join("") : ""; html.push( '<div class="objectBox-element"', uidString, '">', '<span ', cacheID, '="', uid, '" class="nodeBox">', '&lt;<span class="nodeTag">', node.nodeName.toLowerCase(), '</span>'); for (var i = 0; i < node.attributes.length; ++i) { var attr = node.attributes[i]; if (!attr.specified || attr.nodeName == cacheID) continue; var name = attr.nodeName.toLowerCase(); var value = name == "style" ? node.style.cssText : attr.nodeValue; html.push('&nbsp;<span class="nodeName">', name, '</span>=&quot;<span class="nodeValue">', escapeHTML(value), '</span>&quot;'); } if (node.firstChild) { html.push('&gt;</div><div class="nodeChildren">'); for (var child = node.firstChild; child; child = child.nextSibling) this.appendNode(child, html); html.push('</div><div class="objectBox-element">&lt;/<span class="nodeTag">', node.nodeName.toLowerCase(), '&gt;</span></span></div>'); } else html.push('/&gt;</span></div>'); } else if (node.nodeType == 3) { var value = trim(node.nodeValue); if (value) html.push('<div class="nodeText">', escapeHTML(value),'</div>'); } }, appendArray: function(object, html) { html.push('<span class="objectBox-array"><b>[</b> '); for (var i = 0, l = object.length, obj; i < l; ++i) { this.appendObject(object[i], html); if (i < l-1) html.push(', '); } html.push(' <b>]</b></span>'); } }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ /* Hack: Firebug.chrome.currentPanel = Firebug.chrome.selectedPanel; Firebug.showInfoTips = true; Firebug.InfoTip.initializeBrowser(Firebug.chrome); /**/ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // Constants var maxWidth = 100, maxHeight = 80; var infoTipMargin = 10; var infoTipWindowPadding = 25; // ************************************************************************************************ Firebug.InfoTip = extend(Firebug.Module, { dispatchName: "infoTip", tags: domplate( { infoTipTag: DIV({"class": "infoTip"}), colorTag: DIV({style: "background: $rgbValue; width: 100px; height: 40px"}, "&nbsp;"), imgTag: DIV({"class": "infoTipImageBox infoTipLoading"}, IMG({"class": "infoTipImage", src: "$urlValue", repeat: "$repeat", onload: "$onLoadImage"}), IMG({"class": "infoTipBgImage", collapsed: true, src: "blank.gif"}), DIV({"class": "infoTipCaption"}) ), onLoadImage: function(event) { var img = event.currentTarget || event.srcElement; ///var bgImg = img.nextSibling; ///if (!bgImg) /// return; // Sometimes gets called after element is dead ///var caption = bgImg.nextSibling; var innerBox = img.parentNode; /// TODO: xxxpedro infoTip hack var caption = getElementByClass(innerBox, "infoTipCaption"); var bgImg = getElementByClass(innerBox, "infoTipBgImage"); if (!bgImg) return; // Sometimes gets called after element is dead // TODO: xxxpedro infoTip IE and timing issue // TODO: use offline document to avoid flickering if (isIE) removeClass(innerBox, "infoTipLoading"); var updateInfoTip = function(){ var w = img.naturalWidth || img.width || 10, h = img.naturalHeight || img.height || 10; var repeat = img.getAttribute("repeat"); if (repeat == "repeat-x" || (w == 1 && h > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-x"; bgImg.style.width = maxWidth + "px"; if (h > maxHeight) bgImg.style.height = maxHeight + "px"; else bgImg.style.height = h + "px"; } else if (repeat == "repeat-y" || (h == 1 && w > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-y"; bgImg.style.height = maxHeight + "px"; if (w > maxWidth) bgImg.style.width = maxWidth + "px"; else bgImg.style.width = w + "px"; } else if (repeat == "repeat" || (w == 1 && h == 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat"; bgImg.style.width = maxWidth + "px"; bgImg.style.height = maxHeight + "px"; } else { if (w > maxWidth || h > maxHeight) { if (w > h) { img.style.width = maxWidth + "px"; img.style.height = Math.round((h / w) * maxWidth) + "px"; } else { img.style.width = Math.round((w / h) * maxHeight) + "px"; img.style.height = maxHeight + "px"; } } } //caption.innerHTML = $STRF("Dimensions", [w, h]); caption.innerHTML = $STRF(w + " x " + h); }; if (isIE) setTimeout(updateInfoTip, 0); else { updateInfoTip(); removeClass(innerBox, "infoTipLoading"); } /// } /* /// onLoadImage original onLoadImage: function(event) { var img = event.currentTarget; var bgImg = img.nextSibling; if (!bgImg) return; // Sometimes gets called after element is dead var caption = bgImg.nextSibling; var innerBox = img.parentNode; var w = img.naturalWidth, h = img.naturalHeight; var repeat = img.getAttribute("repeat"); if (repeat == "repeat-x" || (w == 1 && h > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-x"; bgImg.style.width = maxWidth + "px"; if (h > maxHeight) bgImg.style.height = maxHeight + "px"; else bgImg.style.height = h + "px"; } else if (repeat == "repeat-y" || (h == 1 && w > 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat-y"; bgImg.style.height = maxHeight + "px"; if (w > maxWidth) bgImg.style.width = maxWidth + "px"; else bgImg.style.width = w + "px"; } else if (repeat == "repeat" || (w == 1 && h == 1)) { collapse(img, true); collapse(bgImg, false); bgImg.style.background = "url(" + img.src + ") repeat"; bgImg.style.width = maxWidth + "px"; bgImg.style.height = maxHeight + "px"; } else { if (w > maxWidth || h > maxHeight) { if (w > h) { img.style.width = maxWidth + "px"; img.style.height = Math.round((h / w) * maxWidth) + "px"; } else { img.style.width = Math.round((w / h) * maxHeight) + "px"; img.style.height = maxHeight + "px"; } } } caption.innerHTML = $STRF("Dimensions", [w, h]); removeClass(innerBox, "infoTipLoading"); } /**/ }), initializeBrowser: function(browser) { browser.onInfoTipMouseOut = bind(this.onMouseOut, this, browser); browser.onInfoTipMouseMove = bind(this.onMouseMove, this, browser); ///var doc = browser.contentDocument; var doc = browser.document; if (!doc) return; ///doc.addEventListener("mouseover", browser.onInfoTipMouseMove, true); ///doc.addEventListener("mouseout", browser.onInfoTipMouseOut, true); ///doc.addEventListener("mousemove", browser.onInfoTipMouseMove, true); addEvent(doc, "mouseover", browser.onInfoTipMouseMove); addEvent(doc, "mouseout", browser.onInfoTipMouseOut); addEvent(doc, "mousemove", browser.onInfoTipMouseMove); return browser.infoTip = this.tags.infoTipTag.append({}, getBody(doc)); }, uninitializeBrowser: function(browser) { if (browser.infoTip) { ///var doc = browser.contentDocument; var doc = browser.document; ///doc.removeEventListener("mouseover", browser.onInfoTipMouseMove, true); ///doc.removeEventListener("mouseout", browser.onInfoTipMouseOut, true); ///doc.removeEventListener("mousemove", browser.onInfoTipMouseMove, true); removeEvent(doc, "mouseover", browser.onInfoTipMouseMove); removeEvent(doc, "mouseout", browser.onInfoTipMouseOut); removeEvent(doc, "mousemove", browser.onInfoTipMouseMove); browser.infoTip.parentNode.removeChild(browser.infoTip); delete browser.infoTip; delete browser.onInfoTipMouseMove; } }, showInfoTip: function(infoTip, panel, target, x, y, rangeParent, rangeOffset) { if (!Firebug.showInfoTips) return; var scrollParent = getOverflowParent(target); var scrollX = x + (scrollParent ? scrollParent.scrollLeft : 0); if (panel.showInfoTip(infoTip, target, scrollX, y, rangeParent, rangeOffset)) { var htmlElt = infoTip.ownerDocument.documentElement; var panelWidth = htmlElt.clientWidth; var panelHeight = htmlElt.clientHeight; if (x+infoTip.offsetWidth+infoTipMargin > panelWidth) { infoTip.style.left = Math.max(0, panelWidth-(infoTip.offsetWidth+infoTipMargin)) + "px"; infoTip.style.right = "auto"; } else { infoTip.style.left = (x+infoTipMargin) + "px"; infoTip.style.right = "auto"; } if (y+infoTip.offsetHeight+infoTipMargin > panelHeight) { infoTip.style.top = Math.max(0, panelHeight-(infoTip.offsetHeight+infoTipMargin)) + "px"; infoTip.style.bottom = "auto"; } else { infoTip.style.top = (y+infoTipMargin) + "px"; infoTip.style.bottom = "auto"; } if (FBTrace.DBG_INFOTIP) FBTrace.sysout("infotip.showInfoTip; top: " + infoTip.style.top + ", left: " + infoTip.style.left + ", bottom: " + infoTip.style.bottom + ", right:" + infoTip.style.right + ", offsetHeight: " + infoTip.offsetHeight + ", offsetWidth: " + infoTip.offsetWidth + ", x: " + x + ", panelWidth: " + panelWidth + ", y: " + y + ", panelHeight: " + panelHeight); infoTip.setAttribute("active", "true"); } else this.hideInfoTip(infoTip); }, hideInfoTip: function(infoTip) { if (infoTip) infoTip.removeAttribute("active"); }, onMouseOut: function(event, browser) { if (!event.relatedTarget) this.hideInfoTip(browser.infoTip); }, onMouseMove: function(event, browser) { // Ignore if the mouse is moving over the existing info tip. if (getAncestorByClass(event.target, "infoTip")) return; if (browser.currentPanel) { var x = event.clientX, y = event.clientY, target = event.target || event.srcElement; this.showInfoTip(browser.infoTip, browser.currentPanel, target, x, y, event.rangeParent, event.rangeOffset); } else this.hideInfoTip(browser.infoTip); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * populateColorInfoTip: function(infoTip, color) { this.tags.colorTag.replace({rgbValue: color}, infoTip); return true; }, populateImageInfoTip: function(infoTip, url, repeat) { if (!repeat) repeat = "no-repeat"; this.tags.imgTag.replace({urlValue: url, repeat: repeat}, infoTip); return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Module disable: function() { // XXXjoe For each browser, call uninitializeBrowser }, showPanel: function(browser, panel) { if (panel) { var infoTip = panel.panelBrowser.infoTip; if (!infoTip) infoTip = this.initializeBrowser(panel.panelBrowser); this.hideInfoTip(infoTip); } }, showSidePanel: function(browser, panel) { this.showPanel(browser, panel); } }); // ************************************************************************************************ Firebug.registerModule(Firebug.InfoTip); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ var CssParser = null; // ************************************************************************************************ // Simple CSS stylesheet parser from: // https://github.com/sergeche/webkit-css /** * Simple CSS stylesheet parser that remembers rule's lines in file * @author Sergey Chikuyonok (serge.che@gmail.com) * @link http://chikuyonok.ru */ CssParser = (function(){ /** * Returns rule object * @param {Number} start Character index where CSS rule definition starts * @param {Number} body_start Character index where CSS rule's body starts * @param {Number} end Character index where CSS rule definition ends */ function rule(start, body_start, end) { return { start: start || 0, body_start: body_start || 0, end: end || 0, line: -1, selector: null, parent: null, /** @type {rule[]} */ children: [], addChild: function(start, body_start, end) { var r = rule(start, body_start, end); r.parent = this; this.children.push(r); return r; }, /** * Returns last child element * @return {rule} */ lastChild: function() { return this.children[this.children.length - 1]; } }; } /** * Replaces all occurances of substring defined by regexp * @param {String} str * @return {RegExp} re * @return {String} */ function removeAll(str, re) { var m; while (m = str.match(re)) { str = str.substring(m[0].length); } return str; } /** * Trims whitespace from the beginning and the end of string * @param {String} str * @return {String} */ function trim(str) { return str.replace(/^\s+|\s+$/g, ''); } /** * Normalizes CSS rules selector * @param {String} selector */ function normalizeSelector(selector) { // remove newlines selector = selector.replace(/[\n\r]/g, ' '); selector = trim(selector); // remove spaces after commas selector = selector.replace(/\s*,\s*/g, ','); return selector; } /** * Preprocesses parsed rules: adjusts char indexes, skipping whitespace and * newlines, saves rule selector, removes comments, etc. * @param {String} text CSS stylesheet * @param {rule} rule_node CSS rule node * @return {rule[]} */ function preprocessRules(text, rule_node) { for (var i = 0, il = rule_node.children.length; i < il; i++) { var r = rule_node.children[i], rule_start = text.substring(r.start, r.body_start), cur_len = rule_start.length; // remove newlines for better regexp matching rule_start = rule_start.replace(/[\n\r]/g, ' '); // remove @import rules // rule_start = removeAll(rule_start, /^\s*@import\s*url\((['"])?.+?\1?\)\;?/g); // remove comments rule_start = removeAll(rule_start, /^\s*\/\*.*?\*\/[\s\t]*/); // remove whitespace rule_start = rule_start.replace(/^[\s\t]+/, ''); r.start += (cur_len - rule_start.length); r.selector = normalizeSelector(rule_start); } return rule_node; } /** * Saves all lise starting indexes for faster search * @param {String} text CSS stylesheet * @return {Number[]} */ function saveLineIndexes(text) { var result = [0], i = 0, il = text.length, ch, ch2; while (i < il) { ch = text.charAt(i); if (ch == '\n' || ch == '\r') { if (ch == '\r' && i < il - 1 && text.charAt(i + 1) == '\n') { // windows line ending: CRLF. Skip next character i++; } result.push(i + 1); } i++; } return result; } /** * Saves line number for parsed rules * @param {String} text CSS stylesheet * @param {rule} rule_node Rule node * @return {rule[]} */ function saveLineNumbers(text, rule_node, line_indexes, startLine) { preprocessRules(text, rule_node); startLine = startLine || 0; // remember lines start indexes, preserving line ending characters if (!line_indexes) var line_indexes = saveLineIndexes(text); // now find each rule's line for (var i = 0, il = rule_node.children.length; i < il; i++) { var r = rule_node.children[i]; r.line = line_indexes.length + startLine; for (var j = 0, jl = line_indexes.length - 1; j < jl; j++) { var line_ix = line_indexes[j]; if (r.start >= line_indexes[j] && r.start < line_indexes[j + 1]) { r.line = j + 1 + startLine; break; } } saveLineNumbers(text, r, line_indexes); } return rule_node; } return { /** * Parses text as CSS stylesheet, remembring each rule position inside * text * @param {String} text CSS stylesheet to parse */ read: function(text, startLine) { var rule_start = [], rule_body_start = [], rules = [], in_comment = 0, root = rule(), cur_parent = root, last_rule = null, stack = [], ch, ch2; stack.last = function() { return this[this.length - 1]; }; function hasStr(pos, substr) { return text.substr(pos, substr.length) == substr; } for (var i = 0, il = text.length; i < il; i++) { ch = text.charAt(i); ch2 = i < il - 1 ? text.charAt(i + 1) : ''; if (!rule_start.length) rule_start.push(i); switch (ch) { case '@': if (!in_comment) { if (hasStr(i, '@import')) { var m = text.substr(i).match(/^@import\s*url\((['"])?.+?\1?\)\;?/); if (m) { cur_parent.addChild(i, i + 7, i + m[0].length); i += m[0].length; rule_start.pop(); } break; } } case '/': // xxxpedro allowing comment inside comment if (!in_comment && ch2 == '*') { // comment start in_comment++; } break; case '*': if (ch2 == '/') { // comment end in_comment--; } break; case '{': if (!in_comment) { rule_body_start.push(i); cur_parent = cur_parent.addChild(rule_start.pop()); stack.push(cur_parent); } break; case '}': // found the end of the rule if (!in_comment) { /** @type {rule} */ var last_rule = stack.pop(); rule_start.pop(); last_rule.body_start = rule_body_start.pop(); last_rule.end = i; cur_parent = last_rule.parent || root; } break; } } return saveLineNumbers(text, root, null, startLine); }, normalizeSelector: normalizeSelector, /** * Find matched rule by selector. * @param {rule} rule_node Parsed rule node * @param {String} selector CSS selector * @param {String} source CSS stylesheet source code * * @return {rule[]|null} Array of matched rules, sorted by priority (most * recent on top) */ findBySelector: function(rule_node, selector, source) { var selector = normalizeSelector(selector), result = []; if (rule_node) { for (var i = 0, il = rule_node.children.length; i < il; i++) { /** @type {rule} */ var r = rule_node.children[i]; if (r.selector == selector) { result.push(r); } } } if (result.length) { return result; } else { return null; } } }; })(); // ************************************************************************************************ FBL.CssParser = CssParser; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // StyleSheet Parser var CssAnalyzer = {}; // ************************************************************************************************ // Locals var CSSRuleMap = {}; var ElementCSSRulesMap = {}; var internalStyleSheetIndex = -1; var reSelectorTag = /(^|\s)(?:\w+)/g; var reSelectorClass = /\.[\w\d_-]+/g; var reSelectorId = /#[\w\d_-]+/g; var globalCSSRuleIndex; var processAllStyleSheetsTimeout = null; var externalStyleSheetURLs = []; var ElementCache = Firebug.Lite.Cache.Element; var StyleSheetCache = Firebug.Lite.Cache.StyleSheet; //************************************************************************************************ // CSS Analyzer templates CssAnalyzer.externalStyleSheetWarning = domplate(Firebug.Rep, { tag: DIV({"class": "warning focusRow", style: "font-weight:normal;", role: 'listitem'}, SPAN("$object|STR"), A({"href": "$href", target:"_blank"}, "$link|STR") ) }); // ************************************************************************************************ // CSS Analyzer methods CssAnalyzer.processAllStyleSheets = function(doc, styleSheetIterator) { try { processAllStyleSheets(doc, styleSheetIterator); } catch(e) { // TODO: FBTrace condition FBTrace.sysout("CssAnalyzer.processAllStyleSheets fails: ", e); } }; /** * * @param element * @returns {String[]} Array of IDs of CSS Rules */ CssAnalyzer.getElementCSSRules = function(element) { try { return getElementCSSRules(element); } catch(e) { // TODO: FBTrace condition FBTrace.sysout("CssAnalyzer.getElementCSSRules fails: ", e); } }; CssAnalyzer.getRuleData = function(ruleId) { return CSSRuleMap[ruleId]; }; // TODO: do we need this? CssAnalyzer.getRuleLine = function() { }; CssAnalyzer.hasExternalStyleSheet = function() { return externalStyleSheetURLs.length > 0; }; CssAnalyzer.parseStyleSheet = function(href) { var sourceData = extractSourceData(href); var parsedObj = CssParser.read(sourceData.source, sourceData.startLine); var parsedRules = parsedObj.children; // See: Issue 4776: [Firebug lite] CSS Media Types // // Ignore all special selectors like @media and @page for(var i=0; i < parsedRules.length; ) { if (parsedRules[i].selector.indexOf("@") != -1) { parsedRules.splice(i, 1); } else i++; } return parsedRules; }; //************************************************************************************************ // Internals //************************************************************************************************ // ************************************************************************************************ // StyleSheet processing var processAllStyleSheets = function(doc, styleSheetIterator) { styleSheetIterator = styleSheetIterator || processStyleSheet; globalCSSRuleIndex = -1; var styleSheets = doc.styleSheets; var importedStyleSheets = []; if (FBTrace.DBG_CSS) var start = new Date().getTime(); for(var i=0, length=styleSheets.length; i<length; i++) { try { var styleSheet = styleSheets[i]; if ("firebugIgnore" in styleSheet) continue; // we must read the length to make sure we have permission to read // the stylesheet's content. If an error occurs here, we cannot // read the stylesheet due to access restriction policy var rules = isIE ? styleSheet.rules : styleSheet.cssRules; rules.length; } catch(e) { externalStyleSheetURLs.push(styleSheet.href); styleSheet.restricted = true; var ssid = StyleSheetCache(styleSheet); /// TODO: xxxpedro external css //loadExternalStylesheet(doc, styleSheetIterator, styleSheet); } // process internal and external styleSheets styleSheetIterator(doc, styleSheet); var importedStyleSheet, importedRules; // process imported styleSheets in IE if (isIE) { var imports = styleSheet.imports; for(var j=0, importsLength=imports.length; j<importsLength; j++) { try { importedStyleSheet = imports[j]; // we must read the length to make sure we have permission // to read the imported stylesheet's content. importedRules = importedStyleSheet.rules; importedRules.length; } catch(e) { externalStyleSheetURLs.push(styleSheet.href); importedStyleSheet.restricted = true; var ssid = StyleSheetCache(importedStyleSheet); } styleSheetIterator(doc, importedStyleSheet); } } // process imported styleSheets in other browsers else if (rules) { for(var j=0, rulesLength=rules.length; j<rulesLength; j++) { try { var rule = rules[j]; importedStyleSheet = rule.styleSheet; if (importedStyleSheet) { // we must read the length to make sure we have permission // to read the imported stylesheet's content. importedRules = importedStyleSheet.cssRules; importedRules.length; } else break; } catch(e) { externalStyleSheetURLs.push(styleSheet.href); importedStyleSheet.restricted = true; var ssid = StyleSheetCache(importedStyleSheet); } styleSheetIterator(doc, importedStyleSheet); } } }; if (FBTrace.DBG_CSS) { FBTrace.sysout("FBL.processAllStyleSheets", "all stylesheet rules processed in " + (new Date().getTime() - start) + "ms"); } }; // ************************************************************************************************ var processStyleSheet = function(doc, styleSheet) { if (styleSheet.restricted) return; var rules = isIE ? styleSheet.rules : styleSheet.cssRules; var ssid = StyleSheetCache(styleSheet); var href = styleSheet.href; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // CSS Parser var shouldParseCSS = typeof CssParser != "undefined" && !Firebug.disableResourceFetching; if (shouldParseCSS) { try { var parsedRules = CssAnalyzer.parseStyleSheet(href); } catch(e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("processStyleSheet FAILS", e.message || e); shouldParseCSS = false; } finally { var parsedRulesIndex = 0; var dontSupportGroupedRules = isIE && browserVersion < 9; var group = []; var groupItem; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * for (var i=0, length=rules.length; i<length; i++) { // TODO: xxxpedro is there a better way to cache CSS Rules? The problem is that // we cannot add expando properties in the rule object in IE var rid = ssid + ":" + i; var rule = rules[i]; var selector = rule.selectorText || ""; var lineNo = null; // See: Issue 4776: [Firebug lite] CSS Media Types // // Ignore all special selectors like @media and @page if (!selector || selector.indexOf("@") != -1) continue; if (isIE) selector = selector.replace(reSelectorTag, function(s){return s.toLowerCase();}); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // CSS Parser if (shouldParseCSS) { var parsedRule = parsedRules[parsedRulesIndex]; var parsedSelector = parsedRule.selector; if (dontSupportGroupedRules && parsedSelector.indexOf(",") != -1 && group.length == 0) group = parsedSelector.split(","); if (dontSupportGroupedRules && group.length > 0) { groupItem = group.shift(); if (CssParser.normalizeSelector(selector) == groupItem) lineNo = parsedRule.line; if (group.length == 0) parsedRulesIndex++; } else if (CssParser.normalizeSelector(selector) == parsedRule.selector) { lineNo = parsedRule.line; parsedRulesIndex++; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * CSSRuleMap[rid] = { styleSheetId: ssid, styleSheetIndex: i, order: ++globalCSSRuleIndex, specificity: // See: Issue 4777: [Firebug lite] Specificity of CSS Rules // // if it is a normal selector then calculate the specificity selector && selector.indexOf(",") == -1 ? getCSSRuleSpecificity(selector) : // See: Issue 3262: [Firebug lite] Specificity of grouped CSS Rules // // if it is a grouped selector, do not calculate the specificity // because the correct value will depend of the matched element. // The proper specificity value for grouped selectors are calculated // via getElementCSSRules(element) 0, rule: rule, lineNo: lineNo, selector: selector, cssText: rule.style ? rule.style.cssText : rule.cssText ? rule.cssText : "" }; // TODO: what happens with elements added after this? Need to create a test case. // Maybe we should place this at getElementCSSRules() but it will make the function // a lot more expensive. // // Maybe add a "refresh" button? var elements = Firebug.Selector(selector, doc); for (var j=0, elementsLength=elements.length; j<elementsLength; j++) { var element = elements[j]; var eid = ElementCache(element); if (!ElementCSSRulesMap[eid]) ElementCSSRulesMap[eid] = []; ElementCSSRulesMap[eid].push(rid); } //console.log(selector, elements); } }; // ************************************************************************************************ // External StyleSheet Loader var loadExternalStylesheet = function(doc, styleSheetIterator, styleSheet) { var url = styleSheet.href; styleSheet.firebugIgnore = true; var source = Firebug.Lite.Proxy.load(url); // TODO: check for null and error responses // remove comments //var reMultiComment = /(\/\*([^\*]|\*(?!\/))*\*\/)/g; //source = source.replace(reMultiComment, ""); // convert relative addresses to absolute ones source = source.replace(/url\(([^\)]+)\)/g, function(a,name){ var hasDomain = /\w+:\/\/./.test(name); if (!hasDomain) { name = name.replace(/^(["'])(.+)\1$/, "$2"); var first = name.charAt(0); // relative path, based on root if (first == "/") { // TODO: xxxpedro move to lib or Firebug.Lite.something // getURLRoot var m = /^([^:]+:\/{1,3}[^\/]+)/.exec(url); return m ? "url(" + m[1] + name + ")" : "url(" + name + ")"; } // relative path, based on current location else { // TODO: xxxpedro move to lib or Firebug.Lite.something // getURLPath var path = url.replace(/[^\/]+\.[\w\d]+(\?.+|#.+)?$/g, ""); path = path + name; var reBack = /[^\/]+\/\.\.\//; while(reBack.test(path)) { path = path.replace(reBack, ""); } //console.log("url(" + path + ")"); return "url(" + path + ")"; } } // if it is an absolute path, there is nothing to do return a; }); var oldStyle = styleSheet.ownerNode; if (!oldStyle) return; if (!oldStyle.parentNode) return; var style = createGlobalElement("style"); style.setAttribute("charset","utf-8"); style.setAttribute("type", "text/css"); style.innerHTML = source; //debugger; oldStyle.parentNode.insertBefore(style, oldStyle.nextSibling); oldStyle.parentNode.removeChild(oldStyle); doc.styleSheets[doc.styleSheets.length-1].externalURL = url; console.log(url, "call " + externalStyleSheetURLs.length, source); externalStyleSheetURLs.pop(); if (processAllStyleSheetsTimeout) { clearTimeout(processAllStyleSheetsTimeout); } processAllStyleSheetsTimeout = setTimeout(function(){ console.log("processing"); FBL.processAllStyleSheets(doc, styleSheetIterator); processAllStyleSheetsTimeout = null; },200); }; //************************************************************************************************ // getElementCSSRules var getElementCSSRules = function(element) { var eid = ElementCache(element); var rules = ElementCSSRulesMap[eid]; if (!rules) return; var arr = [element]; var Selector = Firebug.Selector; var ruleId, rule; // for the case of grouped selectors, we need to calculate the highest // specificity within the selectors of the group that matches the element, // so we can sort the rules properly without over estimating the specificity // of grouped selectors for (var i = 0, length = rules.length; i < length; i++) { ruleId = rules[i]; rule = CSSRuleMap[ruleId]; // check if it is a grouped selector if (rule.selector.indexOf(",") != -1) { var selectors = rule.selector.split(","); var maxSpecificity = -1; var sel, spec, mostSpecificSelector; // loop over all selectors in the group for (var j, len = selectors.length; j < len; j++) { sel = selectors[j]; // find if the selector matches the element if (Selector.matches(sel, arr).length == 1) { spec = getCSSRuleSpecificity(sel); // find the most specific selector that macthes the element if (spec > maxSpecificity) { maxSpecificity = spec; mostSpecificSelector = sel; } } } rule.specificity = maxSpecificity; } } rules.sort(sortElementRules); //rules.sort(solveRulesTied); return rules; }; // ************************************************************************************************ // Rule Specificity var sortElementRules = function(a, b) { var ruleA = CSSRuleMap[a]; var ruleB = CSSRuleMap[b]; var specificityA = ruleA.specificity; var specificityB = ruleB.specificity; if (specificityA > specificityB) return 1; else if (specificityA < specificityB) return -1; else return ruleA.order > ruleB.order ? 1 : -1; }; var solveRulesTied = function(a, b) { var ruleA = CSSRuleMap[a]; var ruleB = CSSRuleMap[b]; if (ruleA.specificity == ruleB.specificity) return ruleA.order > ruleB.order ? 1 : -1; return null; }; var getCSSRuleSpecificity = function(selector) { var match = selector.match(reSelectorTag); var tagCount = match ? match.length : 0; match = selector.match(reSelectorClass); var classCount = match ? match.length : 0; match = selector.match(reSelectorId); var idCount = match ? match.length : 0; return tagCount + 10*classCount + 100*idCount; }; // ************************************************************************************************ // StyleSheet data var extractSourceData = function(href) { var sourceData = { source: null, startLine: 0 }; if (href) { sourceData.source = Firebug.Lite.Proxy.load(href); } else { // TODO: create extractInternalSourceData(index) // TODO: pre process the position of the inline styles so this will happen only once // in case of having multiple inline styles var index = 0; var ssIndex = ++internalStyleSheetIndex; var reStyleTag = /\<\s*style.*\>/gi; var reEndStyleTag = /\<\/\s*style.*\>/gi; var source = Firebug.Lite.Proxy.load(Env.browser.location.href); source = source.replace(/\n\r|\r\n/g, "\n"); // normalize line breaks var startLine = 0; do { var matchStyleTag = source.match(reStyleTag); var i0 = source.indexOf(matchStyleTag[0]) + matchStyleTag[0].length; for (var i=0; i < i0; i++) { if (source.charAt(i) == "\n") startLine++; } source = source.substr(i0); index++; } while (index <= ssIndex); var matchEndStyleTag = source.match(reEndStyleTag); var i1 = source.indexOf(matchEndStyleTag[0]); var extractedSource = source.substr(0, i1); sourceData.source = extractedSource; sourceData.startLine = startLine; } return sourceData; }; // ************************************************************************************************ // Registration FBL.CssAnalyzer = CssAnalyzer; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ // move to FBL (function() { // ************************************************************************************************ // XPath /** * Gets an XPath for an element which describes its hierarchical location. */ this.getElementXPath = function(element) { try { if (element && element.id) return '//*[@id="' + element.id + '"]'; else return this.getElementTreeXPath(element); } catch(E) { // xxxpedro: trying to detect the mysterious error: // Security error" code: "1000 //debugger; } }; this.getElementTreeXPath = function(element) { var paths = []; for (; element && element.nodeType == 1; element = element.parentNode) { var index = 0; var nodeName = element.nodeName; for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) { if (sibling.nodeType != 1) continue; if (sibling.nodeName == nodeName) ++index; } var tagName = element.nodeName.toLowerCase(); var pathIndex = (index ? "[" + (index+1) + "]" : ""); paths.splice(0, 0, tagName + pathIndex); } return paths.length ? "/" + paths.join("/") : null; }; this.getElementsByXPath = function(doc, xpath) { var nodes = []; try { var result = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null); for (var item = result.iterateNext(); item; item = result.iterateNext()) nodes.push(item); } catch (exc) { // Invalid xpath expressions make their way here sometimes. If that happens, // we still want to return an empty set without an exception. } return nodes; }; this.getRuleMatchingElements = function(rule, doc) { var css = rule.selectorText; var xpath = this.cssToXPath(css); return this.getElementsByXPath(doc, xpath); }; }).call(FBL); FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ var toCamelCase = function toCamelCase(s) { return s.replace(reSelectorCase, toCamelCaseReplaceFn); }; var toSelectorCase = function toSelectorCase(s) { return s.replace(reCamelCase, "-$1").toLowerCase(); }; var reCamelCase = /([A-Z])/g; var reSelectorCase = /\-(.)/g; var toCamelCaseReplaceFn = function toCamelCaseReplaceFn(m,g) { return g.toUpperCase(); }; // ************************************************************************************************ var ElementCache = Firebug.Lite.Cache.Element; var StyleSheetCache = Firebug.Lite.Cache.StyleSheet; // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // ************************************************************************************************ // Constants //const Cc = Components.classes; //const Ci = Components.interfaces; //const nsIDOMCSSStyleRule = Ci.nsIDOMCSSStyleRule; //const nsIInterfaceRequestor = Ci.nsIInterfaceRequestor; //const nsISelectionDisplay = Ci.nsISelectionDisplay; //const nsISelectionController = Ci.nsISelectionController; // See: http://mxr.mozilla.org/mozilla1.9.2/source/content/events/public/nsIEventStateManager.h#153 //const STATE_ACTIVE = 0x01; //const STATE_FOCUS = 0x02; //const STATE_HOVER = 0x04; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Firebug.SourceBoxPanel = Firebug.Panel; var reSelectorTag = /(^|\s)(?:\w+)/g; var domUtils = null; var textContent = isIE ? "innerText" : "textContent"; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var CSSDomplateBase = { isEditable: function(rule) { return !rule.isSystemSheet; }, isSelectorEditable: function(rule) { return rule.isSelectorEditable && this.isEditable(rule); } }; var CSSPropTag = domplate(CSSDomplateBase, { tag: DIV({"class": "cssProp focusRow", $disabledStyle: "$prop.disabled", $editGroup: "$rule|isEditable", $cssOverridden: "$prop.overridden", role : "option"}, A({"class": "cssPropDisable"}, "&nbsp;&nbsp;"), SPAN({"class": "cssPropName", $editable: "$rule|isEditable"}, "$prop.name"), SPAN({"class": "cssColon"}, ":"), SPAN({"class": "cssPropValue", $editable: "$rule|isEditable"}, "$prop.value$prop.important"), SPAN({"class": "cssSemi"}, ";") ) }); var CSSRuleTag = TAG("$rule.tag", {rule: "$rule"}); var CSSImportRuleTag = domplate({ tag: DIV({"class": "cssRule insertInto focusRow importRule", _repObject: "$rule.rule"}, "@import &quot;", A({"class": "objectLink", _repObject: "$rule.rule.styleSheet"}, "$rule.rule.href"), "&quot;;" ) }); var CSSStyleRuleTag = domplate(CSSDomplateBase, { tag: DIV({"class": "cssRule insertInto", $cssEditableRule: "$rule|isEditable", $editGroup: "$rule|isSelectorEditable", _repObject: "$rule.rule", "ruleId": "$rule.id", role : 'presentation'}, DIV({"class": "cssHead focusRow", role : 'listitem'}, SPAN({"class": "cssSelector", $editable: "$rule|isSelectorEditable"}, "$rule.selector"), " {" ), DIV({role : 'group'}, DIV({"class": "cssPropertyListBox", role : 'listbox'}, FOR("prop", "$rule.props", TAG(CSSPropTag.tag, {rule: "$rule", prop: "$prop"}) ) ) ), DIV({"class": "editable insertBefore", role:"presentation"}, "}") ) }); var reSplitCSS = /(url\("?[^"\)]+?"?\))|(rgb\(.*?\))|(#[\dA-Fa-f]+)|(-?\d+(\.\d+)?(%|[a-z]{1,2})?)|([^,\s]+)|"(.*?)"/; var reURL = /url\("?([^"\)]+)?"?\)/; var reRepeat = /no-repeat|repeat-x|repeat-y|repeat/; //const sothinkInstalled = !!$("swfcatcherKey_sidebar"); var sothinkInstalled = false; var styleGroups = { text: [ "font-family", "font-size", "font-weight", "font-style", "color", "text-transform", "text-decoration", "letter-spacing", "word-spacing", "line-height", "text-align", "vertical-align", "direction", "column-count", "column-gap", "column-width" ], background: [ "background-color", "background-image", "background-repeat", "background-position", "background-attachment", "opacity" ], box: [ "width", "height", "top", "right", "bottom", "left", "margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-style", "border-right-style", "border-bottom-style", "border-left-style", "-moz-border-top-radius", "-moz-border-right-radius", "-moz-border-bottom-radius", "-moz-border-left-radius", "outline-top-width", "outline-right-width", "outline-bottom-width", "outline-left-width", "outline-top-color", "outline-right-color", "outline-bottom-color", "outline-left-color", "outline-top-style", "outline-right-style", "outline-bottom-style", "outline-left-style" ], layout: [ "position", "display", "visibility", "z-index", "overflow-x", // http://www.w3.org/TR/2002/WD-css3-box-20021024/#overflow "overflow-y", "overflow-clip", "white-space", "clip", "float", "clear", "-moz-box-sizing" ], other: [ "cursor", "list-style-image", "list-style-position", "list-style-type", "marker-offset", "user-focus", "user-select", "user-modify", "user-input" ] }; var styleGroupTitles = { text: "Text", background: "Background", box: "Box Model", layout: "Layout", other: "Other" }; Firebug.CSSModule = extend(Firebug.Module, { freeEdit: function(styleSheet, value) { if (!styleSheet.editStyleSheet) { var ownerNode = getStyleSheetOwnerNode(styleSheet); styleSheet.disabled = true; var url = CCSV("@mozilla.org/network/standard-url;1", Components.interfaces.nsIURL); url.spec = styleSheet.href; var editStyleSheet = ownerNode.ownerDocument.createElementNS( "http://www.w3.org/1999/xhtml", "style"); unwrapObject(editStyleSheet).firebugIgnore = true; editStyleSheet.setAttribute("type", "text/css"); editStyleSheet.setAttributeNS( "http://www.w3.org/XML/1998/namespace", "base", url.directory); if (ownerNode.hasAttribute("media")) { editStyleSheet.setAttribute("media", ownerNode.getAttribute("media")); } // Insert the edited stylesheet directly after the old one to ensure the styles // cascade properly. ownerNode.parentNode.insertBefore(editStyleSheet, ownerNode.nextSibling); styleSheet.editStyleSheet = editStyleSheet; } styleSheet.editStyleSheet.innerHTML = value; if (FBTrace.DBG_CSS) FBTrace.sysout("css.saveEdit styleSheet.href:"+styleSheet.href+" got innerHTML:"+value+"\n"); dispatch(this.fbListeners, "onCSSFreeEdit", [styleSheet, value]); }, insertRule: function(styleSheet, cssText, ruleIndex) { if (FBTrace.DBG_CSS) FBTrace.sysout("Insert: " + ruleIndex + " " + cssText); var insertIndex = styleSheet.insertRule(cssText, ruleIndex); dispatch(this.fbListeners, "onCSSInsertRule", [styleSheet, cssText, ruleIndex]); return insertIndex; }, deleteRule: function(styleSheet, ruleIndex) { if (FBTrace.DBG_CSS) FBTrace.sysout("deleteRule: " + ruleIndex + " " + styleSheet.cssRules.length, styleSheet.cssRules); dispatch(this.fbListeners, "onCSSDeleteRule", [styleSheet, ruleIndex]); styleSheet.deleteRule(ruleIndex); }, setProperty: function(rule, propName, propValue, propPriority) { var style = rule.style || rule; // Record the original CSS text for the inline case so we can reconstruct at a later // point for diffing purposes var baseText = style.cssText; // good browsers if (style.getPropertyValue) { var prevValue = style.getPropertyValue(propName); var prevPriority = style.getPropertyPriority(propName); // XXXjoe Gecko bug workaround: Just changing priority doesn't have any effect // unless we remove the property first style.removeProperty(propName); style.setProperty(propName, propValue, propPriority); } // sad browsers else { // TODO: xxxpedro parse CSS rule to find property priority in IE? //console.log(propName, propValue); style[toCamelCase(propName)] = propValue; } if (propName) { dispatch(this.fbListeners, "onCSSSetProperty", [style, propName, propValue, propPriority, prevValue, prevPriority, rule, baseText]); } }, removeProperty: function(rule, propName, parent) { var style = rule.style || rule; // Record the original CSS text for the inline case so we can reconstruct at a later // point for diffing purposes var baseText = style.cssText; if (style.getPropertyValue) { var prevValue = style.getPropertyValue(propName); var prevPriority = style.getPropertyPriority(propName); style.removeProperty(propName); } else { style[toCamelCase(propName)] = ""; } if (propName) { dispatch(this.fbListeners, "onCSSRemoveProperty", [style, propName, prevValue, prevPriority, rule, baseText]); } }/*, cleanupSheets: function(doc, context) { // Due to the manner in which the layout engine handles multiple // references to the same sheet we need to kick it a little bit. // The injecting a simple stylesheet then removing it will force // Firefox to regenerate it's CSS hierarchy. // // WARN: This behavior was determined anecdotally. // See http://code.google.com/p/fbug/issues/detail?id=2440 var style = doc.createElementNS("http://www.w3.org/1999/xhtml", "style"); style.setAttribute("charset","utf-8"); unwrapObject(style).firebugIgnore = true; style.setAttribute("type", "text/css"); style.innerHTML = "#fbIgnoreStyleDO_NOT_USE {}"; addStyleSheet(doc, style); style.parentNode.removeChild(style); // https://bugzilla.mozilla.org/show_bug.cgi?id=500365 // This voodoo touches each style sheet to force some Firefox internal change to allow edits. var styleSheets = getAllStyleSheets(context); for(var i = 0; i < styleSheets.length; i++) { try { var rules = styleSheets[i].cssRules; if (rules.length > 0) var touch = rules[0]; if (FBTrace.DBG_CSS && touch) FBTrace.sysout("css.show() touch "+typeof(touch)+" in "+(styleSheets[i].href?styleSheets[i].href:context.getName())); } catch(e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("css.show: sheet.cssRules FAILS for "+(styleSheets[i]?styleSheets[i].href:"null sheet")+e, e); } } }, cleanupSheetHandler: function(event, context) { var target = event.target || event.srcElement, tagName = (target.tagName || "").toLowerCase(); if (tagName == "link") { this.cleanupSheets(target.ownerDocument, context); } }, watchWindow: function(context, win) { var cleanupSheets = bind(this.cleanupSheets, this), cleanupSheetHandler = bind(this.cleanupSheetHandler, this, context), doc = win.document; //doc.addEventListener("DOMAttrModified", cleanupSheetHandler, false); //doc.addEventListener("DOMNodeInserted", cleanupSheetHandler, false); }, loadedContext: function(context) { var self = this; iterateWindows(context.browser.contentWindow, function(subwin) { self.cleanupSheets(subwin.document, context); }); } /**/ }); // ************************************************************************************************ Firebug.CSSStyleSheetPanel = function() {}; Firebug.CSSStyleSheetPanel.prototype = extend(Firebug.SourceBoxPanel, { template: domplate( { tag: DIV({"class": "cssSheet insertInto a11yCSSView"}, FOR("rule", "$rules", CSSRuleTag ), DIV({"class": "cssSheet editable insertBefore"}, "") ) }), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * refresh: function() { if (this.location) this.updateLocation(this.location); else if (this.selection) this.updateSelection(this.selection); }, toggleEditing: function() { if (!this.stylesheetEditor) this.stylesheetEditor = new StyleSheetEditor(this.document); if (this.editing) Firebug.Editor.stopEditing(); else { if (!this.location) return; var styleSheet = this.location.editStyleSheet ? this.location.editStyleSheet.sheet : this.location; var css = getStyleSheetCSS(styleSheet, this.context); //var topmost = getTopmostRuleLine(this.panelNode); this.stylesheetEditor.styleSheet = this.location; Firebug.Editor.startEditing(this.panelNode, css, this.stylesheetEditor); //this.stylesheetEditor.scrollToLine(topmost.line, topmost.offset); } }, getStylesheetURL: function(rule) { if (this.location.href) return this.location.href; else return this.context.window.location.href; }, getRuleByLine: function(styleSheet, line) { if (!domUtils) return null; var cssRules = styleSheet.cssRules; for (var i = 0; i < cssRules.length; ++i) { var rule = cssRules[i]; if (rule instanceof CSSStyleRule) { var ruleLine = domUtils.getRuleLine(rule); if (ruleLine >= line) return rule; } } }, highlightRule: function(rule) { var ruleElement = Firebug.getElementByRepObject(this.panelNode.firstChild, rule); if (ruleElement) { scrollIntoCenterView(ruleElement, this.panelNode); setClassTimed(ruleElement, "jumpHighlight", this.context); } }, getStyleSheetRules: function(context, styleSheet) { var isSystemSheet = isSystemStyleSheet(styleSheet); function appendRules(cssRules) { for (var i = 0; i < cssRules.length; ++i) { var rule = cssRules[i]; // TODO: xxxpedro opera instanceof stylesheet remove the following comments when // the issue with opera and style sheet Classes has been solved. //if (rule instanceof CSSStyleRule) if (instanceOf(rule, "CSSStyleRule")) { var props = this.getRuleProperties(context, rule); //var line = domUtils.getRuleLine(rule); var line = null; var selector = rule.selectorText; if (isIE) { selector = selector.replace(reSelectorTag, function(s){return s.toLowerCase();}); } var ruleId = rule.selectorText+"/"+line; rules.push({tag: CSSStyleRuleTag.tag, rule: rule, id: ruleId, selector: selector, props: props, isSystemSheet: isSystemSheet, isSelectorEditable: true}); } //else if (rule instanceof CSSImportRule) else if (instanceOf(rule, "CSSImportRule")) rules.push({tag: CSSImportRuleTag.tag, rule: rule}); //else if (rule instanceof CSSMediaRule) else if (instanceOf(rule, "CSSMediaRule")) appendRules.apply(this, [rule.cssRules]); else { if (FBTrace.DBG_ERRORS || FBTrace.DBG_CSS) FBTrace.sysout("css getStyleSheetRules failed to classify a rule ", rule); } } } var rules = []; appendRules.apply(this, [styleSheet.cssRules || styleSheet.rules]); return rules; }, parseCSSProps: function(style, inheritMode) { var props = []; if (Firebug.expandShorthandProps) { var count = style.length-1, index = style.length; while (index--) { var propName = style.item(count - index); this.addProperty(propName, style.getPropertyValue(propName), !!style.getPropertyPriority(propName), false, inheritMode, props); } } else { var lines = style.cssText.match(/(?:[^;\(]*(?:\([^\)]*?\))?[^;\(]*)*;?/g); var propRE = /\s*([^:\s]*)\s*:\s*(.*?)\s*(! important)?;?$/; var line,i=0; // TODO: xxxpedro port to firebug: variable leaked into global namespace var m; while(line=lines[i++]){ m = propRE.exec(line); if(!m) continue; //var name = m[1], value = m[2], important = !!m[3]; if (m[2]) this.addProperty(m[1], m[2], !!m[3], false, inheritMode, props); }; } return props; }, getRuleProperties: function(context, rule, inheritMode) { var props = this.parseCSSProps(rule.style, inheritMode); // TODO: xxxpedro port to firebug: variable leaked into global namespace //var line = domUtils.getRuleLine(rule); var line; var ruleId = rule.selectorText+"/"+line; this.addOldProperties(context, ruleId, inheritMode, props); sortProperties(props); return props; }, addOldProperties: function(context, ruleId, inheritMode, props) { if (context.selectorMap && context.selectorMap.hasOwnProperty(ruleId) ) { var moreProps = context.selectorMap[ruleId]; for (var i = 0; i < moreProps.length; ++i) { var prop = moreProps[i]; this.addProperty(prop.name, prop.value, prop.important, true, inheritMode, props); } } }, addProperty: function(name, value, important, disabled, inheritMode, props) { name = name.toLowerCase(); if (inheritMode && !inheritedStyleNames[name]) return; name = this.translateName(name, value); if (name) { value = stripUnits(rgbToHex(value)); important = important ? " !important" : ""; var prop = {name: name, value: value, important: important, disabled: disabled}; props.push(prop); } }, translateName: function(name, value) { // Don't show these proprietary Mozilla properties if ((value == "-moz-initial" && (name == "-moz-background-clip" || name == "-moz-background-origin" || name == "-moz-background-inline-policy")) || (value == "physical" && (name == "margin-left-ltr-source" || name == "margin-left-rtl-source" || name == "margin-right-ltr-source" || name == "margin-right-rtl-source")) || (value == "physical" && (name == "padding-left-ltr-source" || name == "padding-left-rtl-source" || name == "padding-right-ltr-source" || name == "padding-right-rtl-source"))) return null; // Translate these back to the form the user probably expects if (name == "margin-left-value") return "margin-left"; else if (name == "margin-right-value") return "margin-right"; else if (name == "margin-top-value") return "margin-top"; else if (name == "margin-bottom-value") return "margin-bottom"; else if (name == "padding-left-value") return "padding-left"; else if (name == "padding-right-value") return "padding-right"; else if (name == "padding-top-value") return "padding-top"; else if (name == "padding-bottom-value") return "padding-bottom"; // XXXjoe What about border! else return name; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * editElementStyle: function() { ///var rulesBox = this.panelNode.getElementsByClassName("cssElementRuleContainer")[0]; var rulesBox = $$(".cssElementRuleContainer", this.panelNode)[0]; var styleRuleBox = rulesBox && Firebug.getElementByRepObject(rulesBox, this.selection); if (!styleRuleBox) { var rule = {rule: this.selection, inherited: false, selector: "element.style", props: []}; if (!rulesBox) { // The element did not have any displayed styles. We need to create the whole tree and remove // the no styles message styleRuleBox = this.template.cascadedTag.replace({ rules: [rule], inherited: [], inheritLabel: "Inherited from" // $STR("InheritedFrom") }, this.panelNode); ///styleRuleBox = styleRuleBox.getElementsByClassName("cssElementRuleContainer")[0]; styleRuleBox = $$(".cssElementRuleContainer", styleRuleBox)[0]; } else styleRuleBox = this.template.ruleTag.insertBefore({rule: rule}, rulesBox); ///styleRuleBox = styleRuleBox.getElementsByClassName("insertInto")[0]; styleRuleBox = $$(".insertInto", styleRuleBox)[0]; } Firebug.Editor.insertRowForObject(styleRuleBox); }, insertPropertyRow: function(row) { Firebug.Editor.insertRowForObject(row); }, insertRule: function(row) { var location = getAncestorByClass(row, "cssRule"); if (!location) { location = getChildByClass(this.panelNode, "cssSheet"); Firebug.Editor.insertRowForObject(location); } else { Firebug.Editor.insertRow(location, "before"); } }, editPropertyRow: function(row) { var propValueBox = getChildByClass(row, "cssPropValue"); Firebug.Editor.startEditing(propValueBox); }, deletePropertyRow: function(row) { var rule = Firebug.getRepObject(row); var propName = getChildByClass(row, "cssPropName")[textContent]; Firebug.CSSModule.removeProperty(rule, propName); // Remove the property from the selector map, if it was disabled var ruleId = Firebug.getRepNode(row).getAttribute("ruleId"); if ( this.context.selectorMap && this.context.selectorMap.hasOwnProperty(ruleId) ) { var map = this.context.selectorMap[ruleId]; for (var i = 0; i < map.length; ++i) { if (map[i].name == propName) { map.splice(i, 1); break; } } } if (this.name == "stylesheet") dispatch([Firebug.A11yModel], 'onInlineEditorClose', [this, row.firstChild, true]); row.parentNode.removeChild(row); this.markChange(this.name == "stylesheet"); }, disablePropertyRow: function(row) { toggleClass(row, "disabledStyle"); var rule = Firebug.getRepObject(row); var propName = getChildByClass(row, "cssPropName")[textContent]; if (!this.context.selectorMap) this.context.selectorMap = {}; // XXXjoe Generate unique key for elements too var ruleId = Firebug.getRepNode(row).getAttribute("ruleId"); if (!(this.context.selectorMap.hasOwnProperty(ruleId))) this.context.selectorMap[ruleId] = []; var map = this.context.selectorMap[ruleId]; var propValue = getChildByClass(row, "cssPropValue")[textContent]; var parsedValue = parsePriority(propValue); if (hasClass(row, "disabledStyle")) { Firebug.CSSModule.removeProperty(rule, propName); map.push({"name": propName, "value": parsedValue.value, "important": parsedValue.priority}); } else { Firebug.CSSModule.setProperty(rule, propName, parsedValue.value, parsedValue.priority); var index = findPropByName(map, propName); map.splice(index, 1); } this.markChange(this.name == "stylesheet"); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onMouseDown: function(event) { //console.log("onMouseDown", event.target || event.srcElement, event); // xxxpedro adjusting coordinates because the panel isn't a window yet var offset = event.clientX - this.panelNode.parentNode.offsetLeft; // XXjoe Hack to only allow clicking on the checkbox if (!isLeftClick(event) || offset > 20) return; var target = event.target || event.srcElement; if (hasClass(target, "textEditor")) return; var row = getAncestorByClass(target, "cssProp"); if (row && hasClass(row, "editGroup")) { this.disablePropertyRow(row); cancelEvent(event); } }, onDoubleClick: function(event) { //console.log("onDoubleClick", event.target || event.srcElement, event); // xxxpedro adjusting coordinates because the panel isn't a window yet var offset = event.clientX - this.panelNode.parentNode.offsetLeft; if (!isLeftClick(event) || offset <= 20) return; var target = event.target || event.srcElement; //console.log("ok", target, hasClass(target, "textEditorInner"), !isLeftClick(event), offset <= 20); // if the inline editor was clicked, don't insert a new rule if (hasClass(target, "textEditorInner")) return; var row = getAncestorByClass(target, "cssRule"); if (row && !getAncestorByClass(target, "cssPropName") && !getAncestorByClass(target, "cssPropValue")) { this.insertPropertyRow(row); cancelEvent(event); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "stylesheet", title: "CSS", parentPanel: null, searchable: true, dependents: ["css", "stylesheet", "dom", "domSide", "layout"], options: { hasToolButtons: true }, create: function() { Firebug.Panel.create.apply(this, arguments); this.onMouseDown = bind(this.onMouseDown, this); this.onDoubleClick = bind(this.onDoubleClick, this); if (this.name == "stylesheet") { this.onChangeSelect = bind(this.onChangeSelect, this); var doc = Firebug.browser.document; var selectNode = this.selectNode = createElement("select"); CssAnalyzer.processAllStyleSheets(doc, function(doc, styleSheet) { var key = StyleSheetCache.key(styleSheet); var fileName = getFileName(styleSheet.href) || getFileName(doc.location.href); var option = createElement("option", {value: key}); option.appendChild(Firebug.chrome.document.createTextNode(fileName)); selectNode.appendChild(option); }); this.toolButtonsNode.appendChild(selectNode); } /**/ }, onChangeSelect: function(event) { event = event || window.event; var target = event.srcElement || event.currentTarget; var key = target.value; var styleSheet = StyleSheetCache.get(key); this.updateLocation(styleSheet); }, initialize: function() { Firebug.Panel.initialize.apply(this, arguments); //if (!domUtils) //{ // try { // domUtils = CCSV("@mozilla.org/inspector/dom-utils;1", "inIDOMUtils"); // } catch (exc) { // if (FBTrace.DBG_ERRORS) // FBTrace.sysout("@mozilla.org/inspector/dom-utils;1 FAILED to load: "+exc, exc); // } //} //TODO: xxxpedro this.context = Firebug.chrome; // TODO: xxxpedro css2 this.document = Firebug.chrome.document; // TODO: xxxpedro css2 this.initializeNode(); if (this.name == "stylesheet") { var styleSheets = Firebug.browser.document.styleSheets; if (styleSheets.length > 0) { addEvent(this.selectNode, "change", this.onChangeSelect); this.updateLocation(styleSheets[0]); } } //Firebug.SourceBoxPanel.initialize.apply(this, arguments); }, shutdown: function() { // must destroy the editor when we leave the panel to avoid problems (Issue 2981) Firebug.Editor.stopEditing(); if (this.name == "stylesheet") { removeEvent(this.selectNode, "change", this.onChangeSelect); } this.destroyNode(); Firebug.Panel.shutdown.apply(this, arguments); }, destroy: function(state) { //state.scrollTop = this.panelNode.scrollTop ? this.panelNode.scrollTop : this.lastScrollTop; //persistObjects(this, state); // xxxpedro we are stopping the editor in the shutdown method already //Firebug.Editor.stopEditing(); Firebug.Panel.destroy.apply(this, arguments); }, initializeNode: function(oldPanelNode) { addEvent(this.panelNode, "mousedown", this.onMouseDown); addEvent(this.panelNode, "dblclick", this.onDoubleClick); //Firebug.SourceBoxPanel.initializeNode.apply(this, arguments); //dispatch([Firebug.A11yModel], 'onInitializeNode', [this, 'css']); }, destroyNode: function() { removeEvent(this.panelNode, "mousedown", this.onMouseDown); removeEvent(this.panelNode, "dblclick", this.onDoubleClick); //Firebug.SourceBoxPanel.destroyNode.apply(this, arguments); //dispatch([Firebug.A11yModel], 'onDestroyNode', [this, 'css']); }, ishow: function(state) { Firebug.Inspector.stopInspecting(true); this.showToolbarButtons("fbCSSButtons", true); if (this.context.loaded && !this.location) // wait for loadedContext to restore the panel { restoreObjects(this, state); if (!this.location) this.location = this.getDefaultLocation(); if (state && state.scrollTop) this.panelNode.scrollTop = state.scrollTop; } }, ihide: function() { this.showToolbarButtons("fbCSSButtons", false); this.lastScrollTop = this.panelNode.scrollTop; }, supportsObject: function(object) { if (object instanceof CSSStyleSheet) return 1; else if (object instanceof CSSStyleRule) return 2; else if (object instanceof CSSStyleDeclaration) return 2; else if (object instanceof SourceLink && object.type == "css" && reCSS.test(object.href)) return 2; else return 0; }, updateLocation: function(styleSheet) { if (!styleSheet) return; if (styleSheet.editStyleSheet) styleSheet = styleSheet.editStyleSheet.sheet; // if it is a restricted stylesheet, show the warning message and abort the update process if (styleSheet.restricted) { FirebugReps.Warning.tag.replace({object: "AccessRestricted"}, this.panelNode); // TODO: xxxpedro remove when there the external resource problem is fixed CssAnalyzer.externalStyleSheetWarning.tag.append({ object: "The stylesheet could not be loaded due to access restrictions. ", link: "more...", href: "http://getfirebug.com/wiki/index.php/Firebug_Lite_FAQ#I_keep_seeing_.22Access_to_restricted_URI_denied.22" }, this.panelNode); return; } var rules = this.getStyleSheetRules(this.context, styleSheet); var result; if (rules.length) // FIXME xxxpedro chromenew this is making iPad's Safari to crash result = this.template.tag.replace({rules: rules}, this.panelNode); else result = FirebugReps.Warning.tag.replace({object: "EmptyStyleSheet"}, this.panelNode); // TODO: xxxpedro need to fix showToolbarButtons function //this.showToolbarButtons("fbCSSButtons", !isSystemStyleSheet(this.location)); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, this.panelNode]); }, updateSelection: function(object) { this.selection = null; if (object instanceof CSSStyleDeclaration) { object = object.parentRule; } if (object instanceof CSSStyleRule) { this.navigate(object.parentStyleSheet); this.highlightRule(object); } else if (object instanceof CSSStyleSheet) { this.navigate(object); } else if (object instanceof SourceLink) { try { var sourceLink = object; var sourceFile = getSourceFileByHref(sourceLink.href, this.context); if (sourceFile) { clearNode(this.panelNode); // replace rendered stylesheets this.showSourceFile(sourceFile); var lineNo = object.line; if (lineNo) this.scrollToLine(lineNo, this.jumpHighlightFactory(lineNo, this.context)); } else // XXXjjb we should not be taking this path { var stylesheet = getStyleSheetByHref(sourceLink.href, this.context); if (stylesheet) this.navigate(stylesheet); else { if (FBTrace.DBG_CSS) FBTrace.sysout("css.updateSelection no sourceFile for "+sourceLink.href, sourceLink); } } } catch(exc) { if (FBTrace.DBG_CSS) FBTrace.sysout("css.upDateSelection FAILS "+exc, exc); } } }, updateOption: function(name, value) { if (name == "expandShorthandProps") this.refresh(); }, getLocationList: function() { var styleSheets = getAllStyleSheets(this.context); return styleSheets; }, getOptionsMenuItems: function() { return [ {label: "Expand Shorthand Properties", type: "checkbox", checked: Firebug.expandShorthandProps, command: bindFixed(Firebug.togglePref, Firebug, "expandShorthandProps") }, "-", {label: "Refresh", command: bind(this.refresh, this) } ]; }, getContextMenuItems: function(style, target) { var items = []; if (this.infoTipType == "color") { items.push( {label: "CopyColor", command: bindFixed(copyToClipboard, FBL, this.infoTipObject) } ); } else if (this.infoTipType == "image") { items.push( {label: "CopyImageLocation", command: bindFixed(copyToClipboard, FBL, this.infoTipObject) }, {label: "OpenImageInNewTab", command: bindFixed(openNewTab, FBL, this.infoTipObject) } ); } ///if (this.selection instanceof Element) if (isElement(this.selection)) { items.push( //"-", {label: "EditStyle", command: bindFixed(this.editElementStyle, this) } ); } else if (!isSystemStyleSheet(this.selection)) { items.push( //"-", {label: "NewRule", command: bindFixed(this.insertRule, this, target) } ); } var cssRule = getAncestorByClass(target, "cssRule"); if (cssRule && hasClass(cssRule, "cssEditableRule")) { items.push( "-", {label: "NewProp", command: bindFixed(this.insertPropertyRow, this, target) } ); var propRow = getAncestorByClass(target, "cssProp"); if (propRow) { var propName = getChildByClass(propRow, "cssPropName")[textContent]; var isDisabled = hasClass(propRow, "disabledStyle"); items.push( {label: $STRF("EditProp", [propName]), nol10n: true, command: bindFixed(this.editPropertyRow, this, propRow) }, {label: $STRF("DeleteProp", [propName]), nol10n: true, command: bindFixed(this.deletePropertyRow, this, propRow) }, {label: $STRF("DisableProp", [propName]), nol10n: true, type: "checkbox", checked: isDisabled, command: bindFixed(this.disablePropertyRow, this, propRow) } ); } } items.push( "-", {label: "Refresh", command: bind(this.refresh, this) } ); return items; }, browseObject: function(object) { if (this.infoTipType == "image") { openNewTab(this.infoTipObject); return true; } }, showInfoTip: function(infoTip, target, x, y) { var propValue = getAncestorByClass(target, "cssPropValue"); if (propValue) { var offset = getClientOffset(propValue); var offsetX = x-offset.x; var text = propValue[textContent]; var charWidth = propValue.offsetWidth/text.length; var charOffset = Math.floor(offsetX/charWidth); var cssValue = parseCSSValue(text, charOffset); if (cssValue) { if (cssValue.value == this.infoTipValue) return true; this.infoTipValue = cssValue.value; if (cssValue.type == "rgb" || (!cssValue.type && isColorKeyword(cssValue.value))) { this.infoTipType = "color"; this.infoTipObject = cssValue.value; return Firebug.InfoTip.populateColorInfoTip(infoTip, cssValue.value); } else if (cssValue.type == "url") { ///var propNameNode = target.parentNode.getElementsByClassName("cssPropName").item(0); var propNameNode = getElementByClass(target.parentNode, "cssPropName"); if (propNameNode && isImageRule(propNameNode[textContent])) { var rule = Firebug.getRepObject(target); var baseURL = this.getStylesheetURL(rule); var relURL = parseURLValue(cssValue.value); var absURL = isDataURL(relURL) ? relURL:absoluteURL(relURL, baseURL); var repeat = parseRepeatValue(text); this.infoTipType = "image"; this.infoTipObject = absURL; return Firebug.InfoTip.populateImageInfoTip(infoTip, absURL, repeat); } } } } delete this.infoTipType; delete this.infoTipValue; delete this.infoTipObject; }, getEditor: function(target, value) { if (target == this.panelNode || hasClass(target, "cssSelector") || hasClass(target, "cssRule") || hasClass(target, "cssSheet")) { if (!this.ruleEditor) this.ruleEditor = new CSSRuleEditor(this.document); return this.ruleEditor; } else { if (!this.editor) this.editor = new CSSEditor(this.document); return this.editor; } }, getDefaultLocation: function() { try { var styleSheets = this.context.window.document.styleSheets; if (styleSheets.length) { var sheet = styleSheets[0]; return (Firebug.filterSystemURLs && isSystemURL(getURLForStyleSheet(sheet))) ? null : sheet; } } catch (exc) { if (FBTrace.DBG_LOCATIONS) FBTrace.sysout("css.getDefaultLocation FAILS "+exc, exc); } }, getObjectDescription: function(styleSheet) { var url = getURLForStyleSheet(styleSheet); var instance = getInstanceForStyleSheet(styleSheet); var baseDescription = splitURLBase(url); if (instance) { baseDescription.name = baseDescription.name + " #" + (instance + 1); } return baseDescription; }, search: function(text, reverse) { var curDoc = this.searchCurrentDoc(!Firebug.searchGlobal, text, reverse); if (!curDoc && Firebug.searchGlobal) { return this.searchOtherDocs(text, reverse); } return curDoc; }, searchOtherDocs: function(text, reverse) { var scanRE = Firebug.Search.getTestingRegex(text); function scanDoc(styleSheet) { // we don't care about reverse here as we are just looking for existence, // if we do have a result we will handle the reverse logic on display for (var i = 0; i < styleSheet.cssRules.length; i++) { if (scanRE.test(styleSheet.cssRules[i].cssText)) { return true; } } } if (this.navigateToNextDocument(scanDoc, reverse)) { return this.searchCurrentDoc(true, text, reverse); } }, searchCurrentDoc: function(wrapSearch, text, reverse) { if (!text) { delete this.currentSearch; return false; } var row; if (this.currentSearch && text == this.currentSearch.text) { row = this.currentSearch.findNext(wrapSearch, false, reverse, Firebug.Search.isCaseSensitive(text)); } else { if (this.editing) { this.currentSearch = new TextSearch(this.stylesheetEditor.box); row = this.currentSearch.find(text, reverse, Firebug.Search.isCaseSensitive(text)); if (row) { var sel = this.document.defaultView.getSelection(); sel.removeAllRanges(); sel.addRange(this.currentSearch.range); scrollSelectionIntoView(this); return true; } else return false; } else { function findRow(node) { return node.nodeType == 1 ? node : node.parentNode; } this.currentSearch = new TextSearch(this.panelNode, findRow); row = this.currentSearch.find(text, reverse, Firebug.Search.isCaseSensitive(text)); } } if (row) { this.document.defaultView.getSelection().selectAllChildren(row); scrollIntoCenterView(row, this.panelNode); dispatch([Firebug.A11yModel], 'onCSSSearchMatchFound', [this, text, row]); return true; } else { dispatch([Firebug.A11yModel], 'onCSSSearchMatchFound', [this, text, null]); return false; } }, getSearchOptionsMenuItems: function() { return [ Firebug.Search.searchOptionMenu("search.Case_Sensitive", "searchCaseSensitive"), Firebug.Search.searchOptionMenu("search.Multiple_Files", "searchGlobal") ]; } }); /**/ // ************************************************************************************************ function CSSElementPanel() {} CSSElementPanel.prototype = extend(Firebug.CSSStyleSheetPanel.prototype, { template: domplate( { cascadedTag: DIV({"class": "a11yCSSView", role : 'presentation'}, DIV({role : 'list', 'aria-label' : $STR('aria.labels.style rules') }, FOR("rule", "$rules", TAG("$ruleTag", {rule: "$rule"}) ) ), DIV({role : "list", 'aria-label' :$STR('aria.labels.inherited style rules')}, FOR("section", "$inherited", H1({"class": "cssInheritHeader groupHeader focusRow", role : 'listitem' }, SPAN({"class": "cssInheritLabel"}, "$inheritLabel"), TAG(FirebugReps.Element.shortTag, {object: "$section.element"}) ), DIV({role : 'group'}, FOR("rule", "$section.rules", TAG("$ruleTag", {rule: "$rule"}) ) ) ) ) ), ruleTag: isIE ? // IE needs the sourceLink first, otherwise it will be rendered outside the panel DIV({"class": "cssElementRuleContainer"}, TAG(FirebugReps.SourceLink.tag, {object: "$rule.sourceLink"}), TAG(CSSStyleRuleTag.tag, {rule: "$rule"}) ) : // other browsers need the sourceLink last, otherwise it will cause an extra space // before the rule representation DIV({"class": "cssElementRuleContainer"}, TAG(CSSStyleRuleTag.tag, {rule: "$rule"}), TAG(FirebugReps.SourceLink.tag, {object: "$rule.sourceLink"}) ) }), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateCascadeView: function(element) { //dispatch([Firebug.A11yModel], 'onBeforeCSSRulesAdded', [this]); var rules = [], sections = [], usedProps = {}; this.getInheritedRules(element, sections, usedProps); this.getElementRules(element, rules, usedProps); if (rules.length || sections.length) { var inheritLabel = "Inherited from"; // $STR("InheritedFrom"); var result = this.template.cascadedTag.replace({rules: rules, inherited: sections, inheritLabel: inheritLabel}, this.panelNode); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, result]); } else { var result = FirebugReps.Warning.tag.replace({object: "EmptyElementCSS"}, this.panelNode); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, result]); } // TODO: xxxpedro remove when there the external resource problem is fixed if (CssAnalyzer.hasExternalStyleSheet()) CssAnalyzer.externalStyleSheetWarning.tag.append({ object: "The results here may be inaccurate because some " + "stylesheets could not be loaded due to access restrictions. ", link: "more...", href: "http://getfirebug.com/wiki/index.php/Firebug_Lite_FAQ#I_keep_seeing_.22This_element_has_no_style_rules.22" }, this.panelNode); }, getStylesheetURL: function(rule) { // if the parentStyleSheet.href is null, CSS std says its inline style. // TODO: xxxpedro IE doesn't have rule.parentStyleSheet so we must fall back to the doc.location if (rule && rule.parentStyleSheet && rule.parentStyleSheet.href) return rule.parentStyleSheet.href; else return this.selection.ownerDocument.location.href; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getInheritedRules: function(element, sections, usedProps) { var parent = element.parentNode; if (parent && parent.nodeType == 1) { this.getInheritedRules(parent, sections, usedProps); var rules = []; this.getElementRules(parent, rules, usedProps, true); if (rules.length) sections.splice(0, 0, {element: parent, rules: rules}); } }, getElementRules: function(element, rules, usedProps, inheritMode) { var inspectedRules, displayedRules = {}; inspectedRules = CssAnalyzer.getElementCSSRules(element); if (inspectedRules) { for (var i = 0, length=inspectedRules.length; i < length; ++i) { var ruleId = inspectedRules[i]; var ruleData = CssAnalyzer.getRuleData(ruleId); var rule = ruleData.rule; var ssid = ruleData.styleSheetId; var parentStyleSheet = StyleSheetCache.get(ssid); var href = parentStyleSheet.externalURL ? parentStyleSheet.externalURL : parentStyleSheet.href; // Null means inline var instance = null; //var instance = getInstanceForStyleSheet(rule.parentStyleSheet, element.ownerDocument); var isSystemSheet = false; //var isSystemSheet = isSystemStyleSheet(rule.parentStyleSheet); if (!Firebug.showUserAgentCSS && isSystemSheet) // This removes user agent rules continue; if (!href) href = element.ownerDocument.location.href; // http://code.google.com/p/fbug/issues/detail?id=452 var props = this.getRuleProperties(this.context, rule, inheritMode); if (inheritMode && !props.length) continue; // //var line = domUtils.getRuleLine(rule); // TODO: xxxpedro CSS line number var line = ruleData.lineNo; var ruleId = rule.selectorText+"/"+line; var sourceLink = new SourceLink(href, line, "css", rule, instance); this.markOverridenProps(props, usedProps, inheritMode); rules.splice(0, 0, {rule: rule, id: ruleId, selector: ruleData.selector, sourceLink: sourceLink, props: props, inherited: inheritMode, isSystemSheet: isSystemSheet}); } } if (element.style) this.getStyleProperties(element, rules, usedProps, inheritMode); if (FBTrace.DBG_CSS) FBTrace.sysout("getElementRules "+rules.length+" rules for "+getElementXPath(element), rules); }, /* getElementRules: function(element, rules, usedProps, inheritMode) { var inspectedRules, displayedRules = {}; try { inspectedRules = domUtils ? domUtils.getCSSStyleRules(element) : null; } catch (exc) {} if (inspectedRules) { for (var i = 0; i < inspectedRules.Count(); ++i) { var rule = QI(inspectedRules.GetElementAt(i), nsIDOMCSSStyleRule); var href = rule.parentStyleSheet.href; // Null means inline var instance = getInstanceForStyleSheet(rule.parentStyleSheet, element.ownerDocument); var isSystemSheet = isSystemStyleSheet(rule.parentStyleSheet); if (!Firebug.showUserAgentCSS && isSystemSheet) // This removes user agent rules continue; if (!href) href = element.ownerDocument.location.href; // http://code.google.com/p/fbug/issues/detail?id=452 var props = this.getRuleProperties(this.context, rule, inheritMode); if (inheritMode && !props.length) continue; var line = domUtils.getRuleLine(rule); var ruleId = rule.selectorText+"/"+line; var sourceLink = new SourceLink(href, line, "css", rule, instance); this.markOverridenProps(props, usedProps, inheritMode); rules.splice(0, 0, {rule: rule, id: ruleId, selector: rule.selectorText, sourceLink: sourceLink, props: props, inherited: inheritMode, isSystemSheet: isSystemSheet}); } } if (element.style) this.getStyleProperties(element, rules, usedProps, inheritMode); if (FBTrace.DBG_CSS) FBTrace.sysout("getElementRules "+rules.length+" rules for "+getElementXPath(element), rules); }, /**/ markOverridenProps: function(props, usedProps, inheritMode) { for (var i = 0; i < props.length; ++i) { var prop = props[i]; if ( usedProps.hasOwnProperty(prop.name) ) { var deadProps = usedProps[prop.name]; // all previous occurrences of this property for (var j = 0; j < deadProps.length; ++j) { var deadProp = deadProps[j]; if (!deadProp.disabled && !deadProp.wasInherited && deadProp.important && !prop.important) prop.overridden = true; // new occurrence overridden else if (!prop.disabled) deadProp.overridden = true; // previous occurrences overridden } } else usedProps[prop.name] = []; prop.wasInherited = inheritMode ? true : false; usedProps[prop.name].push(prop); // all occurrences of a property seen so far, by name } }, getStyleProperties: function(element, rules, usedProps, inheritMode) { var props = this.parseCSSProps(element.style, inheritMode); this.addOldProperties(this.context, getElementXPath(element), inheritMode, props); sortProperties(props); this.markOverridenProps(props, usedProps, inheritMode); if (props.length) rules.splice(0, 0, {rule: element, id: getElementXPath(element), selector: "element.style", props: props, inherited: inheritMode}); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "css", title: "Style", parentPanel: "HTML", order: 0, initialize: function() { this.context = Firebug.chrome; // TODO: xxxpedro css2 this.document = Firebug.chrome.document; // TODO: xxxpedro css2 Firebug.CSSStyleSheetPanel.prototype.initialize.apply(this, arguments); // TODO: xxxpedro css2 var selection = ElementCache.get(Firebug.context.persistedState.selectedHTMLElementId); if (selection) this.select(selection, true); //this.updateCascadeView(document.getElementsByTagName("h1")[0]); //this.updateCascadeView(document.getElementById("build")); /* this.onStateChange = bindFixed(this.contentStateCheck, this); this.onHoverChange = bindFixed(this.contentStateCheck, this, STATE_HOVER); this.onActiveChange = bindFixed(this.contentStateCheck, this, STATE_ACTIVE); /**/ }, ishow: function(state) { }, watchWindow: function(win) { if (domUtils) { // Normally these would not be required, but in order to update after the state is set // using the options menu we need to monitor these global events as well var doc = win.document; ///addEvent(doc, "mouseover", this.onHoverChange); ///addEvent(doc, "mousedown", this.onActiveChange); } }, unwatchWindow: function(win) { var doc = win.document; ///removeEvent(doc, "mouseover", this.onHoverChange); ///removeEvent(doc, "mousedown", this.onActiveChange); if (isAncestor(this.stateChangeEl, doc)) { this.removeStateChangeHandlers(); } }, supportsObject: function(object) { return object instanceof Element ? 1 : 0; }, updateView: function(element) { this.updateCascadeView(element); if (domUtils) { this.contentState = safeGetContentState(element); this.addStateChangeHandlers(element); } }, updateSelection: function(element) { if ( !instanceOf(element , "Element") ) // html supports SourceLink return; if (sothinkInstalled) { FirebugReps.Warning.tag.replace({object: "SothinkWarning"}, this.panelNode); return; } /* if (!domUtils) { FirebugReps.Warning.tag.replace({object: "DOMInspectorWarning"}, this.panelNode); return; } /**/ if (!element) return; this.updateView(element); }, updateOption: function(name, value) { if (name == "showUserAgentCSS" || name == "expandShorthandProps") this.refresh(); }, getOptionsMenuItems: function() { var ret = [ {label: "Show User Agent CSS", type: "checkbox", checked: Firebug.showUserAgentCSS, command: bindFixed(Firebug.togglePref, Firebug, "showUserAgentCSS") }, {label: "Expand Shorthand Properties", type: "checkbox", checked: Firebug.expandShorthandProps, command: bindFixed(Firebug.togglePref, Firebug, "expandShorthandProps") } ]; if (domUtils && this.selection) { var state = safeGetContentState(this.selection); ret.push("-"); ret.push({label: ":active", type: "checkbox", checked: state & STATE_ACTIVE, command: bindFixed(this.updateContentState, this, STATE_ACTIVE, state & STATE_ACTIVE)}); ret.push({label: ":hover", type: "checkbox", checked: state & STATE_HOVER, command: bindFixed(this.updateContentState, this, STATE_HOVER, state & STATE_HOVER)}); } return ret; }, updateContentState: function(state, remove) { domUtils.setContentState(remove ? this.selection.ownerDocument.documentElement : this.selection, state); this.refresh(); }, addStateChangeHandlers: function(el) { this.removeStateChangeHandlers(); /* addEvent(el, "focus", this.onStateChange); addEvent(el, "blur", this.onStateChange); addEvent(el, "mouseup", this.onStateChange); addEvent(el, "mousedown", this.onStateChange); addEvent(el, "mouseover", this.onStateChange); addEvent(el, "mouseout", this.onStateChange); /**/ this.stateChangeEl = el; }, removeStateChangeHandlers: function() { var sel = this.stateChangeEl; if (sel) { /* removeEvent(sel, "focus", this.onStateChange); removeEvent(sel, "blur", this.onStateChange); removeEvent(sel, "mouseup", this.onStateChange); removeEvent(sel, "mousedown", this.onStateChange); removeEvent(sel, "mouseover", this.onStateChange); removeEvent(sel, "mouseout", this.onStateChange); /**/ } }, contentStateCheck: function(state) { if (!state || this.contentState & state) { var timeoutRunner = bindFixed(function() { var newState = safeGetContentState(this.selection); if (newState != this.contentState) { this.context.invalidatePanels(this.name); } }, this); // Delay exec until after the event has processed and the state has been updated setTimeout(timeoutRunner, 0); } } }); function safeGetContentState(selection) { try { return domUtils.getContentState(selection); } catch (e) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("css.safeGetContentState; EXCEPTION", e); } } // ************************************************************************************************ function CSSComputedElementPanel() {} CSSComputedElementPanel.prototype = extend(CSSElementPanel.prototype, { template: domplate( { computedTag: DIV({"class": "a11yCSSView", role : "list", "aria-label" : $STR('aria.labels.computed styles')}, FOR("group", "$groups", H1({"class": "cssInheritHeader groupHeader focusRow", role : "listitem"}, SPAN({"class": "cssInheritLabel"}, "$group.title") ), TABLE({width: "100%", role : 'group'}, TBODY({role : 'presentation'}, FOR("prop", "$group.props", TR({"class": 'focusRow computedStyleRow', role : 'listitem'}, TD({"class": "stylePropName", role : 'presentation'}, "$prop.name"), TD({"class": "stylePropValue", role : 'presentation'}, "$prop.value") ) ) ) ) ) ) }), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * updateComputedView: function(element) { var win = isIE ? element.ownerDocument.parentWindow : element.ownerDocument.defaultView; var style = isIE ? element.currentStyle : win.getComputedStyle(element, ""); var groups = []; for (var groupName in styleGroups) { // TODO: xxxpedro i18n $STR //var title = $STR("StyleGroup-" + groupName); var title = styleGroupTitles[groupName]; var group = {title: title, props: []}; groups.push(group); var props = styleGroups[groupName]; for (var i = 0; i < props.length; ++i) { var propName = props[i]; var propValue = style.getPropertyValue ? style.getPropertyValue(propName) : ""+style[toCamelCase(propName)]; if (propValue === undefined || propValue === null) continue; propValue = stripUnits(rgbToHex(propValue)); if (propValue) group.props.push({name: propName, value: propValue}); } } var result = this.template.computedTag.replace({groups: groups}, this.panelNode); //dispatch([Firebug.A11yModel], 'onCSSRulesAdded', [this, result]); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "computed", title: "Computed", parentPanel: "HTML", order: 1, updateView: function(element) { this.updateComputedView(element); }, getOptionsMenuItems: function() { return [ {label: "Refresh", command: bind(this.refresh, this) } ]; } }); // ************************************************************************************************ // CSSEditor function CSSEditor(doc) { this.initializeInline(doc); } CSSEditor.prototype = domplate(Firebug.InlineEditor.prototype, { insertNewRow: function(target, insertWhere) { var rule = Firebug.getRepObject(target); var emptyProp = { // TODO: xxxpedro - uses charCode(255) to force the element being rendered, // allowing webkit to get the correct position of the property name "span", // when inserting a new CSS rule? name: "", value: "", important: "" }; if (insertWhere == "before") return CSSPropTag.tag.insertBefore({prop: emptyProp, rule: rule}, target); else return CSSPropTag.tag.insertAfter({prop: emptyProp, rule: rule}, target); }, saveEdit: function(target, value, previousValue) { // We need to check the value first in order to avoid a problem in IE8 // See Issue 3038: Empty (null) styles when adding CSS styles in Firebug Lite if (!value) return; target.innerHTML = escapeForCss(value); var row = getAncestorByClass(target, "cssProp"); if (hasClass(row, "disabledStyle")) toggleClass(row, "disabledStyle"); var rule = Firebug.getRepObject(target); if (hasClass(target, "cssPropName")) { if (value && previousValue != value) // name of property has changed. { var propValue = getChildByClass(row, "cssPropValue")[textContent]; var parsedValue = parsePriority(propValue); if (propValue && propValue != "undefined") { if (FBTrace.DBG_CSS) FBTrace.sysout("CSSEditor.saveEdit : "+previousValue+"->"+value+" = "+propValue+"\n"); if (previousValue) Firebug.CSSModule.removeProperty(rule, previousValue); Firebug.CSSModule.setProperty(rule, value, parsedValue.value, parsedValue.priority); } } else if (!value) // name of the property has been deleted, so remove the property. Firebug.CSSModule.removeProperty(rule, previousValue); } else if (getAncestorByClass(target, "cssPropValue")) { var propName = getChildByClass(row, "cssPropName")[textContent]; var propValue = getChildByClass(row, "cssPropValue")[textContent]; if (FBTrace.DBG_CSS) { FBTrace.sysout("CSSEditor.saveEdit propName=propValue: "+propName +" = "+propValue+"\n"); // FBTrace.sysout("CSSEditor.saveEdit BEFORE style:",style); } if (value && value != "null") { var parsedValue = parsePriority(value); Firebug.CSSModule.setProperty(rule, propName, parsedValue.value, parsedValue.priority); } else if (previousValue && previousValue != "null") Firebug.CSSModule.removeProperty(rule, propName); } this.panel.markChange(this.panel.name == "stylesheet"); }, advanceToNext: function(target, charCode) { if (charCode == 58 /*":"*/ && hasClass(target, "cssPropName")) return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * getAutoCompleteRange: function(value, offset) { if (hasClass(this.target, "cssPropName")) return {start: 0, end: value.length-1}; else return parseCSSValue(value, offset); }, getAutoCompleteList: function(preExpr, expr, postExpr) { if (hasClass(this.target, "cssPropName")) { return getCSSPropertyNames(); } else { var row = getAncestorByClass(this.target, "cssProp"); var propName = getChildByClass(row, "cssPropName")[textContent]; return getCSSKeywordsByProperty(propName); } } }); //************************************************************************************************ //CSSRuleEditor function CSSRuleEditor(doc) { this.initializeInline(doc); this.completeAsYouType = false; } CSSRuleEditor.uniquifier = 0; CSSRuleEditor.prototype = domplate(Firebug.InlineEditor.prototype, { insertNewRow: function(target, insertWhere) { var emptyRule = { selector: "", id: "", props: [], isSelectorEditable: true }; if (insertWhere == "before") return CSSStyleRuleTag.tag.insertBefore({rule: emptyRule}, target); else return CSSStyleRuleTag.tag.insertAfter({rule: emptyRule}, target); }, saveEdit: function(target, value, previousValue) { if (FBTrace.DBG_CSS) FBTrace.sysout("CSSRuleEditor.saveEdit: '" + value + "' '" + previousValue + "'", target); target.innerHTML = escapeForCss(value); if (value === previousValue) return; var row = getAncestorByClass(target, "cssRule"); var styleSheet = this.panel.location; styleSheet = styleSheet.editStyleSheet ? styleSheet.editStyleSheet.sheet : styleSheet; var cssRules = styleSheet.cssRules; var rule = Firebug.getRepObject(target), oldRule = rule; var ruleIndex = cssRules.length; if (rule || Firebug.getRepObject(row.nextSibling)) { var searchRule = rule || Firebug.getRepObject(row.nextSibling); for (ruleIndex=0; ruleIndex<cssRules.length && searchRule!=cssRules[ruleIndex]; ruleIndex++) {} } // Delete in all cases except for new add // We want to do this before the insert to ease change tracking if (oldRule) { Firebug.CSSModule.deleteRule(styleSheet, ruleIndex); } // Firefox does not follow the spec for the update selector text case. // When attempting to update the value, firefox will silently fail. // See https://bugzilla.mozilla.org/show_bug.cgi?id=37468 for the quite // old discussion of this bug. // As a result we need to recreate the style every time the selector // changes. if (value) { var cssText = [ value, "{" ]; var props = row.getElementsByClassName("cssProp"); for (var i = 0; i < props.length; i++) { var propEl = props[i]; if (!hasClass(propEl, "disabledStyle")) { cssText.push(getChildByClass(propEl, "cssPropName")[textContent]); cssText.push(":"); cssText.push(getChildByClass(propEl, "cssPropValue")[textContent]); cssText.push(";"); } } cssText.push("}"); cssText = cssText.join(""); try { var insertLoc = Firebug.CSSModule.insertRule(styleSheet, cssText, ruleIndex); rule = cssRules[insertLoc]; ruleIndex++; } catch (err) { if (FBTrace.DBG_CSS || FBTrace.DBG_ERRORS) FBTrace.sysout("CSS Insert Error: "+err, err); target.innerHTML = escapeForCss(previousValue); row.repObject = undefined; return; } } else { rule = undefined; } // Update the rep object row.repObject = rule; if (!oldRule) { // Who knows what the domutils will return for rule line // for a recently created rule. To be safe we just generate // a unique value as this is only used as an internal key. var ruleId = "new/"+value+"/"+(++CSSRuleEditor.uniquifier); row.setAttribute("ruleId", ruleId); } this.panel.markChange(this.panel.name == "stylesheet"); } }); // ************************************************************************************************ // StyleSheetEditor function StyleSheetEditor(doc) { this.box = this.tag.replace({}, doc, this); this.input = this.box.firstChild; } StyleSheetEditor.prototype = domplate(Firebug.BaseEditor, { multiLine: true, tag: DIV( TEXTAREA({"class": "styleSheetEditor fullPanelEditor", oninput: "$onInput"}) ), getValue: function() { return this.input.value; }, setValue: function(value) { return this.input.value = value; }, show: function(target, panel, value, textSize, targetSize) { this.target = target; this.panel = panel; this.panel.panelNode.appendChild(this.box); this.input.value = value; this.input.focus(); var command = Firebug.chrome.$("cmd_toggleCSSEditing"); command.setAttribute("checked", true); }, hide: function() { var command = Firebug.chrome.$("cmd_toggleCSSEditing"); command.setAttribute("checked", false); if (this.box.parentNode == this.panel.panelNode) this.panel.panelNode.removeChild(this.box); delete this.target; delete this.panel; delete this.styleSheet; }, saveEdit: function(target, value, previousValue) { Firebug.CSSModule.freeEdit(this.styleSheet, value); }, endEditing: function() { this.panel.refresh(); return true; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onInput: function() { Firebug.Editor.update(); }, scrollToLine: function(line, offset) { this.startMeasuring(this.input); var lineHeight = this.measureText().height; this.stopMeasuring(); this.input.scrollTop = (line * lineHeight) + offset; } }); // ************************************************************************************************ // Local Helpers var rgbToHex = function rgbToHex(value) { return value.replace(/\brgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)/gi, rgbToHexReplacer); }; var rgbToHexReplacer = function(_, r, g, b) { return '#' + ((1 << 24) + (r << 16) + (g << 8) + (b << 0)).toString(16).substr(-6).toUpperCase(); }; var stripUnits = function stripUnits(value) { // remove units from '0px', '0em' etc. leave non-zero units in-tact. return value.replace(/(url\(.*?\)|[^0]\S*\s*)|0(%|em|ex|px|in|cm|mm|pt|pc)(\s|$)/gi, stripUnitsReplacer); }; var stripUnitsReplacer = function(_, skip, remove, whitespace) { return skip || ('0' + whitespace); }; function parsePriority(value) { var rePriority = /(.*?)\s*(!important)?$/; var m = rePriority.exec(value); var propValue = m ? m[1] : ""; var priority = m && m[2] ? "important" : ""; return {value: propValue, priority: priority}; } function parseURLValue(value) { var m = reURL.exec(value); return m ? m[1] : ""; } function parseRepeatValue(value) { var m = reRepeat.exec(value); return m ? m[0] : ""; } function parseCSSValue(value, offset) { var start = 0; var m; while (1) { m = reSplitCSS.exec(value); if (m && m.index+m[0].length < offset) { value = value.substr(m.index+m[0].length); start += m.index+m[0].length; offset -= m.index+m[0].length; } else break; } if (m) { var type; if (m[1]) type = "url"; else if (m[2] || m[3]) type = "rgb"; else if (m[4]) type = "int"; return {value: m[0], start: start+m.index, end: start+m.index+(m[0].length-1), type: type}; } } function findPropByName(props, name) { for (var i = 0; i < props.length; ++i) { if (props[i].name == name) return i; } } function sortProperties(props) { props.sort(function(a, b) { return a.name > b.name ? 1 : -1; }); } function getTopmostRuleLine(panelNode) { for (var child = panelNode.firstChild; child; child = child.nextSibling) { if (child.offsetTop+child.offsetHeight > panelNode.scrollTop) { var rule = child.repObject; if (rule) return { line: domUtils.getRuleLine(rule), offset: panelNode.scrollTop-child.offsetTop }; } } return 0; } function getStyleSheetCSS(sheet, context) { if (sheet.ownerNode instanceof HTMLStyleElement) return sheet.ownerNode.innerHTML; else return context.sourceCache.load(sheet.href).join(""); } function getStyleSheetOwnerNode(sheet) { for (; sheet && !sheet.ownerNode; sheet = sheet.parentStyleSheet); return sheet.ownerNode; } function scrollSelectionIntoView(panel) { var selCon = getSelectionController(panel); selCon.scrollSelectionIntoView( nsISelectionController.SELECTION_NORMAL, nsISelectionController.SELECTION_FOCUS_REGION, true); } function getSelectionController(panel) { var browser = Firebug.chrome.getPanelBrowser(panel); return browser.docShell.QueryInterface(nsIInterfaceRequestor) .getInterface(nsISelectionDisplay) .QueryInterface(nsISelectionController); } // ************************************************************************************************ Firebug.registerModule(Firebug.CSSModule); Firebug.registerPanel(Firebug.CSSStyleSheetPanel); Firebug.registerPanel(CSSElementPanel); Firebug.registerPanel(CSSComputedElementPanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Script Module Firebug.Script = extend(Firebug.Module, { getPanel: function() { return Firebug.chrome ? Firebug.chrome.getPanel("Script") : null; }, selectSourceCode: function(index) { this.getPanel().selectSourceCode(index); } }); Firebug.registerModule(Firebug.Script); // ************************************************************************************************ // Script Panel function ScriptPanel(){}; ScriptPanel.prototype = extend(Firebug.Panel, { name: "Script", title: "Script", selectIndex: 0, // index of the current selectNode's option sourceIndex: -1, // index of the script node, based in doc.getElementsByTagName("script") options: { hasToolButtons: true }, create: function() { Firebug.Panel.create.apply(this, arguments); this.onChangeSelect = bind(this.onChangeSelect, this); var doc = Firebug.browser.document; var scripts = doc.getElementsByTagName("script"); var selectNode = this.selectNode = createElement("select"); for(var i=0, script; script=scripts[i]; i++) { // Don't show Firebug Lite source code in the list of options if (Firebug.ignoreFirebugElements && script.getAttribute("firebugIgnore")) continue; var fileName = getFileName(script.src) || getFileName(doc.location.href); var option = createElement("option", {value:i}); option.appendChild(Firebug.chrome.document.createTextNode(fileName)); selectNode.appendChild(option); }; this.toolButtonsNode.appendChild(selectNode); }, initialize: function() { // we must render the code first, so the persistent state can be restore this.selectSourceCode(this.selectIndex); Firebug.Panel.initialize.apply(this, arguments); addEvent(this.selectNode, "change", this.onChangeSelect); }, shutdown: function() { removeEvent(this.selectNode, "change", this.onChangeSelect); Firebug.Panel.shutdown.apply(this, arguments); }, detach: function(oldChrome, newChrome) { Firebug.Panel.detach.apply(this, arguments); var oldPanel = oldChrome.getPanel("Script"); var index = oldPanel.selectIndex; this.selectNode.selectedIndex = index; this.selectIndex = index; this.sourceIndex = -1; }, onChangeSelect: function(event) { var select = this.selectNode; this.selectIndex = select.selectedIndex; var option = select.options[select.selectedIndex]; if (!option) return; var selectedSourceIndex = parseInt(option.value); this.renderSourceCode(selectedSourceIndex); }, selectSourceCode: function(index) { var select = this.selectNode; select.selectedIndex = index; var option = select.options[index]; if (!option) return; var selectedSourceIndex = parseInt(option.value); this.renderSourceCode(selectedSourceIndex); }, renderSourceCode: function(index) { if (this.sourceIndex != index) { var renderProcess = function renderProcess(src) { var html = [], hl = 0; src = isIE && !isExternal ? src+'\n' : // IE put an extra line when reading source of local resources '\n'+src; // find the number of lines of code src = src.replace(/\n\r|\r\n/g, "\n"); var match = src.match(/[\n]/g); var lines=match ? match.length : 0; // render the full source code + line numbers html html[hl++] = '<div><div class="sourceBox" style="left:'; html[hl++] = 35 + 7*(lines+'').length; html[hl++] = 'px;"><pre class="sourceCode">'; html[hl++] = escapeHTML(src); html[hl++] = '</pre></div><div class="lineNo">'; // render the line number divs for(var l=1, lines; l<=lines; l++) { html[hl++] = '<div line="'; html[hl++] = l; html[hl++] = '">'; html[hl++] = l; html[hl++] = '</div>'; } html[hl++] = '</div></div>'; updatePanel(html); }; var updatePanel = function(html) { self.panelNode.innerHTML = html.join(""); // IE needs this timeout, otherwise the panel won't scroll setTimeout(function(){ self.synchronizeUI(); },0); }; var onFailure = function() { FirebugReps.Warning.tag.replace({object: "AccessRestricted"}, self.panelNode); }; var self = this; var doc = Firebug.browser.document; var script = doc.getElementsByTagName("script")[index]; var url = getScriptURL(script); var isExternal = url && url != doc.location.href; try { if (Firebug.disableResourceFetching) { renderProcess(Firebug.Lite.Proxy.fetchResourceDisabledMessage); } else if (isExternal) { Ajax.request({url: url, onSuccess: renderProcess, onFailure: onFailure}); } else { var src = script.innerHTML; renderProcess(src); } } catch(e) { onFailure(); } this.sourceIndex = index; } } }); Firebug.registerPanel(ScriptPanel); // ************************************************************************************************ var getScriptURL = function getScriptURL(script) { var reFile = /([^\/\?#]+)(#.+)?$/; var rePath = /^(.*\/)/; var reProtocol = /^\w+:\/\//; var path = null; var doc = Firebug.browser.document; var file = reFile.exec(script.src); if (file) { var fileName = file[1]; var fileOptions = file[2]; // absolute path if (reProtocol.test(script.src)) { path = rePath.exec(script.src)[1]; } // relative path else { var r = rePath.exec(script.src); var src = r ? r[1] : script.src; var backDir = /^((?:\.\.\/)+)(.*)/.exec(src); var reLastDir = /^(.*\/)[^\/]+\/$/; path = rePath.exec(doc.location.href)[1]; // "../some/path" if (backDir) { var j = backDir[1].length/3; var p; while (j-- > 0) path = reLastDir.exec(path)[1]; path += backDir[2]; } else if(src.indexOf("/") != -1) { // "./some/path" if(/^\.\/./.test(src)) { path += src.substring(2); } // "/some/path" else if(/^\/./.test(src)) { var domain = /^(\w+:\/\/[^\/]+)/.exec(path); path = domain[1] + src; } // "some/path" else { path += src; } } } } var m = path && path.match(/([^\/]+)\/$/) || null; if (path && m) { return path + fileName; } }; var getFileName = function getFileName(path) { if (!path) return ""; var match = path && path.match(/[^\/]+(\?.*)?(#.*)?$/); return match && match[0] || path; }; // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var ElementCache = Firebug.Lite.Cache.Element; var insertSliceSize = 18; var insertInterval = 40; var ignoreVars = { "__firebug__": 1, "eval": 1, // We are forced to ignore Java-related variables, because // trying to access them causes browser freeze "java": 1, "sun": 1, "Packages": 1, "JavaArray": 1, "JavaMember": 1, "JavaObject": 1, "JavaClass": 1, "JavaPackage": 1, "_firebug": 1, "_FirebugConsole": 1, "_FirebugCommandLine": 1 }; if (Firebug.ignoreFirebugElements) ignoreVars[Firebug.Lite.Cache.ID] = 1; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * var memberPanelRep = isIE6 ? {"class": "memberLabel $member.type\\Label", href: "javacript:void(0)"} : {"class": "memberLabel $member.type\\Label"}; var RowTag = TR({"class": "memberRow $member.open $member.type\\Row", $hasChildren: "$member.hasChildren", role : 'presentation', level: "$member.level"}, TD({"class": "memberLabelCell", style: "padding-left: $member.indent\\px", role : 'presentation'}, A(memberPanelRep, SPAN({}, "$member.name") ) ), TD({"class": "memberValueCell", role : 'presentation'}, TAG("$member.tag", {object: "$member.value"}) ) ); var WatchRowTag = TR({"class": "watchNewRow", level: 0}, TD({"class": "watchEditCell", colspan: 2}, DIV({"class": "watchEditBox a11yFocusNoTab", role: "button", 'tabindex' : '0', 'aria-label' : $STR('press enter to add new watch expression')}, $STR("NewWatch") ) ) ); var SizerRow = TR({role : 'presentation'}, TD({width: "30%"}), TD({width: "70%"}) ); var domTableClass = isIElt8 ? "domTable domTableIE" : "domTable"; var DirTablePlate = domplate(Firebug.Rep, { tag: TABLE({"class": domTableClass, cellpadding: 0, cellspacing: 0, onclick: "$onClick", role :"tree"}, TBODY({role: 'presentation'}, SizerRow, FOR("member", "$object|memberIterator", RowTag) ) ), watchTag: TABLE({"class": domTableClass, cellpadding: 0, cellspacing: 0, _toggles: "$toggles", _domPanel: "$domPanel", onclick: "$onClick", role : 'tree'}, TBODY({role : 'presentation'}, SizerRow, WatchRowTag ) ), tableTag: TABLE({"class": domTableClass, cellpadding: 0, cellspacing: 0, _toggles: "$toggles", _domPanel: "$domPanel", onclick: "$onClick", role : 'tree'}, TBODY({role : 'presentation'}, SizerRow ) ), rowTag: FOR("member", "$members", RowTag), memberIterator: function(object, level) { return getMembers(object, level); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onClick: function(event) { if (!isLeftClick(event)) return; var target = event.target || event.srcElement; var row = getAncestorByClass(target, "memberRow"); var label = getAncestorByClass(target, "memberLabel"); if (label && hasClass(row, "hasChildren")) { var row = label.parentNode.parentNode; this.toggleRow(row); } else { var object = Firebug.getRepObject(target); if (typeof(object) == "function") { Firebug.chrome.select(object, "script"); cancelEvent(event); } else if (event.detail == 2 && !object) { var panel = row.parentNode.parentNode.domPanel; if (panel) { var rowValue = panel.getRowPropertyValue(row); if (typeof(rowValue) == "boolean") panel.setPropertyValue(row, !rowValue); else panel.editProperty(row); cancelEvent(event); } } } return false; }, toggleRow: function(row) { var level = parseInt(row.getAttribute("level")); var toggles = row.parentNode.parentNode.toggles; if (hasClass(row, "opened")) { removeClass(row, "opened"); if (toggles) { var path = getPath(row); // Remove the path from the toggle tree for (var i = 0; i < path.length; ++i) { if (i == path.length-1) delete toggles[path[i]]; else toggles = toggles[path[i]]; } } var rowTag = this.rowTag; var tbody = row.parentNode; setTimeout(function() { for (var firstRow = row.nextSibling; firstRow; firstRow = row.nextSibling) { if (parseInt(firstRow.getAttribute("level")) <= level) break; tbody.removeChild(firstRow); } }, row.insertTimeout ? row.insertTimeout : 0); } else { setClass(row, "opened"); if (toggles) { var path = getPath(row); // Mark the path in the toggle tree for (var i = 0; i < path.length; ++i) { var name = path[i]; if (toggles.hasOwnProperty(name)) toggles = toggles[name]; else toggles = toggles[name] = {}; } } var value = row.lastChild.firstChild.repObject; var members = getMembers(value, level+1); var rowTag = this.rowTag; var lastRow = row; var delay = 0; //var setSize = members.length; //var rowCount = 1; while (members.length) { with({slice: members.splice(0, insertSliceSize), isLast: !members.length}) { setTimeout(function() { if (lastRow.parentNode) { var result = rowTag.insertRows({members: slice}, lastRow); lastRow = result[1]; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [null, result, rowCount, setSize]); //rowCount += insertSliceSize; } if (isLast) row.removeAttribute("insertTimeout"); }, delay); } delay += insertInterval; } row.insertTimeout = delay; } } }); // ************************************************************************************************ Firebug.DOMBasePanel = function() {}; Firebug.DOMBasePanel.prototype = extend(Firebug.Panel, { tag: DirTablePlate.tableTag, getRealObject: function(object) { // TODO: Move this to some global location // TODO: Unwrapping should be centralized rather than sprinkling it around ad hoc. // TODO: We might be able to make this check more authoritative with QueryInterface. if (!object) return object; if (object.wrappedJSObject) return object.wrappedJSObject; return object; }, rebuild: function(update, scrollTop) { //dispatch([Firebug.A11yModel], 'onBeforeDomUpdateSelection', [this]); var members = getMembers(this.selection); expandMembers(members, this.toggles, 0, 0); this.showMembers(members, update, scrollTop); //TODO: xxxpedro statusbar if (!this.parentPanel) updateStatusBar(this); }, showMembers: function(members, update, scrollTop) { // If we are still in the midst of inserting rows, cancel all pending // insertions here - this is a big speedup when stepping in the debugger if (this.timeouts) { for (var i = 0; i < this.timeouts.length; ++i) this.context.clearTimeout(this.timeouts[i]); delete this.timeouts; } if (!members.length) return this.showEmptyMembers(); var panelNode = this.panelNode; var priorScrollTop = scrollTop == undefined ? panelNode.scrollTop : scrollTop; // If we are asked to "update" the current view, then build the new table // offscreen and swap it in when it's done var offscreen = update && panelNode.firstChild; var dest = offscreen ? panelNode.ownerDocument : panelNode; var table = this.tag.replace({domPanel: this, toggles: this.toggles}, dest); var tbody = table.lastChild; var rowTag = DirTablePlate.rowTag; // Insert the first slice immediately //var slice = members.splice(0, insertSliceSize); //var result = rowTag.insertRows({members: slice}, tbody.lastChild); //var setSize = members.length; //var rowCount = 1; var panel = this; var result; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); var timeouts = []; var delay = 0; // enable to measure rendering performance var renderStart = new Date().getTime(); while (members.length) { with({slice: members.splice(0, insertSliceSize), isLast: !members.length}) { timeouts.push(this.context.setTimeout(function() { // TODO: xxxpedro can this be a timing error related to the // "iteration number" approach insted of "duration time"? // avoid error in IE8 if (!tbody.lastChild) return; result = rowTag.insertRows({members: slice}, tbody.lastChild); //rowCount += insertSliceSize; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); if ((panelNode.scrollHeight+panelNode.offsetHeight) >= priorScrollTop) panelNode.scrollTop = priorScrollTop; // enable to measure rendering performance //if (isLast) alert(new Date().getTime() - renderStart + "ms"); }, delay)); delay += insertInterval; } } if (offscreen) { timeouts.push(this.context.setTimeout(function() { if (panelNode.firstChild) panelNode.replaceChild(table, panelNode.firstChild); else panelNode.appendChild(table); // Scroll back to where we were before panelNode.scrollTop = priorScrollTop; }, delay)); } else { timeouts.push(this.context.setTimeout(function() { panelNode.scrollTop = scrollTop == undefined ? 0 : scrollTop; }, delay)); } this.timeouts = timeouts; }, /* // new showMembers: function(members, update, scrollTop) { // If we are still in the midst of inserting rows, cancel all pending // insertions here - this is a big speedup when stepping in the debugger if (this.timeouts) { for (var i = 0; i < this.timeouts.length; ++i) this.context.clearTimeout(this.timeouts[i]); delete this.timeouts; } if (!members.length) return this.showEmptyMembers(); var panelNode = this.panelNode; var priorScrollTop = scrollTop == undefined ? panelNode.scrollTop : scrollTop; // If we are asked to "update" the current view, then build the new table // offscreen and swap it in when it's done var offscreen = update && panelNode.firstChild; var dest = offscreen ? panelNode.ownerDocument : panelNode; var table = this.tag.replace({domPanel: this, toggles: this.toggles}, dest); var tbody = table.lastChild; var rowTag = DirTablePlate.rowTag; // Insert the first slice immediately //var slice = members.splice(0, insertSliceSize); //var result = rowTag.insertRows({members: slice}, tbody.lastChild); //var setSize = members.length; //var rowCount = 1; var panel = this; var result; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); var timeouts = []; var delay = 0; var _insertSliceSize = insertSliceSize; var _insertInterval = insertInterval; // enable to measure rendering performance var renderStart = new Date().getTime(); var lastSkip = renderStart, now; while (members.length) { with({slice: members.splice(0, _insertSliceSize), isLast: !members.length}) { var _tbody = tbody; var _rowTag = rowTag; var _panelNode = panelNode; var _priorScrollTop = priorScrollTop; timeouts.push(this.context.setTimeout(function() { // TODO: xxxpedro can this be a timing error related to the // "iteration number" approach insted of "duration time"? // avoid error in IE8 if (!_tbody.lastChild) return; result = _rowTag.insertRows({members: slice}, _tbody.lastChild); //rowCount += _insertSliceSize; //dispatch([Firebug.A11yModel], 'onMemberRowSliceAdded', [panel, result, rowCount, setSize]); if ((_panelNode.scrollHeight + _panelNode.offsetHeight) >= _priorScrollTop) _panelNode.scrollTop = _priorScrollTop; // enable to measure rendering performance //alert("gap: " + (new Date().getTime() - lastSkip)); //lastSkip = new Date().getTime(); //if (isLast) alert("new: " + (new Date().getTime() - renderStart) + "ms"); }, delay)); delay += _insertInterval; } } if (offscreen) { timeouts.push(this.context.setTimeout(function() { if (panelNode.firstChild) panelNode.replaceChild(table, panelNode.firstChild); else panelNode.appendChild(table); // Scroll back to where we were before panelNode.scrollTop = priorScrollTop; }, delay)); } else { timeouts.push(this.context.setTimeout(function() { panelNode.scrollTop = scrollTop == undefined ? 0 : scrollTop; }, delay)); } this.timeouts = timeouts; }, /**/ showEmptyMembers: function() { FirebugReps.Warning.tag.replace({object: "NoMembersWarning"}, this.panelNode); }, findPathObject: function(object) { var pathIndex = -1; for (var i = 0; i < this.objectPath.length; ++i) { // IE needs === instead of == or otherwise some objects will // be considered equal to different objects, returning the // wrong index of the objectPath array if (this.getPathObject(i) === object) return i; } return -1; }, getPathObject: function(index) { var object = this.objectPath[index]; if (object instanceof Property) return object.getObject(); else return object; }, getRowObject: function(row) { var object = getRowOwnerObject(row); return object ? object : this.selection; }, getRowPropertyValue: function(row) { var object = this.getRowObject(row); object = this.getRealObject(object); if (object) { var propName = getRowName(row); if (object instanceof jsdIStackFrame) return Firebug.Debugger.evaluate(propName, this.context); else return object[propName]; } }, /* copyProperty: function(row) { var value = this.getRowPropertyValue(row); copyToClipboard(value); }, editProperty: function(row, editValue) { if (hasClass(row, "watchNewRow")) { if (this.context.stopped) Firebug.Editor.startEditing(row, ""); else if (Firebug.Console.isAlwaysEnabled()) // not stopped in debugger, need command line { if (Firebug.CommandLine.onCommandLineFocus()) Firebug.Editor.startEditing(row, ""); else row.innerHTML = $STR("warning.Command line blocked?"); } else row.innerHTML = $STR("warning.Console must be enabled"); } else if (hasClass(row, "watchRow")) Firebug.Editor.startEditing(row, getRowName(row)); else { var object = this.getRowObject(row); this.context.thisValue = object; if (!editValue) { var propValue = this.getRowPropertyValue(row); var type = typeof(propValue); if (type == "undefined" || type == "number" || type == "boolean") editValue = propValue; else if (type == "string") editValue = "\"" + escapeJS(propValue) + "\""; else if (propValue == null) editValue = "null"; else if (object instanceof Window || object instanceof jsdIStackFrame) editValue = getRowName(row); else editValue = "this." + getRowName(row); } Firebug.Editor.startEditing(row, editValue); } }, deleteProperty: function(row) { if (hasClass(row, "watchRow")) this.deleteWatch(row); else { var object = getRowOwnerObject(row); if (!object) object = this.selection; object = this.getRealObject(object); if (object) { var name = getRowName(row); try { delete object[name]; } catch (exc) { return; } this.rebuild(true); this.markChange(); } } }, setPropertyValue: function(row, value) // value must be string { if(FBTrace.DBG_DOM) { FBTrace.sysout("row: "+row); FBTrace.sysout("value: "+value+" type "+typeof(value), value); } var name = getRowName(row); if (name == "this") return; var object = this.getRowObject(row); object = this.getRealObject(object); if (object && !(object instanceof jsdIStackFrame)) { // unwrappedJSObject.property = unwrappedJSObject Firebug.CommandLine.evaluate(value, this.context, object, this.context.getGlobalScope(), function success(result, context) { if (FBTrace.DBG_DOM) FBTrace.sysout("setPropertyValue evaluate success object["+name+"]="+result+" type "+typeof(result), result); object[name] = result; }, function failed(exc, context) { try { if (FBTrace.DBG_DOM) FBTrace.sysout("setPropertyValue evaluate failed with exc:"+exc+" object["+name+"]="+value+" type "+typeof(value), exc); // If the value doesn't parse, then just store it as a string. Some users will // not realize they're supposed to enter a JavaScript expression and just type // literal text object[name] = String(value); // unwrappedJSobject.property = string } catch (exc) { return; } } ); } else if (this.context.stopped) { try { Firebug.CommandLine.evaluate(name+"="+value, this.context); } catch (exc) { try { // See catch block above... object[name] = String(value); // unwrappedJSobject.property = string } catch (exc) { return; } } } this.rebuild(true); this.markChange(); }, highlightRow: function(row) { if (this.highlightedRow) cancelClassTimed(this.highlightedRow, "jumpHighlight", this.context); this.highlightedRow = row; if (row) setClassTimed(row, "jumpHighlight", this.context); },/**/ onMouseMove: function(event) { var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink-element"); object = object ? object.repObject : null; if(object && instanceOf(object, "Element") && object.nodeType == 1) { if(object != lastHighlightedObject) { Firebug.Inspector.drawBoxModel(object); object = lastHighlightedObject; } } else Firebug.Inspector.hideBoxModel(); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel create: function() { // TODO: xxxpedro this.context = Firebug.browser; this.objectPath = []; this.propertyPath = []; this.viewPath = []; this.pathIndex = -1; this.toggles = {}; Firebug.Panel.create.apply(this, arguments); this.panelNode.style.padding = "0 1px"; }, initialize: function(){ Firebug.Panel.initialize.apply(this, arguments); addEvent(this.panelNode, "mousemove", this.onMouseMove); }, shutdown: function() { removeEvent(this.panelNode, "mousemove", this.onMouseMove); Firebug.Panel.shutdown.apply(this, arguments); }, /* destroy: function(state) { var view = this.viewPath[this.pathIndex]; if (view && this.panelNode.scrollTop) view.scrollTop = this.panelNode.scrollTop; if (this.pathIndex) state.pathIndex = this.pathIndex; if (this.viewPath) state.viewPath = this.viewPath; if (this.propertyPath) state.propertyPath = this.propertyPath; if (this.propertyPath.length > 0 && !this.propertyPath[1]) state.firstSelection = persistObject(this.getPathObject(1), this.context); Firebug.Panel.destroy.apply(this, arguments); }, /**/ ishow: function(state) { if (this.context.loaded && !this.selection) { if (!state) { this.select(null); return; } if (state.viewPath) this.viewPath = state.viewPath; if (state.propertyPath) this.propertyPath = state.propertyPath; var defaultObject = this.getDefaultSelection(this.context); var selectObject = defaultObject; if (state.firstSelection) { var restored = state.firstSelection(this.context); if (restored) { selectObject = restored; this.objectPath = [defaultObject, restored]; } else this.objectPath = [defaultObject]; } else this.objectPath = [defaultObject]; if (this.propertyPath.length > 1) { for (var i = 1; i < this.propertyPath.length; ++i) { var name = this.propertyPath[i]; if (!name) continue; var object = selectObject; try { selectObject = object[name]; } catch (exc) { selectObject = null; } if (selectObject) { this.objectPath.push(new Property(object, name)); } else { // If we can't access a property, just stop this.viewPath.splice(i); this.propertyPath.splice(i); this.objectPath.splice(i); selectObject = this.getPathObject(this.objectPath.length-1); break; } } } var selection = state.pathIndex <= this.objectPath.length-1 ? this.getPathObject(state.pathIndex) : this.getPathObject(this.objectPath.length-1); this.select(selection); } }, /* hide: function() { var view = this.viewPath[this.pathIndex]; if (view && this.panelNode.scrollTop) view.scrollTop = this.panelNode.scrollTop; }, /**/ supportsObject: function(object) { if (object == null) return 1000; if (typeof(object) == "undefined") return 1000; else if (object instanceof SourceLink) return 0; else return 1; // just agree to support everything but not agressively. }, refresh: function() { this.rebuild(true); }, updateSelection: function(object) { var previousIndex = this.pathIndex; var previousView = previousIndex == -1 ? null : this.viewPath[previousIndex]; var newPath = this.pathToAppend; delete this.pathToAppend; var pathIndex = this.findPathObject(object); if (newPath || pathIndex == -1) { this.toggles = {}; if (newPath) { // Remove everything after the point where we are inserting, so we // essentially replace it with the new path if (previousView) { if (this.panelNode.scrollTop) previousView.scrollTop = this.panelNode.scrollTop; var start = previousIndex + 1, // Opera needs the length argument in splice(), otherwise // it will consider that only one element should be removed length = this.objectPath.length - start; this.objectPath.splice(start, length); this.propertyPath.splice(start, length); this.viewPath.splice(start, length); } var value = this.getPathObject(previousIndex); if (!value) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("dom.updateSelection no pathObject for "+previousIndex+"\n"); return; } for (var i = 0, length = newPath.length; i < length; ++i) { var name = newPath[i]; var object = value; try { value = value[name]; } catch(exc) { if (FBTrace.DBG_ERRORS) FBTrace.sysout("dom.updateSelection FAILS at path_i="+i+" for name:"+name+"\n"); return; } ++this.pathIndex; this.objectPath.push(new Property(object, name)); this.propertyPath.push(name); this.viewPath.push({toggles: this.toggles, scrollTop: 0}); } } else { this.toggles = {}; var win = Firebug.browser.window; //var win = this.context.getGlobalScope(); if (object === win) { this.pathIndex = 0; this.objectPath = [win]; this.propertyPath = [null]; this.viewPath = [{toggles: this.toggles, scrollTop: 0}]; } else { this.pathIndex = 1; this.objectPath = [win, object]; this.propertyPath = [null, null]; this.viewPath = [ {toggles: {}, scrollTop: 0}, {toggles: this.toggles, scrollTop: 0} ]; } } this.panelNode.scrollTop = 0; this.rebuild(); } else { this.pathIndex = pathIndex; var view = this.viewPath[pathIndex]; this.toggles = view.toggles; // Persist the current scroll location if (previousView && this.panelNode.scrollTop) previousView.scrollTop = this.panelNode.scrollTop; this.rebuild(false, view.scrollTop); } }, getObjectPath: function(object) { return this.objectPath; }, getDefaultSelection: function() { return Firebug.browser.window; //return this.context.getGlobalScope(); }/*, updateOption: function(name, value) { const optionMap = {showUserProps: 1, showUserFuncs: 1, showDOMProps: 1, showDOMFuncs: 1, showDOMConstants: 1}; if ( optionMap.hasOwnProperty(name) ) this.rebuild(true); }, getOptionsMenuItems: function() { return [ optionMenu("ShowUserProps", "showUserProps"), optionMenu("ShowUserFuncs", "showUserFuncs"), optionMenu("ShowDOMProps", "showDOMProps"), optionMenu("ShowDOMFuncs", "showDOMFuncs"), optionMenu("ShowDOMConstants", "showDOMConstants"), "-", {label: "Refresh", command: bindFixed(this.rebuild, this, true) } ]; }, getContextMenuItems: function(object, target) { var row = getAncestorByClass(target, "memberRow"); var items = []; if (row) { var rowName = getRowName(row); var rowObject = this.getRowObject(row); var rowValue = this.getRowPropertyValue(row); var isWatch = hasClass(row, "watchRow"); var isStackFrame = rowObject instanceof jsdIStackFrame; if (typeof(rowValue) == "string" || typeof(rowValue) == "number") { // Functions already have a copy item in their context menu items.push( "-", {label: "CopyValue", command: bindFixed(this.copyProperty, this, row) } ); } items.push( "-", {label: isWatch ? "EditWatch" : (isStackFrame ? "EditVariable" : "EditProperty"), command: bindFixed(this.editProperty, this, row) } ); if (isWatch || (!isStackFrame && !isDOMMember(rowObject, rowName))) { items.push( {label: isWatch ? "DeleteWatch" : "DeleteProperty", command: bindFixed(this.deleteProperty, this, row) } ); } } items.push( "-", {label: "Refresh", command: bindFixed(this.rebuild, this, true) } ); return items; }, getEditor: function(target, value) { if (!this.editor) this.editor = new DOMEditor(this.document); return this.editor; }/**/ }); // ************************************************************************************************ // TODO: xxxpedro statusbar var updateStatusBar = function(panel) { var path = panel.propertyPath; var index = panel.pathIndex; var r = []; for (var i=0, l=path.length; i<l; i++) { r.push(i==index ? '<a class="fbHover fbButton fbBtnSelected" ' : '<a class="fbHover fbButton" '); r.push('pathIndex='); r.push(i); if(isIE6) r.push(' href="javascript:void(0)"'); r.push('>'); r.push(i==0 ? "window" : path[i] || "Object"); r.push('</a>'); if(i < l-1) r.push('<span class="fbStatusSeparator">&gt;</span>'); } panel.statusBarNode.innerHTML = r.join(""); }; var DOMMainPanel = Firebug.DOMPanel = function () {}; Firebug.DOMPanel.DirTable = DirTablePlate; DOMMainPanel.prototype = extend(Firebug.DOMBasePanel.prototype, { onClickStatusBar: function(event) { var target = event.srcElement || event.target; var element = getAncestorByClass(target, "fbHover"); if(element) { var pathIndex = element.getAttribute("pathIndex"); if(pathIndex) { this.select(this.getPathObject(pathIndex)); } } }, selectRow: function(row, target) { if (!target) target = row.lastChild.firstChild; if (!target || !target.repObject) return; this.pathToAppend = getPath(row); // If the object is inside an array, look up its index var valueBox = row.lastChild.firstChild; if (hasClass(valueBox, "objectBox-array")) { var arrayIndex = FirebugReps.Arr.getItemIndex(target); this.pathToAppend.push(arrayIndex); } // Make sure we get a fresh status path for the object, since otherwise // it might find the object in the existing path and not refresh it //Firebug.chrome.clearStatusPath(); this.select(target.repObject, true); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onClick: function(event) { var target = event.srcElement || event.target; var repNode = Firebug.getRepNode(target); if (repNode) { var row = getAncestorByClass(target, "memberRow"); if (row) { this.selectRow(row, repNode); cancelEvent(event); } } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "DOM", title: "DOM", searchable: true, statusSeparator: ">", options: { hasToolButtons: true, hasStatusBar: true }, create: function() { Firebug.DOMBasePanel.prototype.create.apply(this, arguments); this.onClick = bind(this.onClick, this); //TODO: xxxpedro this.onClickStatusBar = bind(this.onClickStatusBar, this); this.panelNode.style.padding = "0 1px"; }, initialize: function(oldPanelNode) { //this.panelNode.addEventListener("click", this.onClick, false); //dispatch([Firebug.A11yModel], 'onInitializeNode', [this, 'console']); Firebug.DOMBasePanel.prototype.initialize.apply(this, arguments); addEvent(this.panelNode, "click", this.onClick); // TODO: xxxpedro dom this.ishow(); //TODO: xxxpedro addEvent(this.statusBarNode, "click", this.onClickStatusBar); }, shutdown: function() { //this.panelNode.removeEventListener("click", this.onClick, false); //dispatch([Firebug.A11yModel], 'onDestroyNode', [this, 'console']); removeEvent(this.panelNode, "click", this.onClick); Firebug.DOMBasePanel.prototype.shutdown.apply(this, arguments); }/*, search: function(text, reverse) { if (!text) { delete this.currentSearch; this.highlightRow(null); return false; } var row; if (this.currentSearch && text == this.currentSearch.text) row = this.currentSearch.findNext(true, undefined, reverse, Firebug.searchCaseSensitive); else { function findRow(node) { return getAncestorByClass(node, "memberRow"); } this.currentSearch = new TextSearch(this.panelNode, findRow); row = this.currentSearch.find(text, reverse, Firebug.searchCaseSensitive); } if (row) { var sel = this.document.defaultView.getSelection(); sel.removeAllRanges(); sel.addRange(this.currentSearch.range); scrollIntoCenterView(row, this.panelNode); this.highlightRow(row); dispatch([Firebug.A11yModel], 'onDomSearchMatchFound', [this, text, row]); return true; } else { dispatch([Firebug.A11yModel], 'onDomSearchMatchFound', [this, text, null]); return false; } }/**/ }); Firebug.registerPanel(DOMMainPanel); // ************************************************************************************************ // ************************************************************************************************ // Local Helpers var getMembers = function getMembers(object, level) // we expect object to be user-level object wrapped in security blanket { if (!level) level = 0; var ordinals = [], userProps = [], userClasses = [], userFuncs = [], domProps = [], domFuncs = [], domConstants = []; try { var domMembers = getDOMMembers(object); //var domMembers = {}; // TODO: xxxpedro //var domConstantMap = {}; // TODO: xxxpedro if (object.wrappedJSObject) var insecureObject = object.wrappedJSObject; else var insecureObject = object; // IE function prototype is not listed in (for..in) if (isIE && isFunction(object)) addMember("user", userProps, "prototype", object.prototype, level); for (var name in insecureObject) // enumeration is safe { if (ignoreVars[name] == 1) // javascript.options.strict says ignoreVars is undefined. continue; var val; try { val = insecureObject[name]; // getter is safe } catch (exc) { // Sometimes we get exceptions trying to access certain members if (FBTrace.DBG_ERRORS && FBTrace.DBG_DOM) FBTrace.sysout("dom.getMembers cannot access "+name, exc); } var ordinal = parseInt(name); if (ordinal || ordinal == 0) { addMember("ordinal", ordinals, name, val, level); } else if (isFunction(val)) { if (isClassFunction(val) && !(name in domMembers)) addMember("userClass", userClasses, name, val, level); else if (name in domMembers) addMember("domFunction", domFuncs, name, val, level, domMembers[name]); else addMember("userFunction", userFuncs, name, val, level); } else { //TODO: xxxpedro /* var getterFunction = insecureObject.__lookupGetter__(name), setterFunction = insecureObject.__lookupSetter__(name), prefix = ""; if(getterFunction && !setterFunction) prefix = "get "; /**/ var prefix = ""; if (name in domMembers && !(name in domConstantMap)) addMember("dom", domProps, (prefix+name), val, level, domMembers[name]); else if (name in domConstantMap) addMember("dom", domConstants, (prefix+name), val, level); else addMember("user", userProps, (prefix+name), val, level); } } } catch (exc) { // Sometimes we get exceptions just from trying to iterate the members // of certain objects, like StorageList, but don't let that gum up the works throw exc; if (FBTrace.DBG_ERRORS && FBTrace.DBG_DOM) FBTrace.sysout("dom.getMembers FAILS: ", exc); //throw exc; } function sortName(a, b) { return a.name > b.name ? 1 : -1; } function sortOrder(a, b) { return a.order > b.order ? 1 : -1; } var members = []; members.push.apply(members, ordinals); Firebug.showUserProps = true; // TODO: xxxpedro Firebug.showUserFuncs = true; // TODO: xxxpedro Firebug.showDOMProps = true; Firebug.showDOMFuncs = true; Firebug.showDOMConstants = true; if (Firebug.showUserProps) { userProps.sort(sortName); members.push.apply(members, userProps); } if (Firebug.showUserFuncs) { userClasses.sort(sortName); members.push.apply(members, userClasses); userFuncs.sort(sortName); members.push.apply(members, userFuncs); } if (Firebug.showDOMProps) { domProps.sort(sortName); members.push.apply(members, domProps); } if (Firebug.showDOMFuncs) { domFuncs.sort(sortName); members.push.apply(members, domFuncs); } if (Firebug.showDOMConstants) members.push.apply(members, domConstants); return members; }; function expandMembers(members, toggles, offset, level) // recursion starts with offset=0, level=0 { var expanded = 0; for (var i = offset; i < members.length; ++i) { var member = members[i]; if (member.level > level) break; if ( toggles.hasOwnProperty(member.name) ) { member.open = "opened"; // member.level <= level && member.name in toggles. var newMembers = getMembers(member.value, level+1); // sets newMembers.level to level+1 var args = [i+1, 0]; args.push.apply(args, newMembers); members.splice.apply(members, args); /* if (FBTrace.DBG_DOM) { FBTrace.sysout("expandMembers member.name", member.name); FBTrace.sysout("expandMembers toggles", toggles); FBTrace.sysout("expandMembers toggles[member.name]", toggles[member.name]); FBTrace.sysout("dom.expandedMembers level: "+level+" member", member); } /**/ expanded += newMembers.length; i += newMembers.length + expandMembers(members, toggles[member.name], i+1, level+1); } } return expanded; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * function isClassFunction(fn) { try { for (var name in fn.prototype) return true; } catch (exc) {} return false; } // FIXME: xxxpedro This function is already defined in Lib. If we keep this definition here, it // will crash IE9 when not running the IE Developer Tool with JavaScript Debugging enabled!!! // Check if this function is in fact defined in Firebug for Firefox. If so, we should remove // this from here. The only difference of this function is the IE hack to show up the prototype // of functions, but Firebug no longer shows the prototype for simple functions. //var hasProperties = function hasProperties(ob) //{ // try // { // for (var name in ob) // return true; // } catch (exc) {} // // // IE function prototype is not listed in (for..in) // if (isFunction(ob)) return true; // // return false; //}; FBL.ErrorCopy = function(message) { this.message = message; }; var addMember = function addMember(type, props, name, value, level, order) { var rep = Firebug.getRep(value); // do this first in case a call to instanceof reveals contents var tag = rep.shortTag ? rep.shortTag : rep.tag; var ErrorCopy = function(){}; //TODO: xxxpedro var valueType = typeof(value); var hasChildren = hasProperties(value) && !(value instanceof ErrorCopy) && (isFunction(value) || (valueType == "object" && value != null) || (valueType == "string" && value.length > Firebug.stringCropLength)); props.push({ name: name, value: value, type: type, rowClass: "memberRow-"+type, open: "", order: order, level: level, indent: level*16, hasChildren: hasChildren, tag: tag }); }; var getWatchRowIndex = function getWatchRowIndex(row) { var index = -1; for (; row && hasClass(row, "watchRow"); row = row.previousSibling) ++index; return index; }; var getRowName = function getRowName(row) { var node = row.firstChild; return node.textContent ? node.textContent : node.innerText; }; var getRowValue = function getRowValue(row) { return row.lastChild.firstChild.repObject; }; var getRowOwnerObject = function getRowOwnerObject(row) { var parentRow = getParentRow(row); if (parentRow) return getRowValue(parentRow); }; var getParentRow = function getParentRow(row) { var level = parseInt(row.getAttribute("level"))-1; for (row = row.previousSibling; row; row = row.previousSibling) { if (parseInt(row.getAttribute("level")) == level) return row; } }; var getPath = function getPath(row) { var name = getRowName(row); var path = [name]; var level = parseInt(row.getAttribute("level"))-1; for (row = row.previousSibling; row; row = row.previousSibling) { if (parseInt(row.getAttribute("level")) == level) { var name = getRowName(row); path.splice(0, 0, name); --level; } } return path; }; // ************************************************************************************************ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ************************************************************************************************ // DOM Module Firebug.DOM = extend(Firebug.Module, { getPanel: function() { return Firebug.chrome ? Firebug.chrome.getPanel("DOM") : null; } }); Firebug.registerModule(Firebug.DOM); // ************************************************************************************************ // DOM Panel var lastHighlightedObject; function DOMSidePanel(){}; DOMSidePanel.prototype = extend(Firebug.DOMBasePanel.prototype, { selectRow: function(row, target) { if (!target) target = row.lastChild.firstChild; if (!target || !target.repObject) return; this.pathToAppend = getPath(row); // If the object is inside an array, look up its index var valueBox = row.lastChild.firstChild; if (hasClass(valueBox, "objectBox-array")) { var arrayIndex = FirebugReps.Arr.getItemIndex(target); this.pathToAppend.push(arrayIndex); } // Make sure we get a fresh status path for the object, since otherwise // it might find the object in the existing path and not refresh it //Firebug.chrome.clearStatusPath(); var object = target.repObject; if (instanceOf(object, "Element")) { Firebug.HTML.selectTreeNode(ElementCache(object)); } else { Firebug.chrome.selectPanel("DOM"); Firebug.chrome.getPanel("DOM").select(object, true); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * onClick: function(event) { /* var target = event.srcElement || event.target; var object = getAncestorByClass(target, "objectLink"); object = object ? object.repObject : null; if(!object) return; if (instanceOf(object, "Element")) { Firebug.HTML.selectTreeNode(ElementCache(object)); } else { Firebug.chrome.selectPanel("DOM"); Firebug.chrome.getPanel("DOM").select(object, true); } /**/ var target = event.srcElement || event.target; var repNode = Firebug.getRepNode(target); if (repNode) { var row = getAncestorByClass(target, "memberRow"); if (row) { this.selectRow(row, repNode); cancelEvent(event); } } /**/ }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // extends Panel name: "DOMSidePanel", parentPanel: "HTML", title: "DOM", options: { hasToolButtons: true }, isInitialized: false, create: function() { Firebug.DOMBasePanel.prototype.create.apply(this, arguments); this.onClick = bind(this.onClick, this); }, initialize: function(){ Firebug.DOMBasePanel.prototype.initialize.apply(this, arguments); addEvent(this.panelNode, "click", this.onClick); // TODO: xxxpedro css2 var selection = ElementCache.get(Firebug.context.persistedState.selectedHTMLElementId); if (selection) this.select(selection, true); }, shutdown: function() { removeEvent(this.panelNode, "click", this.onClick); Firebug.DOMBasePanel.prototype.shutdown.apply(this, arguments); }, reattach: function(oldChrome) { //this.isInitialized = oldChrome.getPanel("DOM").isInitialized; this.toggles = oldChrome.getPanel("DOMSidePanel").toggles; } }); Firebug.registerPanel(DOMSidePanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.FBTrace = {}; (function() { // ************************************************************************************************ var traceOptions = { DBG_TIMESTAMP: 1, DBG_INITIALIZE: 1, DBG_CHROME: 1, DBG_ERRORS: 1, DBG_DISPATCH: 1, DBG_CSS: 1 }; this.module = null; this.initialize = function() { if (!this.messageQueue) this.messageQueue = []; for (var name in traceOptions) this[name] = traceOptions[name]; }; // ************************************************************************************************ // FBTrace API this.sysout = function() { return this.logFormatted(arguments, ""); }; this.dumpProperties = function(title, object) { return this.logFormatted("dumpProperties() not supported.", "warning"); }; this.dumpStack = function() { return this.logFormatted("dumpStack() not supported.", "warning"); }; this.flush = function(module) { this.module = module; var queue = this.messageQueue; this.messageQueue = []; for (var i = 0; i < queue.length; ++i) this.writeMessage(queue[i][0], queue[i][1], queue[i][2]); }; this.getPanel = function() { return this.module ? this.module.getPanel() : null; }; //************************************************************************************************* this.logFormatted = function(objects, className) { var html = this.DBG_TIMESTAMP ? [getTimestamp(), " | "] : []; var length = objects.length; for (var i = 0; i < length; ++i) { appendText(" ", html); var object = objects[i]; if (i == 0) { html.push("<b>"); appendText(object, html); html.push("</b>"); } else appendText(object, html); } return this.logRow(html, className); }; this.logRow = function(message, className) { var panel = this.getPanel(); if (panel && panel.panelNode) this.writeMessage(message, className); else { this.messageQueue.push([message, className]); } return this.LOG_COMMAND; }; this.writeMessage = function(message, className) { var container = this.getPanel().containerNode; var isScrolledToBottom = container.scrollTop + container.offsetHeight >= container.scrollHeight; this.writeRow.call(this, message, className); if (isScrolledToBottom) container.scrollTop = container.scrollHeight - container.offsetHeight; }; this.appendRow = function(row) { var container = this.getPanel().panelNode; container.appendChild(row); }; this.writeRow = function(message, className) { var row = this.getPanel().panelNode.ownerDocument.createElement("div"); row.className = "logRow" + (className ? " logRow-"+className : ""); row.innerHTML = message.join(""); this.appendRow(row); }; //************************************************************************************************* function appendText(object, html) { html.push(escapeHTML(objectToString(object))); }; function getTimestamp() { var now = new Date(); var ms = "" + (now.getMilliseconds() / 1000).toFixed(3); ms = ms.substr(2); return now.toLocaleTimeString() + "." + ms; }; //************************************************************************************************* var HTMLtoEntity = { "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&#39;", '"': "&quot;" }; function replaceChars(ch) { return HTMLtoEntity[ch]; }; function escapeHTML(value) { return (value+"").replace(/[<>&"']/g, replaceChars); }; //************************************************************************************************* function objectToString(object) { try { return object+""; } catch (exc) { return null; } }; // ************************************************************************************************ }).apply(FBL.FBTrace); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // If application isn't in trace mode, the FBTrace panel won't be loaded if (!Env.Options.enableTrace) return; // ************************************************************************************************ // FBTrace Module Firebug.Trace = extend(Firebug.Module, { getPanel: function() { return Firebug.chrome ? Firebug.chrome.getPanel("Trace") : null; }, clear: function() { this.getPanel().panelNode.innerHTML = ""; } }); Firebug.registerModule(Firebug.Trace); // ************************************************************************************************ // FBTrace Panel function TracePanel(){}; TracePanel.prototype = extend(Firebug.Panel, { name: "Trace", title: "Trace", options: { hasToolButtons: true, innerHTMLSync: true }, create: function(){ Firebug.Panel.create.apply(this, arguments); this.clearButton = new Button({ caption: "Clear", title: "Clear FBTrace logs", owner: Firebug.Trace, onClick: Firebug.Trace.clear }); }, initialize: function(){ Firebug.Panel.initialize.apply(this, arguments); this.clearButton.initialize(); }, shutdown: function() { this.clearButton.shutdown(); Firebug.Panel.shutdown.apply(this, arguments); } }); Firebug.registerPanel(TracePanel); // ************************************************************************************************ }}); /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { // ************************************************************************************************ // ************************************************************************************************ // Globals var modules = []; var panelTypes = []; var panelTypeMap = {}; var parentPanelMap = {}; var registerModule = Firebug.registerModule; var registerPanel = Firebug.registerPanel; // ************************************************************************************************ append(Firebug, { extend: function(fn) { if (Firebug.chrome && Firebug.chrome.addPanel) { var namespace = ns(fn); fn.call(namespace, FBL); } else { setTimeout(function(){Firebug.extend(fn);},100); } }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Registration registerModule: function() { registerModule.apply(Firebug, arguments); modules.push.apply(modules, arguments); dispatch(modules, "initialize", []); if (FBTrace.DBG_INITIALIZE) FBTrace.sysout("Firebug.registerModule"); }, registerPanel: function() { registerPanel.apply(Firebug, arguments); panelTypes.push.apply(panelTypes, arguments); for (var i = 0, panelType; panelType = arguments[i]; ++i) { // TODO: xxxpedro investigate why Dev Panel throws an error if (panelType.prototype.name == "Dev") continue; panelTypeMap[panelType.prototype.name] = arguments[i]; var parentPanelName = panelType.prototype.parentPanel; if (parentPanelName) { parentPanelMap[parentPanelName] = 1; } else { var panelName = panelType.prototype.name; var chrome = Firebug.chrome; chrome.addPanel(panelName); // tab click handler var onTabClick = function onTabClick() { chrome.selectPanel(panelName); return false; }; chrome.addController([chrome.panelMap[panelName].tabNode, "mousedown", onTabClick]); } } if (FBTrace.DBG_INITIALIZE) for (var i = 0; i < arguments.length; ++i) FBTrace.sysout("Firebug.registerPanel", arguments[i].prototype.name); } }); // ************************************************************************************************ }}); FBL.ns(function() { with (FBL) { // ************************************************************************************************ FirebugChrome.Skin = { CSS: '.obscured{left:-999999px !important;}.collapsed{display:none;}[collapsed="true"]{display:none;}#fbCSS{padding:0 !important;}.cssPropDisable{float:left;display:block;width:2em;cursor:default;}.infoTip{z-index:2147483647;position:fixed;padding:2px 3px;border:1px solid #CBE087;background:LightYellow;font-family:Monaco,monospace;color:#000000;display:none;white-space:nowrap;pointer-events:none;}.infoTip[active="true"]{display:block;}.infoTipLoading{width:16px;height:16px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/loading_16.gif) no-repeat;}.infoTipImageBox{font-size:11px;min-width:100px;text-align:center;}.infoTipCaption{font-size:11px;font:Monaco,monospace;}.infoTipLoading > .infoTipImage,.infoTipLoading > .infoTipCaption{display:none;}h1.groupHeader{padding:2px 4px;margin:0 0 4px 0;border-top:1px solid #CCCCCC;border-bottom:1px solid #CCCCCC;background:#eee url(https://getfirebug.com/releases/lite/latest/skin/xp/group.gif) repeat-x;font-size:11px;font-weight:bold;_position:relative;}.inlineEditor,.fixedWidthEditor{z-index:2147483647;position:absolute;display:none;}.inlineEditor{margin-left:-6px;margin-top:-3px;}.textEditorInner,.fixedWidthEditor{margin:0 0 0 0 !important;padding:0;border:none !important;font:inherit;text-decoration:inherit;background-color:#FFFFFF;}.fixedWidthEditor{border-top:1px solid #888888 !important;border-bottom:1px solid #888888 !important;}.textEditorInner{position:relative;top:-7px;left:-5px;outline:none;resize:none;}.textEditorInner1{padding-left:11px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.png) repeat-y;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.gif) repeat-y;_overflow:hidden;}.textEditorInner2{position:relative;padding-right:2px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.png) repeat-y 100% 0;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorBorders.gif) repeat-y 100% 0;_position:fixed;}.textEditorTop1{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat 100% 0;margin-left:11px;height:10px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat 100% 0;_overflow:hidden;}.textEditorTop2{position:relative;left:-11px;width:11px;height:10px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat;}.textEditorBottom1{position:relative;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat 100% 100%;margin-left:11px;height:12px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat 100% 100%;}.textEditorBottom2{position:relative;left:-11px;width:11px;height:12px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.png) no-repeat 0 100%;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/textEditorCorners.gif) no-repeat 0 100%;}.panelNode-css{overflow-x:hidden;}.cssSheet > .insertBefore{height:1.5em;}.cssRule{position:relative;margin:0;padding:1em 0 0 6px;font-family:Monaco,monospace;color:#000000;}.cssRule:first-child{padding-top:6px;}.cssElementRuleContainer{position:relative;}.cssHead{padding-right:150px;}.cssProp{}.cssPropName{color:DarkGreen;}.cssPropValue{margin-left:8px;color:DarkBlue;}.cssOverridden span{text-decoration:line-through;}.cssInheritedRule{}.cssInheritLabel{margin-right:0.5em;font-weight:bold;}.cssRule .objectLink-sourceLink{top:0;}.cssProp.editGroup:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disable.png) no-repeat 2px 1px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disable.gif) no-repeat 2px 1px;}.cssProp.editGroup.editing{background:none;}.cssProp.disabledStyle{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disableHover.png) no-repeat 2px 1px;_background:url(https://getfirebug.com/releases/lite/latest/skin/xp/disableHover.gif) no-repeat 2px 1px;opacity:1;color:#CCCCCC;}.disabledStyle .cssPropName,.disabledStyle .cssPropValue{color:#CCCCCC;}.cssPropValue.editing + .cssSemi,.inlineExpander + .cssSemi{display:none;}.cssPropValue.editing{white-space:nowrap;}.stylePropName{font-weight:bold;padding:0 4px 4px 4px;width:50%;}.stylePropValue{width:50%;}.panelNode-net{overflow-x:hidden;}.netTable{width:100%;}.hideCategory-undefined .category-undefined,.hideCategory-html .category-html,.hideCategory-css .category-css,.hideCategory-js .category-js,.hideCategory-image .category-image,.hideCategory-xhr .category-xhr,.hideCategory-flash .category-flash,.hideCategory-txt .category-txt,.hideCategory-bin .category-bin{display:none;}.netHeadRow{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/group.gif) repeat-x #FFFFFF;}.netHeadCol{border-bottom:1px solid #CCCCCC;padding:2px 4px 2px 18px;font-weight:bold;}.netHeadLabel{white-space:nowrap;overflow:hidden;}.netHeaderRow{height:16px;}.netHeaderCell{cursor:pointer;-moz-user-select:none;border-bottom:1px solid #9C9C9C;padding:0 !important;font-weight:bold;background:#BBBBBB url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeader.gif) repeat-x;white-space:nowrap;}.netHeaderRow > .netHeaderCell:first-child > .netHeaderCellBox{padding:2px 14px 2px 18px;}.netHeaderCellBox{padding:2px 14px 2px 10px;border-left:1px solid #D9D9D9;border-right:1px solid #9C9C9C;}.netHeaderCell:hover:active{background:#959595 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeaderActive.gif) repeat-x;}.netHeaderSorted{background:#7D93B2 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeaderSorted.gif) repeat-x;}.netHeaderSorted > .netHeaderCellBox{border-right-color:#6B7C93;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/arrowDown.png) no-repeat right;}.netHeaderSorted.sortedAscending > .netHeaderCellBox{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/arrowUp.png);}.netHeaderSorted:hover:active{background:#536B90 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/tableHeaderSortedActive.gif) repeat-x;}.panelNode-net .netRowHeader{display:block;}.netRowHeader{cursor:pointer;display:none;height:15px;margin-right:0 !important;}.netRow .netRowHeader{background-position:5px 1px;}.netRow[breakpoint="true"] .netRowHeader{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/breakpoint.png);}.netRow[breakpoint="true"][disabledBreakpoint="true"] .netRowHeader{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/breakpointDisabled.png);}.netRow.category-xhr:hover .netRowHeader{background-color:#F6F6F6;}#netBreakpointBar{max-width:38px;}#netHrefCol > .netHeaderCellBox{border-left:0px;}.netRow .netRowHeader{width:3px;}.netInfoRow .netRowHeader{display:table-cell;}.netTable[hiddenCols~=netHrefCol] TD[id="netHrefCol"],.netTable[hiddenCols~=netHrefCol] TD.netHrefCol,.netTable[hiddenCols~=netStatusCol] TD[id="netStatusCol"],.netTable[hiddenCols~=netStatusCol] TD.netStatusCol,.netTable[hiddenCols~=netDomainCol] TD[id="netDomainCol"],.netTable[hiddenCols~=netDomainCol] TD.netDomainCol,.netTable[hiddenCols~=netSizeCol] TD[id="netSizeCol"],.netTable[hiddenCols~=netSizeCol] TD.netSizeCol,.netTable[hiddenCols~=netTimeCol] TD[id="netTimeCol"],.netTable[hiddenCols~=netTimeCol] TD.netTimeCol{display:none;}.netRow{background:LightYellow;}.netRow.loaded{background:#FFFFFF;}.netRow.loaded:hover{background:#EFEFEF;}.netCol{padding:0;vertical-align:top;border-bottom:1px solid #EFEFEF;white-space:nowrap;height:17px;}.netLabel{width:100%;}.netStatusCol{padding-left:10px;color:rgb(128,128,128);}.responseError > .netStatusCol{color:red;}.netDomainCol{padding-left:5px;}.netSizeCol{text-align:right;padding-right:10px;}.netHrefLabel{-moz-box-sizing:padding-box;overflow:hidden;z-index:10;position:absolute;padding-left:18px;padding-top:1px;max-width:15%;font-weight:bold;}.netFullHrefLabel{display:none;-moz-user-select:none;padding-right:10px;padding-bottom:3px;max-width:100%;background:#FFFFFF;z-index:200;}.netHrefCol:hover > .netFullHrefLabel{display:block;}.netRow.loaded:hover .netCol > .netFullHrefLabel{background-color:#EFEFEF;}.useA11y .a11yShowFullLabel{display:block;background-image:none !important;border:1px solid #CBE087;background-color:LightYellow;font-family:Monaco,monospace;color:#000000;font-size:10px;z-index:2147483647;}.netSizeLabel{padding-left:6px;}.netStatusLabel,.netDomainLabel,.netSizeLabel,.netBar{padding:1px 0 2px 0 !important;}.responseError{color:red;}.hasHeaders .netHrefLabel:hover{cursor:pointer;color:blue;text-decoration:underline;}.netLoadingIcon{position:absolute;border:0;margin-left:14px;width:16px;height:16px;background:transparent no-repeat 0 0;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/loading_16.gif);display:inline-block;}.loaded .netLoadingIcon{display:none;}.netBar,.netSummaryBar{position:relative;border-right:50px solid transparent;}.netResolvingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarResolving.gif) repeat-x;z-index:60;}.netConnectingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarConnecting.gif) repeat-x;z-index:50;}.netBlockingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarWaiting.gif) repeat-x;z-index:40;}.netSendingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarSending.gif) repeat-x;z-index:30;}.netWaitingBar{position:absolute;left:0;top:0;bottom:0;background:#FFFFFF url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarResponded.gif) repeat-x;z-index:20;min-width:1px;}.netReceivingBar{position:absolute;left:0;top:0;bottom:0;background:#38D63B url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarLoading.gif) repeat-x;z-index:10;}.netWindowLoadBar,.netContentLoadBar{position:absolute;left:0;top:0;bottom:0;width:1px;background-color:red;z-index:70;opacity:0.5;display:none;margin-bottom:-1px;}.netContentLoadBar{background-color:Blue;}.netTimeLabel{-moz-box-sizing:padding-box;position:absolute;top:1px;left:100%;padding-left:6px;color:#444444;min-width:16px;}.loaded .netReceivingBar,.loaded.netReceivingBar{background:#B6B6B6 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarLoaded.gif) repeat-x;border-color:#B6B6B6;}.fromCache .netReceivingBar,.fromCache.netReceivingBar{background:#D6D6D6 url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/netBarCached.gif) repeat-x;border-color:#D6D6D6;}.netSummaryRow .netTimeLabel,.loaded .netTimeLabel{background:transparent;}.timeInfoTip{width:150px; height:40px}.timeInfoTipBar,.timeInfoTipEventBar{position:relative;display:block;margin:0;opacity:1;height:15px;width:4px;}.timeInfoTipEventBar{width:1px !important;}.timeInfoTipCell.startTime{padding-right:8px;}.timeInfoTipCell.elapsedTime{text-align:right;padding-right:8px;}.sizeInfoLabelCol{font-weight:bold;padding-right:10px;font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;}.sizeInfoSizeCol{font-weight:bold;}.sizeInfoDetailCol{color:gray;text-align:right;}.sizeInfoDescCol{font-style:italic;}.netSummaryRow .netReceivingBar{background:#BBBBBB;border:none;}.netSummaryLabel{color:#222222;}.netSummaryRow{background:#BBBBBB !important;font-weight:bold;}.netSummaryRow .netBar{border-right-color:#BBBBBB;}.netSummaryRow > .netCol{border-top:1px solid #999999;border-bottom:2px solid;-moz-border-bottom-colors:#EFEFEF #999999;padding-top:1px;padding-bottom:2px;}.netSummaryRow > .netHrefCol:hover{background:transparent !important;}.netCountLabel{padding-left:18px;}.netTotalSizeCol{text-align:right;padding-right:10px;}.netTotalTimeCol{text-align:right;}.netCacheSizeLabel{position:absolute;z-index:1000;left:0;top:0;}.netLimitRow{background:rgb(255,255,225) !important;font-weight:normal;color:black;font-weight:normal;}.netLimitLabel{padding-left:18px;}.netLimitRow > .netCol{border-bottom:2px solid;-moz-border-bottom-colors:#EFEFEF #999999;vertical-align:middle !important;padding-top:2px;padding-bottom:2px;}.netLimitButton{font-size:11px;padding-top:1px;padding-bottom:1px;}.netInfoCol{border-top:1px solid #EEEEEE;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/group.gif) repeat-x #FFFFFF;}.netInfoBody{margin:10px 0 4px 10px;}.netInfoTabs{position:relative;padding-left:17px;}.netInfoTab{position:relative;top:-3px;margin-top:10px;padding:4px 6px;border:1px solid transparent;border-bottom:none;_border:none;font-weight:bold;color:#565656;cursor:pointer;}.netInfoTabSelected{cursor:default !important;border:1px solid #D7D7D7 !important;border-bottom:none !important;-moz-border-radius:4px 4px 0 0;-webkit-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;background-color:#FFFFFF;}.logRow-netInfo.error .netInfoTitle{color:red;}.logRow-netInfo.loading .netInfoResponseText{font-style:italic;color:#888888;}.loading .netInfoResponseHeadersTitle{display:none;}.netInfoResponseSizeLimit{font-family:Lucida Grande,Tahoma,sans-serif;padding-top:10px;font-size:11px;}.netInfoText{display:none;margin:0;border:1px solid #D7D7D7;border-right:none;padding:8px;background-color:#FFFFFF;font-family:Monaco,monospace;white-space:pre-wrap;}.netInfoTextSelected{display:block;}.netInfoParamName{padding-right:10px;font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;vertical-align:top;text-align:right;white-space:nowrap;}.netInfoPostText .netInfoParamName{width:1px;}.netInfoParamValue{width:100%;}.netInfoHeadersText,.netInfoPostText,.netInfoPutText{padding-top:0;}.netInfoHeadersGroup,.netInfoPostParams,.netInfoPostSource{margin-bottom:4px;border-bottom:1px solid #D7D7D7;padding-top:8px;padding-bottom:2px;font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;color:#565656;}.netInfoPostParamsTable,.netInfoPostPartsTable,.netInfoPostJSONTable,.netInfoPostXMLTable,.netInfoPostSourceTable{margin-bottom:10px;width:100%;}.netInfoPostContentType{color:#bdbdbd;padding-left:50px;font-weight:normal;}.netInfoHtmlPreview{border:0;width:100%;height:100%;}.netHeadersViewSource{color:#bdbdbd;margin-left:200px;font-weight:normal;}.netHeadersViewSource:hover{color:blue;cursor:pointer;}.netActivationRow,.netPageSeparatorRow{background:rgb(229,229,229) !important;font-weight:normal;color:black;}.netActivationLabel{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/chrome://firebug/skin/infoIcon.png) no-repeat 3px 2px;padding-left:22px;}.netPageSeparatorRow{height:5px !important;}.netPageSeparatorLabel{padding-left:22px;height:5px !important;}.netPageRow{background-color:rgb(255,255,255);}.netPageRow:hover{background:#EFEFEF;}.netPageLabel{padding:1px 0 2px 18px !important;font-weight:bold;}.netActivationRow > .netCol{border-bottom:2px solid;-moz-border-bottom-colors:#EFEFEF #999999;padding-top:2px;padding-bottom:3px;}.twisty,.logRow-errorMessage > .hasTwisty > .errorTitle,.logRow-log > .objectBox-array.hasTwisty,.logRow-spy .spyHead .spyTitle,.logGroup > .logRow,.memberRow.hasChildren > .memberLabelCell > .memberLabel,.hasHeaders .netHrefLabel,.netPageRow > .netCol > .netPageTitle{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_open.gif);background-repeat:no-repeat;background-position:2px 2px;min-height:12px;}.logRow-errorMessage > .hasTwisty.opened > .errorTitle,.logRow-log > .objectBox-array.hasTwisty.opened,.logRow-spy.opened .spyHead .spyTitle,.logGroup.opened > .logRow,.memberRow.hasChildren.opened > .memberLabelCell > .memberLabel,.nodeBox.highlightOpen > .nodeLabel > .twisty,.nodeBox.open > .nodeLabel > .twisty,.netRow.opened > .netCol > .netHrefLabel,.netPageRow.opened > .netCol > .netPageTitle{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_close.gif);}.twisty{background-position:4px 4px;}* html .logRow-spy .spyHead .spyTitle,* html .logGroup .logGroupLabel,* html .hasChildren .memberLabelCell .memberLabel,* html .hasHeaders .netHrefLabel{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_open.gif);background-repeat:no-repeat;background-position:2px 2px;}* html .opened .spyHead .spyTitle,* html .opened .logGroupLabel,* html .opened .memberLabelCell .memberLabel{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_close.gif);background-repeat:no-repeat;background-position:2px 2px;}.panelNode-console{overflow-x:hidden;}.objectLink{text-decoration:none;}.objectLink:hover{cursor:pointer;text-decoration:underline;}.logRow{position:relative;margin:0;border-bottom:1px solid #D7D7D7;padding:2px 4px 1px 6px;background-color:#FFFFFF;overflow:hidden !important;}.useA11y .logRow:focus{border-bottom:1px solid #000000 !important;outline:none !important;background-color:#FFFFAD !important;}.useA11y .logRow:focus a.objectLink-sourceLink{background-color:#FFFFAD;}.useA11y .a11yFocus:focus,.useA11y .objectBox:focus{outline:2px solid #FF9933;background-color:#FFFFAD;}.useA11y .objectBox-null:focus,.useA11y .objectBox-undefined:focus{background-color:#888888 !important;}.useA11y .logGroup.opened > .logRow{border-bottom:1px solid #ffffff;}.logGroup{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/group.gif) repeat-x #FFFFFF;padding:0 !important;border:none !important;}.logGroupBody{display:none;margin-left:16px;border-left:1px solid #D7D7D7;border-top:1px solid #D7D7D7;background:#FFFFFF;}.logGroup > .logRow{background-color:transparent !important;font-weight:bold;}.logGroup.opened > .logRow{border-bottom:none;}.logGroup.opened > .logGroupBody{display:block;}.logRow-command > .objectBox-text{font-family:Monaco,monospace;color:#0000FF;white-space:pre-wrap;}.logRow-info,.logRow-warn,.logRow-error,.logRow-assert,.logRow-warningMessage,.logRow-errorMessage{padding-left:22px;background-repeat:no-repeat;background-position:4px 2px;}.logRow-assert,.logRow-warningMessage,.logRow-errorMessage{padding-top:0;padding-bottom:0;}.logRow-info,.logRow-info .objectLink-sourceLink{background-color:#FFFFFF;}.logRow-warn,.logRow-warningMessage,.logRow-warn .objectLink-sourceLink,.logRow-warningMessage .objectLink-sourceLink{background-color:cyan;}.logRow-error,.logRow-assert,.logRow-errorMessage,.logRow-error .objectLink-sourceLink,.logRow-errorMessage .objectLink-sourceLink{background-color:LightYellow;}.logRow-error,.logRow-assert,.logRow-errorMessage{color:#FF0000;}.logRow-info{}.logRow-warn,.logRow-warningMessage{}.logRow-error,.logRow-assert,.logRow-errorMessage{}.objectBox-string,.objectBox-text,.objectBox-number,.objectLink-element,.objectLink-textNode,.objectLink-function,.objectBox-stackTrace,.objectLink-profile{font-family:Monaco,monospace;}.objectBox-string,.objectBox-text,.objectLink-textNode{white-space:pre-wrap;}.objectBox-number,.objectLink-styleRule,.objectLink-element,.objectLink-textNode{color:#000088;}.objectBox-string{color:#FF0000;}.objectLink-function,.objectBox-stackTrace,.objectLink-profile{color:DarkGreen;}.objectBox-null,.objectBox-undefined{padding:0 2px;border:1px solid #666666;background-color:#888888;color:#FFFFFF;}.objectBox-exception{padding:0 2px 0 18px;color:red;}.objectLink-sourceLink{position:absolute;right:4px;top:2px;padding-left:8px;font-family:Lucida Grande,sans-serif;font-weight:bold;color:#0000FF;}.errorTitle{margin-top:0px;margin-bottom:1px;padding-top:2px;padding-bottom:2px;}.errorTrace{margin-left:17px;}.errorSourceBox{margin:2px 0;}.errorSource-none{display:none;}.errorSource-syntax > .errorBreak{visibility:hidden;}.errorSource{cursor:pointer;font-family:Monaco,monospace;color:DarkGreen;}.errorSource:hover{text-decoration:underline;}.errorBreak{cursor:pointer;display:none;margin:0 6px 0 0;width:13px;height:14px;vertical-align:bottom;opacity:0.1;}.hasBreakSwitch .errorBreak{display:inline;}.breakForError .errorBreak{opacity:1;}.assertDescription{margin:0;}.logRow-profile > .logRow > .objectBox-text{font-family:Lucida Grande,Tahoma,sans-serif;color:#000000;}.logRow-profile > .logRow > .objectBox-text:last-child{color:#555555;font-style:italic;}.logRow-profile.opened > .logRow{padding-bottom:4px;}.profilerRunning > .logRow{padding-left:22px !important;}.profileSizer{width:100%;overflow-x:auto;overflow-y:scroll;}.profileTable{border-bottom:1px solid #D7D7D7;padding:0 0 4px 0;}.profileTable tr[odd="1"]{background-color:#F5F5F5;vertical-align:middle;}.profileTable a{vertical-align:middle;}.profileTable td{padding:1px 4px 0 4px;}.headerCell{cursor:pointer;-moz-user-select:none;border-bottom:1px solid #9C9C9C;padding:0 !important;font-weight:bold;}.headerCellBox{padding:2px 4px;border-left:1px solid #D9D9D9;border-right:1px solid #9C9C9C;}.headerCell:hover:active{}.headerSorted{}.headerSorted > .headerCellBox{border-right-color:#6B7C93;}.headerSorted.sortedAscending > .headerCellBox{}.headerSorted:hover:active{}.linkCell{text-align:right;}.linkCell > .objectLink-sourceLink{position:static;}.logRow-stackTrace{padding-top:0;background:#f8f8f8;}.logRow-stackTrace > .objectBox-stackFrame{position:relative;padding-top:2px;}.objectLink-object{font-family:Lucida Grande,sans-serif;font-weight:bold;color:DarkGreen;white-space:pre-wrap;}.objectProp-object{color:DarkGreen;}.objectProps{color:#000;font-weight:normal;}.objectPropName{color:#777;}.objectProps .objectProp-string{color:#f55;}.objectProps .objectProp-number{color:#55a;}.objectProps .objectProp-object{color:#585;}.selectorTag,.selectorId,.selectorClass{font-family:Monaco,monospace;font-weight:normal;}.selectorTag{color:#0000FF;}.selectorId{color:DarkBlue;}.selectorClass{color:red;}.selectorHidden > .selectorTag{color:#5F82D9;}.selectorHidden > .selectorId{color:#888888;}.selectorHidden > .selectorClass{color:#D86060;}.selectorValue{font-family:Lucida Grande,sans-serif;font-style:italic;color:#555555;}.panelNode.searching .logRow{display:none;}.logRow.matched{display:block !important;}.logRow.matching{position:absolute;left:-1000px;top:-1000px;max-width:0;max-height:0;overflow:hidden;}.objectLeftBrace,.objectRightBrace,.objectEqual,.objectComma,.arrayLeftBracket,.arrayRightBracket,.arrayComma{font-family:Monaco,monospace;}.objectLeftBrace,.objectRightBrace,.arrayLeftBracket,.arrayRightBracket{font-weight:bold;}.objectLeftBrace,.arrayLeftBracket{margin-right:4px;}.objectRightBrace,.arrayRightBracket{margin-left:4px;}.logRow-dir{padding:0;}.logRow-errorMessage .hasTwisty .errorTitle,.logRow-spy .spyHead .spyTitle,.logGroup .logRow{cursor:pointer;padding-left:18px;background-repeat:no-repeat;background-position:3px 3px;}.logRow-errorMessage > .hasTwisty > .errorTitle{background-position:2px 3px;}.logRow-errorMessage > .hasTwisty > .errorTitle:hover,.logRow-spy .spyHead .spyTitle:hover,.logGroup > .logRow:hover{text-decoration:underline;}.logRow-spy{padding:0 !important;}.logRow-spy,.logRow-spy .objectLink-sourceLink{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/group.gif) repeat-x #FFFFFF;padding-right:4px;right:0;}.logRow-spy.opened{padding-bottom:4px;border-bottom:none;}.spyTitle{color:#000000;font-weight:bold;-moz-box-sizing:padding-box;overflow:hidden;z-index:100;padding-left:18px;}.spyCol{padding:0;white-space:nowrap;height:16px;}.spyTitleCol:hover > .objectLink-sourceLink,.spyTitleCol:hover > .spyTime,.spyTitleCol:hover > .spyStatus,.spyTitleCol:hover > .spyTitle{display:none;}.spyFullTitle{display:none;-moz-user-select:none;max-width:100%;background-color:Transparent;}.spyTitleCol:hover > .spyFullTitle{display:block;}.spyStatus{padding-left:10px;color:rgb(128,128,128);}.spyTime{margin-left:4px;margin-right:4px;color:rgb(128,128,128);}.spyIcon{margin-right:4px;margin-left:4px;width:16px;height:16px;vertical-align:middle;background:transparent no-repeat 0 0;display:none;}.loading .spyHead .spyRow .spyIcon{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/loading_16.gif);display:block;}.logRow-spy.loaded:not(.error) .spyHead .spyRow .spyIcon{width:0;margin:0;}.logRow-spy.error .spyHead .spyRow .spyIcon{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon-sm.png);display:block;background-position:2px 2px;}.logRow-spy .spyHead .netInfoBody{display:none;}.logRow-spy.opened .spyHead .netInfoBody{margin-top:10px;display:block;}.logRow-spy.error .spyTitle,.logRow-spy.error .spyStatus,.logRow-spy.error .spyTime{color:red;}.logRow-spy.loading .spyResponseText{font-style:italic;color:#888888;}.caption{font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;color:#444444;}.warning{padding:10px;font-family:Lucida Grande,Tahoma,sans-serif;font-weight:bold;color:#888888;}.panelNode-dom{overflow-x:hidden !important;}.domTable{font-size:1em;width:100%;table-layout:fixed;background:#fff;}.domTableIE{width:auto;}.memberLabelCell{padding:2px 0 2px 0;vertical-align:top;}.memberValueCell{padding:1px 0 1px 5px;display:block;overflow:hidden;}.memberLabel{display:block;cursor:default;-moz-user-select:none;overflow:hidden;padding-left:18px;background-color:#FFFFFF;text-decoration:none;}.memberRow.hasChildren .memberLabelCell .memberLabel:hover{cursor:pointer;color:blue;text-decoration:underline;}.userLabel{color:#000000;font-weight:bold;}.userClassLabel{color:#E90000;font-weight:bold;}.userFunctionLabel{color:#025E2A;font-weight:bold;}.domLabel{color:#000000;}.domFunctionLabel{color:#025E2A;}.ordinalLabel{color:SlateBlue;font-weight:bold;}.scopesRow{padding:2px 18px;background-color:LightYellow;border-bottom:5px solid #BEBEBE;color:#666666;}.scopesLabel{background-color:LightYellow;}.watchEditCell{padding:2px 18px;background-color:LightYellow;border-bottom:1px solid #BEBEBE;color:#666666;}.editor-watchNewRow,.editor-memberRow{font-family:Monaco,monospace !important;}.editor-memberRow{padding:1px 0 !important;}.editor-watchRow{padding-bottom:0 !important;}.watchRow > .memberLabelCell{font-family:Monaco,monospace;padding-top:1px;padding-bottom:1px;}.watchRow > .memberLabelCell > .memberLabel{background-color:transparent;}.watchRow > .memberValueCell{padding-top:2px;padding-bottom:2px;}.watchRow > .memberLabelCell,.watchRow > .memberValueCell{background-color:#F5F5F5;border-bottom:1px solid #BEBEBE;}.watchToolbox{z-index:2147483647;position:absolute;right:0;padding:1px 2px;}#fbConsole{overflow-x:hidden !important;}#fbCSS{font:1em Monaco,monospace;padding:0 7px;}#fbstylesheetButtons select,#fbScriptButtons select{font:11px Lucida Grande,Tahoma,sans-serif;margin-top:1px;padding-left:3px;background:#fafafa;border:1px inset #fff;width:220px;outline:none;}.Selector{margin-top:10px}.CSSItem{margin-left:4%}.CSSText{padding-left:20px;}.CSSProperty{color:#005500;}.CSSValue{padding-left:5px; color:#000088;}#fbHTMLStatusBar{display:inline;}.fbToolbarButtons{display:none;}.fbStatusSeparator{display:block;float:left;padding-top:4px;}#fbStatusBarBox{display:none;}#fbToolbarContent{display:block;position:absolute;_position:absolute;top:0;padding-top:4px;height:23px;clip:rect(0,2048px,27px,0);}.fbTabMenuTarget{display:none !important;float:left;width:10px;height:10px;margin-top:6px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuTarget.png);}.fbTabMenuTarget:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuTargetHover.png);}.fbShadow{float:left;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/shadowAlpha.png) no-repeat bottom right !important;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/shadow2.gif) no-repeat bottom right;margin:10px 0 0 10px !important;margin:10px 0 0 5px;}.fbShadowContent{display:block;position:relative;background-color:#fff;border:1px solid #a9a9a9;top:-6px;left:-6px;}.fbMenu{display:none;position:absolute;font-size:11px;line-height:13px;z-index:2147483647;}.fbMenuContent{padding:2px;}.fbMenuSeparator{display:block;position:relative;padding:1px 18px 0;text-decoration:none;color:#000;cursor:default;background:#ACA899;margin:4px 0;}.fbMenuOption{display:block;position:relative;padding:2px 18px;text-decoration:none;color:#000;cursor:default;}.fbMenuOption:hover{color:#fff;background:#316AC5;}.fbMenuGroup{background:transparent url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuPin.png) no-repeat right 0;}.fbMenuGroup:hover{background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuPin.png) no-repeat right -17px;}.fbMenuGroupSelected{color:#fff;background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuPin.png) no-repeat right -17px;}.fbMenuChecked{background:transparent url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuCheckbox.png) no-repeat 4px 0;}.fbMenuChecked:hover{background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuCheckbox.png) no-repeat 4px -17px;}.fbMenuRadioSelected{background:transparent url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuRadio.png) no-repeat 4px 0;}.fbMenuRadioSelected:hover{background:#316AC5 url(https://getfirebug.com/releases/lite/latest/skin/xp/tabMenuRadio.png) no-repeat 4px -17px;}.fbMenuShortcut{padding-right:85px;}.fbMenuShortcutKey{position:absolute;right:0;top:2px;width:77px;}#fbFirebugMenu{top:22px;left:0;}.fbMenuDisabled{color:#ACA899 !important;}#fbFirebugSettingsMenu{left:245px;top:99px;}#fbConsoleMenu{top:42px;left:48px;}.fbIconButton{display:block;}.fbIconButton{display:block;}.fbIconButton{display:block;float:left;height:20px;width:20px;color:#000;margin-right:2px;text-decoration:none;cursor:default;}.fbIconButton:hover{position:relative;top:-1px;left:-1px;margin-right:0;_margin-right:1px;color:#333;border:1px solid #fff;border-bottom:1px solid #bbb;border-right:1px solid #bbb;}.fbIconPressed{position:relative;margin-right:0;_margin-right:1px;top:0 !important;left:0 !important;height:19px;color:#333 !important;border:1px solid #bbb !important;border-bottom:1px solid #cfcfcf !important;border-right:1px solid #ddd !important;}#fbErrorPopup{position:absolute;right:0;bottom:0;height:19px;width:75px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;z-index:999;}#fbErrorPopupContent{position:absolute;right:0;top:1px;height:18px;width:75px;_width:74px;border-left:1px solid #aca899;}#fbErrorIndicator{position:absolute;top:2px;right:5px;}.fbBtnInspectActive{background:#aaa;color:#fff !important;}.fbBody{margin:0;padding:0;overflow:hidden;font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;background:#fff;}.clear{clear:both;}#fbMiniChrome{display:none;right:0;height:27px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;margin-left:1px;}#fbMiniContent{display:block;position:relative;left:-1px;right:0;top:1px;height:25px;border-left:1px solid #aca899;}#fbToolbarSearch{float:right;border:1px solid #ccc;margin:0 5px 0 0;background:#fff url(https://getfirebug.com/releases/lite/latest/skin/xp/search.png) no-repeat 4px 2px !important;background:#fff url(https://getfirebug.com/releases/lite/latest/skin/xp/search.gif) no-repeat 4px 2px;padding-left:20px;font-size:11px;}#fbToolbarErrors{float:right;margin:1px 4px 0 0;font-size:11px;}#fbLeftToolbarErrors{float:left;margin:7px 0px 0 5px;font-size:11px;}.fbErrors{padding-left:20px;height:14px;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.png) no-repeat !important;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.gif) no-repeat;color:#f00;font-weight:bold;}#fbMiniErrors{display:inline;display:none;float:right;margin:5px 2px 0 5px;}#fbMiniIcon{float:right;margin:3px 4px 0;height:20px;width:20px;float:right;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -135px;cursor:pointer;}#fbChrome{font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;position:absolute;_position:static;top:0;left:0;height:100%;width:100%;border-collapse:collapse;border-spacing:0;background:#fff;overflow:hidden;}#fbChrome > tbody > tr > td{padding:0;}#fbTop{height:49px;}#fbToolbar{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;height:27px;font-size:11px;line-height:13px;}#fbPanelBarBox{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #dbd9c9 0 -27px;height:22px;}#fbContent{height:100%;vertical-align:top;}#fbBottom{height:18px;background:#fff;}#fbToolbarIcon{float:left;padding:0 5px 0;}#fbToolbarIcon a{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -135px;}#fbToolbarButtons{padding:0 2px 0 5px;}#fbToolbarButtons{padding:0 2px 0 5px;}.fbButton{text-decoration:none;display:block;float:left;color:#000;padding:4px 6px 4px 7px;cursor:default;}.fbButton:hover{color:#333;background:#f5f5ef url(https://getfirebug.com/releases/lite/latest/skin/xp/buttonBg.png);padding:3px 5px 3px 6px;border:1px solid #fff;border-bottom:1px solid #bbb;border-right:1px solid #bbb;}.fbBtnPressed{background:#e3e3db url(https://getfirebug.com/releases/lite/latest/skin/xp/buttonBgHover.png) !important;padding:3px 4px 2px 6px !important;margin:1px 0 0 1px !important;border:1px solid #ACA899 !important;border-color:#ACA899 #ECEBE3 #ECEBE3 #ACA899 !important;}#fbStatusBarBox{top:4px;cursor:default;}.fbToolbarSeparator{overflow:hidden;border:1px solid;border-color:transparent #fff transparent #777;_border-color:#eee #fff #eee #777;height:7px;margin:6px 3px;float:left;}.fbBtnSelected{font-weight:bold;}.fbStatusBar{color:#aca899;}.fbStatusBar a{text-decoration:none;color:black;}.fbStatusBar a:hover{color:blue;cursor:pointer;}#fbWindowButtons{position:absolute;white-space:nowrap;right:0;top:0;height:17px;width:48px;padding:5px;z-index:6;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 0;}#fbPanelBar1{width:1024px; z-index:8;left:0;white-space:nowrap;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #dbd9c9 0 -27px;position:absolute;left:4px;}#fbPanelBar2Box{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #dbd9c9 0 -27px;position:absolute;height:22px;width:300px; z-index:9;right:0;}#fbPanelBar2{position:absolute;width:290px; height:22px;padding-left:4px;}.fbPanel{display:none;}#fbPanelBox1,#fbPanelBox2{max-height:inherit;height:100%;font-size:1em;}#fbPanelBox2{background:#fff;}#fbPanelBox2{width:300px;background:#fff;}#fbPanel2{margin-left:6px;background:#fff;}#fbLargeCommandLine{display:none;position:absolute;z-index:9;top:27px;right:0;width:294px;height:201px;border-width:0;margin:0;padding:2px 0 0 2px;resize:none;outline:none;font-size:11px;overflow:auto;border-top:1px solid #B9B7AF;_right:-1px;_border-left:1px solid #fff;}#fbLargeCommandButtons{display:none;background:#ECE9D8;bottom:0;right:0;width:294px;height:21px;padding-top:1px;position:fixed;border-top:1px solid #ACA899;z-index:9;}#fbSmallCommandLineIcon{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/down.png) no-repeat;position:absolute;right:2px;bottom:3px;z-index:99;}#fbSmallCommandLineIcon:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/downHover.png) no-repeat;}.hide{overflow:hidden !important;position:fixed !important;display:none !important;visibility:hidden !important;}#fbCommand{height:18px;}#fbCommandBox{position:fixed;_position:absolute;width:100%;height:18px;bottom:0;overflow:hidden;z-index:9;background:#fff;border:0;border-top:1px solid #ccc;}#fbCommandIcon{position:absolute;color:#00f;top:2px;left:6px;display:inline;font:11px Monaco,monospace;z-index:10;}#fbCommandLine{position:absolute;width:100%;top:0;left:0;border:0;margin:0;padding:2px 0 2px 32px;font:11px Monaco,monospace;z-index:9;outline:none;}#fbLargeCommandLineIcon{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/up.png) no-repeat;position:absolute;right:1px;bottom:1px;z-index:10;}#fbLargeCommandLineIcon:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/upHover.png) no-repeat;}div.fbFitHeight{overflow:auto;position:relative;}.fbSmallButton{overflow:hidden;width:16px;height:16px;display:block;text-decoration:none;cursor:default;}#fbWindowButtons .fbSmallButton{float:right;}#fbWindow_btClose{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/min.png);}#fbWindow_btClose:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/minHover.png);}#fbWindow_btDetach{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/detach.png);}#fbWindow_btDetach:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/detachHover.png);}#fbWindow_btDeactivate{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/off.png);}#fbWindow_btDeactivate:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/offHover.png);}.fbTab{text-decoration:none;display:none;float:left;width:auto;float:left;cursor:default;font-family:Lucida Grande,Tahoma,sans-serif;font-size:11px;line-height:13px;font-weight:bold;height:22px;color:#565656;}.fbPanelBar span{float:left;}.fbPanelBar .fbTabL,.fbPanelBar .fbTabR{height:22px;width:8px;}.fbPanelBar .fbTabText{padding:4px 1px 0;}a.fbTab:hover{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -73px;}a.fbTab:hover .fbTabL{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) -16px -96px;}a.fbTab:hover .fbTabR{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) -24px -96px;}.fbSelectedTab{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) #f1f2ee 0 -50px !important;color:#000;}.fbSelectedTab .fbTabL{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) 0 -96px !important;}.fbSelectedTab .fbTabR{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png) -8px -96px !important;}#fbHSplitter{position:fixed;_position:absolute;left:0;top:0;width:100%;height:5px;overflow:hidden;cursor:n-resize !important;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/pixel_transparent.gif);z-index:9;}#fbHSplitter.fbOnMovingHSplitter{height:100%;z-index:100;}.fbVSplitter{background:#ece9d8;color:#000;border:1px solid #716f64;border-width:0 1px;border-left-color:#aca899;width:4px;cursor:e-resize;overflow:hidden;right:294px;text-decoration:none;z-index:10;position:absolute;height:100%;top:27px;}div.lineNo{font:1em/1.4545em Monaco,monospace;position:relative;float:left;top:0;left:0;margin:0 5px 0 0;padding:0 5px 0 10px;background:#eee;color:#888;border-right:1px solid #ccc;text-align:right;}.sourceBox{position:absolute;}.sourceCode{font:1em Monaco,monospace;overflow:hidden;white-space:pre;display:inline;}.nodeControl{margin-top:3px;margin-left:-14px;float:left;width:9px;height:9px;overflow:hidden;cursor:default;background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_open.gif);_float:none;_display:inline;_position:absolute;}div.nodeMaximized{background:url(https://getfirebug.com/releases/lite/latest/skin/xp/tree_close.gif);}div.objectBox-element{padding:1px 3px;}.objectBox-selector{cursor:default;}.selectedElement{background:highlight;color:#fff !important;}.selectedElement span{color:#fff !important;}* html .selectedElement{position:relative;}@media screen and (-webkit-min-device-pixel-ratio:0){.selectedElement{background:#316AC5;color:#fff !important;}}.logRow *{font-size:1em;}.logRow{position:relative;border-bottom:1px solid #D7D7D7;padding:2px 4px 1px 6px;zbackground-color:#FFFFFF;}.logRow-command{font-family:Monaco,monospace;color:blue;}.objectBox-string,.objectBox-text,.objectBox-number,.objectBox-function,.objectLink-element,.objectLink-textNode,.objectLink-function,.objectBox-stackTrace,.objectLink-profile{font-family:Monaco,monospace;}.objectBox-null{padding:0 2px;border:1px solid #666666;background-color:#888888;color:#FFFFFF;}.objectBox-string{color:red;}.objectBox-number{color:#000088;}.objectBox-function{color:DarkGreen;}.objectBox-object{color:DarkGreen;font-weight:bold;font-family:Lucida Grande,sans-serif;}.objectBox-array{color:#000;}.logRow-info,.logRow-error,.logRow-warn{background:#fff no-repeat 2px 2px;padding-left:20px;padding-bottom:3px;}.logRow-info{background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/infoIcon.png) !important;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/infoIcon.gif);}.logRow-warn{background-color:cyan;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/warningIcon.png) !important;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/warningIcon.gif);}.logRow-error{background-color:LightYellow;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.png) !important;background-image:url(https://getfirebug.com/releases/lite/latest/skin/xp/errorIcon.gif);color:#f00;}.errorMessage{vertical-align:top;color:#f00;}.objectBox-sourceLink{position:absolute;right:4px;top:2px;padding-left:8px;font-family:Lucida Grande,sans-serif;font-weight:bold;color:#0000FF;}.selectorTag,.selectorId,.selectorClass{font-family:Monaco,monospace;font-weight:normal;}.selectorTag{color:#0000FF;}.selectorId{color:DarkBlue;}.selectorClass{color:red;}.objectBox-element{font-family:Monaco,monospace;color:#000088;}.nodeChildren{padding-left:26px;}.nodeTag{color:blue;cursor:pointer;}.nodeValue{color:#FF0000;font-weight:normal;}.nodeText,.nodeComment{margin:0 2px;vertical-align:top;}.nodeText{color:#333333;font-family:Monaco,monospace;}.nodeComment{color:DarkGreen;}.nodeHidden,.nodeHidden *{color:#888888;}.nodeHidden .nodeTag{color:#5F82D9;}.nodeHidden .nodeValue{color:#D86060;}.selectedElement .nodeHidden,.selectedElement .nodeHidden *{color:SkyBlue !important;}.log-object{}.property{position:relative;clear:both;height:15px;}.propertyNameCell{vertical-align:top;float:left;width:28%;position:absolute;left:0;z-index:0;}.propertyValueCell{float:right;width:68%;background:#fff;position:absolute;padding-left:5px;display:table-cell;right:0;z-index:1;}.propertyName{font-weight:bold;}.FirebugPopup{height:100% !important;}.FirebugPopup #fbWindowButtons{display:none !important;}.FirebugPopup #fbHSplitter{display:none !important;}', HTML: '<table id="fbChrome" cellpadding="0" cellspacing="0" border="0"><tbody><tr><td id="fbTop" colspan="2"><div id="fbWindowButtons"><a id="fbWindow_btDeactivate" class="fbSmallButton fbHover" title="Deactivate Firebug for this web page">&nbsp;</a><a id="fbWindow_btDetach" class="fbSmallButton fbHover" title="Open Firebug in popup window">&nbsp;</a><a id="fbWindow_btClose" class="fbSmallButton fbHover" title="Minimize Firebug">&nbsp;</a></div><div id="fbToolbar"><div id="fbToolbarContent"><span id="fbToolbarIcon"><a id="fbFirebugButton" class="fbIconButton" class="fbHover" target="_blank">&nbsp;</a></span><span id="fbToolbarButtons"><span id="fbFixedButtons"><a id="fbChrome_btInspect" class="fbButton fbHover" title="Click an element in the page to inspect">Inspect</a></span><span id="fbConsoleButtons" class="fbToolbarButtons"><a id="fbConsole_btClear" class="fbButton fbHover" title="Clear the console">Clear</a></span></span><span id="fbStatusBarBox"><span class="fbToolbarSeparator"></span></span></div></div><div id="fbPanelBarBox"><div id="fbPanelBar1" class="fbPanelBar"><a id="fbConsoleTab" class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">Console</span><span class="fbTabMenuTarget"></span><span class="fbTabR"></span></a><a id="fbHTMLTab" class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">HTML</span><span class="fbTabR"></span></a><a class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">CSS</span><span class="fbTabR"></span></a><a class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">Script</span><span class="fbTabR"></span></a><a class="fbTab fbHover"><span class="fbTabL"></span><span class="fbTabText">DOM</span><span class="fbTabR"></span></a></div><div id="fbPanelBar2Box" class="hide"><div id="fbPanelBar2" class="fbPanelBar"></div></div></div><div id="fbHSplitter">&nbsp;</div></td></tr><tr id="fbContent"><td id="fbPanelBox1"><div id="fbPanel1" class="fbFitHeight"><div id="fbConsole" class="fbPanel"></div><div id="fbHTML" class="fbPanel"></div></div></td><td id="fbPanelBox2" class="hide"><div id="fbVSplitter" class="fbVSplitter">&nbsp;</div><div id="fbPanel2" class="fbFitHeight"><div id="fbHTML_Style" class="fbPanel"></div><div id="fbHTML_Layout" class="fbPanel"></div><div id="fbHTML_DOM" class="fbPanel"></div></div><textarea id="fbLargeCommandLine" class="fbFitHeight"></textarea><div id="fbLargeCommandButtons"><a id="fbCommand_btRun" class="fbButton fbHover">Run</a><a id="fbCommand_btClear" class="fbButton fbHover">Clear</a><a id="fbSmallCommandLineIcon" class="fbSmallButton fbHover"></a></div></td></tr><tr id="fbBottom" class="hide"><td id="fbCommand" colspan="2"><div id="fbCommandBox"><div id="fbCommandIcon">&gt;&gt;&gt;</div><input id="fbCommandLine" name="fbCommandLine" type="text"/><a id="fbLargeCommandLineIcon" class="fbSmallButton fbHover"></a></div></td></tr></tbody></table><span id="fbMiniChrome"><span id="fbMiniContent"><span id="fbMiniIcon" title="Open Firebug Lite"></span><span id="fbMiniErrors" class="fbErrors"></span></span></span>' }; // ************************************************************************************************ }}); // ************************************************************************************************ FBL.initialize(); // ************************************************************************************************ })();
app/scripts/components/matched-results.js
hustbill/network-verification-ui
import React from 'react'; import MatchedText from './matched-text'; const SHOW_ROW_COUNT = 2; const MAX_MATCH_LENGTH = 24; const Match = match => ( <div className="matched-results-match" key={match.label}> <div className="matched-results-match-wrapper"> <span className="matched-results-match-label"> {match.label}: </span> <MatchedText text={match.text} match={match} maxLength={MAX_MATCH_LENGTH} truncate={match.truncate} /> </div> </div> ); export default class MatchedResults extends React.PureComponent { render() { const { matches, style } = this.props; if (!matches) { return null; } let moreFieldMatches; let moreFieldMatchesTitle; if (matches.size > SHOW_ROW_COUNT) { moreFieldMatches = matches .valueSeq() .skip(SHOW_ROW_COUNT) .map(field => field.label); moreFieldMatchesTitle = `More matches:\n${moreFieldMatches.join(',\n')}`; } return ( <div className="matched-results" style={style}> {matches.keySeq().take(SHOW_ROW_COUNT).map(fieldId => Match(matches.get(fieldId)))} {moreFieldMatches && <div className="matched-results-more" title={moreFieldMatchesTitle}> {`${moreFieldMatches.size} more matches`} </div>} </div> ); } }
ui/app/index.js
mmadej85/todo-list
import './styles/app.css' import React from 'react'; import ReactDOM from 'react-dom'; import TaskBox from './components/TaskBox.jsx'; import {CONFIG} from './constants/constants'; ReactDOM.render(<TaskBox url={CONFIG.urlTasks} pollInterval={CONFIG.pollInterval} />, document.getElementById('root'));
ajax/libs/yui/3.4.1pr1/yui/yui-debug.js
melvinsembrano/cdnjs
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. If YUI is already defined, the existing YUI object will not be overwritten so that defined namespaces are preserved. It is the constructor for the object the end user interacts with. As indicated below, each instance has full custom event support, but only if the event system is available. This is a self-instantiable factory function. You can invoke it directly like this: YUI().use('*', function(Y) { // ready }); But it also works like this: var Y = YUI(); @class YUI @constructor @global @uses EventTarget @param o* {Object} 0..n optional configuration objects. these values are store in Y.config. See <a href="config.html">Config</a> for the list of supported properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** YUI.GlobalConfig is a master configuration that might span multiple contexts in a non-browser environment. It is applied first to all instances in all contexts. @property GlobalConfig @type {Object} @global @static @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** YUI_config is a page-level config. It is applied to all instances created on the page. This is applied after YUI.GlobalConfig, and before the instance level configuration objects. @global @property YUI_config @type {Object} @example //Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, [ 'loader-base', 'loader-rollup', 'loader-yui3' ])); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {Object} o the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, rls = config.rls, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (rls && name == 'rls') { clobber(rls, attr); } else if (name == 'win') { config[name] = attr.contentWindow || attr; config.doc = config[name].document; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { win: win, doc: doc, debug: true, useBrowserConsole: true, throwFail: true, bootstrap: true, cacheUse: true, fetchCSS: true, use_rls: false, rls_timeout: 2000 }; if (YUI.Env.rls_disabled) { Y.config.use_rls = false; } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, //extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3']; extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } // Y.log(Y.id + ' initialized', 'info', 'yui'); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m.apply(instance, args); } return null; }, /** Registers a module with the YUI global. The easiest way to create a first-class YUI module is to use the YUI component build tool. http://yuilibrary.com/projects/builder The build system will produce the `YUI.add` wrapper for you module, along with any configuration info required for the module. @method add @param name {String} module name. @param fn {Function} entry point into the module that is used to bind module to the YUI instance. @param {YUI} fn.Y The YUI instance this module is executed in. @param {String} fn.name The name of the module @param version {String} version string. @param details {Object} optional config data: @param details.requires {Array} features that must be present before this module can be attached. @param details.optional {Array} optional features that should be present if loadOptional is defined. Note: modules are not often loaded this way in YUI 3, but this field is still useful to inform the user that certain features in the component will require additional dependencies. @param details.use {Array} features that are included within this module which need to be attached automatically when this module is attached. This supports the YUI 3 rollup system -- a module with submodules defined will need to have the submodules listed in the 'use' config. The YUI component build tool does this for you. @return {YUI} the YUI instance. @example YUI.add('davglass', function(Y, name) { Y.davglass = function() { alert('Dav was here!'); }; }, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] }); */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name]) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @param {Array} r The array of modules to attach * @param {Boolean} [moot=false] Don't throw a warning if the module is not attached * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { Y.Object.each(loader.conditions[name], function(def) { var go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } }); } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } // Y.log('no js def for: ' + name, 'info', 'yui'); //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { if (!names.length) { return; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = false; Y._use(args, function() { Y.log('Nested use callback: ' + data, 'info', 'yui'); if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { // Y.log('attaching from loader: ' + data, 'info', 'yui'); ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui'); // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } // Y.log('before loader requirements: ' + args, 'info', 'yui'); // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui'); } // dynamic load if (boot && len && Y.Loader) { // Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui'); Y.log('Using Loader', 'info', 'yui'); Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); // loader.partial(missing, (fetchCSS) ? null : 'js'); } else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) { G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue(); // server side loader service handleRLS = function(instance, argz) { var rls_end = function(o) { handleLoader(o); instance.rls_advance(); }, rls_url = instance._rls(argz); if (rls_url) { Y.log('Fetching RLS url', 'info', 'rls'); instance.rls_oncomplete(function(o) { rls_end(o); }); instance.Get.script(rls_url, { data: argz, timeout: instance.config.rls_timeout, onFailure: instance.rls_handleFailure, onTimeout: instance.rls_handleTimeout }); } else { rls_end({ success: true, data: argz }); } }; G_ENV._rls_queue.add(function() { Y.log('executing queued rls request', 'info', 'rls'); G_ENV._rls_in_progress = true; Y.rls_callback = callback; Y.rls_locals(Y, args, handleRLS); }); if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) { G_ENV._rls_queue.next()(); } } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { Y.log('Waiting for loader', 'info', 'yui'); queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui'); Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { Y.log('Attaching available dependencies: ' + args, 'info', 'yui'); ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Adds a namespace object onto the YUI global if called statically. // creates YUI.your.namespace.here as nested objects YUI.namespace("your.namespace.here"); If called as a method on a YUI <em>instance</em>, it creates the namespace on the instance. // creates Y.property.package Y.namespace("property.package"); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", the token is discarded. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace("really.long.nested.namespace"); @method namespace @param {String} namespace* namespaces to create. @return {Object} A reference to the last namespace object created. **/ namespace: function() { var a = arguments, o = this, i = 0, j, d, arg; for (; i < a.length; i++) { // d = ('' + a[i]).split('.'); arg = a[i]; if (arg.indexOf(PERIOD)) { d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param data Optional additional info * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, data) { var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error'); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default). * * @property core * @type string[] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js' * } * } * * @property modules * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.8.1 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 1 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * The parameter defaults for the remote loader service. **Requires the rls seed file.** The properties that are supported: * * * `m`: comma separated list of module requirements. This * must be the param name even for custom implemetations. * * `v`: the version of YUI to load. Defaults to the version * of YUI that is being used. * * `gv`: the version of the gallery to load (see the gallery config) * * `env`: comma separated list of modules already on the page. * this must be the param name even for custom implemetations. * * `lang`: the languages supported on the page (see the lang config) * * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config). * * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers * * `filt`: a filter def to apply to the urls (see the filter config). * * `filts`: a list of custom filters to apply per module * * `tests`: this is a map of conditional module test function id keys * with the values of 1 if the test passes, 0 if not. This must be * the name of the querystring param in custom templates. * * @since 3.2.0 * @property rls * @type {Object} */ /** * The base path to the remote loader service. **Requires the rls seed file.** * * @since 3.2.0 * @property rls_base * @type {String} */ /** * The template to use for building the querystring portion * of the remote loader service url. The default is determined * by the rls config -- each property that has a value will be * represented. **Requires the rls seed file.** * * @since 3.2.0 * @property rls_tmpl * @type {String} * @example * m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests} * */ /** * Configure the instance to use a remote loader service instead of * the client loader. **Requires the rls seed file.** * * @since 3.2.0 * @property use_rls * @type {Boolean} */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementation. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype); /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = (!unsafeNatives && Array.isArray) || function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * <p> * Returns a string representing the type of the item passed in. * </p> * * <p> * Known issues: * </p> * * <ul> * <li> * <code>typeof HTMLElementCollection</code> returns function in Safari, but * <code>Y.type()</code> reports object, which could be a good thing -- * but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. * </li> * </ul> * * @method type * @param o the item to test. * @return {string} the detected type. * @static */ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Native.indexOf ? function (array, value) { // TODO: support fromIndex return Native.indexOf.call(array, value); } : function (array, value) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && array[i] === value) { return i; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Native.some ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var hasOwn = Object.prototype.hasOwnProperty, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementations. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype), UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type {Boolean} * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = (!unsafeNatives && Object.keys) || function (obj) { if (!Y.Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; for (key in obj) { if (owns(obj, key)) { keys.push(key); } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Y.Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(obj).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @returns {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome o.safari = 0; //Reset safari back to 0 } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //It was a parsed UA, do not assign the global value. if (!subUA) { YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["controller","model","model-list","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"] }; }, '@VERSION@' ); YUI.add('get', function(Y) { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ var ua = Y.UA, L = Y.Lang, TYPE_JS = 'text/javascript', TYPE_CSS = 'text/css', STYLESHEET = 'stylesheet', SCRIPT = 'script', AUTOPURGE = 'autopurge', UTF8 = 'utf-8', LINK = 'link', ASYNC = 'async', ALL = true, // FireFox does not support the onload event for link nodes, so // there is no way to make the css requests synchronous. This means // that the css rules in multiple files could be applied out of order // in this browser if a later request returns before an earlier one. // Safari too. ONLOAD_SUPPORTED = { script: ALL, css: !(ua.webkit || ua.gecko) }, /** * hash of queues to manage multiple requests * @property queues * @private */ queues = {}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx = 0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging, /** * Clear timeout state * * @method _clearTimeout * @param {Object} q Queue data * @private */ _clearTimeout = function(q) { var timer = q.timer; if (timer) { clearTimeout(timer); q.timer = null; } }, /** * Generates an HTML element, this is not appended to a document * @method _node * @param {string} type the type of element. * @param {Object} attr the fixed set of attribute for the type. * @param {Object} custAttrs optional Any custom attributes provided by the user. * @param {Window} win optional window to create the element in. * @return {HTMLElement} the generated node. * @private */ _node = function(type, attr, custAttrs, win) { var w = win || Y.config.win, d = w.document, n = d.createElement(type), i; if (custAttrs) { Y.mix(attr, custAttrs); } for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param {string} url the url for the css file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _linkNode = function(url, win, attributes) { return _node(LINK, { id: Y.guid(), type: TYPE_CSS, rel: STYLESHEET, href: url }, attributes, win); }, /** * Generates a script node * @method _scriptNode * @param {string} url the url for the script file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _scriptNode = function(url, win, attributes) { return _node(SCRIPT, { id: Y.guid(), type: TYPE_JS, src: url }, attributes, win); }, /** * Returns the data payload for callback functions. * @method _returnData * @param {object} q the queue. * @param {string} msg the result message. * @param {string} result the status message from the request. * @return {object} the state data from the request. * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param {string} id the id of the request. * @param {string} msg the result message. * @param {string} result the status message from the request. * @private */ _end = function(id, msg, result) { var q = queues[id], onEnd = q && q.onEnd; q.finished = true; if (onEnd) { onEnd.call(q.context, _returnData(q, msg, result)); } }, /** * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param {string} id the id of the request * @private */ _fail = function(id, msg) { Y.log('get failure: ' + msg, 'warn', 'get'); var q = queues[id], onFailure = q.onFailure; _clearTimeout(q); if (onFailure) { onFailure.call(q.context, _returnData(q, msg)); } _end(id, msg, 'failure'); }, /** * Abort the transaction * * @method _abort * @param {Object} id * @private */ _abort = function(id) { _fail(id, 'transaction ' + id + ' was aborted'); }, /** * The request is complete, so executing the requester's callback * @method _complete * @param {string} id the id of the request. * @private */ _complete = function(id) { Y.log("Finishing transaction " + id, "info", "get"); var q = queues[id], onSuccess = q.onSuccess; _clearTimeout(q); if (q.aborted) { _abort(id); } else { if (onSuccess) { onSuccess.call(q.context, _returnData(q)); } // 3.3.0 had undefined msg for this path. _end(id, undefined, 'OK'); } }, /** * Get node reference, from string * * @method _getNodeRef * @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned. * @param {String} tId Queue id, used to determine document for queue * @private */ _getNodeRef = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, 'target node not found: ' + nId); } return n; }, /** * Removes the nodes for the specified queue * @method _purge * @param {string} tId the transaction id. * @private */ _purge = function(tId) { var nodes, doc, parent, sibling, node, attr, insertBefore, i, l, q = queues[tId]; if (q) { nodes = q.nodes; l = nodes.length; // TODO: Why is node.parentNode undefined? Which forces us to do this... /* doc = q.win.document; parent = doc.getElementsByTagName('head')[0]; insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0]; if (insertBefore) { sibling = _getNodeRef(insertBefore, tId); if (sibling) { parent = sibling.parentNode; } } */ for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parentNode; if (node.clearAttributes) { node.clearAttributes(); } else { // This destroys parentNode ref, so we hold onto it above first. for (attr in node) { if (node.hasOwnProperty(attr)) { delete node[attr]; } } } parent.removeChild(node); } } q.nodes = []; }, /** * Progress callback * * @method _progress * @param {string} id The id of the request. * @param {string} The url which just completed. * @private */ _progress = function(id, url) { var q = queues[id], onProgress = q.onProgress, o; if (onProgress) { o = _returnData(q); o.url = url; onProgress.call(q.context, o); } }, /** * Timeout detected * @method _timeout * @param {string} id the id of the request. * @private */ _timeout = function(id) { Y.log('Timeout ' + id, 'info', 'get'); var q = queues[id], onTimeout = q.onTimeout; if (onTimeout) { onTimeout.call(q.context, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * onload callback * @method _loaded * @param {string} id the id of the request. * @return {string} the result. * @private */ _loaded = function(id, url) { var q = queues[id], sync = (q && !q.async); if (!q) { return; } if (sync) { _clearTimeout(q); } _progress(id, url); // TODO: Cleaning up flow to have a consistent end point // !q.finished check is for the async case, // where scripts may still be loading when we've // already aborted. Ideally there should be a single path // for this. if (!q.finished) { if (q.aborted) { _abort(id); } else { if ((--q.remaining) === 0) { _complete(id); } else if (sync) { _next(id); } } } }, /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _trackLoad * @param {string} type the type of node to track. * @param {HTMLElement} n the node to track. * @param {string} id the id of the request. * @param {string} url the url that is being loaded. * @private */ _trackLoad = function(type, n, id, url) { // TODO: Can we massage this to use ONLOAD_SUPPORTED[type]? // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ('loaded' === rs || 'complete' === rs) { // Y.log(id + " onreadstatechange " + url, "info", "get"); n.onreadystatechange = null; _loaded(id, url); } }; } else if (ua.webkit) { // webkit prior to 3.x is no longer supported if (type === SCRIPT) { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener('load', function() { _loaded(id, url); }, false); } } else { // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link nodes. n.onload = function() { // Y.log(id + " onload " + url, "info", "get"); _loaded(id, url); }; n.onerror = function(e) { _fail(id, e + ': ' + url); }; } }, _insertInDoc = function(node, id, win) { // Add it to the head or insert it before 'insertBefore'. // Work around IE bug if there is a base tag. var q = queues[id], doc = win.document, insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0], sibling; if (insertBefore) { sibling = _getNodeRef(insertBefore, id); if (sibling) { Y.log('inserting before: ' + insertBefore, 'info', 'get'); sibling.parentNode.insertBefore(node, sibling); } } else { // 3.3.0 assumed head is always around. doc.getElementsByTagName('head')[0].appendChild(node); } }, /** * Loads the next item for a given request * @method _next * @param {string} id the id of the request. * @return {string} the result. * @private */ _next = function(id) { // Assigning out here for readability var q = queues[id], type = q.type, attrs = q.attributes, win = q.win, timeout = q.timeout, node, url; if (q.url.length > 0) { url = q.url.shift(); Y.log('attempting to load ' + url, 'info', 'get'); // !q.timer ensures that this only happens once for async if (timeout && !q.timer) { q.timer = setTimeout(function() { _timeout(id); }, timeout); } if (type === SCRIPT) { node = _scriptNode(url, win, attrs); } else { node = _linkNode(url, win, attrs); } // add the node to the queue so we can return it in the callback q.nodes.push(node); _trackLoad(type, node, id, url); _insertInDoc(node, id, win); if (!ONLOAD_SUPPORTED[type]) { _loaded(id, url); } if (q.async) { // For sync, the _next call is chained in _loaded _next(id); } } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param {string} type the type of node to insert. * @param {string} url the url to load. * @param {object} opts the hash of options for this request. * @return {object} transaction object. * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = 'q' + (qidx++), thresh = opts.purgethreshold || Y.Get.PURGE_THRESH, q; if (qidx % thresh === 0) { _autoPurge(); } // Merge to protect opts (grandfathered in). q = queues[id] = Y.merge(opts); // Avoid mix, merge overhead. Known set of props. q.tId = id; q.type = type; q.url = url; q.finished = false; q.nodes = []; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || UTF8; if (ASYNC in q && type === SCRIPT) { q.attributes.async = q.async; } q.url = (L.isString(q.url)) ? [q.url] : q.url; // TODO: Do we really need to account for this developer error? // If the url is undefined, this is probably a trailing comma problem in IE. if (!q.url[0]) { q.url.shift(); Y.log('skipping empty url'); } q.remaining = q.url.length; _next(id); return { tId: id }; }; Y.Get = { /** * The number of request required before an automatic purge. * Can be configured via the 'purgethreshold' config * @property PURGE_THRESH * @static * @type int * @default 20 * @private */ PURGE_THRESH: 20, /** * Abort a transaction * @method abort * @static * @param {string|object} o Either the tId or the object returned from * script() or css(). */ abort : function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { Y.log('Aborting ' + id, 'info', 'get'); q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param {string|string[]} url the url or urls to the script(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, * regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading * (useful when passing in an array of js files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> * property, which identifies the file which was loaded.</dd> * <dt>async</dt> * <dd> * <p>When passing in an array of JS files, setting this flag to true * will insert them into the document in parallel, as opposed to the * default behavior, which is to chain load them serially. It will also * set the async attribute on the script node to true.</p> * <p>Setting async:true * will lead to optimal file download performance allowing the browser to * download multiple scripts in parallel, and execute them as soon as they * are available.</p> * <p>Note that async:true does not guarantee execution order of the * scripts being downloaded. They are executed in whichever order they * are received.</p> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling. * If this is not specified, nodes will be inserted before a base * tag should it exist. Otherwise, the nodes will be appended to the * end of the document head.</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing * the timeout event</dd> * <pre> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; Y.log(o.data); // foo * &nbsp; Y.log(o.nodes.length === 2) // true * &nbsp; // o.purge(); // optionally remove the script nodes * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; Y.log("transaction failed"); * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; Y.log("transaction timed out"); * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ script: function(url, opts) { return _queue(SCRIPT, url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param {string} url the url or urls to the css file(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers, * where onload for css is detected accurately.</dd> * <dt>async</dt> * <dd>When passing in an array of css files, setting this flag to true will insert them * into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible). * This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * </dl> * <pre> * Y.Get.css("http://localhost/css/menu.css"); * </pre> * <pre> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; "http://localhost/css/logger.css"], &#123; * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ css: function(url, opts) { return _queue('css', url, opts); } }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // graphics-canvas-default add('load', '0', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-svg add('load', '2', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // history-hash-ie add('load', '3', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // graphics-vml-default add('load', '4', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-svg-default add('load', '5', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // widget-base-ie add('load', '6', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // transition-timer add('load', '7', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // dom-style-ie add('load', '8', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // selector-css2 add('load', '9', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // event-base-ie add('load', '10', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // dd-gestures add('load', '11', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // scrollview-base-ie add('load', '12', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // graphics-canvas add('load', '13', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml add('load', '14', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('loader-base', function(Y) { /** * The YUI loader core * @module loader * @submodule loader-base */ if (!YUI.Env[Y.version]) { (function() { var VERSION = Y.version, BUILD = '/build/', ROOT = VERSION + BUILD, CDN_BASE = Y.Env.base, GALLERY_VERSION = 'gallery-2011.09.14-20-40', TNT = '2in3', TNT_VERSION = '4', YUI2_VERSION = '2.9.0', COMBO_BASE = CDN_BASE + 'combo?', META = { version: VERSION, root: ROOT, base: Y.Env.base, comboBase: COMBO_BASE, skin: { defaultSkin: 'sam', base: 'assets/skins/', path: 'skin.css', after: ['cssreset', 'cssfonts', 'cssgrids', 'cssbase', 'cssreset-context', 'cssfonts-context']}, groups: {}, patterns: {} }, groups = META.groups, yui2Update = function(tnt, yui2) { var root = TNT + '.' + (tnt || TNT_VERSION) + '/' + (yui2 || YUI2_VERSION) + BUILD; groups.yui2.base = CDN_BASE + root; groups.yui2.root = root; }, galleryUpdate = function(tag) { var root = (tag || GALLERY_VERSION) + BUILD; groups.gallery.base = CDN_BASE + root; groups.gallery.root = root; }; groups[VERSION] = {}; groups.gallery = { ext: false, combine: true, comboBase: COMBO_BASE, update: galleryUpdate, patterns: { 'gallery-': { }, 'lang/gallery-': {}, 'gallerycss-': { type: 'css' } } }; groups.yui2 = { combine: true, ext: false, comboBase: COMBO_BASE, update: yui2Update, patterns: { 'yui2-': { configFn: function(me) { if (/-skin|reset|fonts|grids|base/.test(me.name)) { me.type = 'css'; me.path = me.path.replace(/\.js/, '.css'); // this makes skins in builds earlier than // 2.6.0 work as long as combine is false me.path = me.path.replace(/\/yui2-skin/, '/assets/skins/sam/yui2-skin'); } } } } }; galleryUpdate(); yui2Update(); YUI.Env[VERSION] = META; }()); } /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * @module loader * @main loader * @submodule loader-base */ var NOT_FOUND = {}, NO_REQUIREMENTS = [], MAX_URL_LENGTH = 2048, GLOBAL_ENV = YUI.Env, GLOBAL_LOADED = GLOBAL_ENV._loaded, CSS = 'css', JS = 'js', INTL = 'intl', VERSION = Y.version, ROOT_LANG = '', YObject = Y.Object, oeach = YObject.each, YArray = Y.Array, _queue = GLOBAL_ENV._loaderQueue, META = GLOBAL_ENV[VERSION], SKIN_PREFIX = 'skin-', L = Y.Lang, ON_PAGE = GLOBAL_ENV.mods, modulekey, cache, _path = function(dir, file, type, nomin) { var path = dir + '/' + file; if (!nomin) { path += '-min'; } path += '.' + (type || CSS); return path; }; if (YUI.Env.aliases) { YUI.Env.aliases = {}; //Don't need aliases if Loader is present } /** * The component metadata is stored in Y.Env.meta. * Part of the loader module. * @property meta * @for YUI */ Y.Env.meta = META; /** * Loader dynamically loads script and css files. It includes the dependency * info for the version of the library in use, and will automatically pull in * dependencies for the modules requested. It supports rollup files and will * automatically use these when appropriate in order to minimize the number of * http connections required to load all of the dependencies. It can load the * files from the Yahoo! CDN, and it can utilize the combo service provided on * this network to reduce the number of http connections required to download * YUI files. * * While the loader can be instantiated by the end user, it normally is not. * @see YUI.use for the normal use case. The use function automatically will * pull in missing dependencies. * * @constructor * @class Loader * @param {object} o an optional set of configuration options. Valid options: * <ul> * <li>base: * The base dir</li> * <li>comboBase: * The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li> * <li>root: * The root path to prepend to module names for the combo service. * Ex: 2.5.2/build/</li> * <li>filter:. * * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * * </li> * <li>filters: per-component filter specification. If specified * for a given component, this overrides the filter config. _Note:_ This does not work on combo urls, use the filter property instead.</li> * <li>combine: * Use the YUI combo service to reduce the number of http connections * required to load your dependencies</li> * <li>ignore: * A list of modules that should never be dynamically loaded</li> * <li>force: * A list of modules that should always be loaded when required, even if * already present on the page</li> * <li>insertBefore: * Node or id for a node that should be used as the insertion point for * new nodes</li> * <li>charset: * charset for dynamic nodes (deprecated, use jsAttributes or cssAttributes) * </li> * <li>jsAttributes: object literal containing attributes to add to script * nodes</li> * <li>cssAttributes: object literal containing attributes to add to link * nodes</li> * <li>timeout: * The number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout</li> * <li>context: * execution context for all callbacks</li> * <li>onSuccess: * callback for the 'success' event</li> * <li>onFailure: callback for the 'failure' event</li> * <li>onCSS: callback for the 'CSSComplete' event. When loading YUI * components with CSS the CSS is loaded first, then the script. This * provides a moment you can tie into to improve * the presentation of the page while the script is loading.</li> * <li>onTimeout: * callback for the 'timeout' event</li> * <li>onProgress: * callback executed each time a script or css file is loaded</li> * <li>modules: * A list of module definitions. See Loader.addModule for the supported * module metadata</li> * <li>groups: * A list of group definitions. Each group can contain specific definitions * for base, comboBase, combine, and accepts a list of modules. See above * for the description of these properties.</li> * <li>2in3: the version of the YUI 2 in 3 wrapper to use. The intrinsic * support for YUI 2 modules in YUI 3 relies on versions of the YUI 2 * components inside YUI 3 module wrappers. These wrappers * change over time to accomodate the issues that arise from running YUI 2 * in a YUI 3 sandbox.</li> * <li>yui2: when using the 2in3 project, you can select the version of * YUI 2 to use. Valid values * are 2.2.2, 2.3.1, 2.4.1, 2.5.2, 2.6.0, * 2.7.0, 2.8.0, and 2.8.1 [default] -- plus all versions of YUI 2 * going forward.</li> * </ul> */ Y.Loader = function(o) { var defaults = META.modules, self = this; modulekey = META.md5; /** * Internal callback to handle multiple internal insert() calls * so that css is inserted prior to js * @property _internalCallback * @private */ // self._internalCallback = null; /** * Callback that will be executed when the loader is finished * with an insert * @method onSuccess * @type function */ // self.onSuccess = null; /** * Callback that will be executed if there is a failure * @method onFailure * @type function */ // self.onFailure = null; /** * Callback for the 'CSSComplete' event. When loading YUI components * with CSS the CSS is loaded first, then the script. This provides * a moment you can tie into to improve the presentation of the page * while the script is loading. * @method onCSS * @type function */ // self.onCSS = null; /** * Callback executed each time a script or css file is loaded * @method onProgress * @type function */ // self.onProgress = null; /** * Callback that will be executed if a timeout occurs * @method onTimeout * @type function */ // self.onTimeout = null; /** * The execution context for all callbacks * @property context * @default {YUI} the YUI instance */ self.context = Y; /** * Data that is passed to all callbacks * @property data */ // self.data = null; /** * Node reference or id where new nodes should be inserted before * @property insertBefore * @type string|HTMLElement */ // self.insertBefore = null; /** * The charset attribute for inserted nodes * @property charset * @type string * @deprecated , use cssAttributes or jsAttributes. */ // self.charset = null; /** * An object literal containing attributes to add to link nodes * @property cssAttributes * @type object */ // self.cssAttributes = null; /** * An object literal containing attributes to add to script nodes * @property jsAttributes * @type object */ // self.jsAttributes = null; /** * The base directory. * @property base * @type string * @default http://yui.yahooapis.com/[YUI VERSION]/build/ */ self.base = Y.Env.meta.base + Y.Env.meta.root; /** * Base path for the combo service * @property comboBase * @type string * @default http://yui.yahooapis.com/combo? */ self.comboBase = Y.Env.meta.comboBase; /* * Base path for language packs. */ // self.langBase = Y.Env.meta.langBase; // self.lang = ""; /** * If configured, the loader will attempt to use the combo * service for YUI resources and configured external resources. * @property combine * @type boolean * @default true if a base dir isn't in the config */ self.combine = o.base && (o.base.indexOf(self.comboBase.substr(0, 20)) > -1); /** * The default seperator to use between files in a combo URL * @property comboSep * @type {String} * @default Ampersand */ self.comboSep = '&'; /** * Max url length for combo urls. The default is 2048. This is the URL * limit for the Yahoo! hosted combo servers. If consuming * a different combo service that has a different URL limit * it is possible to override this default by supplying * the maxURLLength config option. The config option will * only take effect if lower than the default. * * @property maxURLLength * @type int */ self.maxURLLength = MAX_URL_LENGTH; /** * Ignore modules registered on the YUI global * @property ignoreRegistered * @default false */ // self.ignoreRegistered = false; /** * Root path to prepend to module path for the combo * service * @property root * @type string * @default [YUI VERSION]/build/ */ self.root = Y.Env.meta.root; /** * Timeout value in milliseconds. If set, self value will be used by * the get utility. the timeout event will fire if * a timeout occurs. * @property timeout * @type int */ self.timeout = 0; /** * A list of modules that should not be loaded, even if * they turn up in the dependency tree * @property ignore * @type string[] */ // self.ignore = null; /** * A list of modules that should always be loaded, even * if they have already been inserted into the page. * @property force * @type string[] */ // self.force = null; self.forceMap = {}; /** * Should we allow rollups * @property allowRollup * @type boolean * @default false */ self.allowRollup = false; /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js). * </dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * <pre> * myFilter: &#123; * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * &#125; * </pre> * @property filter * @type string| {searchExp: string, replaceStr: string} */ // self.filter = null; /** * per-component filter specification. If specified for a given * component, this overrides the filter config. * @property filters * @type object */ self.filters = {}; /** * The list of requested modules * @property required * @type {string: boolean} */ self.required = {}; /** * If a module name is predefined when requested, it is checked againsts * the patterns provided in this property. If there is a match, the * module is added with the default configuration. * * At the moment only supporting module prefixes, but anticipate * supporting at least regular expressions. * @property patterns * @type Object */ // self.patterns = Y.merge(Y.Env.meta.patterns); self.patterns = {}; /** * The library metadata * @property moduleInfo */ // self.moduleInfo = Y.merge(Y.Env.meta.moduleInfo); self.moduleInfo = {}; self.groups = Y.merge(Y.Env.meta.groups); /** * Provides the information used to skin the skinnable components. * The following skin definition would result in 'skin1' and 'skin2' * being loaded for calendar (if calendar was requested), and * 'sam' for all other skinnable components: * * <code> * skin: { * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. ex: * // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/ * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * calendar: ['skin1', 'skin2'] * } * } * </code> * @property skin */ self.skin = Y.merge(Y.Env.meta.skin); /* * Map of conditional modules * @since 3.2.0 */ self.conditions = {}; // map of modules with a hash of modules that meet the requirement // self.provides = {}; self.config = o; self._internal = true; cache = GLOBAL_ENV._renderedMods; if (cache) { oeach(cache, function modCache(v, k) { //self.moduleInfo[k] = Y.merge(v); self.moduleInfo[k] = v; }); cache = GLOBAL_ENV._conditions; oeach(cache, function condCache(v, k) { //self.conditions[k] = Y.merge(v); self.conditions[k] = v; }); } else { oeach(defaults, self.addModule, self); } if (!GLOBAL_ENV._renderedMods) { //GLOBAL_ENV._renderedMods = Y.merge(self.moduleInfo); //GLOBAL_ENV._conditions = Y.merge(self.conditions); GLOBAL_ENV._renderedMods = self.moduleInfo; GLOBAL_ENV._conditions = self.conditions; } self._inspectPage(); self._internal = false; self._config(o); self.testresults = null; if (Y.config.tests) { self.testresults = Y.config.tests; } /** * List of rollup files found in the library metadata * @property rollups */ // self.rollups = null; /** * Whether or not to load optional dependencies for * the requested modules * @property loadOptional * @type boolean * @default false */ // self.loadOptional = false; /** * All of the derived dependencies in sorted order, which * will be populated when either calculate() or insert() * is called * @property sorted * @type string[] */ self.sorted = []; /** * Set when beginning to compute the dependency tree. * Composed of what YUI reports to be loaded combined * with what has been loaded by any instance on the page * with the version number specified in the metadata. * @property loaded * @type {string: boolean} */ self.loaded = GLOBAL_LOADED[VERSION]; /* * A list of modules to attach to the YUI instance when complete. * If not supplied, the sorted list of dependencies are applied. * @property attaching */ // self.attaching = null; /** * Flag to indicate the dependency tree needs to be recomputed * if insert is called again. * @property dirty * @type boolean * @default true */ self.dirty = true; /** * List of modules inserted by the utility * @property inserted * @type {string: boolean} */ self.inserted = {}; /** * List of skipped modules during insert() because the module * was not defined * @property skipped */ self.skipped = {}; // Y.on('yui:load', self.loadNext, self); self.tested = {}; /* * Cached sorted calculate results * @property results * @since 3.2.0 */ //self.results = {}; }; Y.Loader.prototype = { FILTER_DEFS: { RAW: { 'searchExp': '-min\\.js', 'replaceStr': '.js' }, DEBUG: { 'searchExp': '-min\\.js', 'replaceStr': '-debug.js' } }, /* * Check the pages meta-data and cache the result. * @method _inspectPage * @private */ _inspectPage: function() { oeach(ON_PAGE, function(v, k) { if (v.details) { var m = this.moduleInfo[k], req = v.details.requires, mr = m && m.requires; if (m) { if (!m._inspected && req && mr.length != req.length) { // console.log('deleting ' + m.name); // m.requres = YObject.keys(Y.merge(YArray.hash(req), YArray.hash(mr))); delete m.expanded; // delete m.expanded_map; } } else { m = this.addModule(v.details, k); } m._inspected = true; } }, this); }, /* * returns true if b is not loaded, and is required directly or by means of modules it supersedes. * @private * @method _requires * @param {String} mod1 The first module to compare * @param {String} mod2 The second module to compare */ _requires: function(mod1, mod2) { var i, rm, after_map, s, info = this.moduleInfo, m = info[mod1], other = info[mod2]; if (!m || !other) { return false; } rm = m.expanded_map; after_map = m.after_map; // check if this module should be sorted after the other // do this first to short circut circular deps if (after_map && (mod2 in after_map)) { return true; } after_map = other.after_map; // and vis-versa if (after_map && (mod1 in after_map)) { return false; } // check if this module requires one the other supersedes s = info[mod2] && info[mod2].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod1, s[i])) { return true; } } } s = info[mod1] && info[mod1].supersedes; if (s) { for (i = 0; i < s.length; i++) { if (this._requires(mod2, s[i])) { return false; } } } // check if this module requires the other directly // if (r && YArray.indexOf(r, mod2) > -1) { if (rm && (mod2 in rm)) { return true; } // external css files should be sorted below yui css if (m.ext && m.type == CSS && !other.ext && other.type == CSS) { return true; } return false; }, /** * Apply a new config to the Loader instance * @method _config * @param {Object} o The new configuration */ _config: function(o) { var i, j, val, f, group, groupName, self = this; // apply config values if (o) { for (i in o) { if (o.hasOwnProperty(i)) { val = o[i]; if (i == 'require') { self.require(val); } else if (i == 'skin') { Y.mix(self.skin, o[i], true); } else if (i == 'groups') { for (j in val) { if (val.hasOwnProperty(j)) { // Y.log('group: ' + j); groupName = j; group = val[j]; self.addGroup(group, groupName); } } } else if (i == 'modules') { // add a hash of module definitions oeach(val, self.addModule, self); } else if (i == 'gallery') { this.groups.gallery.update(val); } else if (i == 'yui2' || i == '2in3') { this.groups.yui2.update(o['2in3'], o.yui2); } else if (i == 'maxURLLength') { self[i] = Math.min(MAX_URL_LENGTH, val); } else { self[i] = val; } } } } // fix filter f = self.filter; if (L.isString(f)) { f = f.toUpperCase(); self.filterName = f; self.filter = self.FILTER_DEFS[f]; if (f == 'DEBUG') { self.require('yui-log', 'dump'); } } if (self.lang) { self.require('intl-base', 'intl'); } }, /** * Returns the skin module name for the specified skin name. If a * module name is supplied, the returned skin module name is * specific to the module passed in. * @method formatSkin * @param {string} skin the name of the skin. * @param {string} mod optional: the name of a module to skin. * @return {string} the full skin module name. */ formatSkin: function(skin, mod) { var s = SKIN_PREFIX + skin; if (mod) { s = s + '-' + mod; } return s; }, /** * Adds the skin def to the module info * @method _addSkin * @param {string} skin the name of the skin. * @param {string} mod the name of the module. * @param {string} parent parent module if this is a skin of a * submodule or plugin. * @return {string} the module name for the skin. * @private */ _addSkin: function(skin, mod, parent) { var mdef, pkg, name, nmod, info = this.moduleInfo, sinf = this.skin, ext = info[mod] && info[mod].ext; // Add a module definition for the module-specific skin css if (mod) { name = this.formatSkin(skin, mod); if (!info[name]) { mdef = info[mod]; pkg = mdef.pkg || mod; nmod = { name: name, group: mdef.group, type: 'css', after: sinf.after, path: (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css', ext: ext }; if (mdef.base) { nmod.base = mdef.base; } if (mdef.configFn) { nmod.configFn = mdef.configFn; } this.addModule(nmod, name); Y.log('adding skin ' + name + ', ' + parent + ', ' + pkg + ', ' + info[name].path); } } return name; }, /** * Add a new module group * <dl> * <dt>name:</dt> <dd>required, the group name</dd> * <dt>base:</dt> <dd>The base dir for this module group</dd> * <dt>root:</dt> <dd>The root path to add to each combo * resource path</dd> * <dt>combine:</dt> <dd>combo handle</dd> * <dt>comboBase:</dt> <dd>combo service base path</dd> * <dt>modules:</dt> <dd>the group of modules</dd> * </dl> * @method addGroup * @param {object} o An object containing the module data. * @param {string} name the group name. */ addGroup: function(o, name) { var mods = o.modules, self = this; name = name || o.name; o.name = name; self.groups[name] = o; if (o.patterns) { oeach(o.patterns, function(v, k) { v.group = name; self.patterns[k] = v; }); } if (mods) { oeach(mods, function(v, k) { v.group = name; self.addModule(v, k); }, self); } }, /** * Add a new module to the component metadata. * <dl> * <dt>name:</dt> <dd>required, the component name</dd> * <dt>type:</dt> <dd>required, the component type (js or css) * </dd> * <dt>path:</dt> <dd>required, the path to the script from * "base"</dd> * <dt>requires:</dt> <dd>array of modules required by this * component</dd> * <dt>optional:</dt> <dd>array of optional modules for this * component</dd> * <dt>supersedes:</dt> <dd>array of the modules this component * replaces</dd> * <dt>after:</dt> <dd>array of modules the components which, if * present, should be sorted above this one</dd> * <dt>after_map:</dt> <dd>faster alternative to 'after' -- supply * a hash instead of an array</dd> * <dt>rollup:</dt> <dd>the number of superseded modules required * for automatic rollup</dd> * <dt>fullpath:</dt> <dd>If fullpath is specified, this is used * instead of the configured base + path</dd> * <dt>skinnable:</dt> <dd>flag to determine if skin assets should * automatically be pulled in</dd> * <dt>submodules:</dt> <dd>a hash of submodules</dd> * <dt>group:</dt> <dd>The group the module belongs to -- this * is set automatically when it is added as part of a group * configuration.</dd> * <dt>lang:</dt> * <dd>array of BCP 47 language tags of languages for which this * module has localized resource bundles, * e.g., ["en-GB","zh-Hans-CN"]</dd> * <dt>condition:</dt> * <dd>Specifies that the module should be loaded automatically if * a condition is met. This is an object with up to three fields: * [trigger] - the name of a module that can trigger the auto-load * [test] - a function that returns true when the module is to be * loaded. * [when] - specifies the load order of the conditional module * with regard to the position of the trigger module. * This should be one of three values: 'before', 'after', or * 'instead'. The default is 'after'. * </dd> * <dt>testresults:</dt><dd>a hash of test results from Y.Features.all()</dd> * </dl> * @method addModule * @param {object} o An object containing the module data. * @param {string} name the module name (optional), required if not * in the module data. * @return {object} the module definition or null if * the object passed in did not provide all required attributes. */ addModule: function(o, name) { name = name || o.name; //Only merge this data if the temp flag is set //from an earlier pass from a pattern or else //an override module (YUI_config) can not be used to //replace a default module. if (this.moduleInfo[name] && this.moduleInfo[name].temp) { //This catches temp modules loaded via a pattern // The module will be added twice, once from the pattern and // Once from the actual add call, this ensures that properties // that were added to the module the first time around (group: gallery) // are also added the second time around too. o = Y.merge(this.moduleInfo[name], o); } o.name = name; if (!o || !o.name) { return null; } if (!o.type) { o.type = JS; } if (!o.path && !o.fullpath) { o.path = _path(name, name, o.type); } o.supersedes = o.supersedes || o.use; o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true; o.requires = this.filterRequires(o.requires) || []; // Handle submodule logic var subs = o.submodules, i, l, t, sup, s, smod, plugins, plug, j, langs, packName, supName, flatSup, flatLang, lang, ret, overrides, skinname, when, conditions = this.conditions, trigger; // , existing = this.moduleInfo[name], newr; this.moduleInfo[name] = o; if (!o.langPack && o.lang) { langs = YArray(o.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } } } if (subs) { sup = o.supersedes || []; l = 0; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; s.path = s.path || _path(name, i, o.type); s.pkg = name; s.group = o.group; if (s.supersedes) { sup = sup.concat(s.supersedes); } smod = this.addModule(s, i); sup.push(i); if (smod.skinnable) { o.skinnable = true; overrides = this.skin.overrides; if (overrides && overrides[i]) { for (j = 0; j < overrides[i].length; j++) { skinname = this._addSkin(overrides[i][j], i, name); sup.push(skinname); } } skinname = this._addSkin(this.skin.defaultSkin, i, name); sup.push(skinname); } // looks like we are expected to work out the metadata // for the parent module language packs from what is // specified in the child modules. if (s.lang && s.lang.length) { langs = YArray(s.lang); for (j = 0; j < langs.length; j++) { lang = langs[j]; packName = this.getLangPackName(lang, name); supName = this.getLangPackName(lang, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } flatSup = flatSup || YArray.hash(smod.supersedes); if (!(supName in flatSup)) { smod.supersedes.push(supName); } o.lang = o.lang || []; flatLang = flatLang || YArray.hash(o.lang); if (!(lang in flatLang)) { o.lang.push(lang); } // Y.log('pack ' + packName + ' should supersede ' + supName); // Add rollup file, need to add to supersedes list too // default packages packName = this.getLangPackName(ROOT_LANG, name); supName = this.getLangPackName(ROOT_LANG, i); smod = this.moduleInfo[packName]; if (!smod) { smod = this._addLangPack(lang, o, packName); } if (!(supName in flatSup)) { smod.supersedes.push(supName); } // Y.log('pack ' + packName + ' should supersede ' + supName); // Add rollup file, need to add to supersedes list too } } l++; } } //o.supersedes = YObject.keys(YArray.hash(sup)); o.supersedes = YArray.dedupe(sup); if (this.allowRollup) { o.rollup = (l < 4) ? l : Math.min(l - 1, 4); } } plugins = o.plugins; if (plugins) { for (i in plugins) { if (plugins.hasOwnProperty(i)) { plug = plugins[i]; plug.pkg = name; plug.path = plug.path || _path(name, i, o.type); plug.requires = plug.requires || []; plug.group = o.group; this.addModule(plug, i); if (o.skinnable) { this._addSkin(this.skin.defaultSkin, i, name); } } } } if (o.condition) { t = o.condition.trigger; if (YUI.Env.aliases[t]) { t = YUI.Env.aliases[t]; } if (!Y.Lang.isArray(t)) { t = [t]; } for (i = 0; i < t.length; i++) { trigger = t[i]; when = o.condition.when; conditions[trigger] = conditions[trigger] || {}; conditions[trigger][name] = o.condition; // the 'when' attribute can be 'before', 'after', or 'instead' // the default is after. if (when && when != 'after') { if (when == 'instead') { // replace the trigger o.supersedes = o.supersedes || []; o.supersedes.push(trigger); } else { // before the trigger // the trigger requires the conditional mod, // so it should appear before the conditional // mod if we do not intersede. } } else { // after the trigger o.after = o.after || []; o.after.push(trigger); } } } if (o.after) { o.after_map = YArray.hash(o.after); } // this.dirty = true; if (o.configFn) { ret = o.configFn(o); if (ret === false) { delete this.moduleInfo[name]; o = null; } } return o; }, /** * Add a requirement for one or more module * @method require * @param {string[] | string*} what the modules to load. */ require: function(what) { var a = (typeof what === 'string') ? YArray(arguments) : what; this.dirty = true; this.required = Y.merge(this.required, YArray.hash(this.filterRequires(a))); this._explodeRollups(); }, /** * Grab all the items that were asked for, check to see if the Loader * meta-data contains a "use" array. If it doesm remove the asked item and replace it with * the content of the "use". * This will make asking for: "dd" * Actually ask for: "dd-ddm-base,dd-ddm,dd-ddm-drop,dd-drag,dd-proxy,dd-constrain,dd-drop,dd-scroll,dd-drop-plugin" * @private * @method _explodeRollups */ _explodeRollups: function() { var self = this, m, r = self.required; if (!self.allowRollup) { oeach(r, function(v, name) { m = self.getModule(name); if (m && m.use) { //delete r[name]; YArray.each(m.use, function(v) { m = self.getModule(v); if (m && m.use) { //delete r[v]; YArray.each(m.use, function(v) { r[v] = true; }); } else { r[v] = true; } }); } }); self.required = r; } }, /** * Explodes the required array to remove aliases and replace them with real modules * @method filterRequires * @param {Array} r The original requires array * @return {Array} The new array of exploded requirements */ filterRequires: function(r) { if (r) { if (!Y.Lang.isArray(r)) { r = [r]; } r = Y.Array(r); var c = [], i, mod, o, m; for (i = 0; i < r.length; i++) { mod = this.getModule(r[i]); if (mod && mod.use) { for (o = 0; o < mod.use.length; o++) { //Must walk the other modules in case a module is a rollup of rollups (datatype) m = this.getModule(mod.use[o]); if (m && m.use) { c = Y.Array.dedupe([].concat(c, this.filterRequires(m.use))); } else { c.push(mod.use[o]); } } } else { c.push(r[i]); } } r = c; } return r; }, /** * Returns an object containing properties for all modules required * in order to load the requested module * @method getRequires * @param {object} mod The module definition from moduleInfo. * @return {array} the expanded requirement list. */ getRequires: function(mod) { if (!mod || mod._parsed) { // Y.log('returning no reqs for ' + mod.name); return NO_REQUIREMENTS; } var i, m, j, add, packName, lang, testresults = this.testresults, name = mod.name, cond, go, adddef = ON_PAGE[name] && ON_PAGE[name].details, d, k, m1, r, old_mod, o, skinmod, skindef, skinpar, skinname, intl = mod.lang || mod.intl, info = this.moduleInfo, ftests = Y.Features && Y.Features.tests.load, hash; // console.log(name); // pattern match leaves module stub that needs to be filled out if (mod.temp && adddef) { old_mod = mod; mod = this.addModule(adddef, name); mod.group = old_mod.group; mod.pkg = old_mod.pkg; delete mod.expanded; } // console.log('cache: ' + mod.langCache + ' == ' + this.lang); // if (mod.expanded && (!mod.langCache || mod.langCache == this.lang)) { if (mod.expanded && (!this.lang || mod.langCache === this.lang)) { //Y.log('Already expanded ' + name + ', ' + mod.expanded); return mod.expanded; } d = []; hash = {}; r = this.filterRequires(mod.requires); if (mod.lang) { //If a module has a lang attribute, auto add the intl requirement. d.unshift('intl'); r.unshift('intl'); intl = true; } o = this.filterRequires(mod.optional); // Y.log("getRequires: " + name + " (dirty:" + this.dirty + // ", expanded:" + mod.expanded + ")"); mod._parsed = true; mod.langCache = this.lang; for (i = 0; i < r.length; i++) { //Y.log(name + ' requiring ' + r[i], 'info', 'loader'); if (!hash[r[i]]) { d.push(r[i]); hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } // get the requirements from superseded modules, if any r = this.filterRequires(mod.supersedes); if (r) { for (i = 0; i < r.length; i++) { if (!hash[r[i]]) { // if this module has submodules, the requirements list is // expanded to include the submodules. This is so we can // prevent dups when a submodule is already loaded and the // parent is requested. if (mod.submodules) { d.push(r[i]); } hash[r[i]] = true; m = this.getModule(r[i]); if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } if (o && this.loadOptional) { for (i = 0; i < o.length; i++) { if (!hash[o[i]]) { d.push(o[i]); hash[o[i]] = true; m = info[o[i]]; if (m) { add = this.getRequires(m); intl = intl || (m.expanded_map && (INTL in m.expanded_map)); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } } cond = this.conditions[name]; if (cond) { if (testresults && ftests) { oeach(testresults, function(result, id) { var condmod = ftests[id].name; if (!hash[condmod] && ftests[id].trigger == name) { if (result && ftests[id]) { hash[condmod] = true; d.push(condmod); } } }); } else { oeach(cond, function(def, condmod) { if (!hash[condmod]) { go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y, r))); if (go) { hash[condmod] = true; d.push(condmod); m = this.getModule(condmod); // Y.log('conditional', m); if (m) { add = this.getRequires(m); for (j = 0; j < add.length; j++) { d.push(add[j]); } } } } }, this); } } // Create skin modules if (mod.skinnable) { skindef = this.skin.overrides; oeach(YUI.Env.aliases, function(o, n) { if (Y.Array.indexOf(o, name) > -1) { skinpar = n; } }); if (skindef && (skindef[name] || (skinpar && skindef[skinpar]))) { skinname = name; if (skindef[skinpar]) { skinname = skinpar; } for (i = 0; i < skindef[skinname].length; i++) { skinmod = this._addSkin(skindef[skinname][i], name); d.push(skinmod); } } else { skinmod = this._addSkin(this.skin.defaultSkin, name); d.push(skinmod); } } mod._parsed = false; if (intl) { if (mod.lang && !mod.langPack && Y.Intl) { lang = Y.Intl.lookupBestLang(this.lang || ROOT_LANG, mod.lang); //Y.log('Best lang: ' + lang + ', this.lang: ' + this.lang + ', mod.lang: ' + mod.lang); packName = this.getLangPackName(lang, name); if (packName) { d.unshift(packName); } } d.unshift(INTL); } mod.expanded_map = YArray.hash(d); mod.expanded = YObject.keys(mod.expanded_map); return mod.expanded; }, /** * Returns a hash of module names the supplied module satisfies. * @method getProvides * @param {string} name The name of the module. * @return {object} what this module provides. */ getProvides: function(name) { var m = this.getModule(name), o, s; // supmap = this.provides; if (!m) { return NOT_FOUND; } if (m && !m.provides) { o = {}; s = m.supersedes; if (s) { YArray.each(s, function(v) { Y.mix(o, this.getProvides(v)); }, this); } o[name] = true; m.provides = o; } return m.provides; }, /** * Calculates the dependency tree, the result is stored in the sorted * property. * @method calculate * @param {object} o optional options object. * @param {string} type optional argument to prune modules. */ calculate: function(o, type) { if (o || type || this.dirty) { if (o) { this._config(o); } if (!this._init) { this._setup(); } this._explode(); if (this.allowRollup) { this._rollup(); } else { this._explodeRollups(); } this._reduce(); this._sort(); } }, /** * Creates a "psuedo" package for languages provided in the lang array * @method _addLangPack * @param {String} lang The language to create * @param {Object} m The module definition to create the language pack around * @param {String} packName The name of the package (e.g: lang/datatype-date-en-US) * @return {Object} The module definition */ _addLangPack: function(lang, m, packName) { var name = m.name, packPath, existing = this.moduleInfo[packName]; if (!existing) { packPath = _path((m.pkg || name), packName, JS, true); this.addModule({ path: packPath, intl: true, langPack: true, ext: m.ext, group: m.group, supersedes: [] }, packName); if (lang) { Y.Env.lang = Y.Env.lang || {}; Y.Env.lang[lang] = Y.Env.lang[lang] || {}; Y.Env.lang[lang][name] = true; } } return this.moduleInfo[packName]; }, /** * Investigates the current YUI configuration on the page. By default, * modules already detected will not be loaded again unless a force * option is encountered. Called by calculate() * @method _setup * @private */ _setup: function() { var info = this.moduleInfo, name, i, j, m, l, packName; for (name in info) { if (info.hasOwnProperty(name)) { m = info[name]; if (m) { // remove dups //m.requires = YObject.keys(YArray.hash(m.requires)); m.requires = YArray.dedupe(m.requires); // Create lang pack modules if (m.lang && m.lang.length) { // Setup root package if the module has lang defined, // it needs to provide a root language pack packName = this.getLangPackName(ROOT_LANG, name); this._addLangPack(null, m, packName); } } } } //l = Y.merge(this.inserted); l = {}; // available modules if (!this.ignoreRegistered) { Y.mix(l, GLOBAL_ENV.mods); } // add the ignore list to the list of loaded packages if (this.ignore) { Y.mix(l, YArray.hash(this.ignore)); } // expand the list to include superseded modules for (j in l) { if (l.hasOwnProperty(j)) { Y.mix(l, this.getProvides(j)); } } // remove modules on the force list from the loaded list if (this.force) { for (i = 0; i < this.force.length; i++) { if (this.force[i] in l) { delete l[this.force[i]]; } } } Y.mix(this.loaded, l); this._init = true; }, /** * Builds a module name for a language pack * @method getLangPackName * @param {string} lang the language code. * @param {string} mname the module to build it for. * @return {string} the language pack module name. */ getLangPackName: function(lang, mname) { return ('lang/' + mname + ((lang) ? '_' + lang : '')); }, /** * Inspects the required modules list looking for additional * dependencies. Expands the required list to include all * required modules. Called by calculate() * @method _explode * @private */ _explode: function() { var r = this.required, m, reqs, done = {}, self = this; // the setup phase is over, all modules have been created self.dirty = false; self._explodeRollups(); r = self.required; oeach(r, function(v, name) { if (!done[name]) { done[name] = true; m = self.getModule(name); if (m) { var expound = m.expound; if (expound) { r[expound] = self.getModule(expound); reqs = self.getRequires(r[expound]); Y.mix(r, YArray.hash(reqs)); } reqs = self.getRequires(m); Y.mix(r, YArray.hash(reqs)); } } }); // Y.log('After explode: ' + YObject.keys(r)); }, /** * Get's the loader meta data for the requested module * @method getModule * @param {String} mname The module name to get * @return {Object} The module metadata */ getModule: function(mname) { //TODO: Remove name check - it's a quick hack to fix pattern WIP if (!mname) { return null; } var p, found, pname, m = this.moduleInfo[mname], patterns = this.patterns; // check the patterns library to see if we should automatically add // the module with defaults if (!m) { // Y.log('testing patterns ' + YObject.keys(patterns)); for (pname in patterns) { if (patterns.hasOwnProperty(pname)) { // Y.log('testing pattern ' + i); p = patterns[pname]; // use the metadata supplied for the pattern // as the module definition. if (mname.indexOf(pname) > -1) { found = p; break; } } } if (found) { if (p.action) { // Y.log('executing pattern action: ' + pname); p.action.call(this, mname, pname); } else { Y.log('Undefined module: ' + mname + ', matched a pattern: ' + pname, 'info', 'loader'); // ext true or false? m = this.addModule(Y.merge(found), mname); m.temp = true; } } } return m; }, // impl in rollup submodule _rollup: function() { }, /** * Remove superceded modules and loaded modules. Called by * calculate() after we have the mega list of all dependencies * @method _reduce * @return {object} the reduced dependency hash. * @private */ _reduce: function(r) { r = r || this.required; var i, j, s, m, type = this.loadType, ignore = this.ignore ? YArray.hash(this.ignore) : false; for (i in r) { if (r.hasOwnProperty(i)) { m = this.getModule(i); // remove if already loaded if (((this.loaded[i] || ON_PAGE[i]) && !this.forceMap[i] && !this.ignoreRegistered) || (type && m && m.type != type)) { delete r[i]; } if (ignore && ignore[i]) { delete r[i]; } // remove anything this module supersedes s = m && m.supersedes; if (s) { for (j = 0; j < s.length; j++) { if (s[j] in r) { delete r[s[j]]; } } } } } return r; }, /** * Handles the queue when a module has been loaded for all cases * @method _finish * @private * @param {String} msg The message from Loader * @param {Boolean} success A boolean denoting success or failure */ _finish: function(msg, success) { Y.log('loader finishing: ' + msg + ', ' + Y.id + ', ' + this.data, 'info', 'loader'); _queue.running = false; var onEnd = this.onEnd; if (onEnd) { onEnd.call(this.context, { msg: msg, data: this.data, success: success }); } this._continue(); }, /** * The default Loader onSuccess handler, calls this.onSuccess with a payload * @method _onSuccess * @private */ _onSuccess: function() { var self = this, skipped = Y.merge(self.skipped), fn, failed = [], rreg = self.requireRegistration, success, msg; oeach(skipped, function(k) { delete self.inserted[k]; }); self.skipped = {}; oeach(self.inserted, function(v, k) { var mod = self.getModule(k); if (mod && rreg && mod.type == JS && !(k in YUI.Env.mods)) { failed.push(k); } else { Y.mix(self.loaded, self.getProvides(k)); } }); fn = self.onSuccess; msg = (failed.length) ? 'notregistered' : 'success'; success = !(failed.length); if (fn) { fn.call(self.context, { msg: msg, data: self.data, success: success, failed: failed, skipped: skipped }); } self._finish(msg, success); }, /** * The default Loader onFailure handler, calls this.onFailure with a payload * @method _onFailure * @private */ _onFailure: function(o) { Y.log('load error: ' + o.msg + ', ' + Y.id, 'error', 'loader'); var f = this.onFailure, msg = 'failure: ' + o.msg; if (f) { f.call(this.context, { msg: msg, data: this.data, success: false }); } this._finish(msg, false); }, /** * The default Loader onTimeout handler, calls this.onTimeout with a payload * @method _onTimeout * @private */ _onTimeout: function() { Y.log('loader timeout: ' + Y.id, 'error', 'loader'); var f = this.onTimeout; if (f) { f.call(this.context, { msg: 'timeout', data: this.data, success: false }); } this._finish('timeout', false); }, /** * Sorts the dependency tree. The last step of calculate() * @method _sort * @private */ _sort: function() { // create an indexed list var s = YObject.keys(this.required), // loaded = this.loaded, done = {}, p = 0, l, a, b, j, k, moved, doneKey; // keep going until we make a pass without moving anything for (;;) { l = s.length; moved = false; // start the loop after items that are already sorted for (j = p; j < l; j++) { // check the next module on the list to see if its // dependencies have been met a = s[j]; // check everything below current item and move if we // find a requirement for the current item for (k = j + 1; k < l; k++) { doneKey = a + s[k]; if (!done[doneKey] && this._requires(a, s[k])) { // extract the dependency so we can move it up b = s.splice(k, 1); // insert the dependency above the item that // requires it s.splice(j, 0, b[0]); // only swap two dependencies once to short circut // circular dependencies done[doneKey] = true; // keep working moved = true; break; } } // jump out of loop if we moved something if (moved) { break; // this item is sorted, move our pointer and keep going } else { p++; } } // when we make it here and moved is false, we are // finished sorting if (!moved) { break; } } this.sorted = s; }, /** * (Unimplemented) * @method partial * @unimplemented */ partial: function(partial, o, type) { this.sorted = partial; this.insert(o, type, true); }, /** * Handles the actual insertion of script/link tags * @method _insert * @param {Object} source The YUI instance the request came from * @param {Object} o The metadata to include * @param {String} type JS or CSS * @param {Boolean} [skipcalc=false] Do a Loader.calculate on the meta */ _insert: function(source, o, type, skipcalc) { // Y.log('private _insert() ' + (type || '') + ', ' + Y.id, "info", "loader"); // restore the state at the time of the request if (source) { this._config(source); } // build the dependency list // don't include type so we can process CSS and script in // one pass when the type is not specified. if (!skipcalc) { this.calculate(o); } this.loadType = type; if (!type) { var self = this; // Y.log("trying to load css first"); this._internalCallback = function() { var f = self.onCSS, n, p, sib; // IE hack for style overrides that are not being applied if (this.insertBefore && Y.UA.ie) { n = Y.config.doc.getElementById(this.insertBefore); p = n.parentNode; sib = n.nextSibling; p.removeChild(n); if (sib) { p.insertBefore(n, sib); } else { p.appendChild(n); } } if (f) { f.call(self.context, Y); } self._internalCallback = null; self._insert(null, null, JS); }; this._insert(null, null, CSS); return; } // set a flag to indicate the load has started this._loading = true; // flag to indicate we are done with the combo service // and any additional files will need to be loaded // individually this._combineComplete = {}; // start the load this.loadNext(); }, /** * Once a loader operation is completely finished, process any additional queued items. * @method _continue * @private */ _continue: function() { if (!(_queue.running) && _queue.size() > 0) { _queue.running = true; _queue.next()(); } }, /** * inserts the requested modules and their dependencies. * <code>type</code> can be "js" or "css". Both script and * css are inserted if type is not provided. * @method insert * @param {object} o optional options object. * @param {string} type the type of dependency to insert. */ insert: function(o, type, skipsort) { // Y.log('public insert() ' + (type || '') + ', ' + // Y.Object.keys(this.required), "info", "loader"); var self = this, copy = Y.merge(this); delete copy.require; delete copy.dirty; _queue.add(function() { self._insert(copy, o, type, skipsort); }); this._continue(); }, /** * Executed every time a module is loaded, and if we are in a load * cycle, we attempt to load the next script. Public so that it * is possible to call this if using a method other than * Y.register to determine when scripts are fully loaded * @method loadNext * @param {string} mname optional the name of the module that has * been loaded (which is usually why it is time to load the next * one). */ loadNext: function(mname) { // It is possible that this function is executed due to something // else on the page loading a YUI module. Only react when we // are actively loading something if (!this._loading) { return; } var s, len, i, m, url, fn, msg, attr, group, groupName, j, frag, comboSource, comboSources, mods, combining, urls, comboBase, self = this, type = self.loadType, handleSuccess = function(o) { self.loadNext(o.data); }, handleCombo = function(o) { self._combineComplete[type] = true; var i, len = combining.length; for (i = 0; i < len; i++) { self.inserted[combining[i]] = true; } handleSuccess(o); }; if (self.combine && (!self._combineComplete[type])) { combining = []; self._combining = combining; s = self.sorted; len = s.length; // the default combo base comboBase = self.comboBase; url = comboBase; urls = []; comboSources = {}; for (i = 0; i < len; i++) { comboSource = comboBase; m = self.getModule(s[i]); groupName = m && m.group; if (groupName) { group = self.groups[groupName]; if (!group.combine) { m.combine = false; continue; } m.combine = true; if (group.comboBase) { comboSource = group.comboBase; } if ("root" in group && L.isValue(group.root)) { m.root = group.root; } } comboSources[comboSource] = comboSources[comboSource] || []; comboSources[comboSource].push(m); } for (j in comboSources) { if (comboSources.hasOwnProperty(j)) { url = j; mods = comboSources[j]; len = mods.length; for (i = 0; i < len; i++) { // m = self.getModule(s[i]); m = mods[i]; // Do not try to combine non-yui JS unless combo def // is found if (m && (m.type === type) && (m.combine || !m.ext)) { frag = ((L.isValue(m.root)) ? m.root : self.root) + m.path; frag = self._filter(frag, m.name); if ((url !== j) && (i <= (len - 1)) && ((frag.length + url.length) > self.maxURLLength)) { //Hack until this is rewritten to use an array and not string concat: if (url.substr(url.length - 1, 1) === self.comboSep) { url = url.substr(0, (url.length - 1)); } urls.push(self._filter(url)); url = j; } url += frag; if (i < (len - 1)) { url += self.comboSep; } combining.push(m.name); } } if (combining.length && (url != j)) { //Hack until this is rewritten to use an array and not string concat: if (url.substr(url.length - 1, 1) === self.comboSep) { url = url.substr(0, (url.length - 1)); } urls.push(self._filter(url)); } } } if (combining.length) { Y.log('Attempting to use combo: ' + combining, 'info', 'loader'); // if (m.type === CSS) { if (type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } fn(urls, { data: self._loading, onSuccess: handleCombo, onFailure: self._onFailure, onTimeout: self._onTimeout, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, timeout: self.timeout, autopurge: false, context: self }); return; } else { self._combineComplete[type] = true; } } if (mname) { // if the module that was just loaded isn't what we were expecting, // continue to wait if (mname !== self._loading) { return; } // Y.log("loadNext executing, just loaded " + mname + ", " + // Y.id, "info", "loader"); // The global handler that is called when each module is loaded // will pass that module name to this function. Storing this // data to avoid loading the same module multiple times // centralize this in the callback self.inserted[mname] = true; // self.loaded[mname] = true; // provided = self.getProvides(mname); // Y.mix(self.loaded, provided); // Y.mix(self.inserted, provided); if (self.onProgress) { self.onProgress.call(self.context, { name: mname, data: self.data }); } } s = self.sorted; len = s.length; for (i = 0; i < len; i = i + 1) { // this.inserted keeps track of what the loader has loaded. // move on if this item is done. if (s[i] in self.inserted) { continue; } // Because rollups will cause multiple load notifications // from Y, loadNext may be called multiple times for // the same module when loading a rollup. We can safely // skip the subsequent requests if (s[i] === self._loading) { Y.log('still loading ' + s[i] + ', waiting', 'info', 'loader'); return; } // log("inserting " + s[i]); m = self.getModule(s[i]); if (!m) { if (!self.skipped[s[i]]) { msg = 'Undefined module ' + s[i] + ' skipped'; Y.log(msg, 'warn', 'loader'); // self.inserted[s[i]] = true; self.skipped[s[i]] = true; } continue; } group = (m.group && self.groups[m.group]) || NOT_FOUND; // The load type is stored to offer the possibility to load // the css separately from the script. if (!type || type === m.type) { self._loading = s[i]; Y.log('attempting to load ' + s[i] + ', ' + self.base, 'info', 'loader'); if (m.type === CSS) { fn = Y.Get.css; attr = self.cssAttributes; } else { fn = Y.Get.script; attr = self.jsAttributes; } url = (m.fullpath) ? self._filter(m.fullpath, s[i]) : self._url(m.path, s[i], group.base || m.base); fn(url, { data: s[i], onSuccess: handleSuccess, insertBefore: self.insertBefore, charset: self.charset, attributes: attr, onFailure: self._onFailure, onTimeout: self._onTimeout, timeout: self.timeout, autopurge: false, context: self }); return; } } // we are finished self._loading = null; fn = self._internalCallback; // internal callback for loading css first if (fn) { // Y.log('loader internal'); self._internalCallback = null; fn.call(self); } else { // Y.log('loader complete'); self._onSuccess(); } }, /** * Apply filter defined for this instance to a url/path * @method _filter * @param {string} u the string to filter. * @param {string} name the name of the module, if we are processing * a single module as opposed to a combined url. * @return {string} the filtered string. * @private */ _filter: function(u, name) { var f = this.filter, hasFilter = name && (name in this.filters), modFilter = hasFilter && this.filters[name], groupName = this.moduleInfo[name] ? this.moduleInfo[name].group:null; if (groupName && this.groups[groupName].filter) { modFilter = this.groups[groupName].filter; hasFilter = true; }; if (u) { if (hasFilter) { f = (L.isString(modFilter)) ? this.FILTER_DEFS[modFilter.toUpperCase()] || null : modFilter; } if (f) { u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr); } } return u; }, /** * Generates the full url for a module * @method _url * @param {string} path the path fragment. * @param {String} name The name of the module * @pamra {String} [base=self.base] The base url to use * @return {string} the full url. * @private */ _url: function(path, name, base) { return this._filter((base || this.base || '') + path, name); }, /** * Returns an Object hash of file arrays built from `loader.sorted` or from an arbitrary list of sorted modules. * @method resolve * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [s=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two arrays of file lists * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.resolve(true); * */ resolve: function(calc, s) { var self = this, i, m, url, out = { js: [], css: [] }; if (calc) { self.calculate(); } s = s || self.sorted; for (i = 0; i < s.length; i++) { m = self.getModule(s[i]); if (m) { if (self.combine) { url = self._filter((self.root + m.path), m.name, self.root); } else { url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name); } out[m.type].push(url); } } if (self.combine) { out.js = [self.comboBase + out.js.join(self.comboSep)]; out.css = [self.comboBase + out.css.join(self.comboSep)]; } return out; }, /** * Returns an Object hash of hashes built from `loader.sorted` or from an arbitrary list of sorted modules. * @method hash * @private * @param {Boolean} [calc=false] Perform a loader.calculate() before anything else * @param {Array} [s=loader.sorted] An override for the loader.sorted array * @return {Object} Object hash (js and css) of two object hashes of file lists, with the module name as the key * @example This method can be used as an off-line dep calculator * * var Y = YUI(); * var loader = new Y.Loader({ * filter: 'debug', * base: '../../', * root: 'build/', * combine: true, * require: ['node', 'dd', 'console'] * }); * var out = loader.hash(true); * */ hash: function(calc, s) { var self = this, i, m, url, out = { js: {}, css: {} }; if (calc) { self.calculate(); } s = s || self.sorted; for (i = 0; i < s.length; i++) { m = self.getModule(s[i]); if (m) { url = self._filter(m.fullpath, m.name, '') || self._url(m.path, m.name); out[m.type][m.name] = url; } } return out; } }; }, '@VERSION@' ,{requires:['get']}); YUI.add('loader-rollup', function(Y) { /** * Optional automatic rollup logic for reducing http connections * when not using a combo service. * @module loader * @submodule rollup */ /** * Look for rollup packages to determine if all of the modules a * rollup supersedes are required. If so, include the rollup to * help reduce the total number of connections required. Called * by calculate(). This is an optional feature, and requires the * appropriate submodule to function. * @method _rollup * @for Loader * @private */ Y.Loader.prototype._rollup = function() { var i, j, m, s, r = this.required, roll, info = this.moduleInfo, rolled, c, smod; // find and cache rollup modules if (this.dirty || !this.rollups) { this.rollups = {}; for (i in info) { if (info.hasOwnProperty(i)) { m = this.getModule(i); // if (m && m.rollup && m.supersedes) { if (m && m.rollup) { this.rollups[i] = m; } } } this.forceMap = (this.force) ? Y.Array.hash(this.force) : {}; } // make as many passes as needed to pick up rollup rollups for (;;) { rolled = false; // go through the rollup candidates for (i in this.rollups) { if (this.rollups.hasOwnProperty(i)) { // there can be only one, unless forced if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) { m = this.getModule(i); s = m.supersedes || []; roll = false; // @TODO remove continue if (!m.rollup) { continue; } c = 0; // check the threshold for (j = 0; j < s.length; j++) { smod = info[s[j]]; // if the superseded module is loaded, we can't // load the rollup unless it has been forced. if (this.loaded[s[j]] && !this.forceMap[s[j]]) { roll = false; break; // increment the counter if this module is required. // if we are beyond the rollup threshold, we will // use the rollup module } else if (r[s[j]] && m.type == smod.type) { c++; // Y.log("adding to thresh: " + c + ", " + s[j]); roll = (c >= m.rollup); if (roll) { // Y.log("over thresh " + c + ", " + s[j]); break; } } } if (roll) { // Y.log("adding rollup: " + i); // add the rollup r[i] = true; rolled = true; // expand the rollup's dependencies this.getRequires(m); } } } } // if we made it here w/o rolling up something, we are done if (!rolled) { break; } } }; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('loader-yui3', function(Y) { /* This file is auto-generated by src/loader/scripts/meta_join.py */ /** * YUI 3 module metadata * @module loader * @submodule yui3 */ YUI.Env[Y.version].modules = YUI.Env[Y.version].modules || { "align-plugin": { "requires": [ "node-screen", "node-pluginhost" ] }, "anim": { "use": [ "anim-base", "anim-color", "anim-curve", "anim-easing", "anim-node-plugin", "anim-scroll", "anim-xy" ] }, "anim-base": { "requires": [ "base-base", "node-style" ] }, "anim-color": { "requires": [ "anim-base" ] }, "anim-curve": { "requires": [ "anim-xy" ] }, "anim-easing": { "requires": [ "anim-base" ] }, "anim-node-plugin": { "requires": [ "node-pluginhost", "anim-base" ] }, "anim-scroll": { "requires": [ "anim-base" ] }, "anim-xy": { "requires": [ "anim-base", "node-screen" ] }, "app": { "use": [ "controller", "model", "model-list", "view" ] }, "array-extras": { "requires": [ "yui-base" ] }, "array-invoke": { "requires": [ "yui-base" ] }, "arraylist": { "requires": [ "yui-base" ] }, "arraylist-add": { "requires": [ "arraylist" ] }, "arraylist-filter": { "requires": [ "arraylist" ] }, "arraysort": { "requires": [ "yui-base" ] }, "async-queue": { "requires": [ "event-custom" ] }, "attribute": { "use": [ "attribute-base", "attribute-complex" ] }, "attribute-base": { "requires": [ "event-custom" ] }, "attribute-complex": { "requires": [ "attribute-base" ] }, "autocomplete": { "use": [ "autocomplete-base", "autocomplete-sources", "autocomplete-list", "autocomplete-plugin" ] }, "autocomplete-base": { "optional": [ "autocomplete-sources" ], "requires": [ "array-extras", "base-build", "escape", "event-valuechange", "node-base" ] }, "autocomplete-filters": { "requires": [ "array-extras", "text-wordbreak" ] }, "autocomplete-filters-accentfold": { "requires": [ "array-extras", "text-accentfold", "text-wordbreak" ] }, "autocomplete-highlighters": { "requires": [ "array-extras", "highlight-base" ] }, "autocomplete-highlighters-accentfold": { "requires": [ "array-extras", "highlight-accentfold" ] }, "autocomplete-list": { "after": [ "autocomplete-sources" ], "lang": [ "en" ], "requires": [ "autocomplete-base", "event-resize", "node-screen", "selector-css3", "shim-plugin", "widget", "widget-position", "widget-position-align" ], "skinnable": true }, "autocomplete-list-keys": { "condition": { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }, "requires": [ "autocomplete-list", "base-build" ] }, "autocomplete-plugin": { "requires": [ "autocomplete-list", "node-pluginhost" ] }, "autocomplete-sources": { "optional": [ "io-base", "json-parse", "jsonp", "yql" ], "requires": [ "autocomplete-base" ] }, "base": { "use": [ "base-base", "base-pluginhost", "base-build" ] }, "base-base": { "after": [ "attribute-complex" ], "requires": [ "attribute-base" ] }, "base-build": { "requires": [ "base-base" ] }, "base-pluginhost": { "requires": [ "base-base", "pluginhost" ] }, "cache": { "use": [ "cache-base", "cache-offline", "cache-plugin" ] }, "cache-base": { "requires": [ "base" ] }, "cache-offline": { "requires": [ "cache-base", "json" ] }, "cache-plugin": { "requires": [ "plugin", "cache-base" ] }, "calendar": { "lang": [ "en", "ja", "ru" ], "requires": [ "calendar-base", "calendarnavigator" ], "skinnable": true }, "calendar-base": { "lang": [ "en", "ja", "ru" ], "requires": [ "widget", "substitute", "datatype-date", "datatype-date-math", "cssgrids" ], "skinnable": true }, "calendarnavigator": { "requires": [ "plugin", "classnamemanager", "datatype-date", "node", "substitute" ], "skinnable": true }, "charts": { "requires": [ "dom", "datatype-number", "datatype-date", "event-custom", "event-mouseenter", "widget", "widget-position", "widget-stack", "graphics" ] }, "classnamemanager": { "requires": [ "yui-base" ] }, "clickable-rail": { "requires": [ "slider-base" ] }, "collection": { "use": [ "array-extras", "arraylist", "arraylist-add", "arraylist-filter", "array-invoke" ] }, "console": { "lang": [ "en", "es", "ja" ], "requires": [ "yui-log", "widget", "substitute" ], "skinnable": true }, "console-filters": { "requires": [ "plugin", "console" ], "skinnable": true }, "controller": { "optional": [ "querystring-parse" ], "requires": [ "array-extras", "base-build", "history" ] }, "cookie": { "requires": [ "yui-base" ] }, "createlink-base": { "requires": [ "editor-base" ] }, "cssbase": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssbase-context": { "after": [ "cssreset", "cssfonts", "cssgrids", "cssreset-context", "cssfonts-context", "cssgrids-context" ], "type": "css" }, "cssfonts": { "type": "css" }, "cssfonts-context": { "type": "css" }, "cssgrids": { "optional": [ "cssreset", "cssfonts" ], "type": "css" }, "cssreset": { "type": "css" }, "cssreset-context": { "type": "css" }, "dataschema": { "use": [ "dataschema-base", "dataschema-json", "dataschema-xml", "dataschema-array", "dataschema-text" ] }, "dataschema-array": { "requires": [ "dataschema-base" ] }, "dataschema-base": { "requires": [ "base" ] }, "dataschema-json": { "requires": [ "dataschema-base", "json" ] }, "dataschema-text": { "requires": [ "dataschema-base" ] }, "dataschema-xml": { "requires": [ "dataschema-base" ] }, "datasource": { "use": [ "datasource-local", "datasource-io", "datasource-get", "datasource-function", "datasource-cache", "datasource-jsonschema", "datasource-xmlschema", "datasource-arrayschema", "datasource-textschema", "datasource-polling" ] }, "datasource-arrayschema": { "requires": [ "datasource-local", "plugin", "dataschema-array" ] }, "datasource-cache": { "requires": [ "datasource-local", "plugin", "cache-base" ] }, "datasource-function": { "requires": [ "datasource-local" ] }, "datasource-get": { "requires": [ "datasource-local", "get" ] }, "datasource-io": { "requires": [ "datasource-local", "io-base" ] }, "datasource-jsonschema": { "requires": [ "datasource-local", "plugin", "dataschema-json" ] }, "datasource-local": { "requires": [ "base" ] }, "datasource-polling": { "requires": [ "datasource-local" ] }, "datasource-textschema": { "requires": [ "datasource-local", "plugin", "dataschema-text" ] }, "datasource-xmlschema": { "requires": [ "datasource-local", "plugin", "dataschema-xml" ] }, "datatable": { "use": [ "datatable-base", "datatable-datasource", "datatable-sort", "datatable-scroll" ] }, "datatable-base": { "requires": [ "recordset-base", "widget", "substitute", "event-mouseenter" ], "skinnable": true }, "datatable-datasource": { "requires": [ "datatable-base", "plugin", "datasource-local" ] }, "datatable-scroll": { "requires": [ "datatable-base", "plugin" ] }, "datatable-sort": { "lang": [ "en" ], "requires": [ "datatable-base", "plugin", "recordset-sort" ] }, "datatype": { "use": [ "datatype-number", "datatype-date", "datatype-xml" ] }, "datatype-date": { "supersedes": [ "datatype-date-format" ], "use": [ "datatype-date-parse", "datatype-date-format" ] }, "datatype-date-format": { "lang": [ "ar", "ar-JO", "ca", "ca-ES", "da", "da-DK", "de", "de-AT", "de-DE", "el", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-JO", "en-MY", "en-NZ", "en-PH", "en-SG", "en-US", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-EC", "es-ES", "es-MX", "es-PE", "es-PY", "es-US", "es-UY", "es-VE", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "hi", "hi-IN", "id", "id-ID", "it", "it-IT", "ja", "ja-JP", "ko", "ko-KR", "ms", "ms-MY", "nb", "nb-NO", "nl", "nl-BE", "nl-NL", "pl", "pl-PL", "pt", "pt-BR", "ro", "ro-RO", "ru", "ru-RU", "sv", "sv-SE", "th", "th-TH", "tr", "tr-TR", "vi", "vi-VN", "zh-Hans", "zh-Hans-CN", "zh-Hant", "zh-Hant-HK", "zh-Hant-TW" ] }, "datatype-date-math": { "requires": [ "yui-base" ] }, "datatype-date-parse": {}, "datatype-number": { "use": [ "datatype-number-parse", "datatype-number-format" ] }, "datatype-number-format": {}, "datatype-number-parse": {}, "datatype-xml": { "use": [ "datatype-xml-parse", "datatype-xml-format" ] }, "datatype-xml-format": {}, "datatype-xml-parse": {}, "dd": { "use": [ "dd-ddm-base", "dd-ddm", "dd-ddm-drop", "dd-drag", "dd-proxy", "dd-constrain", "dd-drop", "dd-scroll", "dd-delegate" ] }, "dd-constrain": { "requires": [ "dd-drag" ] }, "dd-ddm": { "requires": [ "dd-ddm-base", "event-resize" ] }, "dd-ddm-base": { "requires": [ "node", "base", "yui-throttle", "classnamemanager" ] }, "dd-ddm-drop": { "requires": [ "dd-ddm" ] }, "dd-delegate": { "requires": [ "dd-drag", "dd-drop-plugin", "event-mouseenter" ] }, "dd-drag": { "requires": [ "dd-ddm-base" ] }, "dd-drop": { "requires": [ "dd-drag", "dd-ddm-drop" ] }, "dd-drop-plugin": { "requires": [ "dd-drop" ] }, "dd-gestures": { "condition": { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }, "requires": [ "dd-drag", "event-synthetic", "event-gestures" ] }, "dd-plugin": { "optional": [ "dd-constrain", "dd-proxy" ], "requires": [ "dd-drag" ] }, "dd-proxy": { "requires": [ "dd-drag" ] }, "dd-scroll": { "requires": [ "dd-drag" ] }, "dial": { "lang": [ "en", "es" ], "requires": [ "widget", "dd-drag", "substitute", "event-mouseenter", "event-move", "event-key", "transition", "intl" ], "skinnable": true }, "dom": { "use": [ "dom-base", "dom-screen", "dom-style", "selector-native", "selector" ] }, "dom-base": { "requires": [ "dom-core" ] }, "dom-core": { "requires": [ "oop", "features" ] }, "dom-deprecated": { "requires": [ "dom-base" ] }, "dom-screen": { "requires": [ "dom-base", "dom-style" ] }, "dom-style": { "requires": [ "dom-base" ] }, "dom-style-ie": { "condition": { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }, "requires": [ "dom-style" ] }, "dump": { "requires": [ "yui-base" ] }, "editor": { "use": [ "frame", "selection", "exec-command", "editor-base", "editor-para", "editor-br", "editor-bidi", "editor-tab", "createlink-base" ] }, "editor-base": { "requires": [ "base", "frame", "node", "exec-command", "selection" ] }, "editor-bidi": { "requires": [ "editor-base" ] }, "editor-br": { "requires": [ "editor-base" ] }, "editor-lists": { "requires": [ "editor-base" ] }, "editor-para": { "requires": [ "editor-base" ] }, "editor-tab": { "requires": [ "editor-base" ] }, "escape": { "requires": [ "yui-base" ] }, "event": { "after": [ "node-base" ], "use": [ "event-base", "event-delegate", "event-synthetic", "event-mousewheel", "event-mouseenter", "event-key", "event-focus", "event-resize", "event-hover", "event-outside" ] }, "event-base": { "after": [ "node-base" ], "requires": [ "event-custom-base" ] }, "event-base-ie": { "after": [ "event-base" ], "condition": { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }, "requires": [ "node-base" ] }, "event-custom": { "use": [ "event-custom-base", "event-custom-complex" ] }, "event-custom-base": { "requires": [ "oop" ] }, "event-custom-complex": { "requires": [ "event-custom-base" ] }, "event-delegate": { "requires": [ "node-base" ] }, "event-flick": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-focus": { "requires": [ "event-synthetic" ] }, "event-gestures": { "use": [ "event-flick", "event-move" ] }, "event-hover": { "requires": [ "event-mouseenter" ] }, "event-key": { "requires": [ "event-synthetic" ] }, "event-mouseenter": { "requires": [ "event-synthetic" ] }, "event-mousewheel": { "requires": [ "node-base" ] }, "event-move": { "requires": [ "node-base", "event-touch", "event-synthetic" ] }, "event-outside": { "requires": [ "event-synthetic" ] }, "event-resize": { "requires": [ "node-base", "event-synthetic" ] }, "event-simulate": { "requires": [ "event-base" ] }, "event-synthetic": { "requires": [ "node-base", "event-custom-complex" ] }, "event-touch": { "requires": [ "node-base" ] }, "event-valuechange": { "requires": [ "event-focus", "event-synthetic" ] }, "exec-command": { "requires": [ "frame" ] }, "features": { "requires": [ "yui-base" ] }, "frame": { "requires": [ "base", "node", "selector-css3", "substitute", "yui-throttle" ] }, "get": { "requires": [ "yui-base" ] }, "graphics": { "requires": [ "node", "event-custom", "pluginhost" ] }, "graphics-canvas": { "condition": { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-canvas-default": { "condition": { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" } }, "graphics-svg": { "condition": { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-svg-default": { "condition": { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" } }, "graphics-vml": { "condition": { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }, "requires": [ "graphics" ] }, "graphics-vml-default": { "condition": { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" } }, "highlight": { "use": [ "highlight-base", "highlight-accentfold" ] }, "highlight-accentfold": { "requires": [ "highlight-base", "text-accentfold" ] }, "highlight-base": { "requires": [ "array-extras", "classnamemanager", "escape", "text-wordbreak" ] }, "history": { "use": [ "history-base", "history-hash", "history-hash-ie", "history-html5" ] }, "history-base": { "requires": [ "event-custom-complex" ] }, "history-hash": { "after": [ "history-html5" ], "requires": [ "event-synthetic", "history-base", "yui-later" ] }, "history-hash-ie": { "condition": { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }, "requires": [ "history-hash", "node-base" ] }, "history-html5": { "optional": [ "json" ], "requires": [ "event-base", "history-base", "node-base" ] }, "imageloader": { "requires": [ "base-base", "node-style", "node-screen" ] }, "intl": { "requires": [ "intl-base", "event-custom" ] }, "intl-base": { "requires": [ "yui-base" ] }, "io": { "use": [ "io-base", "io-xdr", "io-form", "io-upload-iframe", "io-queue" ] }, "io-base": { "requires": [ "event-custom-base", "querystring-stringify-simple" ] }, "io-form": { "requires": [ "io-base", "node-base" ] }, "io-queue": { "requires": [ "io-base", "queue-promote" ] }, "io-upload-iframe": { "requires": [ "io-base", "node-base" ] }, "io-xdr": { "requires": [ "io-base", "datatype-xml" ] }, "json": { "use": [ "json-parse", "json-stringify" ] }, "json-parse": { "requires": [ "yui-base" ] }, "json-stringify": { "requires": [ "yui-base" ] }, "jsonp": { "requires": [ "get", "oop" ] }, "jsonp-url": { "requires": [ "jsonp" ] }, "loader": { "use": [ "loader-base", "loader-rollup", "loader-yui3" ] }, "loader-base": { "requires": [ "get" ] }, "loader-rollup": { "requires": [ "loader-base" ] }, "loader-yui3": { "requires": [ "loader-base" ] }, "model": { "requires": [ "base-build", "escape", "json-parse" ] }, "model-list": { "requires": [ "array-extras", "array-invoke", "arraylist", "base-build", "escape", "json-parse", "model" ] }, "node": { "use": [ "node-base", "node-event-delegate", "node-pluginhost", "node-screen", "node-style" ] }, "node-base": { "requires": [ "event-base", "node-core", "dom-base" ] }, "node-core": { "requires": [ "dom-core", "selector" ] }, "node-deprecated": { "requires": [ "node-base" ] }, "node-event-delegate": { "requires": [ "node-base", "event-delegate" ] }, "node-event-html5": { "requires": [ "node-base" ] }, "node-event-simulate": { "requires": [ "node-base", "event-simulate" ] }, "node-flick": { "requires": [ "classnamemanager", "transition", "event-flick", "plugin" ], "skinnable": true }, "node-focusmanager": { "requires": [ "attribute", "node", "plugin", "node-event-simulate", "event-key", "event-focus" ] }, "node-load": { "requires": [ "node-base", "io-base" ] }, "node-menunav": { "requires": [ "node", "classnamemanager", "plugin", "node-focusmanager" ], "skinnable": true }, "node-pluginhost": { "requires": [ "node-base", "pluginhost" ] }, "node-screen": { "requires": [ "dom-screen", "node-base" ] }, "node-style": { "requires": [ "dom-style", "node-base" ] }, "oop": { "requires": [ "yui-base" ] }, "overlay": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain" ], "skinnable": true }, "panel": { "requires": [ "widget", "widget-stdmod", "widget-position", "widget-position-align", "widget-stack", "widget-position-constrain", "widget-modality", "widget-autohide", "widget-buttons" ], "skinnable": true }, "plugin": { "requires": [ "base-base" ] }, "pluginhost": { "use": [ "pluginhost-base", "pluginhost-config" ] }, "pluginhost-base": { "requires": [ "yui-base" ] }, "pluginhost-config": { "requires": [ "pluginhost-base" ] }, "profiler": { "requires": [ "yui-base" ] }, "querystring": { "use": [ "querystring-parse", "querystring-stringify" ] }, "querystring-parse": { "requires": [ "yui-base", "array-extras" ] }, "querystring-parse-simple": { "requires": [ "yui-base" ] }, "querystring-stringify": { "requires": [ "yui-base" ] }, "querystring-stringify-simple": { "requires": [ "yui-base" ] }, "queue-promote": { "requires": [ "yui-base" ] }, "range-slider": { "requires": [ "slider-base", "slider-value-range", "clickable-rail" ] }, "recordset": { "use": [ "recordset-base", "recordset-sort", "recordset-filter", "recordset-indexer" ] }, "recordset-base": { "requires": [ "base", "arraylist" ] }, "recordset-filter": { "requires": [ "recordset-base", "array-extras", "plugin" ] }, "recordset-indexer": { "requires": [ "recordset-base", "plugin" ] }, "recordset-sort": { "requires": [ "arraysort", "recordset-base", "plugin" ] }, "resize": { "use": [ "resize-base", "resize-proxy", "resize-constrain" ] }, "resize-base": { "requires": [ "base", "widget", "substitute", "event", "oop", "dd-drag", "dd-delegate", "dd-drop" ], "skinnable": true }, "resize-constrain": { "requires": [ "plugin", "resize-base" ] }, "resize-plugin": { "optional": [ "resize-constrain" ], "requires": [ "resize-base", "plugin" ] }, "resize-proxy": { "requires": [ "plugin", "resize-base" ] }, "rls": { "requires": [ "get", "features" ] }, "scrollview": { "requires": [ "scrollview-base", "scrollview-scrollbars" ] }, "scrollview-base": { "requires": [ "widget", "event-gestures", "transition" ], "skinnable": true }, "scrollview-base-ie": { "condition": { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }, "requires": [ "scrollview-base" ] }, "scrollview-list": { "requires": [ "plugin", "classnamemanager" ], "skinnable": true }, "scrollview-paginator": { "requires": [ "plugin" ] }, "scrollview-scrollbars": { "requires": [ "classnamemanager", "transition", "plugin" ], "skinnable": true }, "selection": { "requires": [ "node" ] }, "selector": { "requires": [ "selector-native" ] }, "selector-css2": { "condition": { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }, "requires": [ "selector-native" ] }, "selector-css3": { "requires": [ "selector-native", "selector-css2" ] }, "selector-native": { "requires": [ "dom-base" ] }, "shim-plugin": { "requires": [ "node-style", "node-pluginhost" ] }, "slider": { "use": [ "slider-base", "slider-value-range", "clickable-rail", "range-slider" ] }, "slider-base": { "requires": [ "widget", "dd-constrain", "substitute" ], "skinnable": true }, "slider-value-range": { "requires": [ "slider-base" ] }, "sortable": { "requires": [ "dd-delegate", "dd-drop-plugin", "dd-proxy" ] }, "sortable-scroll": { "requires": [ "dd-scroll", "sortable" ] }, "stylesheet": { "requires": [ "yui-base" ] }, "substitute": { "optional": [ "dump" ], "requires": [ "yui-base" ] }, "swf": { "requires": [ "event-custom", "node", "swfdetect", "escape" ] }, "swfdetect": { "requires": [ "yui-base" ] }, "tabview": { "requires": [ "widget", "widget-parent", "widget-child", "tabview-base", "node-pluginhost", "node-focusmanager" ], "skinnable": true }, "tabview-base": { "requires": [ "node-event-delegate", "classnamemanager", "skin-sam-tabview" ] }, "tabview-plugin": { "requires": [ "tabview-base" ] }, "test": { "requires": [ "event-simulate", "event-custom", "substitute", "json-stringify" ], "skinnable": true }, "text": { "use": [ "text-accentfold", "text-wordbreak" ] }, "text-accentfold": { "requires": [ "array-extras", "text-data-accentfold" ] }, "text-data-accentfold": { "requires": [ "yui-base" ] }, "text-data-wordbreak": { "requires": [ "yui-base" ] }, "text-wordbreak": { "requires": [ "array-extras", "text-data-wordbreak" ] }, "transition": { "requires": [ "node-style" ] }, "transition-timer": { "condition": { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }, "requires": [ "transition" ] }, "uploader": { "requires": [ "event-custom", "node", "base", "swf" ] }, "view": { "requires": [ "base-build", "node-event-delegate" ] }, "widget": { "use": [ "widget-base", "widget-htmlparser", "widget-uievents", "widget-skin" ] }, "widget-anim": { "requires": [ "plugin", "anim-base", "widget" ] }, "widget-autohide": { "requires": [ "widget", "event-outside", "base-build", "event-key" ], "skinnable": false }, "widget-base": { "requires": [ "attribute", "event-focus", "base-base", "base-pluginhost", "node-base", "node-style", "classnamemanager" ], "skinnable": true }, "widget-base-ie": { "condition": { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }, "requires": [ "widget-base" ] }, "widget-buttons": { "requires": [ "widget", "base-build", "widget-stdmod" ], "skinnable": true }, "widget-child": { "requires": [ "base-build", "widget" ] }, "widget-htmlparser": { "requires": [ "widget-base" ] }, "widget-locale": { "requires": [ "widget-base" ] }, "widget-modality": { "requires": [ "widget", "event-outside", "base-build" ], "skinnable": false }, "widget-parent": { "requires": [ "base-build", "arraylist", "widget" ] }, "widget-position": { "requires": [ "base-build", "node-screen", "widget" ] }, "widget-position-align": { "requires": [ "widget-position" ] }, "widget-position-constrain": { "requires": [ "widget-position" ] }, "widget-skin": { "requires": [ "widget-base" ] }, "widget-stack": { "requires": [ "base-build", "widget" ], "skinnable": true }, "widget-stdmod": { "requires": [ "base-build", "widget" ] }, "widget-uievents": { "requires": [ "widget-base", "node-event-delegate" ] }, "yql": { "requires": [ "jsonp", "jsonp-url" ] }, "yui": {}, "yui-base": {}, "yui-later": { "requires": [ "yui-base" ] }, "yui-log": { "requires": [ "yui-base" ] }, "yui-rls": {}, "yui-throttle": { "requires": [ "yui-base" ] } }; YUI.Env[Y.version].md5 = '94b4cd94d5b5f12f01ec8758dc2d9a6e'; }, '@VERSION@' ,{requires:['loader-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later','loader-base', 'loader-rollup', 'loader-yui3' ]});
src/svg-icons/hardware/desktop-mac.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareDesktopMac = (props) => ( <SvgIcon {...props}> <path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7l-2 3v1h8v-1l-2-3h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H3V4h18v10z"/> </SvgIcon> ); HardwareDesktopMac = pure(HardwareDesktopMac); HardwareDesktopMac.displayName = 'HardwareDesktopMac'; HardwareDesktopMac.muiName = 'SvgIcon'; export default HardwareDesktopMac;
src/containers/NotFound/NotFound.js
leifdalan/vega-june
import React from 'react'; export default function NotFound() { return ( <div className="container"> <h1>Leif is working on the site.</h1> <p>Check back again later!</p> </div> ); }
ajax/libs/yui/3.8.0/datatable-core/datatable-core-coverage.js
chrillep/cdnjs
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/datatable-core/datatable-core.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/datatable-core/datatable-core.js", code: [] }; _yuitest_coverage["build/datatable-core/datatable-core.js"].code=["YUI.add('datatable-core', function (Y, NAME) {","","/**","The core implementation of the `DataTable` and `DataTable.Base` Widgets.","","@module datatable","@submodule datatable-core","@since 3.5.0","**/","","var INVALID = Y.Attribute.INVALID_VALUE,",""," Lang = Y.Lang,"," isFunction = Lang.isFunction,"," isObject = Lang.isObject,"," isArray = Lang.isArray,"," isString = Lang.isString,"," isNumber = Lang.isNumber,",""," toArray = Y.Array,",""," keys = Y.Object.keys,",""," Table;"," ","/**","_API docs for this extension are included in the DataTable class._","","Class extension providing the core API and structure for the DataTable Widget.","","Use this class extension with Widget or another Base-based superclass to create","the basic DataTable model API and composing class structure.","","@class DataTable.Core","@for DataTable","@since 3.5.0","**/","Table = Y.namespace('DataTable').Core = function () {};","","Table.ATTRS = {"," /**"," Columns to include in the rendered table."," "," If omitted, the attributes on the configured `recordType` or the first item"," in the `data` collection will be used as a source.",""," This attribute takes an array of strings or objects (mixing the two is"," fine). Each string or object is considered a column to be rendered."," Strings are converted to objects, so `columns: ['first', 'last']` becomes"," `columns: [{ key: 'first' }, { key: 'last' }]`.",""," DataTable.Core only concerns itself with a few properties of columns."," These properties are:",""," * `key` - Used to identify the record field/attribute containing content for"," this column. Also used to create a default Model if no `recordType` or"," `data` are provided during construction. If `name` is not specified, this"," is assigned to the `_id` property (with added incrementer if the key is"," used by multiple columns)."," * `children` - Traversed to initialize nested column objects"," * `name` - Used in place of, or in addition to, the `key`. Useful for"," columns that aren't bound to a field/attribute in the record data. This"," is assigned to the `_id` property."," * `id` - For backward compatibility. Implementers can specify the id of"," the header cell. This should be avoided, if possible, to avoid the"," potential for creating DOM elements with duplicate IDs."," * `field` - For backward compatibility. Implementers should use `name`."," * `_id` - Assigned unique-within-this-instance id for a column. By order"," of preference, assumes the value of `name`, `key`, `id`, or `_yuid`."," This is used by the rendering views as well as feature module"," as a means to identify a specific column without ambiguity (such as"," multiple columns using the same `key`."," * `_yuid` - Guid stamp assigned to the column object."," * `_parent` - Assigned to all child columns, referencing their parent"," column.",""," @attribute columns"," @type {Object[]|String[]}"," @default (from `recordType` ATTRS or first item in the `data`)"," @since 3.5.0"," **/"," columns: {"," // TODO: change to setter to clone input array/objects"," validator: isArray,"," setter: '_setColumns',"," getter: '_getColumns'"," },",""," /**"," Model subclass to use as the `model` for the ModelList stored in the `data`"," attribute.",""," If not provided, it will try really hard to figure out what to use. The"," following attempts will be made to set a default value:"," "," 1. If the `data` attribute is set with a ModelList instance and its `model`"," property is set, that will be used."," 2. If the `data` attribute is set with a ModelList instance, and its"," `model` property is unset, but it is populated, the `ATTRS` of the"," `constructor of the first item will be used."," 3. If the `data` attribute is set with a non-empty array, a Model subclass"," will be generated using the keys of the first item as its `ATTRS` (see"," the `_createRecordClass` method)."," 4. If the `columns` attribute is set, a Model subclass will be generated"," using the columns defined with a `key`. This is least desirable because"," columns can be duplicated or nested in a way that's not parsable."," 5. If neither `data` nor `columns` is set or populated, a change event"," subscriber will listen for the first to be changed and try all over"," again.",""," @attribute recordType"," @type {Function}"," @default (see description)"," @since 3.5.0"," **/"," recordType: {"," getter: '_getRecordType',"," setter: '_setRecordType'"," },",""," /**"," The collection of data records to display. This attribute is a pass"," through to a `data` property, which is a ModelList instance.",""," If this attribute is passed a ModelList or subclass, it will be assigned to"," the property directly. If an array of objects is passed, a new ModelList"," will be created using the configured `recordType` as its `model` property"," and seeded with the array.",""," Retrieving this attribute will return the ModelList stored in the `data`"," property.",""," @attribute data"," @type {ModelList|Object[]}"," @default `new ModelList()`"," @since 3.5.0"," **/"," data: {"," valueFn: '_initData',"," setter : '_setData',"," lazyAdd: false"," },",""," /**"," Content for the `<table summary=\"ATTRIBUTE VALUE HERE\">`. Values assigned"," to this attribute will be HTML escaped for security.",""," @attribute summary"," @type {String}"," @default '' (empty string)"," @since 3.5.0"," **/"," //summary: {},",""," /**"," HTML content of an optional `<caption>` element to appear above the table."," Leave this config unset or set to a falsy value to remove the caption.",""," @attribute caption"," @type HTML"," @default '' (empty string)"," @since 3.5.0"," **/"," //caption: {},",""," /**"," Deprecated as of 3.5.0. Passes through to the `data` attribute.",""," WARNING: `get('recordset')` will NOT return a Recordset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute recordset"," @type {Object[]|Recordset}"," @deprecated Use the `data` attribute"," @since 3.5.0"," **/"," recordset: {"," setter: '_setRecordset',"," getter: '_getRecordset',"," lazyAdd: false"," },",""," /**"," Deprecated as of 3.5.0. Passes through to the `columns` attribute.",""," WARNING: `get('columnset')` will NOT return a Columnset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute columnset"," @type {Object[]}"," @deprecated Use the `columns` attribute"," @since 3.5.0"," **/"," columnset: {"," setter: '_setColumnset',"," getter: '_getColumnset',"," lazyAdd: false"," }","};","","Y.mix(Table.prototype, {"," // -- Instance properties -------------------------------------------------"," /**"," The ModelList that manages the table's data.",""," @property data"," @type {ModelList}"," @default undefined (initially unset)"," @since 3.5.0"," **/"," //data: null,",""," // -- Public methods ------------------------------------------------------",""," /**"," Gets the column configuration object for the given key, name, or index. For"," nested columns, `name` can be an array of indexes, each identifying the index"," of that column in the respective parent's \"children\" array.",""," If you pass a column object, it will be returned.",""," For columns with keys, you can also fetch the column with"," `instance.get('columns.foo')`.",""," @method getColumn"," @param {String|Number|Number[]} name Key, \"name\", index, or index array to"," identify the column"," @return {Object} the column configuration object"," @since 3.5.0"," **/"," getColumn: function (name) {"," var col, columns, i, len, cols;",""," if (isObject(name) && !isArray(name)) {"," // TODO: support getting a column from a DOM node - this will cross"," // the line into the View logic, so it should be relayed",""," // Assume an object passed in is already a column def"," col = name;"," } else {"," col = this.get('columns.' + name);"," }",""," if (col) {"," return col;"," }",""," columns = this.get('columns');",""," if (isNumber(name) || isArray(name)) {"," name = toArray(name);"," cols = columns;",""," for (i = 0, len = name.length - 1; cols && i < len; ++i) {"," cols = cols[name[i]] && cols[name[i]].children;"," }",""," return (cols && cols[name[i]]) || null;"," }",""," return null;"," },",""," /**"," Returns the Model associated to the record `id`, `clientId`, or index (not"," row index). If none of those yield a Model from the `data` ModelList, the"," arguments will be passed to the `view` instance's `getRecord` method"," if it has one.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or"," identifier for a row or child element"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var record = this.data.getById(seed) || this.data.getByClientId(seed);",""," if (!record) {"," if (isNumber(seed)) {"," record = this.data.item(seed);"," }"," "," // TODO: this should be split out to base somehow"," if (!record && this.view && this.view.getRecord) {"," record = this.view.getRecord.apply(this.view, arguments);"," }"," }",""," return record || null;"," },",""," // -- Protected and private properties and methods ------------------------",""," /**"," This tells `Y.Base` that it should create ad-hoc attributes for config"," properties passed to DataTable's constructor. This is useful for setting"," configurations on the DataTable that are intended for the rendering View(s).",""," @property _allowAdHocAttrs"," @type Boolean"," @default true"," @protected"," @since 3.6.0"," **/"," _allowAdHocAttrs: true,",""," /**"," A map of column key to column configuration objects parsed from the"," `columns` attribute.",""," @property _columnMap"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_columnMap: null,",""," /**"," The Node instance of the table containing the data rows. This is set when"," the table is rendered. It may also be set by progressive enhancement,"," though this extension does not provide the logic to parse from source.",""," @property _tableNode"," @type {Node}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_tableNode: null,",""," /**"," Updates the `_columnMap` property in response to changes in the `columns`"," attribute.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," _afterColumnsChange: function (e) {"," this._setColumnMap(e.newVal);"," },",""," /**"," Updates the `modelList` attributes of the rendered views in response to the"," `data` attribute being assigned a new ModelList.",""," @method _afterDataChange"," @param {EventFacade} e the `dataChange` event"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," var modelList = e.newVal;",""," this.data = e.newVal;",""," if (!this.get('columns') && modelList.size()) {"," // TODO: this will cause a re-render twice because the Views are"," // subscribed to columnsChange"," this._initColumns();"," }"," },",""," /**"," Assigns to the new recordType as the model for the data ModelList",""," @method _afterRecordTypeChange"," @param {EventFacade} e recordTypeChange event"," @protected"," @since 3.6.0"," **/"," _afterRecordTypeChange: function (e) {"," var data = this.data.toJSON();",""," this.data.model = e.newVal;",""," this.data.reset(data);",""," if (!this.get('columns') && data) {"," if (data.length) {"," this._initColumns();"," } else {"," this.set('columns', keys(e.newVal.ATTRS));"," }"," }"," },",""," /**"," Creates a Model subclass from an array of attribute names or an object of"," attribute definitions. This is used to generate a class suitable to"," represent the data passed to the `data` attribute if no `recordType` is"," set.",""," @method _createRecordClass"," @param {String[]|Object} attrs Names assigned to the Model subclass's"," `ATTRS` or its entire `ATTRS` definition object"," @return {Model}"," @protected"," @since 3.5.0"," **/"," _createRecordClass: function (attrs) {"," var ATTRS, i, len;",""," if (isArray(attrs)) {"," ATTRS = {};",""," for (i = 0, len = attrs.length; i < len; ++i) {"," ATTRS[attrs[i]] = {};"," }"," } else if (isObject(attrs)) {"," ATTRS = attrs;"," }",""," return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });"," },",""," /**"," Tears down the instance.",""," @method destructor"," @protected"," @since 3.6.0"," **/"," destructor: function () {"," new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();"," },",""," /**"," The getter for the `columns` attribute. Returns the array of column"," configuration objects if `instance.get('columns')` is called, or the"," specific column object if `instance.get('columns.columnKey')` is called.",""," @method _getColumns"," @param {Object[]} columns The full array of column objects"," @param {String} name The attribute name requested"," (e.g. 'columns' or 'columns.foo');"," @protected"," @since 3.5.0"," **/"," _getColumns: function (columns, name) {"," // Workaround for an attribute oddity (ticket #2529254)"," // getter is expected to return an object if get('columns.foo') is called."," // Note 'columns.' is 8 characters"," return name.length > 8 ? this._columnMap : columns;"," },",""," /**"," Relays the `get()` request for the deprecated `columnset` attribute to the"," `columns` attribute.",""," THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will"," expect a Columnset instance returned from `get('columnset')`.",""," @method _getColumnset"," @param {Object} ignored The current value stored in the `columnset` state"," @param {String} name The attribute name requested"," (e.g. 'columnset' or 'columnset.foo');"," @deprecated This will be removed with the `columnset` attribute in a future"," version."," @protected"," @since 3.5.0"," **/"," _getColumnset: function (_, name) {"," return this.get(name.replace(/^columnset/, 'columns'));"," },",""," /**"," Returns the Model class of the instance's `data` attribute ModelList. If"," not set, returns the explicitly configured value.",""," @method _getRecordType"," @param {Model} val The currently configured value"," @return {Model}"," **/"," _getRecordType: function (val) {"," // Prefer the value stored in the attribute because the attribute"," // change event defaultFn sets e.newVal = this.get('recordType')"," // before notifying the after() subs. But if this getter returns"," // this.data.model, then after() subs would get e.newVal === previous"," // model before _afterRecordTypeChange can set"," // this.data.model = e.newVal"," return val || (this.data && this.data.model);"," },",""," /**"," Initializes the `_columnMap` property from the configured `columns`"," attribute. If `columns` is not set, but there are records in the `data`"," ModelList, use"," `ATTRS` of that class.",""," @method _initColumns"," @protected"," @since 3.5.0"," **/"," _initColumns: function () {"," var columns = this.get('columns') || [],"," item;"," "," // Default column definition from the configured recordType"," if (!columns.length && this.data.size()) {"," // TODO: merge superclass attributes up to Model?"," item = this.data.item(0);",""," if (item.toJSON) {"," item = item.toJSON();"," }",""," this.set('columns', keys(item));"," }",""," this._setColumnMap(columns);"," },",""," /**"," Sets up the change event subscriptions to maintain internal state.",""," @method _initCoreEvents"," @protected"," @since 3.6.0"," **/"," _initCoreEvents: function () {"," this._eventHandles.coreAttrChanges = this.after({"," columnsChange : Y.bind('_afterColumnsChange', this),"," recordTypeChange: Y.bind('_afterRecordTypeChange', this),"," dataChange : Y.bind('_afterDataChange', this)"," });"," },",""," /**"," Defaults the `data` attribute to an empty ModelList if not set during"," construction. Uses the configured `recordType` for the ModelList's `model`"," proeprty if set.",""," @method _initData"," @protected"," @return {ModelList}"," @since 3.6.0"," **/"," _initData: function () {"," var recordType = this.get('recordType'),"," // TODO: LazyModelList if recordType doesn't have complex ATTRS"," modelList = new Y.ModelList();",""," if (recordType) {"," modelList.model = recordType;"," }",""," return modelList;"," },",""," /**"," Initializes the instance's `data` property from the value of the `data`"," attribute. If the attribute value is a ModelList, it is assigned directly"," to `this.data`. If it is an array, a ModelList is created, its `model`"," property is set to the configured `recordType` class, and it is seeded with"," the array data. This ModelList is then assigned to `this.data`.",""," @method _initDataProperty"," @param {Array|ModelList|ArrayList} data Collection of data to populate the"," DataTable"," @protected"," @since 3.6.0"," **/"," _initDataProperty: function (data) {"," var recordType;",""," if (!this.data) {"," recordType = this.get('recordType');",""," if (data && data.each && data.toJSON) {"," this.data = data;",""," if (recordType) {"," this.data.model = recordType;"," }"," } else {"," // TODO: customize the ModelList or read the ModelList class"," // from a configuration option?"," this.data = new Y.ModelList();"," "," if (recordType) {"," this.data.model = recordType;"," }"," }",""," // TODO: Replace this with an event relay for specific events."," // Using bubbling causes subscription conflicts with the models'"," // aggregated change event and 'change' events from DOM elements"," // inside the table (via Widget UI event)."," this.data.addTarget(this);"," }"," },",""," /**"," Initializes the columns, `recordType` and data ModelList.",""," @method initializer"," @param {Object} config Configuration object passed to constructor"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," var data = config.data,"," columns = config.columns,"," recordType;",""," // Referencing config.data to allow _setData to be more stringent"," // about its behavior"," this._initDataProperty(data);",""," // Default columns from recordType ATTRS if recordType is supplied at"," // construction. If no recordType is supplied, but the data is"," // supplied as a non-empty array, use the keys of the first item"," // as the columns."," if (!columns) {"," recordType = (config.recordType || config.data === this.data) &&"," this.get('recordType');",""," if (recordType) {"," columns = keys(recordType.ATTRS);"," } else if (isArray(data) && data.length) {"," columns = keys(data[0]);"," }",""," if (columns) {"," this.set('columns', columns);"," }"," }",""," this._initColumns();",""," this._eventHandles = {};",""," this._initCoreEvents();"," },",""," /**"," Iterates the array of column configurations to capture all columns with a"," `key` property. An map is built with column keys as the property name and"," the corresponding column object as the associated value. This map is then"," assigned to the instance's `_columnMap` property.",""," @method _setColumnMap"," @param {Object[]|String[]} columns The array of column config objects"," @protected"," @since 3.6.0"," **/"," _setColumnMap: function (columns) {"," var map = {};"," "," function process(cols) {"," var i, len, col, key;",""," for (i = 0, len = cols.length; i < len; ++i) {"," col = cols[i];"," key = col.key;",""," // First in wins for multiple columns with the same key"," // because the first call to genId (in _setColumns) will"," // return the same key, which will then be overwritten by the"," // subsequent same-keyed column. So table.getColumn(key) would"," // return the last same-keyed column."," if (key && !map[key]) {"," map[key] = col;"," }",""," //TODO: named columns can conflict with keyed columns"," map[col._id] = col;",""," if (col.children) {"," process(col.children);"," }"," }"," }",""," process(columns);",""," this._columnMap = map;"," },",""," /**"," Translates string columns into objects with that string as the value of its"," `key` property.",""," All columns are assigned a `_yuid` stamp and `_id` property corresponding"," to the column's configured `name` or `key` property with any spaces"," replaced with dashes. If the same `name` or `key` appears in multiple"," columns, subsequent appearances will have their `_id` appended with an"," incrementing number (e.g. if column \"foo\" is included in the `columns`"," attribute twice, the first will get `_id` of \"foo\", and the second an `_id`"," of \"foo1\"). Columns that are children of other columns will have the"," `_parent` property added, assigned the column object to which they belong.",""," @method _setColumns"," @param {null|Object[]|String[]} val Array of config objects or strings"," @return {null|Object[]}"," @protected"," **/"," _setColumns: function (val) {"," var keys = {},"," known = [],"," knownCopies = [],"," arrayIndex = Y.Array.indexOf;"," "," function copyObj(o) {"," var copy = {},"," key, val, i;",""," known.push(o);"," knownCopies.push(copy);",""," for (key in o) {"," if (o.hasOwnProperty(key)) {"," val = o[key];",""," if (isArray(val)) {"," copy[key] = val.slice();"," } else if (isObject(val, true)) {"," i = arrayIndex(val, known);",""," copy[key] = i === -1 ? copyObj(val) : knownCopies[i];"," } else {"," copy[key] = o[key];"," }"," }"," }",""," return copy;"," }",""," function genId(name) {"," // Sanitize the name for use in generated CSS classes."," // TODO: is there more to do for other uses of _id?"," name = name.replace(/\\s+/, '-');",""," if (keys[name]) {"," name += (keys[name]++);"," } else {"," keys[name] = 1;"," }",""," return name;"," }",""," function process(cols, parent) {"," var columns = [],"," i, len, col, yuid;",""," for (i = 0, len = cols.length; i < len; ++i) {"," columns[i] = // chained assignment"," col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);",""," yuid = Y.stamp(col);",""," // For backward compatibility"," if (!col.id) {"," // Implementers can shoot themselves in the foot by setting"," // this config property to a non-unique value"," col.id = yuid;"," }"," if (col.field) {"," // Field is now known as \"name\" to avoid confusion with data"," // fields or schema.resultFields"," col.name = col.field;"," }",""," if (parent) {"," col._parent = parent;"," } else {"," delete col._parent;"," }",""," // Unique id based on the column's configured name or key,"," // falling back to the yuid. Duplicates will have a counter"," // added to the end."," col._id = genId(col.name || col.key || col.id);",""," if (isArray(col.children)) {"," col.children = process(col.children, col);"," }"," }",""," return columns;"," }",""," return val && process(val);"," },",""," /**"," Relays attribute assignments of the deprecated `columnset` attribute to the"," `columns` attribute. If a Columnset is object is passed, its basic object"," structure is mined.",""," @method _setColumnset"," @param {Array|Columnset} val The columnset value to relay"," @deprecated This will be removed with the deprecated `columnset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setColumnset: function (val) {"," this.set('columns', val);",""," return isArray(val) ? val : INVALID;"," },",""," /**"," Accepts an object with `each` and `getAttrs` (preferably a ModelList or"," subclass) or an array of data objects. If an array is passes, it will"," create a ModelList to wrap the data. In doing so, it will set the created"," ModelList's `model` property to the class in the `recordType` attribute,"," which will be defaulted if not yet set.",""," If the `data` property is already set with a ModelList, passing an array as"," the value will call the ModelList's `reset()` method with that array rather"," than replacing the stored ModelList wholesale.",""," Any non-ModelList-ish and non-array value is invalid.",""," @method _setData"," @protected"," @since 3.5.0"," **/"," _setData: function (val) {"," if (val === null) {"," val = [];"," }",""," if (isArray(val)) {"," this._initDataProperty();",""," // silent to prevent subscribers to both reset and dataChange"," // from reacting to the change twice."," // TODO: would it be better to return INVALID to silence the"," // dataChange event, or even allow both events?"," this.data.reset(val, { silent: true });",""," // Return the instance ModelList to avoid storing unprocessed"," // data in the state and their vivified Model representations in"," // the instance's data property. Decreases memory consumption."," val = this.data;"," } else if (!val || !val.each || !val.toJSON) {"," // ModelList/ArrayList duck typing"," val = INVALID;"," }",""," return val;"," },",""," /**"," Relays the value assigned to the deprecated `recordset` attribute to the"," `data` attribute. If a Recordset instance is passed, the raw object data"," will be culled from it.",""," @method _setRecordset"," @param {Object[]|Recordset} val The recordset value to relay"," @deprecated This will be removed with the deprecated `recordset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setRecordset: function (val) {"," var data;",""," if (val && Y.Recordset && val instanceof Y.Recordset) {"," data = [];"," val.each(function (record) {"," data.push(record.get('data'));"," });"," val = data;"," }",""," this.set('data', val);",""," return val;"," },",""," /**"," Accepts a Base subclass (preferably a Model subclass). Alternately, it will"," generate a custom Model subclass from an array of attribute names or an"," object defining attributes and their respective configurations (it is"," assigned as the `ATTRS` of the new class).",""," Any other value is invalid.",""," @method _setRecordType"," @param {Function|String[]|Object} val The Model subclass, array of"," attribute names, or the `ATTRS` definition for a custom model"," subclass"," @return {Function} A Base/Model subclass"," @protected"," @since 3.5.0"," **/"," _setRecordType: function (val) {"," var modelClass;",""," // Duck type based on known/likely consumed APIs"," if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {"," modelClass = val;"," } else if (isObject(val)) {"," modelClass = this._createRecordClass(val);"," }",""," return modelClass || INVALID;"," }","","});","","","}, '@VERSION@', {\"requires\": [\"escape\", \"model-list\", \"node-event-delegate\"]});"]; _yuitest_coverage["build/datatable-core/datatable-core.js"].lines = {"1":0,"11":0,"38":0,"40":0,"201":0,"232":0,"234":0,"239":0,"241":0,"244":0,"245":0,"248":0,"250":0,"251":0,"252":0,"254":0,"255":0,"258":0,"261":0,"279":0,"281":0,"282":0,"283":0,"287":0,"288":0,"292":0,"345":0,"358":0,"360":0,"362":0,"365":0,"378":0,"380":0,"382":0,"384":0,"385":0,"386":0,"388":0,"407":0,"409":0,"410":0,"412":0,"413":0,"415":0,"416":0,"419":0,"430":0,"449":0,"469":0,"487":0,"501":0,"505":0,"507":0,"509":0,"510":0,"513":0,"516":0,"527":0,"545":0,"549":0,"550":0,"553":0,"570":0,"572":0,"573":0,"575":0,"576":0,"578":0,"579":0,"584":0,"586":0,"587":0,"595":0,"608":0,"614":0,"620":0,"621":0,"624":0,"625":0,"626":0,"627":0,"630":0,"631":0,"635":0,"637":0,"639":0,"654":0,"656":0,"657":0,"659":0,"660":0,"661":0,"668":0,"669":0,"673":0,"675":0,"676":0,"681":0,"683":0,"705":0,"710":0,"711":0,"714":0,"715":0,"717":0,"718":0,"719":0,"721":0,"722":0,"723":0,"724":0,"726":0,"728":0,"733":0,"736":0,"739":0,"741":0,"742":0,"744":0,"747":0,"750":0,"751":0,"754":0,"755":0,"758":0,"761":0,"764":0,"766":0,"769":0,"772":0,"773":0,"775":0,"781":0,"783":0,"784":0,"788":0,"791":0,"807":0,"809":0,"830":0,"831":0,"834":0,"835":0,"841":0,"846":0,"847":0,"849":0,"852":0,"868":0,"870":0,"871":0,"872":0,"873":0,"875":0,"878":0,"880":0,"900":0,"903":0,"904":0,"905":0,"906":0,"909":0}; _yuitest_coverage["build/datatable-core/datatable-core.js"].functions = {"getColumn:231":0,"getRecord:278":0,"_afterColumnsChange:344":0,"_afterDataChange:357":0,"_afterRecordTypeChange:377":0,"_createRecordClass:406":0,"destructor:429":0,"_getColumns:445":0,"_getColumnset:468":0,"_getRecordType:480":0,"_initColumns:500":0,"_initCoreEvents:526":0,"_initData:544":0,"_initDataProperty:569":0,"initializer:607":0,"process:656":0,"_setColumnMap:653":0,"copyObj:710":0,"genId:736":0,"process:750":0,"_setColumns:704":0,"_setColumnset:806":0,"_setData:829":0,"(anonymous 2):872":0,"_setRecordset:867":0,"_setRecordType:899":0,"(anonymous 1):1":0}; _yuitest_coverage["build/datatable-core/datatable-core.js"].coveredLines = 162; _yuitest_coverage["build/datatable-core/datatable-core.js"].coveredFunctions = 27; _yuitest_coverline("build/datatable-core/datatable-core.js", 1); YUI.add('datatable-core', function (Y, NAME) { /** The core implementation of the `DataTable` and `DataTable.Base` Widgets. @module datatable @submodule datatable-core @since 3.5.0 **/ _yuitest_coverfunc("build/datatable-core/datatable-core.js", "(anonymous 1)", 1); _yuitest_coverline("build/datatable-core/datatable-core.js", 11); var INVALID = Y.Attribute.INVALID_VALUE, Lang = Y.Lang, isFunction = Lang.isFunction, isObject = Lang.isObject, isArray = Lang.isArray, isString = Lang.isString, isNumber = Lang.isNumber, toArray = Y.Array, keys = Y.Object.keys, Table; /** _API docs for this extension are included in the DataTable class._ Class extension providing the core API and structure for the DataTable Widget. Use this class extension with Widget or another Base-based superclass to create the basic DataTable model API and composing class structure. @class DataTable.Core @for DataTable @since 3.5.0 **/ _yuitest_coverline("build/datatable-core/datatable-core.js", 38); Table = Y.namespace('DataTable').Core = function () {}; _yuitest_coverline("build/datatable-core/datatable-core.js", 40); Table.ATTRS = { /** Columns to include in the rendered table. If omitted, the attributes on the configured `recordType` or the first item in the `data` collection will be used as a source. This attribute takes an array of strings or objects (mixing the two is fine). Each string or object is considered a column to be rendered. Strings are converted to objects, so `columns: ['first', 'last']` becomes `columns: [{ key: 'first' }, { key: 'last' }]`. DataTable.Core only concerns itself with a few properties of columns. These properties are: * `key` - Used to identify the record field/attribute containing content for this column. Also used to create a default Model if no `recordType` or `data` are provided during construction. If `name` is not specified, this is assigned to the `_id` property (with added incrementer if the key is used by multiple columns). * `children` - Traversed to initialize nested column objects * `name` - Used in place of, or in addition to, the `key`. Useful for columns that aren't bound to a field/attribute in the record data. This is assigned to the `_id` property. * `id` - For backward compatibility. Implementers can specify the id of the header cell. This should be avoided, if possible, to avoid the potential for creating DOM elements with duplicate IDs. * `field` - For backward compatibility. Implementers should use `name`. * `_id` - Assigned unique-within-this-instance id for a column. By order of preference, assumes the value of `name`, `key`, `id`, or `_yuid`. This is used by the rendering views as well as feature module as a means to identify a specific column without ambiguity (such as multiple columns using the same `key`. * `_yuid` - Guid stamp assigned to the column object. * `_parent` - Assigned to all child columns, referencing their parent column. @attribute columns @type {Object[]|String[]} @default (from `recordType` ATTRS or first item in the `data`) @since 3.5.0 **/ columns: { // TODO: change to setter to clone input array/objects validator: isArray, setter: '_setColumns', getter: '_getColumns' }, /** Model subclass to use as the `model` for the ModelList stored in the `data` attribute. If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value: 1. If the `data` attribute is set with a ModelList instance and its `model` property is set, that will be used. 2. If the `data` attribute is set with a ModelList instance, and its `model` property is unset, but it is populated, the `ATTRS` of the `constructor of the first item will be used. 3. If the `data` attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as its `ATTRS` (see the `_createRecordClass` method). 4. If the `columns` attribute is set, a Model subclass will be generated using the columns defined with a `key`. This is least desirable because columns can be duplicated or nested in a way that's not parsable. 5. If neither `data` nor `columns` is set or populated, a change event subscriber will listen for the first to be changed and try all over again. @attribute recordType @type {Function} @default (see description) @since 3.5.0 **/ recordType: { getter: '_getRecordType', setter: '_setRecordType' }, /** The collection of data records to display. This attribute is a pass through to a `data` property, which is a ModelList instance. If this attribute is passed a ModelList or subclass, it will be assigned to the property directly. If an array of objects is passed, a new ModelList will be created using the configured `recordType` as its `model` property and seeded with the array. Retrieving this attribute will return the ModelList stored in the `data` property. @attribute data @type {ModelList|Object[]} @default `new ModelList()` @since 3.5.0 **/ data: { valueFn: '_initData', setter : '_setData', lazyAdd: false }, /** Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned to this attribute will be HTML escaped for security. @attribute summary @type {String} @default '' (empty string) @since 3.5.0 **/ //summary: {}, /** HTML content of an optional `<caption>` element to appear above the table. Leave this config unset or set to a falsy value to remove the caption. @attribute caption @type HTML @default '' (empty string) @since 3.5.0 **/ //caption: {}, /** Deprecated as of 3.5.0. Passes through to the `data` attribute. WARNING: `get('recordset')` will NOT return a Recordset instance as of 3.5.0. This is a break in backward compatibility. @attribute recordset @type {Object[]|Recordset} @deprecated Use the `data` attribute @since 3.5.0 **/ recordset: { setter: '_setRecordset', getter: '_getRecordset', lazyAdd: false }, /** Deprecated as of 3.5.0. Passes through to the `columns` attribute. WARNING: `get('columnset')` will NOT return a Columnset instance as of 3.5.0. This is a break in backward compatibility. @attribute columnset @type {Object[]} @deprecated Use the `columns` attribute @since 3.5.0 **/ columnset: { setter: '_setColumnset', getter: '_getColumnset', lazyAdd: false } }; _yuitest_coverline("build/datatable-core/datatable-core.js", 201); Y.mix(Table.prototype, { // -- Instance properties ------------------------------------------------- /** The ModelList that manages the table's data. @property data @type {ModelList} @default undefined (initially unset) @since 3.5.0 **/ //data: null, // -- Public methods ------------------------------------------------------ /** Gets the column configuration object for the given key, name, or index. For nested columns, `name` can be an array of indexes, each identifying the index of that column in the respective parent's "children" array. If you pass a column object, it will be returned. For columns with keys, you can also fetch the column with `instance.get('columns.foo')`. @method getColumn @param {String|Number|Number[]} name Key, "name", index, or index array to identify the column @return {Object} the column configuration object @since 3.5.0 **/ getColumn: function (name) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "getColumn", 231); _yuitest_coverline("build/datatable-core/datatable-core.js", 232); var col, columns, i, len, cols; _yuitest_coverline("build/datatable-core/datatable-core.js", 234); if (isObject(name) && !isArray(name)) { // TODO: support getting a column from a DOM node - this will cross // the line into the View logic, so it should be relayed // Assume an object passed in is already a column def _yuitest_coverline("build/datatable-core/datatable-core.js", 239); col = name; } else { _yuitest_coverline("build/datatable-core/datatable-core.js", 241); col = this.get('columns.' + name); } _yuitest_coverline("build/datatable-core/datatable-core.js", 244); if (col) { _yuitest_coverline("build/datatable-core/datatable-core.js", 245); return col; } _yuitest_coverline("build/datatable-core/datatable-core.js", 248); columns = this.get('columns'); _yuitest_coverline("build/datatable-core/datatable-core.js", 250); if (isNumber(name) || isArray(name)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 251); name = toArray(name); _yuitest_coverline("build/datatable-core/datatable-core.js", 252); cols = columns; _yuitest_coverline("build/datatable-core/datatable-core.js", 254); for (i = 0, len = name.length - 1; cols && i < len; ++i) { _yuitest_coverline("build/datatable-core/datatable-core.js", 255); cols = cols[name[i]] && cols[name[i]].children; } _yuitest_coverline("build/datatable-core/datatable-core.js", 258); return (cols && cols[name[i]]) || null; } _yuitest_coverline("build/datatable-core/datatable-core.js", 261); return null; }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If none of those yield a Model from the `data` ModelList, the arguments will be passed to the `view` instance's `getRecord` method if it has one. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "getRecord", 278); _yuitest_coverline("build/datatable-core/datatable-core.js", 279); var record = this.data.getById(seed) || this.data.getByClientId(seed); _yuitest_coverline("build/datatable-core/datatable-core.js", 281); if (!record) { _yuitest_coverline("build/datatable-core/datatable-core.js", 282); if (isNumber(seed)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 283); record = this.data.item(seed); } // TODO: this should be split out to base somehow _yuitest_coverline("build/datatable-core/datatable-core.js", 287); if (!record && this.view && this.view.getRecord) { _yuitest_coverline("build/datatable-core/datatable-core.js", 288); record = this.view.getRecord.apply(this.view, arguments); } } _yuitest_coverline("build/datatable-core/datatable-core.js", 292); return record || null; }, // -- Protected and private properties and methods ------------------------ /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to DataTable's constructor. This is useful for setting configurations on the DataTable that are intended for the rendering View(s). @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.6.0 **/ _allowAdHocAttrs: true, /** A map of column key to column configuration objects parsed from the `columns` attribute. @property _columnMap @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_columnMap: null, /** The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source. @property _tableNode @type {Node} @default undefined (initially unset) @protected @since 3.5.0 **/ //_tableNode: null, /** Updates the `_columnMap` property in response to changes in the `columns` attribute. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ _afterColumnsChange: function (e) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_afterColumnsChange", 344); _yuitest_coverline("build/datatable-core/datatable-core.js", 345); this._setColumnMap(e.newVal); }, /** Updates the `modelList` attributes of the rendered views in response to the `data` attribute being assigned a new ModelList. @method _afterDataChange @param {EventFacade} e the `dataChange` event @protected @since 3.5.0 **/ _afterDataChange: function (e) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_afterDataChange", 357); _yuitest_coverline("build/datatable-core/datatable-core.js", 358); var modelList = e.newVal; _yuitest_coverline("build/datatable-core/datatable-core.js", 360); this.data = e.newVal; _yuitest_coverline("build/datatable-core/datatable-core.js", 362); if (!this.get('columns') && modelList.size()) { // TODO: this will cause a re-render twice because the Views are // subscribed to columnsChange _yuitest_coverline("build/datatable-core/datatable-core.js", 365); this._initColumns(); } }, /** Assigns to the new recordType as the model for the data ModelList @method _afterRecordTypeChange @param {EventFacade} e recordTypeChange event @protected @since 3.6.0 **/ _afterRecordTypeChange: function (e) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_afterRecordTypeChange", 377); _yuitest_coverline("build/datatable-core/datatable-core.js", 378); var data = this.data.toJSON(); _yuitest_coverline("build/datatable-core/datatable-core.js", 380); this.data.model = e.newVal; _yuitest_coverline("build/datatable-core/datatable-core.js", 382); this.data.reset(data); _yuitest_coverline("build/datatable-core/datatable-core.js", 384); if (!this.get('columns') && data) { _yuitest_coverline("build/datatable-core/datatable-core.js", 385); if (data.length) { _yuitest_coverline("build/datatable-core/datatable-core.js", 386); this._initColumns(); } else { _yuitest_coverline("build/datatable-core/datatable-core.js", 388); this.set('columns', keys(e.newVal.ATTRS)); } } }, /** Creates a Model subclass from an array of attribute names or an object of attribute definitions. This is used to generate a class suitable to represent the data passed to the `data` attribute if no `recordType` is set. @method _createRecordClass @param {String[]|Object} attrs Names assigned to the Model subclass's `ATTRS` or its entire `ATTRS` definition object @return {Model} @protected @since 3.5.0 **/ _createRecordClass: function (attrs) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_createRecordClass", 406); _yuitest_coverline("build/datatable-core/datatable-core.js", 407); var ATTRS, i, len; _yuitest_coverline("build/datatable-core/datatable-core.js", 409); if (isArray(attrs)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 410); ATTRS = {}; _yuitest_coverline("build/datatable-core/datatable-core.js", 412); for (i = 0, len = attrs.length; i < len; ++i) { _yuitest_coverline("build/datatable-core/datatable-core.js", 413); ATTRS[attrs[i]] = {}; } } else {_yuitest_coverline("build/datatable-core/datatable-core.js", 415); if (isObject(attrs)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 416); ATTRS = attrs; }} _yuitest_coverline("build/datatable-core/datatable-core.js", 419); return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS }); }, /** Tears down the instance. @method destructor @protected @since 3.6.0 **/ destructor: function () { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "destructor", 429); _yuitest_coverline("build/datatable-core/datatable-core.js", 430); new Y.EventHandle(Y.Object.values(this._eventHandles)).detach(); }, /** The getter for the `columns` attribute. Returns the array of column configuration objects if `instance.get('columns')` is called, or the specific column object if `instance.get('columns.columnKey')` is called. @method _getColumns @param {Object[]} columns The full array of column objects @param {String} name The attribute name requested (e.g. 'columns' or 'columns.foo'); @protected @since 3.5.0 **/ _getColumns: function (columns, name) { // Workaround for an attribute oddity (ticket #2529254) // getter is expected to return an object if get('columns.foo') is called. // Note 'columns.' is 8 characters _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_getColumns", 445); _yuitest_coverline("build/datatable-core/datatable-core.js", 449); return name.length > 8 ? this._columnMap : columns; }, /** Relays the `get()` request for the deprecated `columnset` attribute to the `columns` attribute. THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will expect a Columnset instance returned from `get('columnset')`. @method _getColumnset @param {Object} ignored The current value stored in the `columnset` state @param {String} name The attribute name requested (e.g. 'columnset' or 'columnset.foo'); @deprecated This will be removed with the `columnset` attribute in a future version. @protected @since 3.5.0 **/ _getColumnset: function (_, name) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_getColumnset", 468); _yuitest_coverline("build/datatable-core/datatable-core.js", 469); return this.get(name.replace(/^columnset/, 'columns')); }, /** Returns the Model class of the instance's `data` attribute ModelList. If not set, returns the explicitly configured value. @method _getRecordType @param {Model} val The currently configured value @return {Model} **/ _getRecordType: function (val) { // Prefer the value stored in the attribute because the attribute // change event defaultFn sets e.newVal = this.get('recordType') // before notifying the after() subs. But if this getter returns // this.data.model, then after() subs would get e.newVal === previous // model before _afterRecordTypeChange can set // this.data.model = e.newVal _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_getRecordType", 480); _yuitest_coverline("build/datatable-core/datatable-core.js", 487); return val || (this.data && this.data.model); }, /** Initializes the `_columnMap` property from the configured `columns` attribute. If `columns` is not set, but there are records in the `data` ModelList, use `ATTRS` of that class. @method _initColumns @protected @since 3.5.0 **/ _initColumns: function () { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_initColumns", 500); _yuitest_coverline("build/datatable-core/datatable-core.js", 501); var columns = this.get('columns') || [], item; // Default column definition from the configured recordType _yuitest_coverline("build/datatable-core/datatable-core.js", 505); if (!columns.length && this.data.size()) { // TODO: merge superclass attributes up to Model? _yuitest_coverline("build/datatable-core/datatable-core.js", 507); item = this.data.item(0); _yuitest_coverline("build/datatable-core/datatable-core.js", 509); if (item.toJSON) { _yuitest_coverline("build/datatable-core/datatable-core.js", 510); item = item.toJSON(); } _yuitest_coverline("build/datatable-core/datatable-core.js", 513); this.set('columns', keys(item)); } _yuitest_coverline("build/datatable-core/datatable-core.js", 516); this._setColumnMap(columns); }, /** Sets up the change event subscriptions to maintain internal state. @method _initCoreEvents @protected @since 3.6.0 **/ _initCoreEvents: function () { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_initCoreEvents", 526); _yuitest_coverline("build/datatable-core/datatable-core.js", 527); this._eventHandles.coreAttrChanges = this.after({ columnsChange : Y.bind('_afterColumnsChange', this), recordTypeChange: Y.bind('_afterRecordTypeChange', this), dataChange : Y.bind('_afterDataChange', this) }); }, /** Defaults the `data` attribute to an empty ModelList if not set during construction. Uses the configured `recordType` for the ModelList's `model` proeprty if set. @method _initData @protected @return {ModelList} @since 3.6.0 **/ _initData: function () { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_initData", 544); _yuitest_coverline("build/datatable-core/datatable-core.js", 545); var recordType = this.get('recordType'), // TODO: LazyModelList if recordType doesn't have complex ATTRS modelList = new Y.ModelList(); _yuitest_coverline("build/datatable-core/datatable-core.js", 549); if (recordType) { _yuitest_coverline("build/datatable-core/datatable-core.js", 550); modelList.model = recordType; } _yuitest_coverline("build/datatable-core/datatable-core.js", 553); return modelList; }, /** Initializes the instance's `data` property from the value of the `data` attribute. If the attribute value is a ModelList, it is assigned directly to `this.data`. If it is an array, a ModelList is created, its `model` property is set to the configured `recordType` class, and it is seeded with the array data. This ModelList is then assigned to `this.data`. @method _initDataProperty @param {Array|ModelList|ArrayList} data Collection of data to populate the DataTable @protected @since 3.6.0 **/ _initDataProperty: function (data) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_initDataProperty", 569); _yuitest_coverline("build/datatable-core/datatable-core.js", 570); var recordType; _yuitest_coverline("build/datatable-core/datatable-core.js", 572); if (!this.data) { _yuitest_coverline("build/datatable-core/datatable-core.js", 573); recordType = this.get('recordType'); _yuitest_coverline("build/datatable-core/datatable-core.js", 575); if (data && data.each && data.toJSON) { _yuitest_coverline("build/datatable-core/datatable-core.js", 576); this.data = data; _yuitest_coverline("build/datatable-core/datatable-core.js", 578); if (recordType) { _yuitest_coverline("build/datatable-core/datatable-core.js", 579); this.data.model = recordType; } } else { // TODO: customize the ModelList or read the ModelList class // from a configuration option? _yuitest_coverline("build/datatable-core/datatable-core.js", 584); this.data = new Y.ModelList(); _yuitest_coverline("build/datatable-core/datatable-core.js", 586); if (recordType) { _yuitest_coverline("build/datatable-core/datatable-core.js", 587); this.data.model = recordType; } } // TODO: Replace this with an event relay for specific events. // Using bubbling causes subscription conflicts with the models' // aggregated change event and 'change' events from DOM elements // inside the table (via Widget UI event). _yuitest_coverline("build/datatable-core/datatable-core.js", 595); this.data.addTarget(this); } }, /** Initializes the columns, `recordType` and data ModelList. @method initializer @param {Object} config Configuration object passed to constructor @protected @since 3.5.0 **/ initializer: function (config) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "initializer", 607); _yuitest_coverline("build/datatable-core/datatable-core.js", 608); var data = config.data, columns = config.columns, recordType; // Referencing config.data to allow _setData to be more stringent // about its behavior _yuitest_coverline("build/datatable-core/datatable-core.js", 614); this._initDataProperty(data); // Default columns from recordType ATTRS if recordType is supplied at // construction. If no recordType is supplied, but the data is // supplied as a non-empty array, use the keys of the first item // as the columns. _yuitest_coverline("build/datatable-core/datatable-core.js", 620); if (!columns) { _yuitest_coverline("build/datatable-core/datatable-core.js", 621); recordType = (config.recordType || config.data === this.data) && this.get('recordType'); _yuitest_coverline("build/datatable-core/datatable-core.js", 624); if (recordType) { _yuitest_coverline("build/datatable-core/datatable-core.js", 625); columns = keys(recordType.ATTRS); } else {_yuitest_coverline("build/datatable-core/datatable-core.js", 626); if (isArray(data) && data.length) { _yuitest_coverline("build/datatable-core/datatable-core.js", 627); columns = keys(data[0]); }} _yuitest_coverline("build/datatable-core/datatable-core.js", 630); if (columns) { _yuitest_coverline("build/datatable-core/datatable-core.js", 631); this.set('columns', columns); } } _yuitest_coverline("build/datatable-core/datatable-core.js", 635); this._initColumns(); _yuitest_coverline("build/datatable-core/datatable-core.js", 637); this._eventHandles = {}; _yuitest_coverline("build/datatable-core/datatable-core.js", 639); this._initCoreEvents(); }, /** Iterates the array of column configurations to capture all columns with a `key` property. An map is built with column keys as the property name and the corresponding column object as the associated value. This map is then assigned to the instance's `_columnMap` property. @method _setColumnMap @param {Object[]|String[]} columns The array of column config objects @protected @since 3.6.0 **/ _setColumnMap: function (columns) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_setColumnMap", 653); _yuitest_coverline("build/datatable-core/datatable-core.js", 654); var map = {}; _yuitest_coverline("build/datatable-core/datatable-core.js", 656); function process(cols) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "process", 656); _yuitest_coverline("build/datatable-core/datatable-core.js", 657); var i, len, col, key; _yuitest_coverline("build/datatable-core/datatable-core.js", 659); for (i = 0, len = cols.length; i < len; ++i) { _yuitest_coverline("build/datatable-core/datatable-core.js", 660); col = cols[i]; _yuitest_coverline("build/datatable-core/datatable-core.js", 661); key = col.key; // First in wins for multiple columns with the same key // because the first call to genId (in _setColumns) will // return the same key, which will then be overwritten by the // subsequent same-keyed column. So table.getColumn(key) would // return the last same-keyed column. _yuitest_coverline("build/datatable-core/datatable-core.js", 668); if (key && !map[key]) { _yuitest_coverline("build/datatable-core/datatable-core.js", 669); map[key] = col; } //TODO: named columns can conflict with keyed columns _yuitest_coverline("build/datatable-core/datatable-core.js", 673); map[col._id] = col; _yuitest_coverline("build/datatable-core/datatable-core.js", 675); if (col.children) { _yuitest_coverline("build/datatable-core/datatable-core.js", 676); process(col.children); } } } _yuitest_coverline("build/datatable-core/datatable-core.js", 681); process(columns); _yuitest_coverline("build/datatable-core/datatable-core.js", 683); this._columnMap = map; }, /** Translates string columns into objects with that string as the value of its `key` property. All columns are assigned a `_yuid` stamp and `_id` property corresponding to the column's configured `name` or `key` property with any spaces replaced with dashes. If the same `name` or `key` appears in multiple columns, subsequent appearances will have their `_id` appended with an incrementing number (e.g. if column "foo" is included in the `columns` attribute twice, the first will get `_id` of "foo", and the second an `_id` of "foo1"). Columns that are children of other columns will have the `_parent` property added, assigned the column object to which they belong. @method _setColumns @param {null|Object[]|String[]} val Array of config objects or strings @return {null|Object[]} @protected **/ _setColumns: function (val) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_setColumns", 704); _yuitest_coverline("build/datatable-core/datatable-core.js", 705); var keys = {}, known = [], knownCopies = [], arrayIndex = Y.Array.indexOf; _yuitest_coverline("build/datatable-core/datatable-core.js", 710); function copyObj(o) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "copyObj", 710); _yuitest_coverline("build/datatable-core/datatable-core.js", 711); var copy = {}, key, val, i; _yuitest_coverline("build/datatable-core/datatable-core.js", 714); known.push(o); _yuitest_coverline("build/datatable-core/datatable-core.js", 715); knownCopies.push(copy); _yuitest_coverline("build/datatable-core/datatable-core.js", 717); for (key in o) { _yuitest_coverline("build/datatable-core/datatable-core.js", 718); if (o.hasOwnProperty(key)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 719); val = o[key]; _yuitest_coverline("build/datatable-core/datatable-core.js", 721); if (isArray(val)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 722); copy[key] = val.slice(); } else {_yuitest_coverline("build/datatable-core/datatable-core.js", 723); if (isObject(val, true)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 724); i = arrayIndex(val, known); _yuitest_coverline("build/datatable-core/datatable-core.js", 726); copy[key] = i === -1 ? copyObj(val) : knownCopies[i]; } else { _yuitest_coverline("build/datatable-core/datatable-core.js", 728); copy[key] = o[key]; }} } } _yuitest_coverline("build/datatable-core/datatable-core.js", 733); return copy; } _yuitest_coverline("build/datatable-core/datatable-core.js", 736); function genId(name) { // Sanitize the name for use in generated CSS classes. // TODO: is there more to do for other uses of _id? _yuitest_coverfunc("build/datatable-core/datatable-core.js", "genId", 736); _yuitest_coverline("build/datatable-core/datatable-core.js", 739); name = name.replace(/\s+/, '-'); _yuitest_coverline("build/datatable-core/datatable-core.js", 741); if (keys[name]) { _yuitest_coverline("build/datatable-core/datatable-core.js", 742); name += (keys[name]++); } else { _yuitest_coverline("build/datatable-core/datatable-core.js", 744); keys[name] = 1; } _yuitest_coverline("build/datatable-core/datatable-core.js", 747); return name; } _yuitest_coverline("build/datatable-core/datatable-core.js", 750); function process(cols, parent) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "process", 750); _yuitest_coverline("build/datatable-core/datatable-core.js", 751); var columns = [], i, len, col, yuid; _yuitest_coverline("build/datatable-core/datatable-core.js", 754); for (i = 0, len = cols.length; i < len; ++i) { _yuitest_coverline("build/datatable-core/datatable-core.js", 755); columns[i] = // chained assignment col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]); _yuitest_coverline("build/datatable-core/datatable-core.js", 758); yuid = Y.stamp(col); // For backward compatibility _yuitest_coverline("build/datatable-core/datatable-core.js", 761); if (!col.id) { // Implementers can shoot themselves in the foot by setting // this config property to a non-unique value _yuitest_coverline("build/datatable-core/datatable-core.js", 764); col.id = yuid; } _yuitest_coverline("build/datatable-core/datatable-core.js", 766); if (col.field) { // Field is now known as "name" to avoid confusion with data // fields or schema.resultFields _yuitest_coverline("build/datatable-core/datatable-core.js", 769); col.name = col.field; } _yuitest_coverline("build/datatable-core/datatable-core.js", 772); if (parent) { _yuitest_coverline("build/datatable-core/datatable-core.js", 773); col._parent = parent; } else { _yuitest_coverline("build/datatable-core/datatable-core.js", 775); delete col._parent; } // Unique id based on the column's configured name or key, // falling back to the yuid. Duplicates will have a counter // added to the end. _yuitest_coverline("build/datatable-core/datatable-core.js", 781); col._id = genId(col.name || col.key || col.id); _yuitest_coverline("build/datatable-core/datatable-core.js", 783); if (isArray(col.children)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 784); col.children = process(col.children, col); } } _yuitest_coverline("build/datatable-core/datatable-core.js", 788); return columns; } _yuitest_coverline("build/datatable-core/datatable-core.js", 791); return val && process(val); }, /** Relays attribute assignments of the deprecated `columnset` attribute to the `columns` attribute. If a Columnset is object is passed, its basic object structure is mined. @method _setColumnset @param {Array|Columnset} val The columnset value to relay @deprecated This will be removed with the deprecated `columnset` attribute in a later version. @protected @since 3.5.0 **/ _setColumnset: function (val) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_setColumnset", 806); _yuitest_coverline("build/datatable-core/datatable-core.js", 807); this.set('columns', val); _yuitest_coverline("build/datatable-core/datatable-core.js", 809); return isArray(val) ? val : INVALID; }, /** Accepts an object with `each` and `getAttrs` (preferably a ModelList or subclass) or an array of data objects. If an array is passes, it will create a ModelList to wrap the data. In doing so, it will set the created ModelList's `model` property to the class in the `recordType` attribute, which will be defaulted if not yet set. If the `data` property is already set with a ModelList, passing an array as the value will call the ModelList's `reset()` method with that array rather than replacing the stored ModelList wholesale. Any non-ModelList-ish and non-array value is invalid. @method _setData @protected @since 3.5.0 **/ _setData: function (val) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_setData", 829); _yuitest_coverline("build/datatable-core/datatable-core.js", 830); if (val === null) { _yuitest_coverline("build/datatable-core/datatable-core.js", 831); val = []; } _yuitest_coverline("build/datatable-core/datatable-core.js", 834); if (isArray(val)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 835); this._initDataProperty(); // silent to prevent subscribers to both reset and dataChange // from reacting to the change twice. // TODO: would it be better to return INVALID to silence the // dataChange event, or even allow both events? _yuitest_coverline("build/datatable-core/datatable-core.js", 841); this.data.reset(val, { silent: true }); // Return the instance ModelList to avoid storing unprocessed // data in the state and their vivified Model representations in // the instance's data property. Decreases memory consumption. _yuitest_coverline("build/datatable-core/datatable-core.js", 846); val = this.data; } else {_yuitest_coverline("build/datatable-core/datatable-core.js", 847); if (!val || !val.each || !val.toJSON) { // ModelList/ArrayList duck typing _yuitest_coverline("build/datatable-core/datatable-core.js", 849); val = INVALID; }} _yuitest_coverline("build/datatable-core/datatable-core.js", 852); return val; }, /** Relays the value assigned to the deprecated `recordset` attribute to the `data` attribute. If a Recordset instance is passed, the raw object data will be culled from it. @method _setRecordset @param {Object[]|Recordset} val The recordset value to relay @deprecated This will be removed with the deprecated `recordset` attribute in a later version. @protected @since 3.5.0 **/ _setRecordset: function (val) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_setRecordset", 867); _yuitest_coverline("build/datatable-core/datatable-core.js", 868); var data; _yuitest_coverline("build/datatable-core/datatable-core.js", 870); if (val && Y.Recordset && val instanceof Y.Recordset) { _yuitest_coverline("build/datatable-core/datatable-core.js", 871); data = []; _yuitest_coverline("build/datatable-core/datatable-core.js", 872); val.each(function (record) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "(anonymous 2)", 872); _yuitest_coverline("build/datatable-core/datatable-core.js", 873); data.push(record.get('data')); }); _yuitest_coverline("build/datatable-core/datatable-core.js", 875); val = data; } _yuitest_coverline("build/datatable-core/datatable-core.js", 878); this.set('data', val); _yuitest_coverline("build/datatable-core/datatable-core.js", 880); return val; }, /** Accepts a Base subclass (preferably a Model subclass). Alternately, it will generate a custom Model subclass from an array of attribute names or an object defining attributes and their respective configurations (it is assigned as the `ATTRS` of the new class). Any other value is invalid. @method _setRecordType @param {Function|String[]|Object} val The Model subclass, array of attribute names, or the `ATTRS` definition for a custom model subclass @return {Function} A Base/Model subclass @protected @since 3.5.0 **/ _setRecordType: function (val) { _yuitest_coverfunc("build/datatable-core/datatable-core.js", "_setRecordType", 899); _yuitest_coverline("build/datatable-core/datatable-core.js", 900); var modelClass; // Duck type based on known/likely consumed APIs _yuitest_coverline("build/datatable-core/datatable-core.js", 903); if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) { _yuitest_coverline("build/datatable-core/datatable-core.js", 904); modelClass = val; } else {_yuitest_coverline("build/datatable-core/datatable-core.js", 905); if (isObject(val)) { _yuitest_coverline("build/datatable-core/datatable-core.js", 906); modelClass = this._createRecordClass(val); }} _yuitest_coverline("build/datatable-core/datatable-core.js", 909); return modelClass || INVALID; } }); }, '@VERSION@', {"requires": ["escape", "model-list", "node-event-delegate"]});
app/m_login/m_login.js
jefferchang/reactApp
import 'bootstrap/less/bootstrap.less'; import React from 'react' import { render } from 'react-dom' import { Router, browserHistory} from 'react-router' const rootRoute = { component: 'div', childRoutes: [{ path: '/', component: require('./../components/login/Login'), childRoutes: [ require('./../routes/Login') ] }] } render( <Router history={browserHistory} routes={rootRoute} /> , document.getElementById('loginDiv'));
powerauth-webflow/src/main/js/components/approvalSca.js
lime-company/powerauth-webflow
/* * PowerAuth Web Flow and related software components * Copyright (C) 2019 Wultra s.r.o. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import {connect} from 'react-redux'; // Actions import {cancel, confirm, getOperationData, init} from "../actions/approvalScaActions"; // Components import Spinner from './spinner'; import {Button, Panel} from "react-bootstrap"; import OperationTimeout from "./operationTimeout"; import OperationDetail from "./operationDetail"; import {FormattedMessage} from "react-intl"; import {checkClientCertificate} from "../actions/loginScaActions"; /** * SCA approval component. */ @connect((store) => { return { context: store.dispatching.context } }) export default class ApprovalSca extends React.Component { constructor() { super(); this.handleSubmit = this.handleSubmit.bind(this); this.handleCancel = this.handleCancel.bind(this); } componentWillMount() { const dispatch = this.props.dispatch; dispatch(init(function(initSucceeded) { if (initSucceeded) { // continue only when init() succeeds dispatch(getOperationData()); } })); } handleSubmit(event) { event.preventDefault(); const dispatch = this.props.dispatch; if (this.props.context.clientCertificateUsed) { const certificateVerificationUrl = this.props.context.clientCertificateVerificationUrl; const callbackOnSuccess = function() { // Authentication is performed using client certificate dispatch(confirm()); }; dispatch(checkClientCertificate(certificateVerificationUrl, callbackOnSuccess)); } else { dispatch(confirm()); } } handleCancel(event) { event.preventDefault(); this.props.dispatch(cancel()); } render() { if (this.props.context.formData || this.props.context.data) { return ( <div id="operation"> <form onSubmit={this.handleSubmit}> <Panel> <OperationTimeout timeoutCheckActive="true"/> <OperationDetail/> {(this.props.context.clientCertificateUsed) ? ( <div> <FormattedMessage id="clientCertificate.approval"/> </div> ): undefined} <div className="auth-actions"> <div className="row buttons"> <div className="col-xs-6"> <a href="#" onClick={this.handleCancel} className="btn btn-lg btn-default"> <FormattedMessage id="operation.cancel"/> </a> </div> <div className="col-xs-6"> <Button bsSize="lg" type="submit" bsStyle="success" block> <FormattedMessage id="operation.confirm"/> </Button> </div> </div> </div> </Panel> </form> </div> ) } else { return ( <div id="operation"> <Spinner/> </div> ) } } }
__tests__/index.ios.js
kararnab/Property-Finder
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/templates/categories-list-template.js
apalhu/website
// @flow strict import React from 'react'; import { Link } from 'gatsby'; import kebabCase from 'lodash/kebabCase'; import Sidebar from '../components/Sidebar'; import Layout from '../components/Layout'; import Page from '../components/Page'; import { useSiteMetadata, useCategoriesList } from '../hooks'; const CategoriesListTemplate = () => { const { title, subtitle } = useSiteMetadata(); const categories = useCategoriesList(); return ( <Layout title={`Categories - ${title}`} description={subtitle}> <Sidebar /> <Page title="Categories"> <ul> {categories.map((category) => ( <li key={category.fieldValue}> <Link to={`/category/${kebabCase(category.fieldValue)}/`}> {category.fieldValue} ({category.totalCount}) </Link> </li> ))} </ul> </Page> </Layout> ); }; export default CategoriesListTemplate;
packages/mineral-ui-icons/src/IconGraphicEq.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconGraphicEq(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M7 18h2V6H7v12zm4 4h2V2h-2v20zm-8-8h2v-4H3v4zm12 4h2V6h-2v12zm4-8v4h2v-4h-2z"/> </g> </Icon> ); } IconGraphicEq.displayName = 'IconGraphicEq'; IconGraphicEq.category = 'device';
src/Badge/Badge.spec.js
andrejunges/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import Badge from './Badge'; import getMuiTheme from '../styles/getMuiTheme'; describe('<Badge />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); const badgeTheme = muiTheme.badge; const testChildren = <div className="unique">Hello World</div>; it('renders children and badgeContent', () => { const wrapper = shallowWithContext( <Badge badgeContent={10}>{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); assert.ok(wrapper.find('span').length, 'should contain the badgeContent'); }); it('renders children and overwrite badge styles', () => { const badgeStyle = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <Badge badgeContent={10} badgeStyle={badgeStyle}>{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); assert.equal(wrapper.find('span').node.props.style.backgroundColor, badgeStyle.backgroundColor, 'should overwrite badge backgroundColor'); }); it('renders children by default', () => { const wrapper = shallowWithContext( <Badge badgeContent={10}>{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); }); it('renders children and className', () => { const wrapper = shallowWithContext( <Badge badgeContent={10} className="testClassName">{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); assert.ok(wrapper.is('.testClassName'), 'should contain the className'); }); it('renders children and have primary styles', () => { const wrapper = shallowWithContext( <Badge badgeContent={10} primary={true}>{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); assert.equal(wrapper.find('span').node.props.style.backgroundColor, badgeTheme.primaryColor, 'should have primary badge backgroundColor'); assert.equal(wrapper.find('span').node.props.style.color, badgeTheme.primaryTextColor, 'should have primary badge text color'); }); it('renders children and have secondary styles', () => { const wrapper = shallowWithContext( <Badge badgeContent={10} secondary={true}>{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); assert.equal(wrapper.find('span').node.props.style.backgroundColor, badgeTheme.secondaryColor, 'should have secondary badge backgroundColor'); assert.equal(wrapper.find('span').node.props.style.color, badgeTheme.secondaryTextColor, 'should have secondary badge text color'); }); it('renders children and overwrite root styles', () => { const style = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <Badge badgeContent={10} style={style}>{testChildren}</Badge> ); assert.ok(wrapper.contains(testChildren), 'should contain the children'); assert.equal(wrapper.node.props.style.backgroundColor, style.backgroundColor, 'should overwrite badge backgroundColor'); }); });
src/components/WorkshopMap.js
r-portas/robogals-brisbane-pwa
import React, { Component } from 'react'; class WorkshopMap extends Component { constructor(props) { super(props); this.map = null; this.markers = [ {position: {lat: -27.497686, lng: 153.014022}, title: 'University of Queensland'}, {position: {lat: -27.476547, lng: 153.027841}, title: 'Queensland University of Technology'}, {position: {lat: -27.476690, lng: 153.020662}, title: 'Griffith'} ] this.markerObjs = []; this.options = { center: {lat: -27.4698, lng: 153.0251}, zoom: 13 }; this.setupMap = this.setupMap.bind(this); } createMarker(position, title) { const marker = new window.google.maps.Marker({ map: this.map, position: position }); const infoWindow = new window.google.maps.InfoWindow({ content: ` <div> <h1>${title}</h1> </div> ` }); marker.addListener('click', () => { infoWindow.open(this.map, marker) }); this.markerObjs.push(marker); } renderMarkers() { this.markers.map((marker) => this.createMarker(marker.position, marker.title)); } listMarkers() { return this.markers.map((marker) => { return <li key={marker.title}>{marker.title}</li>; }); } setupMap(ref) { if(ref) { this.map = new window.google.maps.Map(ref, this.options); this.renderMarkers(); } } render() { const style = {height: '300px'}; return ( <div> <div ref={this.setupMap} style={style} /> <div className="content"> <h1>Upcoming Events</h1> <ul> {this.listMarkers()} </ul> </div> </div> ); } } export default WorkshopMap;
server/server.js
saltykovdg/mern-react-redux-nodejs-express-todo-list
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; import IntlWrapper from '../client/modules/Intl/IntlWrapper'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // Initialize the Express App const app = new Express(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import todos from './routes/todo.routes'; import todosDummyData from './todosDummyData'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } // feed some dummy data in DB. todosDummyData(); }); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '20mb' })); app.use(bodyParser.urlencoded({ limit: '20mb', extended: false })); app.use(Express.static(path.resolve(__dirname, '../dist'))); app.use(Express.static(path.resolve(__dirname, './resources'))); app.use('/api', todos); // Render Initial HTML const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link rel="stylesheet" href="./css/bootstrap.min.css"> </head> <body> <div id="root">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <IntlWrapper> <RouterContext {...renderProps} /> </IntlWrapper> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // start app app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running: http://localhost:${serverConfig.port}`); // eslint-disable-line } }); export default app;