code
stringlengths
2
1.05M
// Replaces all require('mano').db with require to base db setup e.g. require('../../db'); 'use strict'; var repeat = require('es5-ext/string/#/repeat') , globalRewrite = require('../utils/global-rewrite') , re1 = /require\('mano'\)\.db(?!D)/g , re2 = /mano\.db(?!D)/g; module.exports = function (path) { return globalRewrite(path, function (content, path) { var nest, replaceString; if (path === 'db.js') return; nest = repeat.call('../', path.split('/').length - 1); replaceString = 'require(\'' + (nest || './') + 'db\')'; return content.replace(re1, replaceString).replace(re2, replaceString); }); };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; module.metadata = { "stability": "experimental" }; const { Cc, Ci, Cr, Cu } = require("chrome"); const { Class } = require("./heritage"); const { isWeak } = require("./reference"); const method = require("../../method/core"); const observerService = Cc['@mozilla.org/observer-service;1']. getService(Ci.nsIObserverService); const { ShimWaiver } = Cu.import("resource://gre/modules/ShimWaiver.jsm"); const addObserver = ShimWaiver.getProperty(observerService, "addObserver"); const removeObserver = ShimWaiver.getProperty(observerService, "removeObserver"); // This is a method that will be invoked when notification observer // subscribed to occurs. const observe = method("observer/observe"); exports.observe = observe; // Method to subscribe to the observer notification. const subscribe = method("observe/subscribe"); exports.subscribe = subscribe; // Method to unsubscribe from the observer notifications. const unsubscribe = method("observer/unsubscribe"); exports.unsubscribe = unsubscribe; // This is wrapper class that takes a `delegate` and produces // instance of `nsIObserver` which will delegate to a given // object when observer notification occurs. const ObserverDelegee = Class({ initialize: function(delegate) { this.delegate = delegate; }, QueryInterface: function(iid) { if (!iid.equals(Ci.nsIObserver) && !iid.equals(Ci.nsISupportsWeakReference) && !iid.equals(Ci.nsISupports)) throw Cr.NS_ERROR_NO_INTERFACE; return this; }, observe: function(subject, topic, data) { observe(this.delegate, subject, topic, data); } }); // Class that can be either mixed in or inherited from in // order to subscribe / unsubscribe for observer notifications. const Observer = Class({}); exports.Observer = Observer; // Weak maps that associates instance of `ObserverDelegee` with // an actual observer. It ensures that `ObserverDelegee` instance // won't be GC-ed until given `observer` is. const subscribers = new WeakMap(); // Implementation of `subscribe` for `Observer` type just registers // observer for an observer service. If `isWeak(observer)` is `true` // observer service won't hold strong reference to a given `observer`. subscribe.define(Observer, (observer, topic) => { if (!subscribers.has(observer)) { const delegee = new ObserverDelegee(observer); subscribers.set(observer, delegee); addObserver(delegee, topic, isWeak(observer)); } }); // Unsubscribes `observer` from observer notifications for the // given `topic`. unsubscribe.define(Observer, (observer, topic) => { const delegee = subscribers.get(observer); if (delegee) { subscribers.delete(observer); removeObserver(delegee, topic); } });
/** * @project Piball * @author André Lademann <vergissberlin@googlemail.com> * @copyright Copyright (c) 2016 piball.io (http://www.piball.io) * @license http://piball.io/license */ var Badge = (function () { var helper; Badge.colours = { green: [67, 157, 161, 255], red: [235, 0, 0, 255], blue: [0, 27, 110, 255] }; Badge.keys = { scoresTotal: 'scoresTotal', eventsMissed: 'eventsMissed' }; /** * Constructor with basic setup */ function Badge() { helper.checkDependencies(); this.setColour('green'); } helper = { /** * Check object dependencies * * @author André Lademann <andre@programmerq.eu> * @private * @throws Exception * @returns {*} */ checkDependencies: function () { if (typeof Store === 'undefined') { throw 'Dependency error: Please load Store object!' } if (typeof chrome === 'undefined') { throw 'Dependency error: This only works in Chrome and Chromium!' } return this; }, /** * Validate score of a game * * @param teamOne * @param teamTwo * @returns {boolean} */ validateScore: function (teamOne, teamTwo) { return !( teamOne > 10 || teamTwo > 10 || teamOne + teamTwo >= 20 ); }, /** * Validate total missed events * * @param eventCount * @returns {string} */ validateEventMissed: function (eventCount) { eventCount = parseInt(eventCount); if (eventCount > 0) { eventCount = (eventCount > 999) ? '999+' : eventCount.toString(); } else { eventCount = ''; } return eventCount; } }; /** * Get badge text * @returns {*} */ Badge.prototype.get = function () { return chrome.browserAction.getBadgeText(); }; /** * Set badge text * * @param message * @returns {Badge} */ Badge.prototype.set = function (message, colour) { if (arguments[0] === undefined) { throw 'Invalid badge text'; } else { if (arguments[1] != undefined) { this.colours(colour); } message = isNaN(message) ? message : message+''; chrome.browserAction.setBadgeText({text: message}); } return this; }; /** * Remove badge bubble * * @returns {Badge} */ Badge.prototype.remove = function () { //Store.removeItem(this.badgeKey); this.setColour('green'); this.set(''); return this; }; /** * Set badge score * * @param teamOne * @param teamTwo * @returns {Badge} */ Badge.prototype.setScore = function (teamOne, teamTwo) { if (this.helper.validateScore(teamOne, teamTwo)) { this.remove(); } else { teamOne = isNaN(teamOne) ? teamOne : teamOne.toString(); teamTwo = isNaN(teamTwo) ? teamTwo : teamTwo.toString(); // @todo remove events from this place if (teamOne === 10 || teamTwo === 10) { this.setColour('red'); } if ((teamOne === 10 || teamTwo === 10) && (teamOne === 0 || teamTwo === 0) ) { console.log('goal'); } else { this.setColour('green'); } this.set(teamOne + ':' + teamTwo); } return this; } ; /** * Set number of missed events * * @param eventMissed number of missed events * @returns {Badge} */ Badge.prototype.setEventMissed = function (eventMissed) { this.set(this.helper.validateEventMissed(eventMissed)); return this; }; /** * Set badge text * * @param colour * @returns {Badge} */ Badge.prototype.setColour = function (colour) { if (colour === 'green') { chrome.browserAction.setBadgeBackgroundColor({color: Badge.colours.green}); } else if (colour === 'red') { chrome.browserAction.setBadgeBackgroundColor({color: Badge.colours.red}); } else if (colour === 'blue') { chrome.browserAction.setBadgeBackgroundColor({color: Badge.colours.blue}); } else { throw 'Invalid colour identifier' } return this; }; return Badge; })(chrome);
/*globals require, console*/ 'use strict'; var production = false; var gulp = require('gulp'); var browserify = require('browserify'); var watchify = require('watchify'); var imagemin = require('gulp-imagemin'); var browserSync = require('browser-sync'); var source = require('vinyl-source-stream'); var reactify = require('reactify'); var gutil = require('gulp-util'); var notify = require('gulp-notify'); gulp.task('default', ['server', 'watch']); gulp.task('compile', ['scripts', 'css', 'html', 'assets']); gulp.task('server', function() { return browserSync.init(['./dist/**/*'], { server: { baseDir: './dist' } }); }); gulp.task('watch', ['watchScripts', 'watchHtml', 'watchCSS']); gulp.task('watchCSS', function() { return gulp.watch('src/css/*.css', ['css']); }); gulp.task('watchHtml', function() { return gulp.watch('src/index.html', ['html']); }); gulp.task('scripts', function() { return scripts(browserify); }); gulp.task('watchScripts', function() { return scripts(watchify); }); function scripts(handler) { var scriptFile = './src/js/app.js'; var bundler = handler(scriptFile); bundler.transform(reactify); var rebundle = function() { var stream = bundler.bundle({ debug: !production }); stream.on('error', function(err) { gutil.beep(); console.log('Browserify error : ' + err); }).on('error', notify.onError({ message: 'Error: <%= error.message %>', title: 'Browserify error' })); return stream.pipe(source('bundle.js')).pipe(gulp.dest('dist/js')); }; bundler.on('update', rebundle); return rebundle(); } gulp.task('css', function() { return gulp.src('src/css/*.css').pipe(gulp.dest('dist/css')); }); gulp.task('html', function() { return gulp.src('src/index.html').pipe(gulp.dest('dist')); }); gulp.task('assets', function() { return gulp.src(['src/assets/*.png', 'src/assets/*.jpg']).pipe(imagemin()).pipe(gulp.dest('dist/assets')); });
"use strict"; var util = require("./util"); var table = module.exports; var getNewConfig = function () { return { head: [ { id: "icon" , label : " " , width: 3, paddingRight: true , visible: true }, { id: "line" , label : "Line" , width: 6, paddingRight: true , visible: true }, { id: "col" , label : "Col" , width: 6, paddingRight: true , visible: true }, { id: "code" , label : "Code" , width: 6, paddingRight: true , visible: false }, { id: "error" , label : "Error" , width: 50, paddingRight: false, visible: true }, { id: "evidence", label : "Evidence", width: null, paddingRight: false, visible: true } ], style: { paddingLeft: " ", paddingRight: " ", minWidth: 20 } }; }; var TableManager = function (verbose) { this._initialize(verbose); }; TableManager.prototype = { constructor: TableManager, setRows: function (rows) { this.rows.push(rows); }, getRow: function (rowId) { var cols = this.options.head; for (var i = 0, n = cols.length; i < n; ++i) { if (cols[i].id === rowId) { return cols[i]; } } return null; }, _initialize: function (verbose) { this.options = getNewConfig(); this.rows = []; var stdCols = process.stdout.columns || 100; var cfg = this.options.head; var minWidth = this.options.style.minWidth; var lastRow = this.getRow("evidence"); var errorRow = this.getRow("error"); if (verbose) { this.getRow("code").visible = true; } var total = this.options.head.reduce(function (prev, curr) { return { width: prev.width + ((curr.visible && curr.width) || 0) }; }); lastRow.width = stdCols - total.width; lastRow.width = lastRow.width - (util.win32 ? 1 : 0); // The last column needs to be hidden if (lastRow.width <= minWidth || cfg.hideLastColumn) { errorRow.width += lastRow.width; this.options.head.pop(); } }, _trim: function (column, text) { var style = this.options.style; var width = column.width - style.paddingLeft.length- style.paddingRight.length; text = text || ""; return text.length > width ? text.substring(0, width - 1) + "…" : this._pad(text, width, column.paddingRight); }, // pad numbers _pad: function (text, width, right, character) { text = text + ""; character = character || " "; if (text.length >= width) { return text; } return right ? new Array(width - text.length + 1).join(character) + text : text + new Array(width - text.length + 1).join(character) ; }, toString: function () { var result = ""; var that = this; var style = this.options.style; var stdCols = process.stdout.columns || 100; var draw = util.colors.draw; var text = null; var columns = this.options.head; // Header result += util.symbols.left + this._pad("", stdCols - 2, false, "─") + util.symbols.right; result += util.win32 ? "" : "\n"; columns.forEach(function (col) { if (!col.visible) { return; } text = that._trim(col, col.label); result += style.paddingLeft + draw("table.head", text) + style.paddingRight; }); result += "\n"; // Body this.rows.forEach(function (row) { columns.forEach(function (col, iCol) { if (!col.visible) { return; } text = that._trim(col, row[iCol]); result += style.paddingLeft + draw("table." + col.id, text) + style.paddingRight; }); result += "\n"; }); return result; } }; // Initialize table style table.getTable = function (verbose) { return new TableManager(verbose); };
const moment = require('moment'); const scrapeOne = require(__dirname + '/scrape_one'); var test = module.exports = exports = function(res, daysToScrape, endDate) { daysToScrape = daysToScrape || 1; queryDate = endDate ? moment(new Date(endDate)) : moment(); var promiseArr = []; for (var i = 0; i < daysToScrape; i++) { var displayDate = queryDate.format('M-D-YYYY'); var scrapePromise = scrapeOne(res, displayDate); promiseArr.push(scrapePromise); // mutates queryDate queryDate.subtract(1, 'days'); } return Promise.all(promiseArr); };
var React = require('react'); var { PropTypes, } = React; var ReactNative = require('react-native'); var { View, NativeMethodsMixin, requireNativeComponent, StyleSheet, } = ReactNative; var MapCircle = React.createClass({ mixins: [NativeMethodsMixin], propTypes: { ...View.propTypes, /** * The coordinate of the center of the circle */ center: PropTypes.shape({ /** * Coordinates for the center of the circle. */ latitude: PropTypes.number.isRequired, longitude: PropTypes.number.isRequired, }).isRequired, /** * The radius of the circle to be drawn (in meters) */ radius: PropTypes.number.isRequired, /** * Callback that is called when the user presses on the circle */ onPress: PropTypes.func, /** * The stroke width to use for the path. */ strokeWidth: PropTypes.number, /** * The stroke color to use for the path. */ strokeColor: PropTypes.string, /** * The fill color to use for the path. */ fillColor: PropTypes.string, /** * The order in which this tile overlay is drawn with respect to other overlays. An overlay * with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays * with the same z-index is arbitrary. The default zIndex is 0. * * @platform android */ zIndex: PropTypes.number, /** * The line cap style to apply to the open ends of the path. * The default style is `round`. * * @platform ios */ lineCap: PropTypes.oneOf([ 'butt', 'round', 'square', ]), /** * The line join style to apply to corners of the path. * The default style is `round`. * * @platform ios */ lineJoin: PropTypes.oneOf([ 'miter', 'round', 'bevel', ]), /** * The limiting value that helps avoid spikes at junctions between connected line segments. * The miter limit helps you avoid spikes in paths that use the `miter` `lineJoin` style. If * the ratio of the miter length—that is, the diagonal length of the miter join—to the line * thickness exceeds the miter limit, the joint is converted to a bevel join. The default * miter limit is 10, which results in the conversion of miters whose angle at the joint * is less than 11 degrees. * * @platform ios */ miterLimit: PropTypes.number, /** * The offset (in points) at which to start drawing the dash pattern. * * Use this property to start drawing a dashed line partway through a segment or gap. For * example, a phase value of 6 for the patter 5-2-3-2 would cause drawing to begin in the * middle of the first gap. * * The default value of this property is 0. * * @platform ios */ lineDashPhase: PropTypes.number, /** * An array of numbers specifying the dash pattern to use for the path. * * The array contains one or more numbers that indicate the lengths (measured in points) of the * line segments and gaps in the pattern. The values in the array alternate, starting with the * first line segment length, followed by the first gap length, followed by the second line * segment length, and so on. * * This property is set to `null` by default, which indicates no line dash pattern. * * @platform ios */ lineDashPattern: PropTypes.arrayOf(PropTypes.number), }, getDefaultProps: function() { return { strokeColor: '#000', strokeWidth: 1, }; }, _onPress: function(e) { this.props.onPress && this.props.onPress(e); }, render: function() { return ( <AIRMapCircle {...this.props} onPress={this._onPress} /> ); }, }); var AIRMapCircle = requireNativeComponent('AIRMapCircle', MapCircle); module.exports = MapCircle;
/* globals console */ let HasPrintNameMixin = Base => class extends Base { printName() { console.log(`{Name: ${this.name}}`); } }; var ValidationMixin = Base => class extends Base { _isStringValid(str, options = {}) { options.min = options.min || 0; options.max = options.max || Number.MAX_VALUE; return str && (typeof str === "string") && str.length > options.min && str.length < options.max; } }; class Person extends ValidationMixin(HasPrintNameMixin(Object)) { constructor(name, age) { super(); this.name = name; this.age = age; } get name() { return this._name; } set name(name) { if (!this._isStringValid(name)) { throw new Error("Invalid name"); } this._name = name; } } let p = new Person("John", 17); p.printName();
'use strict'; angular.module('directives.on-enter-blur', []) .directive('onEnterBlur', function () { return function ($scope, element, attrs) { element.bind('keydown keypress', function (event) { if (event.which === 13) { element.blur(); event.preventDefault(); } }); }; });
define(['exports'], function (exports) { 'use strict'; var UxDialog = (function () { function UxDialog() { } UxDialog.$view = "<template><slot></slot></template>"; UxDialog.$resource = 'ux-dialog'; return UxDialog; }()); exports.UxDialog = UxDialog; }); //# sourceMappingURL=ux-dialog.js.map
$(function() { var FADE_TIME = 150; // 毫秒 var TYPING_TIMER_LENGTH = 400; // 毫秒 var COLORS = [ 'black', 'grey', 'green', 'blue', 'yellow', 'pink', 'yellow', 'brown', 'orange', 'chocolate', 'midnightblue', 'lavender' ]; //初始化 var $window = $(window); var $usernameInput = $('.usernameInput'); var $messages = $('.messages'); var $inputMessage = $('.inputMessage'); var $loginPage = $('.login.page'); var $chatPage = $('.chat.page'); // 建立用户名 var username; var connected = false; var typing = false; var lastTypingTime; var $currentInput = $usernameInput.focus(); var socket = io(); function addParticipantsMessage (data) { var message = ''; if (data.numUsers === 1) { message += "目前有1位参与者"; } else { message += "目前有 " + data.numUsers + " 位参与者"; } log(message); } // 把输入转换为用户名(trim去掉前后空格) function setUsername () { username = cleanInput($usernameInput.val().trim()); // 用户名正确 切换页面 if (username) { $loginPage.fadeOut(); $chatPage.show(); $loginPage.off('click'); $currentInput = $inputMessage.focus(); // 用户名提交至服务器 socket.emit('add user', username); } } // 发送聊天信息 function sendMessage () { var message = $inputMessage.val(); // 防止混入html标签 message = cleanInput(message); if (message && connected) { $inputMessage.val(''); addChatMessage({ username: username, message: message }); // 告诉服务器 socket.emit('new message', message); } } function log (message, options) { var $el = $('<li>').addClass('log').text(message); addMessageElement($el, options); } // 看不懂! function addChatMessage (data, options) { var $typingMessages = getTypingMessages(data); options = options || {}; if ($typingMessages.length !== 0) { options.fade = false; $typingMessages.remove(); } var $usernameDiv = $('<span class="username"/>') .text(data.username) .css('color', getUsernameColor(data.username)); var $messageBodyDiv = $('<span class="messageBody">') .text(data.message); var typingClass = data.typing ? 'typing' : ''; var $messageDiv = $('<li class="message"/>') .data('username', data.username) .addClass(typingClass) .append($usernameDiv, $messageBodyDiv); addMessageElement($messageDiv, options); } // 添加正在输入 function addChatTyping (data) { data.typing = true; data.message = '正在输入'; addChatMessage(data); } //移除正在输入 function removeChatTyping (data) { getTypingMessages(data).fadeOut(function () { $(this).remove(); }); } // 添加消息并且保持页面在底部?? // options.fade - If the element should fade-in (default = true) // options.prepend - If the element should prepend // all other messages (default = false) function addMessageElement (el, options) { var $el = $(el); // 我也不是很懂...求指导 if (!options) { options = {}; } if (typeof options.fade === 'undefined') { options.fade = true; } if (typeof options.prepend === 'undefined') { options.prepend = false; } // 应用选项 if (options.fade) { $el.hide().fadeIn(FADE_TIME); } if (options.prepend) { $messages.prepend($el); } else { $messages.append($el); } $messages[0].scrollTop = $messages[0].scrollHeight; } //确保输入不包含html标签之类的东西 function cleanInput (input) { return $('<div/>').text(input).text(); } // 更新正在输入事件 查看是否正在输入 function updateTyping () { if (connected) { if (!typing) { typing = true; socket.emit('typing'); } lastTypingTime = (new Date()).getTime(); setTimeout(function () { var typingTimer = (new Date()).getTime(); var timeDiff = typingTimer - lastTypingTime; if (timeDiff >= TYPING_TIMER_LENGTH && typing) { socket.emit('stop typing'); typing = false; } }, TYPING_TIMER_LENGTH); } } // 获得是否正在输入的消息 function getTypingMessages (data) { return $('.typing.message').filter(function (i) { return $(this).data('username') === data.username; }); } // 用户名的颜色 使用哈希函数 function getUsernameColor (username) { // 哈希函数代码 var hash = 7; for (var i = 0; i < username.length; i++) { hash = username.charCodeAt(i) + (hash << 5) - hash; } // 计算颜色 var index = Math.abs(hash % COLORS.length); return COLORS[index]; } // 键盘行为 $window.keydown(function (event) { // 键盘按下自动聚焦 if (!(event.ctrlKey || event.metaKey || event.altKey)) { $currentInput.focus(); } // 按下回车键 if (event.which === 13) { if (username) { sendMessage(); socket.emit('stop typing'); typing = false; } else { setUsername(); } } }); $inputMessage.on('input', function() { updateTyping(); }); // 鼠标点击行为 // 鼠标点击时聚焦输入框 $loginPage.click(function () { $currentInput.focus(); }); $inputMessage.click(function () { $inputMessage.focus(); }); // Socket events // 登录信息 socket.on('login', function (data) { connected = true; var message = "使用socket.io制作 "; log(message, { prepend: true }); addParticipantsMessage(data); }); // 有新信息更新 socket.on('new message', function (data) { addChatMessage(data); }); // 用户加入 socket.on('user joined', function (data) { log(data.username + ' 加入了'); addParticipantsMessage(data); }); // 用户离开 socket.on('user left', function (data) { log(data.username + ' 离开了'); addParticipantsMessage(data); removeChatTyping(data); }); // 正在输入 socket.on('typing', function (data) { addChatTyping(data); }); // 删除输入信息 socket.on('stop typing', function (data) { removeChatTyping(data); }); });
"use strict"; import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import * as Three from 'three'; import {parseData, updateScene} from './scene-creator'; import {disposeScene} from './three-memory-cleaner'; import OrbitControls from './libs/orbit-controls'; import diff from 'immutablediff'; import * as SharedStyle from '../../shared-style'; export default class Scene3DViewer extends React.Component { constructor(props) { super(props); this.lastMousePosition = {}; this.width = props.width; this.height = props.height; this.stopRendering = false; this.renderer = window.__threeRenderer || new Three.WebGLRenderer({preserveDrawingBuffer: true}); window.__threeRenderer = this.renderer; } componentDidMount() { let actions = { areaActions: this.context.areaActions, holesActions: this.context.holesActions, itemsActions: this.context.itemsActions, linesActions: this.context.linesActions, projectActions: this.context.projectActions }; let {state} = this.props; let data = state.scene; let canvasWrapper = ReactDOM.findDOMNode(this.refs.canvasWrapper); let scene3D = new Three.Scene(); //RENDERER this.renderer.setClearColor(new Three.Color(SharedStyle.COLORS.white)); this.renderer.setSize(this.width, this.height); // LOAD DATA let planData = parseData(data, actions, this.context.catalog); scene3D.add(planData.plan); scene3D.add(planData.grid); let aspectRatio = this.width / this.height; let camera = new Three.PerspectiveCamera(45, aspectRatio, 1, 300000); scene3D.add(camera); // Set position for the camera let cameraPositionX = -(planData.boundingBox.max.x - planData.boundingBox.min.x) / 2; let cameraPositionY = (planData.boundingBox.max.y - planData.boundingBox.min.y) / 2 * 10; let cameraPositionZ = (planData.boundingBox.max.z - planData.boundingBox.min.z) / 2; camera.position.set(cameraPositionX, cameraPositionY, cameraPositionZ); camera.up = new Three.Vector3(0, 1, 0); // HELPER AXIS // let axisHelper = new Three.AxisHelper(100); // scene3D.add(axisHelper); // LIGHT let light = new Three.AmbientLight(0xafafaf); // soft white light scene3D.add(light); // Add another light let spotLight1 = new Three.SpotLight(SharedStyle.COLORS.white, 0.30); spotLight1.position.set(cameraPositionX, cameraPositionY, cameraPositionZ); scene3D.add(spotLight1); // OBJECT PICKING let toIntersect = [planData.plan]; let mouse = new Three.Vector2(); let raycaster = new Three.Raycaster(); this.mouseDownEvent = (event) => { this.lastMousePosition.x = event.offsetX / this.width * 2 - 1; this.lastMousePosition.y = -event.offsetY / this.height * 2 + 1; }; this.mouseUpEvent = (event) => { event.preventDefault(); mouse.x = (event.offsetX / this.width) * 2 - 1; mouse.y = -(event.offsetY / this.height) * 2 + 1; if (Math.abs(mouse.x - this.lastMousePosition.x) <= 0.02 && Math.abs(mouse.y - this.lastMousePosition.y) <= 0.02) { raycaster.setFromCamera(mouse, camera); let intersects = raycaster.intersectObjects(toIntersect, true); if (intersects.length > 0 && !(isNaN(intersects[0].distance))) { intersects[0].object.interact && intersects[0].object.interact(); } else { this.context.projectActions.unselectAll(); } } }; this.renderer.domElement.addEventListener('mousedown', this.mouseDownEvent); this.renderer.domElement.addEventListener('mouseup', this.mouseUpEvent); this.renderer.domElement.style.display = 'block'; // add the output of the renderer to the html element canvasWrapper.appendChild(this.renderer.domElement); // create orbit controls let orbitController = new OrbitControls(camera, this.renderer.domElement); let spotLightTarget = new Three.Object3D(); spotLightTarget.position.set(orbitController.target.x, orbitController.target.y, orbitController.target.z); scene3D.add(spotLightTarget); spotLight1.target = spotLightTarget; /************************************/ /********* SCENE EXPORTER ***********/ /************************************/ let exportScene = () => { let convertToBufferGeometry = (geometry) => { console.log("geometry = ", geometry); let bufferGeometry = new Three.BufferGeometry().fromGeometry(geometry); return bufferGeometry; }; scene3D.remove(planData.grid); scene3D.traverse((child) => { console.log(child); if (child instanceof Three.Mesh && !(child.geometry instanceof Three.BufferGeometry)) child.geometry = convertToBufferGeometry(child.geometry); }); let output = scene3D.toJSON(); output = JSON.stringify(output, null, '\t'); output = output.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1'); let name = prompt('insert file name'); name = name.trim() || 'scene'; let blob = new Blob([output], {type: 'text/plain'}); let fileOutputLink = document.createElement('a'); let url = window.URL.createObjectURL(blob); fileOutputLink.setAttribute('download', name); fileOutputLink.href = url; document.body.appendChild(fileOutputLink); fileOutputLink.click(); document.body.removeChild(fileOutputLink); scene3D.add(planData.grid); }; // window.exportScene = exportScene; /************************************/ /************************************/ /********** PLAN EXPORTER ***********/ /************************************/ let exportPlan = () => { let convertToBufferGeometry = (geometry) => { console.log("geometry = ", geometry); return new Three.BufferGeometry().fromGeometry(geometry); }; planData.plan.traverse((child) => { console.log(child); if (child instanceof Three.Mesh && !(child.geometry instanceof Three.BufferGeometry)) child.geometry = convertToBufferGeometry(child.geometry); }); let output = planData.plan.toJSON(); output = JSON.stringify(output, null, '\t'); output = output.replace(/[\n\t]+([\d\.e\-\[\]]+)/g, '$1'); let name = prompt('insert file name'); name = name.trim() || 'plan'; let blob = new Blob([output], {type: 'text/plain'}); let fileOutputLink = document.createElement('a'); let url = window.URL.createObjectURL(blob); fileOutputLink.setAttribute('download', name); fileOutputLink.href = url; document.body.appendChild(fileOutputLink); fileOutputLink.click(); document.body.removeChild(fileOutputLink); scene3D.add(planData.grid); }; // window.exportPlan = exportPlan; /************************************/ let render = () => { if (!this.stopRendering) { orbitController.update(); spotLight1.position.set(camera.position.x, camera.position.y, camera.position.z); spotLightTarget.position.set(orbitController.target.x, orbitController.target.y, orbitController.target.z); camera.updateMatrix(); camera.updateMatrixWorld(); for (let elemID in planData.sceneGraph.LODs) { planData.sceneGraph.LODs[elemID].update(camera) } this.renderer.render(scene3D, camera); requestAnimationFrame(render); } }; render(); this.orbitControls = orbitController; this.camera = camera; this.scene3D = scene3D; this.planData = planData; } componentWillUnmount() { this.orbitControls.dispose(); this.stopRendering = true; this.renderer.domElement.removeEventListener('mousedown', this.mouseDownEvent); this.renderer.domElement.removeEventListener('mouseup', this.mouseUpEvent); disposeScene(this.scene3D); this.scene3D.remove(this.planData.plan); this.scene3D.remove(this.planData.grid); this.scene3D = null; // this.planData.sceneGraph = null; this.planData = null; } componentWillReceiveProps(nextProps) { let {width, height} = nextProps; let {camera, renderer, scene3D} = this; let actions = { areaActions: this.context.areaActions, holesActions: this.context.holesActions, itemsActions: this.context.itemsActions, linesActions: this.context.linesActions, projectActions: this.context.projectActions }; this.width = width; this.height = height; camera.aspect = width / height; camera.updateProjectionMatrix(); if (nextProps.state.scene !== this.props.state.scene) { let changedValues = diff(this.props.state.scene, nextProps.state.scene); updateScene(this.planData, nextProps.state.scene, this.props.state.scene, changedValues.toJS(), actions, this.context.catalog); } renderer.setSize(width, height); //renderer.render(scene3D, camera); } render() { return React.createElement("div", { ref: "canvasWrapper" }); } } Scene3DViewer.propTypes = { state: PropTypes.object.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired }; Scene3DViewer.contextTypes = { areaActions: PropTypes.object.isRequired, holesActions: PropTypes.object.isRequired, itemsActions: PropTypes.object.isRequired, linesActions: PropTypes.object.isRequired, projectActions: PropTypes.object.isRequired, catalog: PropTypes.object };
var TextBoxDefinition = { defaultWidth: 100, defaultHeight: null }; export default TextBoxDefinition;
this.primereact = this.primereact || {}; this.primereact.csstransition = (function (exports, React, reactTransitionGroup) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var React__default = /*#__PURE__*/_interopDefaultLegacy(React); 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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var CSSTransition = /*#__PURE__*/function (_Component) { _inherits(CSSTransition, _Component); var _super = _createSuper(CSSTransition); function CSSTransition(props) { var _this; _classCallCheck(this, CSSTransition); _this = _super.call(this, props); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntering = _this.onEntering.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExit = _this.onExit.bind(_assertThisInitialized(_this)); _this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); return _this; } _createClass(CSSTransition, [{ key: "onEnter", value: function onEnter(node, isAppearing) { this.props.onEnter && this.props.onEnter(node, isAppearing); // component this.props.options && this.props.options.onEnter && this.props.options.onEnter(node, isAppearing); // user option } }, { key: "onEntering", value: function onEntering(node, isAppearing) { this.props.onEntering && this.props.onEntering(node, isAppearing); // component this.props.options && this.props.options.onEntering && this.props.options.onEntering(node, isAppearing); // user option } }, { key: "onEntered", value: function onEntered(node, isAppearing) { this.props.onEntered && this.props.onEntered(node, isAppearing); // component this.props.options && this.props.options.onEntered && this.props.options.onEntered(node, isAppearing); // user option } }, { key: "onExit", value: function onExit(node) { this.props.onExit && this.props.onExit(node); // component this.props.options && this.props.options.onExit && this.props.options.onExit(node); // user option } }, { key: "onExiting", value: function onExiting(node) { this.props.onExiting && this.props.onExiting(node); // component this.props.options && this.props.options.onExiting && this.props.options.onExiting(node); // user option } }, { key: "onExited", value: function onExited(node) { this.props.onExited && this.props.onExited(node); // component this.props.options && this.props.options.onExited && this.props.options.onExited(node); // user option } }, { key: "render", value: function render() { var immutableProps = { nodeRef: this.props.nodeRef, in: this.props.in, onEnter: this.onEnter, onEntering: this.onEntering, onEntered: this.onEntered, onExit: this.onExit, onExiting: this.onExiting, onExited: this.onExited }; var mutableProps = { classNames: this.props.classNames, timeout: this.props.timeout, unmountOnExit: this.props.unmountOnExit }; var props = _objectSpread(_objectSpread(_objectSpread({}, mutableProps), this.props.options || {}), immutableProps); return /*#__PURE__*/React__default['default'].createElement(reactTransitionGroup.CSSTransition, props, this.props.children); } }]); return CSSTransition; }(React.Component); exports.CSSTransition = CSSTransition; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}, React, ReactTransitionGroup));
define(['../internal/arrayReduceRight', '../internal/baseCallback', '../internal/baseEachRight', '../internal/baseReduce', '../lang/isArray'], function(arrayReduceRight, baseCallback, baseEachRight, baseReduce, isArray) { /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {*} Returns the accumulated value. * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * _.reduceRight(array, function(flattened, other) { return flattened.concat(other); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator, thisArg) { var func = isArray(collection) ? arrayReduceRight : baseReduce; return func(collection, baseCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEachRight); } return reduceRight; });
require('babel-register')(); require.extensions['.css'] = function() {};
/*! * Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('body').on('click', '.page-scroll a', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1200, 'easeInOutExpo'); event.preventDefault(); }); }); // Floating label headings for the contact form $(function() { $("body").on("input propertychange", ".floating-label-form-group", function(e) { $(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val()); }).on("focus", ".floating-label-form-group", function() { $(this).addClass("floating-label-form-group-with-focus"); }).on("blur", ".floating-label-form-group", function() { $(this).removeClass("floating-label-form-group-with-focus"); }); }); // Highlight the top nav as scrolling occurs $('body').scrollspy({ target: '.navbar-fixed-top' }) // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); });
define([ // '../../../../src/utils/realPath' ], function( // realPath ){ var realPath = hello.utils.realPath; // // Events // describe('utils / realPath', function(){ var test_location_root = window.location.protocol + "//" + window.location.hostname; var test_location_dir = window.location.pathname.replace(/\/[^\/]+$/, '/'); var test_location_filename = 'redirect.html'; it('should return current URL, if no URL is given', function(){ var path = realPath(); expect( path ).to.equal( window.location.href ); }); it('should return a full URL, if a full URL is given', function(){ var url = 'http://test/' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( url ); }); it('should return a full URL, if a protocol-less URL is given', function(){ var url = '//test/' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( window.location.protocol + url ); }); it('should return a full URL, if a base-path is given', function(){ var url = '/test/' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( test_location_root + url ); }); it('should return a full URL, if a relative-path is given', function(){ var url = './' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( test_location_root + ( test_location_dir + url.replace('./', '') ) ); }); it('should return a full URL, if a relative-ascendant-path is given', function(){ var url = '../' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( test_location_root + test_location_dir.replace(/\/[^\/]+\/$/, '/') + test_location_filename ); }); it('should return a full URL, if a deeper relative-ascendant-path is given', function(){ var url = '../../' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( test_location_root + test_location_dir.replace(/\/[^\/]+\/$/, '/').replace(/\/[^\/]+\/$/, '/') + test_location_filename ); }); it('should return a full URL, if a complex relative-ascendant-path is given', function(){ var url = '../../asdasd/asdasd/../../' + test_location_filename; var path = realPath( url ); expect( path ).to.equal( test_location_root + test_location_dir.replace(/\/[^\/]+\/$/, '/').replace(/\/[^\/]+\/$/, '/') + test_location_filename ); }); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PickListSubList = void 0; var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = _interopRequireWildcard(require("react")); var _ObjectUtils = _interopRequireDefault(require("../utils/ObjectUtils")); var _PickListItem = require("./PickListItem"); var _DomHandler = _interopRequireDefault(require("../utils/DomHandler")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } var PickListSubList = /*#__PURE__*/function (_Component) { _inherits(PickListSubList, _Component); var _super = _createSuper(PickListSubList); function PickListSubList() { var _this; _classCallCheck(this, PickListSubList); _this = _super.call(this); _this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this)); _this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(PickListSubList, [{ key: "onItemClick", value: function onItemClick(event) { var originalEvent = event.originalEvent; var item = event.value; var selection = _toConsumableArray(this.props.selection); var index = _ObjectUtils.default.findIndexInList(item, selection); var selected = index !== -1; var metaSelection = this.props.metaKeySelection; if (metaSelection) { var metaKey = originalEvent.metaKey || originalEvent.ctrlKey; if (selected && metaKey) { selection.splice(index, 1); } else { if (!metaKey) { selection.length = 0; } selection.push(item); } } else { if (selected) selection.splice(index, 1);else selection.push(item); } if (this.props.onSelectionChange) { this.props.onSelectionChange({ event: originalEvent, value: selection }); } } }, { key: "onItemKeyDown", value: function onItemKeyDown(event) { var listItem = event.originalEvent.currentTarget; switch (event.originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } event.originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } event.originalEvent.preventDefault(); break; //enter case 13: this.onItemClick(event); event.originalEvent.preventDefault(); break; default: break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return !_DomHandler.default.hasClass(nextItem, 'p-picklist-item') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return !_DomHandler.default.hasClass(prevItem, 'p-picklist-item') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "isSelected", value: function isSelected(item) { return _ObjectUtils.default.findIndexInList(item, this.props.selection) !== -1; } }, { key: "render", value: function render() { var _this2 = this; var header = null; var items = null; var wrapperClassName = (0, _classnames.default)('p-picklist-listwrapper', this.props.className, { 'p-picklist-listwrapper-nocontrols': !this.props.showControls }); var listClassName = (0, _classnames.default)('p-picklist-list', this.props.listClassName); if (this.props.header) { header = /*#__PURE__*/_react.default.createElement("div", { className: "p-picklist-caption" }, this.props.header); } if (this.props.list) { items = this.props.list.map(function (item, i) { return /*#__PURE__*/_react.default.createElement(_PickListItem.PickListItem, { key: JSON.stringify(item), value: item, template: _this2.props.itemTemplate, selected: _this2.isSelected(item), onClick: _this2.onItemClick, onKeyDown: _this2.onItemKeyDown, tabIndex: _this2.props.tabIndex }); }); } return /*#__PURE__*/_react.default.createElement("div", { className: wrapperClassName }, header, /*#__PURE__*/_react.default.createElement("ul", { className: listClassName, style: this.props.style, role: "listbox", "aria-multiselectable": true }, items)); } }]); return PickListSubList; }(_react.Component); exports.PickListSubList = PickListSubList; _defineProperty(PickListSubList, "defaultProps", { list: null, selection: null, header: null, className: null, listClassName: null, style: null, showControls: true, metaKeySelection: true, tabIndex: null, itemTemplate: null, onItemClick: null, onSelectionChange: null }); _defineProperty(PickListSubList, "propTypes", { list: _propTypes.default.array, selection: _propTypes.default.array, header: _propTypes.default.string, className: _propTypes.default.string, listClassName: _propTypes.default.string, style: _propTypes.default.object, showControls: _propTypes.default.bool, metaKeySelection: _propTypes.default.bool, tabIndex: _propTypes.default.string, itemTemplate: _propTypes.default.func, onItemClick: _propTypes.default.func, onSelectionChange: _propTypes.default.func });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OrderListControls = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _Button = require("../button/Button"); var _ObjectUtils = _interopRequireDefault(require("../utils/ObjectUtils")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } var OrderListControls = /*#__PURE__*/function (_Component) { _inherits(OrderListControls, _Component); var _super = _createSuper(OrderListControls); function OrderListControls() { var _this; _classCallCheck(this, OrderListControls); _this = _super.call(this); _this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this)); _this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this)); _this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this)); _this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListControls, [{ key: "moveUp", value: function moveUp(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = _ObjectUtils.default.findIndexInList(selectedItem, value); if (selectedItemIndex !== 0) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex - 1]; value[selectedItemIndex - 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'up' }); } } } }, { key: "moveTop", value: function moveTop(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = _ObjectUtils.default.findIndexInList(selectedItem, value); if (selectedItemIndex !== 0) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.unshift(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'top' }); } } } }, { key: "moveDown", value: function moveDown(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = _ObjectUtils.default.findIndexInList(selectedItem, value); if (selectedItemIndex !== value.length - 1) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex + 1]; value[selectedItemIndex + 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'down' }); } } } }, { key: "moveBottom", value: function moveBottom(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = _ObjectUtils.default.findIndexInList(selectedItem, value); if (selectedItemIndex !== value.length - 1) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.push(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'bottom' }); } } } }, { key: "render", value: function render() { return /*#__PURE__*/_react.default.createElement("div", { className: "p-orderlist-controls" }, /*#__PURE__*/_react.default.createElement(_Button.Button, { type: "button", icon: "pi pi-angle-up", onClick: this.moveUp }), /*#__PURE__*/_react.default.createElement(_Button.Button, { type: "button", icon: "pi pi-angle-double-up", onClick: this.moveTop }), /*#__PURE__*/_react.default.createElement(_Button.Button, { type: "button", icon: "pi pi-angle-down", onClick: this.moveDown }), /*#__PURE__*/_react.default.createElement(_Button.Button, { type: "button", icon: "pi pi-angle-double-down", onClick: this.moveBottom })); } }]); return OrderListControls; }(_react.Component); exports.OrderListControls = OrderListControls; _defineProperty(OrderListControls, "defaultProps", { value: null, selection: null, onReorder: null }); _defineProperty(OrderListControls, "propTypes", { value: _propTypes.default.array, selection: _propTypes.default.array, onReorder: _propTypes.default.func });
import"nanoid/non-secure";import"./Debug-5337ef47.js";import"redux";import"./turn-order-406c4349.js";import"immer";import"lodash.isplainobject";import"./reducer-95b86815.js";import"rfc6902";import"./initialize-6ecd151b.js";import"./transport-ce07b771.js";export{C as Client}from"./client-bc484c95.js";import"flatted";import"setimmediate";import"./ai-763ecd6c.js";export{L as LobbyClient,a as LobbyClientError}from"./client-5f57c3f2.js";
/** * Static HTTP Server */ // modules var static = require( 'node-static' ), port = (process.env.PORT | 0) || 4321, http = require( 'http' ); // config var file = new static.Server( './pub', { cache: 3600, gzip: true } ); // serve http.createServer( function ( request, response ) { request.addListener( 'end', function () { file.serve( request, response ); } ).resume(); } ).listen( port );
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, Link } from 'react-router' import './app.css' const App = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, getInitialState() { return { tacos: [ { name: 'duck confit' }, { name: 'carne asada' }, { name: 'shrimp' } ] } }, addTaco() { let name = prompt('taco name?') this.setState({ tacos: this.state.tacos.concat({ name }) }) }, handleRemoveTaco(removedTaco) { this.setState({ tacos: this.state.tacos.filter(function (taco) { return taco.name != removedTaco }) }) this.context.router.push('/') }, render() { let links = this.state.tacos.map(function (taco, i) { return ( <li key={i}> <Link to={`/taco/${taco.name}`}>{taco.name}</Link> </li> ) }) return ( <div className="App"> <button onClick={this.addTaco}>Add Taco</button> <ul className="Master"> {links} </ul> <div className="Detail"> {this.props.children && React.cloneElement(this.props.children, { onRemoveTaco: this.handleRemoveTaco })} </div> </div> ) } }) const Taco = React.createClass({ remove() { this.props.onRemoveTaco(this.props.params.name) }, render() { return ( <div className="Taco"> <h1>{this.props.params.name}</h1> <button onClick={this.remove}>remove</button> </div> ) } }) render(( <Router history={browserHistory}> <Route path="/" component={App}> <Route path="taco/:name" component={Taco} /> </Route> </Router> ), document.getElementById('example'))
// //Copyright (c) 2014, Priologic Software Inc. //All rights reserved. // //Redistribution and use 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. // //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 HOLDER 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. // var selfEasyrtcid = ""; var waitingForRoomList = true; var isConnected = false; function initApp() { document.getElementById("main").className = "notconnected"; } function addToConversation(who, msgType, content, targeting) { // Escape html special characters, then add linefeeds. if( !content) { content = "**no body**"; } content = content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); content = content.replace(/\n/g, '<br />'); var targetingStr = ""; if (targeting) { if (targeting.targetEasyrtcid) { targetingStr += "user=" + targeting.targetEasyrtcid; } if (targeting.targetRoom) { targetingStr += " room=" + targeting.targetRoom; } if (targeting.targetGroup) { targetingStr += " group=" + targeting.targetGroup; } } document.getElementById('conversation').innerHTML += "<b>" + who + " sent " + targetingStr + ":</b>&nbsp;" + content + "<br />"; } function genRoomDivName(roomName) { return "roomblock_" + roomName; } function genRoomOccupantName(roomName) { return "roomOccupant_" + roomName; } function setCredential(event, value) { if (event.keyCode === 13) { easyrtc.setCredential(value); } } function addRoom(roomName, parmString, userAdded) { if (!roomName) { roomName = document.getElementById("roomToAdd").value; parmString = document.getElementById("optRoomParms").value; } var roomid = genRoomDivName(roomName); if (document.getElementById(roomid)) { return; } function addRoomButton() { var roomButtonHolder = document.getElementById('rooms'); var roomdiv = document.createElement("div"); roomdiv.id = roomid; roomdiv.className = "roomDiv"; var roomButton = document.createElement("button"); roomButton.onclick = function() { sendMessage(null, roomName); }; var roomLabel = (document.createTextNode(roomName)); roomButton.appendChild(roomLabel); roomdiv.appendChild(roomButton); roomButtonHolder.appendChild(roomdiv); var roomOccupants = document.createElement("div"); roomOccupants.id = genRoomOccupantName(roomName); roomOccupants.className = "roomOccupants"; roomdiv.appendChild(roomOccupants); $(roomdiv).append(" -<a href=\"javascript:\leaveRoom('" + roomName + "')\">leave</a>"); } var roomParms = null; if (parmString && parmString !== "") { try { roomParms = JSON.parse(parmString); } catch (error) { roomParms = null; easyrtc.showError(easyrtc.errCodes.DEVELOPER_ERR, "Room Parameters must be an object containing key/value pairs. eg: {\"fruit\":\"banana\",\"color\":\"yellow\"}"); return; } } if (!isConnected || !userAdded) { addRoomButton(); console.log("adding gui for room " + roomName); } else { console.log("not adding gui for room " + roomName + " because already connected and it's a user action"); } if (userAdded) { console.log("calling joinRoom(" + roomName + ") because it was a user action "); easyrtc.joinRoom(roomName, roomParms, function() { /* we'll geta room entry event for the room we were actually added to */ }, function(errorCode, errorText, roomName) { easyrtc.showError(errorCode, errorText + ": room name was(" + roomName + ")"); }); } } function leaveRoom(roomName) { if (!roomName) { roomName = document.getElementById("roomToAdd").value; } var entry = document.getElementById(genRoomDivName(roomName)); var roomButtonHolder = document.getElementById('rooms'); easyrtc.leaveRoom(roomName, null); roomButtonHolder.removeChild(entry); } function roomEntryListener(entered, roomName) { if (entered) { // entered a room console.log("saw add of room " + roomName); addRoom(roomName, null, false); } else { var roomNode = document.getElementById(genRoomDivName(roomName)); if (roomNode) { document.getElementById('#rooms').removeChildNode(roomNode); } } refreshRoomList(); } function refreshRoomList() { if( isConnected) { easyrtc.getRoomList(addQuickJoinButtons, null); } } function peerListener(who, msgType, content, targeting) { addToConversation(who, msgType, content, targeting); } function connect() { easyrtc.setPeerListener(peerListener); easyrtc.setRoomOccupantListener(occupantListener); easyrtc.setRoomEntryListener(roomEntryListener); easyrtc.setDisconnectListener(function() { jQuery('#rooms').empty(); document.getElementById("main").className = "notconnected"; console.log("disconnect listener fired"); }); updatePresence(); var username = document.getElementById("userNameField").value; var password = document.getElementById("credentialField").value; if (username) { easyrtc.setUsername(username); } if (password) { easyrtc.setCredential({password: password}); } easyrtc.connect("easyrtc.instantMessaging", loginSuccess, loginFailure); } function disconnect() { easyrtc.disconnect(); } function addQuickJoinButtons(roomList) { var quickJoinBlock = document.getElementById("quickJoinBlock"); var n = quickJoinBlock.childNodes.length; for (var i = n - 1; i >= 0; i--) { quickJoinBlock.removeChild(quickJoinBlock.childNodes[i]); } function addQuickJoinButton(roomname, numberClients) { var checkid = "roomblock_" + roomname; if (document.getElementById(checkid)) { return; // already present so don't add again } var id = "quickjoin_" + roomname; var div = document.createElement("div"); div.id = id; div.className = "quickJoin"; var parmsField = document.getElementById("optRoomParms"); var button = document.createElement("button"); button.onclick = function() { addRoom(roomname, parmsField.value, true); refreshRoomList(); }; button.appendChild(document.createTextNode("Join " + roomname + "(" + numberClients + ")")); div.appendChild(button); quickJoinBlock.appendChild(div); } if( !roomList["room1"]) { roomList["room1"] = { numberClients:0}; } if( !roomList["room2"]) { roomList["room2"] = { numberClients:0}; } if( !roomList["room3"]) { roomList["room3"] = { numberClients:0}; } for (var roomName in roomList) { addQuickJoinButton(roomName, roomList[roomName].numberClients); } } function occupantListener(roomName, occupants, isPrimary) { if (roomName === null) { return; } var roomId = genRoomOccupantName(roomName); var roomDiv = document.getElementById(roomId); if (!roomDiv) { addRoom(roomName, "", false); roomDiv = document.getElementById(roomId); } else { jQuery(roomDiv).empty(); } for (var easyrtcid in occupants) { var button = document.createElement("button"); button.onclick = (function(roomname, easyrtcid) { return function() { sendMessage(easyrtcid, roomName); }; })(roomName, easyrtcid); var presenceText = ""; if (occupants[easyrtcid].presence) { presenceText += "("; if (occupants[easyrtcid].presence.show) { presenceText += "show=" + occupants[easyrtcid].presence.show + " "; } if (occupants[easyrtcid].presence.status) { presenceText += "status=" + occupants[easyrtcid].presence.status; } presenceText += ")"; } var label = document.createTextNode(easyrtc.idToName(easyrtcid) + presenceText); button.appendChild(label); roomDiv.appendChild(button); } refreshRoomList(); } function getGroupId() { return null; } function sendMessage(destTargetId, destRoom) { var text = document.getElementById('sendMessageText').value; if (text.replace(/\s/g, "").length === 0) { // Don't send just whitespace return; } var dest; var destGroup = getGroupId(); if (destRoom || destGroup) { dest = {}; if (destRoom) { dest.targetRoom = destRoom; } if (destGroup) { dest.targetGroup = destGroup; } if (destTargetId) { dest.targetEasyrtcid = destTargetId; } } else if (destTargetId) { dest = destTargetId; } else { easyrtc.showError("user error", "no destination selected"); return; } if( text === "empty") { easyrtc.sendPeerMessage(dest, "message"); } else { easyrtc.sendDataWS(dest, "message", text, function(reply) { if (reply.msgType === "error") { easyrtc.showError(reply.msgData.errorCode, reply.msgData.errorText); } }); } addToConversation("Me", "message", text); document.getElementById('sendMessageText').value = ""; } function loginSuccess(easyrtcid) { selfEasyrtcid = easyrtcid; document.getElementById("iam").innerHTML = "I am " + easyrtcid; refreshRoomList(); isConnected = true; displayFields(); document.getElementById("main").className = "connected"; } function displayFields() { var outstr = "Application fields<div style='margin-left:1em'>"; outstr += JSON.stringify(easyrtc.getApplicationFields()); outstr += "</div><br>"; outstr += "Session fields<div style='margin-left:1em'>"; outstr += JSON.stringify(easyrtc.getSessionFields()); outstr += "</div><br>"; outstr += "Connection fields<div style='margin-left:1em'>"; outstr += JSON.stringify(easyrtc.getConnectionFields()); outstr += "</div><br>"; var roomlist = easyrtc.getRoomsJoined(); for (var roomname in roomlist) { var roomfields = easyrtc.getRoomFields(roomname); if (roomfields != null) { outstr += "Room " + roomname + " fields<div style='margin-left:1em'>"; outstr += JSON.stringify(roomfields); outstr += "</div><br>"; } } document.getElementById('fields').innerHTML = outstr; } function loginFailure(errorCode, message) { easyrtc.showError("LOGIN-FAILURE", message); document.getElementById('connectButton').disabled = false; jQuery('#rooms').empty(); } var currentShowState = 'chat'; var currentShowText = ''; function setPresence(value) { currentShowState = value; updatePresence(); } function updatePresenceStatus(value) { currentShowText = value; updatePresence(); } function updatePresence() { easyrtc.updatePresence(currentShowState, currentShowText); } function queryRoomNames() { var roomName = document.getElementById("queryRoom").value; if( !roomName ) { roomName = "default"; } if( roomName ) { console.log("getRoomOccupantsAsArray("+ roomName + ")=" + JSON.stringify(easyrtc.getRoomOccupantsAsArray(roomName))); console.log("getRoomOccupantsAsMap(" + roomName + ")=" + JSON.stringify(easyrtc.getRoomOccupantsAsMap(roomName))); } } function addApiField() { var roomName = document.getElementById("apiroomname").value; var fieldname = document.getElementById("apifieldname").value; var fieldvaluetext = document.getElementById("apifieldvalue").value; var fieldvalue; if(fieldvaluetext.indexOf("{") >= 0) { fieldvalue = JSON.parse(fieldvaluetext); } else { fieldvalue = fieldvaluetext; } easyrtc.setRoomApiField(roomName, fieldname, fieldvalue); } function getIdsOfName() { var name = document.getElementById("targetName").value; var ids = easyrtc.usernameToIds(name); document.getElementById("foundIds").innerHTML = JSON.stringify(ids); }
var searchData= [ ['catmullrom',['catmullRom',['../a00775.html#ga8119c04f8210fd0d292757565cd6918d',1,'glm']]], ['ceil',['ceil',['../a00662.html#gafb9d2a645a23aca12d4d6de0104b7657',1,'glm']]], ['ceilmultiple',['ceilMultiple',['../a00719.html#ga1d89ac88582aaf4d5dfa5feb4a376fd4',1,'glm::ceilMultiple(genType v, genType Multiple)'],['../a00719.html#gab77fdcc13f8e92d2e0b1b7d7aeab8e9d',1,'glm::ceilMultiple(vec&lt; L, T, Q &gt; const &amp;v, vec&lt; L, T, Q &gt; const &amp;Multiple)']]], ['ceilpoweroftwo',['ceilPowerOfTwo',['../a00719.html#ga5c3ef36ae32aa4271f1544f92bd578b6',1,'glm::ceilPowerOfTwo(genIUType v)'],['../a00719.html#gab53d4a97c0d3e297be5f693cdfdfe5d2',1,'glm::ceilPowerOfTwo(vec&lt; L, T, Q &gt; const &amp;v)']]], ['circulareasein',['circularEaseIn',['../a00735.html#ga34508d4b204a321ec26d6086aa047997',1,'glm']]], ['circulareaseinout',['circularEaseInOut',['../a00735.html#ga0c1027637a5b02d4bb3612aa12599d69',1,'glm']]], ['circulareaseout',['circularEaseOut',['../a00735.html#ga26fefde9ced9b72745fe21f1a3fe8da7',1,'glm']]], ['circularrand',['circularRand',['../a00717.html#ga9dd05c36025088fae25b97c869e88517',1,'glm']]], ['clamp',['clamp',['../a00662.html#ga7cd77683da6361e297c56443fc70806d',1,'glm::clamp(genType x, genType minVal, genType maxVal)'],['../a00662.html#gafba2e0674deb5953878d89483cd6323d',1,'glm::clamp(vec&lt; L, T, Q &gt; const &amp;x, T minVal, T maxVal)'],['../a00662.html#gaa0f2f12e9108b09e22a3f0b2008a0b5d',1,'glm::clamp(vec&lt; L, T, Q &gt; const &amp;x, vec&lt; L, T, Q &gt; const &amp;minVal, vec&lt; L, T, Q &gt; const &amp;maxVal)'],['../a00786.html#ga6c0cc6bd1d67ea1008d2592e998bad33',1,'glm::clamp(genType const &amp;Texcoord)']]], ['closebounded',['closeBounded',['../a00731.html#gab7d89c14c48ad01f720fb5daf8813161',1,'glm']]], ['closestpointonline',['closestPointOnLine',['../a00727.html#ga36529c278ef716986151d58d151d697d',1,'glm::closestPointOnLine(vec&lt; 3, T, Q &gt; const &amp;point, vec&lt; 3, T, Q &gt; const &amp;a, vec&lt; 3, T, Q &gt; const &amp;b)'],['../a00727.html#ga55bcbcc5fc06cb7ff7bc7a6e0e155eb0',1,'glm::closestPointOnLine(vec&lt; 2, T, Q &gt; const &amp;point, vec&lt; 2, T, Q &gt; const &amp;a, vec&lt; 2, T, Q &gt; const &amp;b)']]], ['colmajor2',['colMajor2',['../a00755.html#gaaff72f11286e59a4a88ed21a347f284c',1,'glm::colMajor2(vec&lt; 2, T, Q &gt; const &amp;v1, vec&lt; 2, T, Q &gt; const &amp;v2)'],['../a00755.html#gafc25fd44196c92b1397b127aec1281ab',1,'glm::colMajor2(mat&lt; 2, 2, T, Q &gt; const &amp;m)']]], ['colmajor3',['colMajor3',['../a00755.html#ga1e25b72b085087740c92f5c70f3b051f',1,'glm::colMajor3(vec&lt; 3, T, Q &gt; const &amp;v1, vec&lt; 3, T, Q &gt; const &amp;v2, vec&lt; 3, T, Q &gt; const &amp;v3)'],['../a00755.html#ga86bd0656e787bb7f217607572590af27',1,'glm::colMajor3(mat&lt; 3, 3, T, Q &gt; const &amp;m)']]], ['colmajor4',['colMajor4',['../a00755.html#gaf4aa6c7e17bfce41a6c13bf6469fab05',1,'glm::colMajor4(vec&lt; 4, T, Q &gt; const &amp;v1, vec&lt; 4, T, Q &gt; const &amp;v2, vec&lt; 4, T, Q &gt; const &amp;v3, vec&lt; 4, T, Q &gt; const &amp;v4)'],['../a00755.html#gaf3f9511c366c20ba2e4a64c9e4cec2b3',1,'glm::colMajor4(mat&lt; 4, 4, T, Q &gt; const &amp;m)']]], ['column',['column',['../a00711.html#ga96022eb0d3fae39d89fc7a954e59b374',1,'glm::column(genType const &amp;m, length_t index)'],['../a00711.html#ga9e757377523890e8b80c5843dbe4dd15',1,'glm::column(genType const &amp;m, length_t index, typename genType::col_type const &amp;x)']]], ['compadd',['compAdd',['../a00733.html#gaf71833350e15e74d31cbf8a3e7f27051',1,'glm']]], ['compmax',['compMax',['../a00733.html#gabfa4bb19298c8c73d4217ba759c496b6',1,'glm']]], ['compmin',['compMin',['../a00733.html#gab5d0832b5c7bb01b8d7395973bfb1425',1,'glm']]], ['compmul',['compMul',['../a00733.html#gae8ab88024197202c9479d33bdc5a8a5d',1,'glm']]], ['compnormalize',['compNormalize',['../a00733.html#ga8f2b81ada8515875e58cb1667b6b9908',1,'glm']]], ['compscale',['compScale',['../a00733.html#ga80abc2980d65d675f435d178c36880eb',1,'glm']]], ['conjugate',['conjugate',['../a00669.html#ga10d7bda73201788ac2ab28cd8d0d409b',1,'glm']]], ['convertd65xyztod50xyz',['convertD65XYZToD50XYZ',['../a00728.html#gad12f4f65022b2c80e33fcba2ced0dc48',1,'glm']]], ['convertd65xyztolinearsrgb',['convertD65XYZToLinearSRGB',['../a00728.html#ga5265386fc3ac29e4c580d37ed470859c',1,'glm']]], ['convertlinearsrgbtod50xyz',['convertLinearSRGBToD50XYZ',['../a00728.html#ga1522ba180e3d83d554a734056da031f9',1,'glm']]], ['convertlinearsrgbtod65xyz',['convertLinearSRGBToD65XYZ',['../a00728.html#gaf9e130d9d4ccf51cc99317de7449f369',1,'glm']]], ['convertlineartosrgb',['convertLinearToSRGB',['../a00707.html#ga42239e7b3da900f7ef37cec7e2476579',1,'glm::convertLinearToSRGB(vec&lt; L, T, Q &gt; const &amp;ColorLinear)'],['../a00707.html#gaace0a21167d13d26116c283009af57f6',1,'glm::convertLinearToSRGB(vec&lt; L, T, Q &gt; const &amp;ColorLinear, T Gamma)']]], ['convertsrgbtolinear',['convertSRGBToLinear',['../a00707.html#ga16c798b7a226b2c3079dedc55083d187',1,'glm::convertSRGBToLinear(vec&lt; L, T, Q &gt; const &amp;ColorSRGB)'],['../a00707.html#gad1b91f27a9726c9cb403f9fee6e2e200',1,'glm::convertSRGBToLinear(vec&lt; L, T, Q &gt; const &amp;ColorSRGB, T Gamma)']]], ['cos',['cos',['../a00790.html#ga6a41efc740e3b3c937447d3a6284130e',1,'glm']]], ['cosh',['cosh',['../a00790.html#ga4e260e372742c5f517aca196cf1e62b3',1,'glm']]], ['cot',['cot',['../a00718.html#ga3a7b517a95bbd3ad74da3aea87a66314',1,'glm']]], ['coth',['coth',['../a00718.html#ga6b8b770eb7198e4dea59d52e6db81442',1,'glm']]], ['cross',['cross',['../a00675.html#ga755beaa929c75751dee646cccba37e4c',1,'glm::cross(qua&lt; T, Q &gt; const &amp;q1, qua&lt; T, Q &gt; const &amp;q2)'],['../a00697.html#gaeeec0794212fe84fc9d261de067c9587',1,'glm::cross(vec&lt; 3, T, Q &gt; const &amp;x, vec&lt; 3, T, Q &gt; const &amp;y)'],['../a00739.html#gac36e72b934ea6a9dd313772d7e78fa93',1,'glm::cross(vec&lt; 2, T, Q &gt; const &amp;v, vec&lt; 2, T, Q &gt; const &amp;u)'],['../a00769.html#ga2f32f970411c44cdd38bb98960198385',1,'glm::cross(qua&lt; T, Q &gt; const &amp;q, vec&lt; 3, T, Q &gt; const &amp;v)'],['../a00769.html#ga9f5f77255756e5668dfee7f0d07ed021',1,'glm::cross(vec&lt; 3, T, Q &gt; const &amp;v, qua&lt; T, Q &gt; const &amp;q)']]], ['csc',['csc',['../a00718.html#ga59dd0005b6474eea48af743b4f14ebbb',1,'glm']]], ['csch',['csch',['../a00718.html#ga6d95843ff3ca6472ab399ba171d290a0',1,'glm']]], ['cubic',['cubic',['../a00775.html#ga6b867eb52e2fc933d2e0bf26aabc9a70',1,'glm']]], ['cubiceasein',['cubicEaseIn',['../a00735.html#gaff52f746102b94864d105563ba8895ae',1,'glm']]], ['cubiceaseinout',['cubicEaseInOut',['../a00735.html#ga55134072b42d75452189321d4a2ad91c',1,'glm']]], ['cubiceaseout',['cubicEaseOut',['../a00735.html#ga40d746385d8bcc5973f5bc6a2340ca91',1,'glm']]] ];
module.exports = { pluginID: "AnotherPlugin", description: function () {}, test: true, templateType: null, };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The response model for the list configuration operation. */ class DscConfigurationListResult extends Array { /** * Create a DscConfigurationListResult. * @member {string} [nextLink] Gets or sets the next link. */ constructor() { super(); } /** * Defines the metadata of DscConfigurationListResult * * @returns {object} metadata of DscConfigurationListResult * */ mapper() { return { required: false, serializedName: 'DscConfigurationListResult', type: { name: 'Composite', className: 'DscConfigurationListResult', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'DscConfigurationElementType', type: { name: 'Composite', className: 'DscConfiguration' } } } }, nextLink: { required: false, serializedName: 'nextLink', type: { name: 'String' } } } } }; } } module.exports = DscConfigurationListResult;
import Telescope from 'meteor/nova:lib'; import Categories from "./collection.js"; import Users from 'meteor/nova:users'; const canInsert = user => Users.canDo(user, "categories.new"); const canEdit = user => Users.canDo(user, "categories.edit.all"); // category schema Categories.schema = new SimpleSchema({ name: { type: String, insertableIf: canInsert, editableIf: canEdit, publish: true }, description: { type: String, optional: true, insertableIf: canInsert, editableIf: canEdit, publish: true, autoform: { rows: 3 } }, order: { type: Number, optional: true, insertableIf: canInsert, editableIf: canEdit, publish: true }, slug: { type: String, optional: true, insertableIf: canInsert, editableIf: canEdit, publish: true }, image: { type: String, optional: true, insertableIf: canInsert, editableIf: canEdit, publish: true }, parentId: { type: String, optional: true, insertableIf: canInsert, editableIf: canEdit, publish: true, autoform: { options: function () { var categories = Categories.find().map(function (category) { return { value: category._id, label: category.name }; }); return categories; } } } }); // Meteor.startup(function(){ // Categories.internationalize(); // }); Categories.attachSchema(Categories.schema); Telescope.settings.collection.addField([ { fieldName: 'categoriesBehavior', fieldSchema: { type: String, optional: true, autoform: { group: 'categories', instructions: 'Let users filter by one or multiple categories at a time.', options: function () { return [ {value: "single", label: "categories_behavior_one_at_a_time"}, {value: "multiple", label: "categories_behavior_multiple"} ]; } } } }, { fieldName: 'hideEmptyCategories', fieldSchema: { type: Boolean, optional: true, autoform: { group: 'categories', instructions: 'Hide empty categories in navigation' } } } ]);
tinymce.addI18n('ug',{ "Redo": "\u0642\u0627\u064a\u062a\u0627 \u0642\u0649\u0644\u0649\u0634", "Undo": "\u0626\u0627\u0631\u0642\u0649\u063a\u0627 \u064a\u06d0\u0646\u0649\u0634", "Cut": "\u0643\u06d0\u0633\u0649\u0634", "Copy": "\u0643\u06c6\u0686\u06c8\u0631\u06c8\u0634", "Paste": "\u0686\u0627\u067e\u0644\u0627\u0634", "Select all": "\u06be\u06d5\u0645\u0645\u0649\u0646\u0649 \u062a\u0627\u0644\u0644\u0627\u0634", "New document": "\u064a\u06d0\u06ad\u0649 \u067e\u06c8\u062a\u06c8\u0643", "Ok": "\u062c\u06d5\u0632\u0649\u0645\u0644\u06d5\u0634", "Cancel": "\u0642\u0627\u0644\u062f\u06c7\u0631\u06c7\u0634", "Visual aids": "\u0626\u06d5\u0633\u0643\u06d5\u0631\u062a\u0649\u0634", "Bold": "\u062a\u0648\u0645", "Italic": "\u064a\u0627\u0646\u062a\u06c7", "Underline": "\u0626\u0627\u0633\u062a\u0649 \u0633\u0649\u0632\u0649\u0642", "Strikethrough": "\u0626\u06c6\u0686\u06c8\u0631\u06c8\u0634 \u0633\u0649\u0632\u0649\u0642\u0649", "Superscript": "\u0626\u06c8\u0633\u062a\u06c8\u0646\u0643\u0649 \u0628\u06d5\u0644\u06af\u06d5", "Subscript": "\u0626\u0627\u0633\u062a\u0649\u0646\u0642\u0649 \u0628\u06d5\u0644\u06af\u06d5", "Clear formatting": "\u0641\u0648\u0631\u0645\u0627\u062a\u0646\u0649 \u062a\u0627\u0632\u0644\u0627\u0634", "Align left": "\u0633\u0648\u0644\u063a\u0627 \u062a\u0648\u063a\u0631\u0649\u0644\u0627\u0634", "Align center": "\u0645\u06d5\u0631\u0643\u06d5\u0632\u06af\u06d5 \u062a\u0648\u063a\u06c7\u0631\u0644\u0627\u0634", "Align right": "\u0626\u0648\u06ad\u063a\u0627 \u062a\u0648\u063a\u06c7\u0631\u0644\u0627\u0634", "Justify": "\u0626\u0649\u0643\u0643\u0649 \u064a\u0627\u0646\u063a\u0627 \u062a\u0648\u063a\u06c7\u0631\u0644\u0627\u0634", "Bullet list": "\u0628\u06d5\u0644\u06af\u06d5 \u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643", "Numbered list": "\u0633\u0627\u0646\u0644\u0649\u0642 \u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643", "Decrease indent": "\u0626\u0627\u0644\u062f\u0649\u063a\u0627 \u0633\u06c8\u0631\u06c8\u0634", "Increase indent": "\u0643\u06d5\u064a\u0646\u0649\u06af\u06d5 \u0633\u06c8\u0631\u06c8\u0634", "Close": "\u062a\u0627\u0642\u0627\u0634", "Formats": "\u0641\u0648\u0631\u0645\u0627\u062a", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "\u0633\u0649\u0632\u0646\u0649\u06ad \u062a\u0648\u0631 \u0643\u06c6\u0631\u06af\u06c8\u0686\u0649\u06ad\u0649\u0632 \u0642\u0649\u064a\u0649\u067e \u0686\u0627\u067e\u0644\u0627\u0634 \u062a\u0627\u062e\u062a\u0649\u0633\u0649 \u0632\u0649\u064a\u0627\u0631\u06d5\u062a \u0642\u0649\u0644\u0649\u0634\u0646\u0649 \u0642\u0648\u0644\u0644\u0649\u0645\u0627\u064a\u062f\u06c7. Ctrl+X\/C\/V \u062a\u06d0\u0632\u0644\u06d5\u062a\u0645\u06d5 \u0643\u06c7\u0646\u06c7\u067e\u0643\u0649\u0633\u0649 \u0626\u0627\u0631\u0642\u0649\u0644\u0649\u0642 \u0643\u06d0\u0633\u0649\u067e \u0686\u0627\u067e\u0644\u0627\u0634 \u0645\u06d5\u0634\u063a\u06c7\u0644\u0627\u062a\u0649 \u0642\u0649\u0644\u0649\u06ad.", "Headers": "\u0628\u06d0\u0634\u0649", "Header 1": "\u062a\u06d0\u0645\u0627 1", "Header 2": "\u062a\u06d0\u0645\u0627 2", "Header 3": "\u062a\u06d0\u0645\u0627 3", "Header 4": "\u062a\u06d0\u0645\u0627 4", "Header 5": "\u062a\u06d0\u0645\u0627 5", "Header 6": "\u062a\u06d0\u0645\u0627 6", "Headings": "\u0645\u0627\u06cb\u0632\u06c7", "Heading 1": "1 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0645\u0627\u06cb\u0632\u06c7", "Heading 2": "2 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0645\u0627\u06cb\u0632\u06c7", "Heading 3": "3 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0645\u0627\u06cb\u0632\u06c7", "Heading 4": "4 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0645\u0627\u06cb\u0632\u06c7", "Heading 5": "5 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0645\u0627\u06cb\u0632\u06c7", "Heading 6": "6 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0645\u0627\u06cb\u0632\u06c7", "Preformatted": "\u0626\u0627\u0644\u062f\u0649\u0646 \u0641\u0648\u0631\u0645\u0627\u062a\u0644\u0627\u0646\u063a\u0627\u0646", "Div": "Div", "Pre": "Pre", "Code": "\u0643\u0648\u062f", "Paragraph": "\u067e\u0627\u0631\u0627\u06af\u0649\u0631\u0627 \u0641", "Blockquote": "\u0626\u06d5\u0633\u0643\u06d5\u0631\u062a\u0649\u0634", "Inline": "\u0626\u0649\u0686\u0643\u0649", "Blocks": "\u0631\u0627\u064a\u0648\u0646", "Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "\u06be\u0627\u0632\u0649\u0631 \u0686\u0627\u067e\u0644\u0649\u0633\u0649\u06ad\u0649\u0632 \u0633\u0627\u067e \u062a\u06d0\u0643\u0649\u0634 \u0645\u06d5\u0632\u0645\u06c7\u0646\u0649 \u0686\u0627\u067e\u0644\u0649\u0646\u0649\u062f\u06c7. \u062a\u06d0\u0643\u0649\u0634 \u0634\u06d5\u0643\u0644\u0649\u062f\u06d5 \u0686\u0627\u067e\u0644\u0627\u0634 \u062a\u06d5\u06ad\u0634\u0649\u0643\u0649\u0646\u0649 \u062a\u0627\u0642\u0649\u06cb\u06d5\u062a\u0643\u06d5\u0646\u06af\u06d5 \u0642\u06d5\u062f\u06d5\u0631.", "Fonts": "\u062e\u06d5\u062a \u0646\u06c7\u0633\u062e\u0649\u0644\u0649\u0631\u0649", "Font Sizes": "\u062e\u06d5\u062a \u0686\u0648\u06ad\u0644\u06c7\u0642\u0649", "Class": "\u062a\u06c8\u0631", "Browse for an image": "\u0631\u06d5\u0633\u0649\u0645\u0646\u0649 \u0643\u06c6\u0631\u0633\u0649\u062a\u0649\u0634", "OR": "\u064a\u0627\u0643\u0649", "Drop an image here": "\u0628\u06c7 \u064a\u06d5\u0631\u062f\u0649\u0643\u0649 \u0631\u06d5\u0633\u0649\u0645\u0646\u0649 \u0626\u06c6\u0686\u06c8\u0631\u06c8\u0634", "Upload": "\u0686\u0649\u0642\u0649\u0631\u0649\u0634", "Block": "\u067e\u0627\u0631\u0686\u06d5", "Align": "\u062a\u0648\u063a\u0631\u0649\u0644\u0649\u0646\u0649\u0634\u0649", "Default": "\u0633\u06c8\u0643\u06c8\u062a", "Circle": "\u0686\u06d5\u0645\u0628\u06d5\u0631", "Disc": "\u062f\u06d0\u0633\u0643\u0627", "Square": "\u0643\u06cb\u0627\u062f\u0631\u0627\u062a", "Lower Alpha": "\u0626\u0649\u0646\u06af\u0649\u0644\u0649\u0632\u0686\u06d5 \u0643\u0649\u0686\u0649\u0643 \u064a\u06d0\u0632\u0649\u0644\u0649\u0634\u0649", "Lower Greek": "\u06af\u0631\u06d0\u062a\u0633\u0649\u064a\u0649\u0686\u06d5 \u0643\u0649\u0686\u0649\u0643 \u064a\u06d0\u0632\u0649\u0644\u0649\u0634\u0649", "Lower Roman": "\u0631\u0649\u0645\u0686\u06d5 \u0643\u0649\u0686\u0649\u0643 \u064a\u06d0\u0632\u0649\u0644\u0649\u0634\u0649", "Upper Alpha": "\u0626\u0649\u0646\u06af\u0649\u0644\u0649\u0632\u0686\u06d5 \u0686\u0648\u06ad \u064a\u06d0\u0632\u0649\u0644\u0649\u0634\u0649", "Upper Roman": "\u0631\u0649\u0645\u0686\u06d5 \u0686\u0648\u06ad \u064a\u06d0\u0632\u0649\u0644\u0649\u0634\u0649", "Anchor...": "\u0644\u06d5\u06ad\u06af\u06d5\u0631...", "Name": "\u0646\u0627\u0645\u0649", "Id": "Id", "Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.": "ID \u0686\u0648\u0642\u06c7\u0645 \u06be\u06d5\u0631\u0649\u067e \u0628\u0649\u0644\u06d5\u0646 \u0628\u0627\u0634\u0644\u0649\u0646\u0649\u0634\u0649 \u0643\u06d0\u0631\u06d5\u0643 \u060c \u0626\u0627\u0631\u0642\u0649\u0633\u0649 \u067e\u06d5\u0642\u06d5\u062a \u06be\u06d5\u0631\u0649\u067e \u060c \u0633\u0627\u0646 \u060c \u0626\u0627\u064a\u0631\u0649\u0634 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649 \u060c \u0686\u0649\u0643\u0649\u062a \u06cb\u06d5 \u0626\u0627\u0633\u062a\u0649 \u0633\u0649\u0632\u0649\u0642\u0649 \u062f\u0649\u0646 \u0626\u0649\u0628\u0627\u0631\u06d5\u062a .", "You have unsaved changes are you sure you want to navigate away?": "\u0633\u0649\u0632 \u062a\u06d0\u062e\u0649 \u0645\u06d5\u0632\u0645\u06c7\u0646\u0646\u0649 \u0633\u0627\u0642\u0644\u0649\u0645\u0649\u062f\u0649\u06ad\u0649\u0632\u060c \u0626\u0627\u064a\u0631\u0649\u0644\u0627\u0645\u0633\u0649\u0632\u061f", "Restore last draft": "\u0626\u0627\u062e\u0649\u0631\u0642\u0649 \u0643\u06c7\u067e\u0649\u064a\u0649\u06af\u06d5 \u0642\u0627\u064a\u062a\u0649\u0634", "Special character...": "\u0626\u0627\u0644\u0627\u06be\u0649\u062f\u06d5 \u06be\u06d5\u0631\u067e-\u0628\u06d5\u0644\u06af\u0649\u0644\u06d5\u0631...", "Source code": "\u0626\u06d5\u0633\u0644\u0649 \u0643\u0648\u062f\u0649", "Insert\/Edit code sample": "\u0643\u0648\u062f \u0645\u0649\u0633\u0627\u0644\u0649\\\u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Language": "\u062a\u0649\u0644", "Code sample...": "\u0626\u06c8\u0644\u06af\u06d5 \u0643\u0648\u062f...", "Color Picker": "\u0631\u06d5\u06ad \u062a\u0627\u0644\u0644\u0649\u063a\u06c7\u0686", "R": "R", "G": "G", "B": "B", "Left to right": "\u0633\u0648\u0644\u062f\u0649\u0646 \u0626\u0648\u06ad\u063a\u0627 ", "Right to left": "\u0626\u0648\u06ad\u062f\u0649\u0646 \u0633\u0648\u0644\u063a\u0627", "Emoticons": "\u0686\u0649\u0631\u0627\u064a \u0626\u0649\u067e\u0627\u062f\u06d5", "Emoticons...": "\u0686\u0649\u0631\u0627\u064a \u0626\u0649\u067e\u0627\u062f\u0649\u0644\u0649\u0631\u0649...", "Metadata and Document Properties": "\u0645\u06d0\u062a\u0627\u0645\u06d5\u0644\u06c7\u0645\u0627\u062a \u06cb\u06d5 \u06be\u06c6\u062c\u062c\u06d5\u062a \u062e\u0627\u0633\u0644\u0649\u0642\u0644\u0649\u0631\u0649", "Title": "\u062a\u06d0\u0645\u0627", "Keywords": "\u06be\u0627\u0644\u0642\u0649\u0644\u0649\u0642 \u0633\u06c6\u0632", "Description": "\u062a\u06d5\u0633\u0649\u06cb\u0649\u0631", "Robots": "\u0645\u0627\u0634\u0649\u0646\u0627 \u0626\u0627\u062f\u06d5\u0645", "Author": "\u0626\u06c7\u0644\u0627\u0646\u0645\u0627", "Encoding": "\u0643\u0648\u062f\u0644\u0627\u0634", "Fullscreen": "\u067e\u06c8\u062a\u06c8\u0646 \u0626\u06d0\u0643\u0631\u0627\u0646", "Action": "\u06be\u06d5\u0631\u0649\u0643\u06d5\u062a", "Shortcut": "\u0642\u0649\u0633\u0642\u0627 \u064a\u0648\u0644", "Help": "\u064a\u0627\u0631\u062f\u06d5\u0645", "Address": "\u0626\u0627\u062f\u0649\u0631\u0649\u0633", "Focus to menubar": "\u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643 \u0633\u0649\u062a\u0648\u0646\u0649\u063a\u0627 \u062f\u0649\u0642\u06d5\u062a", "Focus to toolbar": "\u0642\u06c7\u0631\u0627\u0644 \u0633\u0649\u062a\u0648\u0646\u0649\u063a\u0627 \u062f\u0649\u0642\u06d5\u062a", "Focus to element path": "\u0626\u06d0\u0644\u0649\u0645\u0649\u0646\u062a\u0644\u0627\u0631 \u064a\u0648\u0644\u0649\u063a\u0627 \u062f\u0649\u0642\u06d5\u062a", "Focus to contextual toolbar": "\u0643\u0648\u0646\u062a\u06d0\u0643\u0649\u0633\u062a \u0642\u0648\u0631\u0627\u0644 \u0626\u0649\u0633\u062a\u0648\u0646\u0649\u063a\u0627 \u062f\u06d0\u0642\u06d5\u062a", "Insert link (if link plugin activated)": "\u0626\u06c7\u0644\u0627\u0646\u0645\u0627 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u06ad (\u0626\u06c7\u0644\u0627\u0646\u0645\u0627 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634 \u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0649\u0633\u0649\u0646\u0649 \u0642\u0648\u0632\u063a\u0627\u062a\u0642\u0627\u0646 \u0626\u06d5\u06be\u06cb\u0627\u0644\u062f\u0627)", "Save (if save plugin activated)": "\u0633\u0627\u0642\u0644\u0627\u0634 (\u0633\u0627\u0642\u0644\u0627\u0634 \u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0649\u0633\u0649\u0646\u0649 \u0642\u0648\u0632\u063a\u0627\u062a\u0642\u0627\u0646 \u0626\u06d5\u06be\u06cb\u0627\u0644\u062f\u0627)", "Find (if searchreplace plugin activated)": "\u0626\u0649\u0632\u062f\u06d5\u0634 (\u0626\u0649\u0632\u062f\u06d5\u0634 \u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0649\u0633\u0649 \u0642\u0648\u0632\u063a\u0649\u062a\u0649\u0644\u063a\u0627\u0646 \u0626\u06d5\u06be\u06cb\u0627\u0644\u062f\u0627)", "Plugins installed ({0}):": "\u0642\u0627\u0686\u0649\u0644\u0627\u0646\u063a\u0627\u0646 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0644\u0645\u0627 ({0}):", "Premium plugins:": "\u064a\u06c7\u0642\u0649\u0631\u0649 \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0643 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0644\u0645\u0627 :", "Learn more...": "\u062a\u06d0\u062e\u0649\u0645\u06c7 \u0686\u06c8\u0634\u0649\u0646\u0649\u0634 ...", "You are using {0}": "\u0626\u0649\u0634\u0644\u0649\u062a\u0649\u06cb\u0627\u062a\u0642\u0649\u0646\u0649\u06ad\u0649\u0632 {0}", "Plugins": "\u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0644\u0645\u0627", "Handy Shortcuts": "\u0642\u0648\u0644\u0627\u064a\u0644\u0649\u0642 \u0642\u0649\u0633\u0642\u0627 \u064a\u0648\u0644", "Horizontal line": "\u06af\u0648\u0631\u0632\u0649\u0646\u062a\u0627\u0644 \u0642\u06c7\u0631", "Insert\/edit image": "\u0631\u06d5\u0633\u0649\u0645 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634 \u064a\u0627\u0643\u0649 \u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Alternative description": "\u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0627 \u0686\u06c8\u0634\u06d5\u0646\u062f\u06c8\u0631\u06c8\u0634\u0649", "Accessibility": "\u064a\u0627\u0631\u062f\u06d5\u0645\u0686\u06d5 \u0626\u0649\u0642\u062a\u0649\u062f\u0627\u0631", "Image is decorative": "\u0628\u06d0\u0632\u06d5\u0643 \u0631\u06d5\u0633\u0649\u0645", "Source": "\u0645\u06d5\u0646\u0628\u06d5", "Dimensions": "\u0686\u0648\u06ad-\u0643\u0649\u0686\u0649\u0643", "Constrain proportions": "\u0626\u06d0\u06af\u0649\u0632\u0644\u0649\u0643-\u0643\u06d5\u06ad\u0644\u0649\u0643 \u0646\u0649\u0633\u067e\u0649\u062a\u0649\u0646\u0649 \u0633\u0627\u0642\u0644\u0627\u0634", "General": "\u0626\u0627\u062f\u06d5\u062a\u062a\u0649\u0643\u0649", "Advanced": "\u0626\u0627\u0644\u0627\u06be\u0649\u062f\u06d5", "Style": "\u0626\u06c7\u0633\u0644\u06c7\u067e", "Vertical space": "\u06cb\u06d0\u0631\u062a\u0649\u0643\u0627\u0644 \u0628\u0648\u0634\u0644\u06c7\u0642", "Horizontal space": "\u06af\u0648\u0631\u0632\u0649\u0646\u062a\u0627\u0644 \u0628\u0648\u0634\u0644\u06c7\u0642", "Border": "\u064a\u0627\u0642\u0627", "Insert image": "\u0631\u06d5\u0633\u0649\u0645 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Image...": "\u0631\u06d5\u0633\u0649\u0645...", "Image list": "\u0631\u06d5\u0633\u0649\u0645 \u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643\u0649", "Rotate counterclockwise": "\u200f\u200f\u0633\u0627\u0626\u06d5\u062a\u0643\u06d5 \u0642\u0627\u0631\u0634\u0649 \u0686\u06c6\u0631\u06c8\u0634", "Rotate clockwise": "\u200f\u200f\u0633\u0627\u0626\u06d5\u062a \u064a\u06c6\u0646\u0649\u0644\u0649\u0634\u0649\u062f\u06d5 \u0686\u06c6\u0631\u06c8\u0634", "Flip vertically": "\u06cb\u06d0\u0631\u062a\u0649\u0643\u0627\u0644 \u0626\u06c6\u0631\u06c8\u0634", "Flip horizontally": "\u06af\u0648\u0631\u0649\u0632\u0648\u0646\u062a\u0627\u0644 \u0626\u06c6\u0631\u06c8\u0634", "Edit image": "\u0631\u06d5\u0633\u0649\u0645 \u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Image options": "\u0631\u06d5\u0633\u0649\u0645 \u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0649\u0644\u0649\u0631\u0649", "Zoom in": "\u064a\u06d0\u0642\u0649\u0646\u0644\u0627\u062a\u0645\u0627\u0642", "Zoom out": "\u064a\u0649\u0631\u0627\u0642\u0644\u0627\u062a\u0645\u0627\u0642", "Crop": "\u0642\u0649\u064a\u0649\u0634", "Resize": "\u0686\u0648\u06ad\u0644\u06c7\u0642\u0649\u0646\u0649 \u0626\u06c6\u0632\u06af\u06d5\u0631\u062a\u0649\u0634", "Orientation": "\u064a\u06c6\u0646\u0649\u0644\u0649\u0634", "Brightness": "\u064a\u0648\u0631\u06c7\u0642\u0644\u06c7\u0642\u0649", "Sharpen": "\u0626\u06c6\u062a\u0643\u06c8\u0631\u0644\u06d5\u0634\u062a\u06c8\u0631\u06c8\u0634", "Contrast": "\u0633\u06d0\u0644\u0649\u0634\u062a\u06c7\u0631\u0645\u0627", "Color levels": "\u0631\u06d5\u06ad \u062f\u06d5\u0631\u0649\u062c\u0649\u0644\u0649\u0631\u0649", "Gamma": "\u06af\u0627\u0645\u0645\u0627", "Invert": "\u062a\u06d5\u062a\u06c8\u0631", "Apply": "\u0642\u0648\u0644\u0644\u0649\u0646\u0649\u0634", "Back": "\u0642\u0627\u064a\u062a\u0649\u0634", "Insert date\/time": "\u0686\u0649\u0633\u0644\u0627\/\u06cb\u0627\u0642\u0649\u062a \u0643\u0649\u0631\u06af\u06c8\u0632\u06c8\u0634", "Date\/time": "\u0686\u06d0\u0633\u0644\u0627\\\u06cb\u0627\u0642\u0649\u062a", "Insert\/edit link": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634 \u0642\u06c7\u0633\u062a\u06c7\u0631\u06c7\u0634\/\u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Text to display": "\u0643\u06c6\u0631\u06c8\u0646\u0649\u062f\u0649\u063a\u0627\u0646 \u0645\u06d5\u0632\u0645\u06c7\u0646", "Url": "\u0626\u0627\u062f\u0631\u0649\u0633", "Open link in...": "\u0626\u06c7\u0644\u0627\u0646\u0645\u0627 \u0626\u06d0\u0686\u0649\u0634 \u0626\u0648\u0631\u0646\u0649...", "Current window": "\u0646\u06c6\u06cb\u06d5\u062a\u062a\u0649\u0643\u0649 \u0643\u06c6\u0632\u0646\u06d5\u0643", "None": "\u064a\u0648\u0642", "New window": "\u064a\u06d0\u06ad\u0649 \u0643\u06c6\u0632\u0646\u06d5\u0643", "Open link": "\u0626\u06c7\u0644\u0627\u0646\u0645\u0627 \u0626\u06d0\u0686\u0649\u0634", "Remove link": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634 \u0626\u06c6\u0686\u06c8\u0631\u06c8\u0634", "Anchors": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634", "Link...": "\u0626\u06c7\u0644\u0627\u0646\u0645\u0627...", "Paste or type a link": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634 \u0686\u0627\u067e\u0644\u0627\u06ad \u064a\u0627\u0643\u0649 \u0643\u0649\u0631\u06af\u06c8\u0632\u06c8\u06ad", "The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "\u0633\u0649\u0632 \u0643\u0649\u0631\u06af\u06c8\u0632\u06af\u06d5\u0646 URL \u0628\u0649\u0631 \u0626\u06d0\u0644\u062e\u06d5\u062a \u0626\u0627\u062f\u0631\u06d0\u0633\u0649\u062f\u06d5\u0643 \u0642\u0649\u0644\u0649\u067e \u062a\u06c7\u0631\u0649\u062f\u06c7\u060c\u062a\u06d5\u0644\u06d5\u067e \u0642\u0649\u0644\u0649\u0646\u063a\u0627\u0646 mailto \u0646\u0649 \u0642\u06c7\u0634\u0627\u0645\u0633\u0649\u0632\u061f", "The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "\u0633\u0649\u0632 \u0643\u0649\u0631\u06af\u06c8\u0632\u06af\u06d5\u0646 \u062a\u0648\u0631 \u0626\u0627\u062f\u0631\u06d0\u0633\u0649 \u0633\u0649\u0631\u062a\u0642\u0649 \u0626\u06c7\u0644\u0627\u0646\u0645\u0649\u062f\u06d5\u0643 \u0642\u0649\u0644\u0649\u067e \u062a\u06c7\u0631\u0649\u062f\u06c7 \u060c\u062a\u06d5\u0644\u06d5\u067e \u0642\u0649\u0644\u0649\u0646\u063a\u0627\u0646 http:\/\/ \u0646\u0649 \u0642\u0648\u0634\u0627\u0645\u0633\u0649\u0632\u061f", "The URL you entered seems to be an external link. Do you want to add the required https:\/\/ prefix?": "\u0633\u0649\u0632 \u0643\u0649\u0631\u06af\u06c8\u0632\u06af\u06d5\u0646 \u0626\u0627\u062f\u0631\u06d0\u0633 \u0633\u0649\u0631\u062a\u0642\u0649 \u0626\u06c7\u0644\u0627\u0646\u0645\u0649\u062f\u06d5\u0643 \u062a\u06c7\u0631\u0649\u062f\u06c7. \u062a\u06d5\u0644\u06d5\u067e \u0642\u0649\u0644\u0649\u0646\u063a\u0627\u0646 https:\/\/ \u0626\u0627\u0644\u062f\u0649 \u0642\u0648\u0634\u06c7\u0645\u0686\u0649\u0633\u0649\u0646\u0649 \u0642\u0648\u0634\u0627\u0645\u0633\u0649\u0632\u061f", "Link list": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634 \u062a\u06c8\u0631\u0649", "Insert video": "\u0633\u0649\u0646 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Insert\/edit video": "\u0633\u0649\u0646 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634\/\u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Insert\/edit media": "\u0645\u06d0\u062f\u0649\u064a\u0627 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634\/\u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Alternative source": "\u062a\u06d5\u0633\u06cb\u0649\u0631\u0649", "Alternative source URL": "\u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0627 \u0645\u06d5\u0646\u0628\u06d5 \u0626\u0627\u062f\u0631\u06d0\u0633\u0649", "Media poster (Image URL)": "\u0645\u06d0\u062f\u0649\u064a\u0627 \u0645\u06c7\u0642\u0627\u06cb\u0649\u0633\u0649 (\u0631\u06d5\u0633\u0649\u0645 \u0626\u0627\u062f\u0631\u06d0\u0633\u0649)", "Paste your embed code below:": "\u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0627\u0642\u0686\u0649 \u0628\u0648\u0644\u063a\u0627\u0646 \u0643\u0648\u062f\u0646\u0649 \u0686\u0627\u067e\u0644\u0627\u06ad", "Embed": "\u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Media...": "\u0645\u06d0\u062f\u0649\u064a\u0627...", "Nonbreaking space": "\u0628\u0648\u0634\u0644\u06c7\u0642", "Page break": "\u0628\u06d5\u062a \u0626\u0627\u062e\u0649\u0631\u0644\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Paste as text": "\u062a\u06d0\u0643\u0649\u0634 \u0634\u06d5\u0643\u0644\u0649\u062f\u06d5 \u0686\u0627\u067e\u0644\u0627\u0634", "Preview": "\u0643\u06c6\u0631\u06c8\u0634", "Print...": "\u0628\u06d0\u0633\u0649\u0634...", "Save": "\u0633\u0627\u0642\u0644\u0627\u0634", "Find": "\u0626\u0649\u0632\u062f\u06d5\u0634", "Replace with": "\u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Replace": "\u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Replace all": "\u06be\u06d5\u0645\u0645\u0649\u0646\u0649 \u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Previous": "\u0626\u0627\u0644\u062f\u0649\u0646\u0642\u0649", "Next": "\u0643\u06d0\u064a\u0649\u0646\u0643\u0649\u0633\u0649", "Find and Replace": "\u0626\u0649\u0632\u062f\u06d5\u0634 \u06cb\u06d5 \u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Find and replace...": "\u0626\u0649\u0632\u062f\u06d5\u0634 \u06cb\u06d5 \u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634...", "Could not find the specified string.": "\u0626\u0649\u0632\u062f\u0649\u0645\u06d5\u0643\u0686\u0649 \u0628\u0648\u0644\u063a\u0627\u0646 \u0645\u06d5\u0632\u0645\u06c7\u0646\u0646\u0649 \u062a\u0627\u067e\u0627\u0644\u0645\u0649\u062f\u0649.", "Match case": "\u0686\u0648\u06ad \u0643\u0649\u0686\u0649\u0643 \u06be\u06d5\u0631\u0649\u067e\u0646\u0649 \u067e\u06d5\u0631\u0649\u0642\u0644\u06d5\u0646\u062f\u06c8\u0631\u06c8\u0634", "Find whole words only": "\u067e\u06c8\u062a\u06c8\u0646 \u0633\u06c6\u0632\u0646\u0649\u0644\u0627 \u0626\u0649\u0632\u062f\u06d5\u0634", "Find in selection": "\u062a\u0627\u0644\u0644\u0627\u0646\u063a\u0627\u0646\u062f\u0649\u0646 \u0626\u0649\u0632\u062f\u06d5\u0634", "Spellcheck": "\u0626\u0649\u0645\u0644\u0627 \u062a\u06d5\u0643\u0634\u06c8\u0631\u06c8\u0634", "Spellcheck Language": "\u0626\u0649\u0645\u0644\u0627 \u062a\u06d5\u0643\u0634\u06c8\u0631\u06c8\u0634 \u062a\u0649\u0644\u0649", "No misspellings found.": "\u0626\u0649\u0645\u0644\u0627 \u062e\u0627\u062a\u0627\u0644\u0649\u0642\u0649 \u062a\u06d0\u067e\u0649\u0644\u0645\u0649\u062f\u0649.", "Ignore": "\u0626\u06c6\u062a\u0643\u06c8\u0632\u06c8\u0634", "Ignore all": "\u06be\u06d5\u0645\u0645\u0649\u0646\u0649 \u0626\u06c6\u062a\u0643\u06c8\u0632\u06c8\u0634", "Finish": "\u0626\u0627\u062e\u0649\u0631\u0644\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Add to Dictionary": "\u0644\u06c7\u063a\u06d5\u062a \u0642\u0648\u0634\u06c7\u0634", "Insert table": "\u062c\u06d5\u062f\u06cb\u06d5\u0644 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Table properties": "\u062c\u06d5\u062f\u06cb\u06d5\u0644 \u062e\u0627\u0633\u0644\u0649\u0642\u0649", "Delete table": "\u062c\u06d5\u062f\u06cb\u06d5\u0644 \u0626\u06c6\u0686\u06c8\u0631\u0634", "Cell": "\u0643\u0627\u062a\u06d5\u0643", "Row": "\u0642\u06c7\u0631", "Column": "\u0631\u06d5\u062a", "Cell properties": "\u0643\u0627\u062a\u06d5\u0643 \u062e\u0627\u0633\u0644\u0649\u0642\u0649", "Merge cells": "\u0643\u0627\u062a\u06d5\u0643 \u0628\u0649\u0631\u0644\u06d5\u0634\u062a\u06c8\u0631\u06c8\u0634", "Split cell": "\u0643\u0627\u062a\u06d5\u0643 \u067e\u0627\u0631\u0686\u0649\u0644\u0627\u0634", "Insert row before": "\u0626\u0627\u0644\u062f\u0649\u063a\u0627 \u0642\u06c7\u0631 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Insert row after": "\u0626\u0627\u0631\u0642\u0649\u063a\u0627 \u0642\u06c7\u0631 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Delete row": "\u0642\u06c7\u0631 \u0626\u06c6\u0686\u06c8\u0631\u06c8\u0634", "Row properties": "\u0642\u06c7\u0631 \u062e\u0627\u0633\u0644\u0649\u0642\u0649", "Cut row": "\u0642\u06c7\u0631 \u0643\u06d0\u0633\u0649\u0634", "Copy row": "\u0642\u06c7\u0631 \u0643\u06c6\u0686\u06c8\u0631\u06c8\u0634", "Paste row before": "\u0642\u06c7\u0631 \u0626\u0627\u0644\u062f\u0649\u063a\u0627 \u0686\u0627\u067e\u0644\u0627\u0634", "Paste row after": "\u0642\u06c7\u0631 \u0643\u06d5\u064a\u0646\u0649\u06af\u06d5 \u0686\u0627\u067e\u0644\u0627\u0634", "Insert column before": "\u0631\u06d5\u062a \u0626\u0627\u0644\u062f\u0649\u063a\u0627 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Insert column after": "\u0631\u06d5\u062a \u0643\u06d5\u064a\u0646\u0649\u06af\u06d5 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Delete column": "\u0631\u06d5\u062a \u0626\u06c6\u0686\u06c8\u0631\u06c8\u0634", "Cols": "\u0631\u06d5\u062a", "Rows": "\u0642\u06c7\u0631", "Width": "\u0643\u06d5\u06ad\u0644\u0649\u0643\u0649", "Height": "\u0626\u06d0\u06af\u0649\u0632\u0644\u0649\u0643\u0649", "Cell spacing": "\u0643\u0627\u062a\u06d5\u0643 \u0633\u0649\u0631\u062a\u0642\u0649 \u0626\u0627\u0631\u0649\u0644\u0649\u0642\u0649", "Cell padding": "\u0643\u0627\u062a\u06d5\u0643 \u0626\u0649\u0686\u0643\u0649 \u0626\u0627\u0631\u0649\u0644\u0649\u0642\u0649", "Caption": "\u0686\u06c8\u0634\u06d5\u0646\u062f\u06c8\u0631\u06c8\u0634", "Show caption": "\u062a\u06d0\u0645\u0649\u0633\u0649\u0646\u0649 \u0643\u06c6\u0631\u0633\u0649\u062a\u0649\u0634", "Left": "\u0633\u0648\u0644", "Center": "\u0645\u06d5\u0631\u0643\u06d5\u0632", "Right": "\u0626\u0648\u06ad", "Cell type": "\u0643\u0627\u062a\u06d5\u0643 \u062a\u0649\u067e\u0649", "Scope": "\u062f\u0627\u0626\u0649\u0631\u06d5", "Alignment": "\u064a\u06c6\u0644\u0649\u0646\u0649\u0634\u0649", "H Align": "\u06af\u0648\u0631\u0632\u0649\u0646\u062a\u0627\u0644 \u062a\u0648\u063a\u0631\u0649\u0644\u0627\u0634", "V Align": "\u06cb\u06d0\u0631\u062a\u0649\u0643\u0627\u0644 \u062a\u0648\u063a\u0631\u0649\u0644\u0627\u0634", "Top": "\u0626\u06c8\u0633\u062a\u0649", "Middle": "\u0626\u0648\u062a\u062a\u06c7\u0631\u0633\u0649", "Bottom": "\u0626\u0627\u0633\u062a\u0649", "Header cell": "\u0628\u0627\u0634 \u0643\u0627\u062a\u06d5\u0643", "Row group": "\u0642\u06c7\u0631 \u06af\u06c7\u0631\u06c7\u067e\u067e\u0649\u0633\u0649", "Column group": "\u0631\u06d5\u062a \u06af\u06c7\u0631\u06c7\u067e\u067e\u0649\u0633\u0649", "Row type": "\u0642\u06c7\u0631 \u062a\u0649\u067e\u0649", "Header": "\u0628\u06d0\u0634\u0649", "Body": "\u0628\u06d5\u062f\u0649\u0646\u0649", "Footer": "\u067e\u06c7\u062a\u0649", "Border color": "\u0631\u0627\u0645\u0643\u0627 \u0631\u06d5\u06ad\u06af\u0649", "Insert template...": "\u0642\u06d0\u0644\u0649\u067e \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634...", "Templates": "\u0626\u06c8\u0644\u06af\u0649\u0644\u06d5\u0631", "Template": "\u0626\u06c8\u0644\u06af\u0649\u0644\u06d5\u0631", "Text color": "\u062e\u06d5\u062a \u0631\u06d5\u06ad\u06af\u0649", "Background color": "\u0626\u0627\u0631\u0642\u0627 \u0631\u06d5\u06ad\u06af\u0649", "Custom...": "\u0626\u0649\u062e\u062a\u0649\u064a\u0627\u0631\u0649", "Custom color": "\u0626\u0649\u062e\u062a\u0649\u064a\u0627\u0631\u0649 \u0631\u06d5\u06ad", "No color": "\u0631\u06d5\u06ad \u064a\u0648\u0642", "Remove color": "\u0631\u06d5\u06ad\u0646\u0649 \u0686\u0649\u0642\u0649\u0631\u0649\u06cb\u06d0\u062a\u0649\u0634", "Table of Contents": "\u062c\u06d5\u062f\u06d5\u0644\u0646\u0649\u06ad \u0645\u06d5\u0632\u0645\u06c7\u0646\u0649", "Show blocks": "\u0631\u0627\u064a\u0648\u0646 \u0643\u06c6\u0631\u0633\u0649\u062a\u0649\u0634", "Show invisible characters": "\u0643\u06c6\u0631\u06c8\u0646\u0645\u06d5\u064a\u062f\u0649\u063a\u0627\u0646 \u06be\u06d5\u0631\u0649\u067e\u0644\u06d5\u0631\u0646\u0649 \u0643\u06c6\u0631\u0633\u0649\u062a\u0649\u0634", "Word count": "\u0633\u06c6\u0632 \u0633\u0627\u0646\u0649", "Count": "\u0633\u0627\u0646\u0627\u0634", "Document": "\u06be\u06c6\u062c\u062c\u06d5\u062a", "Selection": "\u062a\u0627\u0644\u0644\u0627\u0646\u063a\u0627\u0646", "Words": "\u0633\u06c6\u0632\u0644\u06d5\u0631", "Words: {0}": "\u0633\u06c6\u0632: {0}", "{0} words": "{0} \u0633\u06c6\u0632", "File": "\u06be\u06c6\u062c\u062c\u06d5\u062a", "Edit": "\u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Insert": "\u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "View": "\u0643\u06c6\u0631\u06c8\u0634", "Format": "\u0641\u0648\u0631\u0645\u0627\u062a", "Table": "\u062c\u06d5\u062f\u06cb\u06d5\u0644", "Tools": "\u0642\u06c7\u0631\u0627\u0644", "Powered by {0}": "\u062a\u06d0\u062e\u0646\u0649\u0643\u0649\u062f\u0627 {0}", "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "\u0645\u0648\u0644 \u0645\u06d5\u0632\u0645\u06c7\u0646\u0644\u06c7\u0642 \u062a\u06d0\u0643\u06d0\u0633\u0649\u062a \u0631\u0627\u0645\u0643\u0649\u0633\u0649 \u0631\u0627\u064a\u0648\u0646\u0649\u062f\u0627 \u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643 \u0626\u06c8\u0686\u06c8\u0646 ALT-F9 \u0646\u0649\u060c \u0642\u0648\u0631\u0627\u0644 \u0628\u0627\u0644\u062f\u0649\u0642\u0649 \u0626\u06c8\u0686\u06c8\u0646 ALT-F10 \u0646\u0649\u060c \u064a\u0627\u0631\u062f\u06d5\u0645 \u0626\u06c8\u0686\u06c8\u0646 ALT-0 \u0646\u0649 \u0628\u06d0\u0633\u0649\u06ad", "Image title": "\u0631\u06d5\u0633\u0649\u0645 \u062a\u06d0\u0645\u0649\u0633\u0649", "Border width": "\u06af\u0649\u0631\u06cb\u06d5\u0643 \u0643\u06d5\u06ad\u0644\u0649\u0643\u0649", "Border style": "\u06af\u0649\u0631\u06cb\u06d5\u0643 \u0626\u06c7\u0633\u0644\u06c7\u0628\u0649", "Error": "\u062e\u0627\u062a\u0627\u0644\u0649\u0642", "Warn": "\u0626\u0627\u06af\u0627\u06be\u0644\u0627\u0646\u062f\u06c7\u0631\u06c7\u0634", "Valid": "\u0626\u06c8\u0646\u06c8\u0645\u0644\u06c8\u0643", "To open the popup, press Shift+Enter": "\u0633\u06d5\u0643\u0631\u0649\u0645\u06d5 \u0643\u06c6\u0632\u0646\u06d5\u0643\u0646\u0649 \u0626\u06d0\u0686\u0649\u0634 \u0626\u06c8\u0686\u06c8\u0646 Shift+Enter \u0646\u0649 \u0628\u06d0\u0633\u0649\u06ad", "Rich Text Area. Press ALT-0 for help.": "\u0641\u0648\u0631\u0645\u0627\u062a\u0644\u0649\u0642 \u062a\u06d0\u0643\u0649\u0633\u062a \u0631\u0627\u064a\u0648\u0646\u0649. \u064a\u0627\u0631\u062f\u06d5\u0645 \u0626\u06c8\u0686\u06c8\u0646 ALT-0 \u0646\u0649 \u0628\u06d0\u0633\u0649\u06ad.", "System Font": "\u0633\u0649\u0633\u062a\u06d0\u0645\u0627 \u062e\u06d5\u062a \u0646\u06c7\u0633\u062e\u0649\u0633\u0649", "Failed to upload image: {0}": "\u0631\u06d5\u0633\u0649\u0645\u0646\u0649 \u064a\u06c8\u0643\u0644\u0649\u064a\u06d5\u0644\u0645\u0649\u062f\u0649: {0}", "Failed to load plugin: {0} from url {1}": "\u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0649\u0646\u0649 \u064a\u06c8\u0643\u0644\u0649\u064a\u06d5\u0644\u0645\u0649\u062f\u0649: {0} \u0646\u0649\u06ad \u0645\u06d5\u0646\u0628\u06d5 \u0626\u0627\u062f\u0631\u06d0\u0633\u0649 {1}", "Failed to load plugin url: {0}": "\u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0649\u0646\u0649 \u064a\u06c8\u0643\u0644\u0649\u064a\u06d5\u0644\u0645\u0649\u062f\u0649 \u0626\u0627\u062f\u0631\u06d0\u0633\u0649: {0}", "Failed to initialize plugin: {0}": "\u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0649\u0646\u0649 \u062f\u06d5\u0633\u0644\u06d5\u067e\u0644\u06d5\u0634\u062a\u06c8\u0631\u06d5\u0644\u0645\u0649\u062f\u0649: {0}", "example": "\u0645\u06d5\u0633\u0649\u0644\u06d5\u0646", "Search": "\u0626\u0649\u0632\u062f\u06d5\u0634", "All": "\u06be\u06d5\u0645\u0645\u06d5", "Currency": "\u067e\u06c7\u0644", "Text": "\u062a\u06d0\u0643\u0649\u0633\u062a", "Quotations": "\u0646\u06d5\u0642\u0649\u0644\u0644\u06d5\u0631", "Mathematical": "\u0645\u0627\u062a\u06d0\u0645\u0627\u062a\u0649\u0643\u0649\u0644\u0649\u0642", "Extended Latin": "\u0643\u06d0\u06ad\u06d5\u064a\u062a\u0649\u0644\u06af\u06d5\u0646 \u0644\u0627\u062a\u0649\u0646 \u06be\u06d5\u0631\u067e\u0644\u0649\u0631\u0649", "Symbols": "\u0628\u06d5\u0644\u06af\u0649\u0644\u06d5\u0631", "Arrows": "\u0626\u0649\u0633\u062a\u0631\u06d0\u0644\u0643\u0649\u0644\u0627\u0631", "User Defined": "\u0626\u0649\u0634\u0644\u06d5\u062a\u0643\u06c8\u0686\u0649 \u0628\u06d5\u0644\u06af\u0649\u0644\u0649\u06af\u06d5\u0646", "dollar sign": "\u062f\u0648\u0644\u0644\u0627\u0631 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "currency sign": "\u067e\u06c7\u0644 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "euro-currency sign": "\u064a\u0627\u06cb\u0631\u0648 \u067e\u06c7\u0644 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "colon sign": "\u0642\u0648\u0634 \u0686\u06d0\u0643\u0649\u062a \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "cruzeiro sign": "\u0643\u0631\u06c7 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "french franc sign": "\u0641\u0649\u0631\u0627\u0646\u0633\u0649\u064a\u06d5 \u0641\u0649\u0631\u0627\u0646\u0643 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "lira sign": "\u0644\u0649\u0631\u0627 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "mill sign": "\u0645\u0649\u0644 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "naira sign": "\u0646\u0627\u064a\u0631\u0627 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "peseta sign": "\u067e\u06d0\u0633\u06d0\u062a\u0627 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "rupee sign": "\u0631\u06c7\u067e\u0649\u064a\u06d5 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "won sign": "\u06cb\u0648\u0646 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "new sheqel sign": "\u064a\u06d0\u06ad\u0649 \u0634\u0649\u0643\u0649\u0644 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "dong sign": "\u06cb\u0649\u064a\u06d0\u062a\u0646\u0627\u0645 \u062f\u0648\u06ad\u0649 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "kip sign": "\u0643\u0649\u067e \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "tugrik sign": "\u062a\u06c8\u06af\u0631\u0649\u0643 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "drachma sign": "\u062f\u0649\u0631\u0627\u062e\u0645\u0627 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "german penny symbol": "\u06af\u06d0\u0631\u0645\u0627\u0646\u0649\u064a\u06d5 \u067e\u06d0\u0646\u0646\u0649 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "peso sign": "\u067e\u06d0\u0633\u0648 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "guarani sign": "\u06af\u06c7\u0626\u0627\u0631\u0627\u0646\u0649 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "austral sign": "\u0626\u0627\u06cb\u0633\u062a\u0631\u0627\u0644\u0649\u064a\u06d5 \u067e\u06c7\u0644 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "hryvnia sign": "hryvnia \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "cedi sign": "\u0633\u06d0\u062f\u0649 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "livre tournois sign": "livre tournois \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "spesmilo sign": "spesmilo \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "tenge sign": "tenge \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "indian rupee sign": "\u06be\u0649\u0646\u062f\u0649\u0633\u062a\u0627\u0646 \u0631\u06c7\u067e\u0649\u064a\u06d5 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "turkish lira sign": "\u062a\u06c8\u0631\u0643\u0649\u064a\u06d5 \u0644\u0649\u0631\u0627 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "nordic mark sign": "\u0634\u0649\u0645\u0627\u0644\u0649\u064a \u064a\u0627\u06cb\u0631\u0648\u067e\u0627 \u0645\u0627\u0631\u0643 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "manat sign": "manat \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "ruble sign": "\u0631\u06c7\u0628\u0644\u0649 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "yen character": "\u064a\u06d0\u0646 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "yuan character": "\u064a\u06c8\u06d5\u0646 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "yuan character, in hong kong and taiwan": "\u064a\u06c8\u06d5\u0646 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649 (\u0634\u064a\u0627\u06ad\u06af\u0627\u06ad \u06cb\u06d5 \u062a\u06d5\u064a\u06cb\u06d5\u0646)", "yen\/yuan character variant one": "\u064a\u06d0\u0646 \u06cb\u06d5 \u064a\u06c8\u06d5\u0646 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649", "Loading emoticons...": "\u0686\u0649\u0631\u0627\u064a \u0626\u0649\u067e\u0627\u062f\u0649\u0644\u0649\u0631\u0649 \u064a\u06c8\u0643\u0644\u0649\u0646\u0649\u06cb\u0627\u062a\u0649\u062f\u06c7...", "Could not load emoticons": "\u0686\u0649\u0631\u0627\u064a \u0626\u0649\u067e\u0627\u062f\u0649\u0644\u0649\u0631\u0649 \u064a\u06c8\u0643\u0644\u06d5\u0646\u0645\u0649\u062f\u0649", "People": "\u0626\u0627\u062f\u06d5\u0645\u0644\u06d5\u0631", "Animals and Nature": "\u06be\u0627\u064a\u06cb\u0627\u0646\u0644\u0627\u0631 \u06cb\u06d5 \u062a\u06d5\u0628\u0649\u0626\u06d5\u062a", "Food and Drink": "\u064a\u06d0\u0645\u06d5\u0643-\u0626\u0649\u0686\u0645\u06d5\u0643", "Activity": "\u067e\u0627\u0626\u0627\u0644\u0649\u064a\u06d5\u062a", "Travel and Places": "\u0633\u0627\u064a\u0627\u06be\u06d5\u062a \u06cb\u06d5 \u062c\u0627\u064a\u0644\u0627\u0631", "Objects": "\u0646\u06d5\u0631\u0633\u0649\u0644\u06d5\u0631", "Flags": "\u0628\u0627\u064a\u0631\u0627\u0642\u0644\u0627\u0631", "Characters": "\u06be\u06d5\u0631\u067e-\u0628\u06d5\u0644\u06af\u0649\u0644\u06d5\u0631", "Characters (no spaces)": "\u06be\u06d5\u0631\u067e-\u0628\u06d5\u0644\u06af\u0649\u0644\u06d5\u0631 (\u0628\u0648\u0634\u0644\u06c7\u0642\u0646\u0649 \u0626\u06c6\u0632 \u0626\u0649\u0686\u0649\u06af\u06d5 \u0626\u0627\u0644\u0645\u0627\u064a\u062f\u06c7)", "{0} characters": "{0} \u06be\u06d5\u0631\u067e-\u0628\u06d5\u0644\u06af\u06d5", "Error: Form submit field collision.": "\u062e\u0627\u062a\u0627\u0644\u0649\u0642: \u0631\u0627\u0645\u0643\u0627 (form) \u064a\u0648\u0644\u0644\u0627\u0634 \u0628\u06c6\u0644\u0649\u0643\u0649 \u062a\u0648\u0642\u06c7\u0646\u06c7\u0634\u062a\u0649.", "Error: No form element found.": "\u062e\u0627\u062a\u0627\u0644\u0649\u0642: \u0631\u0627\u0645\u0643\u0627 (form) \u0626\u06d0\u0644\u06d0\u0645\u06d0\u0646\u062a\u0649 \u062a\u06d0\u067e\u0649\u0644\u0645\u0649\u062f\u0649.", "Update": "\u064a\u06d0\u06ad\u0649\u0644\u0627\u0634", "Color swatch": "\u0631\u06d5\u06ad \u0626\u06c8\u0644\u06af\u0649\u0633\u0649", "Turquoise": "\u0643\u06c6\u0643\u06c8\u0686 \u064a\u06d0\u0634\u0649\u0644", "Green": "\u064a\u06d0\u0634\u0649\u0644", "Blue": "\u0643\u06c6\u0643", "Purple": "\u0628\u0649\u0646\u06d5\u067e\u0634\u06d5", "Navy Blue": "\u062f\u06d0\u06ad\u0649\u0632 \u0643\u06c6\u0643", "Dark Turquoise": "\u062a\u0648\u0642 \u0643\u06c6\u0643\u06c8\u0686 \u064a\u06d0\u0634\u0649\u0644", "Dark Green": "\u062a\u0648\u0642 \u064a\u06d0\u0634\u0649\u0644", "Medium Blue": "\u0626\u0627\u0631\u0627 \u0643\u06c6\u0643", "Medium Purple": "\u0626\u0627\u0631\u0627 \u0628\u0649\u0646\u06d5\u067e\u0634\u06d5", "Midnight Blue": "\u0642\u0627\u0631\u0627 \u0643\u06c6\u0643", "Yellow": "\u0633\u06d0\u0631\u0649\u0642", "Orange": "\u0642\u0649\u0632\u063a\u06c7\u0686 \u0633\u06d0\u0631\u0649\u0642", "Red": "\u0642\u0649\u0632\u0649\u0644", "Light Gray": "\u0626\u0627\u0686 \u0643\u06c8\u0644\u0631\u06d5\u06ad", "Gray": "\u0643\u06c8\u0644\u0631\u06d5\u06ad", "Dark Yellow": "\u062a\u0648\u0642 \u0633\u06d0\u0631\u0649\u0642", "Dark Orange": "\u062a\u0648\u0642 \u0642\u0649\u0632\u063a\u06c7\u0686", "Dark Red": "\u062a\u0648\u0642 \u0642\u0649\u0632\u0649\u0644", "Medium Gray": "\u0626\u0648\u062a\u062a\u06c7\u0631\u06be\u0627\u0644 \u0643\u06c8\u0644\u0631\u06d5\u06ad", "Dark Gray": "\u062a\u0648\u0642 \u0643\u06c8\u0644\u0631\u06d5\u06ad", "Light Green": "\u0626\u0627\u0686 \u064a\u06d0\u0634\u0649\u0644", "Light Yellow": "\u0626\u0627\u0686 \u0633\u06d0\u0631\u0649\u0642", "Light Red": "\u0626\u0627\u0686 \u0642\u0649\u0632\u0649\u0644", "Light Purple": "\u0626\u0627\u0686 \u0628\u0649\u0646\u06d5\u067e\u0634\u06d5", "Light Blue": "\u0626\u0627\u0686 \u0643\u06c6\u0643", "Dark Purple": "\u062a\u0648\u0642 \u0628\u0649\u0646\u06d5\u067e\u0634\u06d5", "Dark Blue": "\u062a\u0648\u0642 \u0643\u06c6\u0643", "Black": "\u0642\u0627\u0631\u0627", "White": "\u0626\u0627\u0642", "Switch to or from fullscreen mode": "\u062a\u0648\u0644\u06c7\u0642 \u0626\u06d0\u0643\u0631\u0627\u0646 \u06be\u0627\u0644\u0649\u062a\u0649\u0646\u0649 \u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Open help dialog": "\u064a\u0627\u0631\u062f\u06d5\u0645 \u062f\u0649\u064a\u0627\u0644\u0648\u06af\u0649\u0646\u0649 \u0626\u06d0\u0686\u0649\u0634", "history": "\u062a\u0627\u0631\u0649\u062e\u0649\u064a \u0626\u06c7\u0686\u06c7\u0631", "styles": "\u0626\u06c7\u0633\u0644\u06c7\u0628\u0644\u0627\u0631", "formatting": "\u0641\u0648\u0631\u0645\u0627\u062a\u0644\u0627\u0634", "alignment": "\u062a\u0648\u063a\u0631\u0649\u0644\u0627\u0634", "indentation": "\u062a\u0627\u0631\u0627\u064a\u062a\u0649\u0634", "Font": "\u062e\u06d5\u062a \u0646\u06c7\u0633\u062e\u0649\u0633\u0649", "Size": "\u0686\u0648\u06ad\u0644\u06c7\u0642\u0649", "More...": "\u062a\u06d0\u062e\u0649\u0645\u06c7 \u0643\u06c6\u067e...", "Select...": "\u062a\u0627\u0644\u0644\u0627\u0634...", "Preferences": "\u0645\u0627\u064a\u0649\u0644\u0644\u0649\u0642\u0644\u0649\u0631\u0649", "Yes": "\u06be\u06d5\u0626\u06d5", "No": "\u064a\u0627\u0642", "Keyboard Navigation": "\u064a\u06c6\u062a\u0643\u0649\u0644\u0649\u0634\u0686\u0627\u0646 \u0643\u06c7\u0646\u06c7\u067e\u0643\u0627 \u062a\u0627\u062e\u062a\u0649\u0633\u0649", "Version": "\u0646\u06d5\u0634\u0631\u0649", "Code view": "\u0643\u0648\u062f \u0643\u06c6\u0631\u06c8\u0646\u06c8\u0634\u0649", "Open popup menu for split buttons": "\u0628\u06c6\u0644\u06c8\u0646\u0645\u06d5 \u0643\u06c7\u0646\u06c7\u067e\u0643\u0649\u0644\u0627\u0631 \u0626\u06c8\u0686\u06c8\u0646 \u0633\u06d5\u0643\u0631\u0649\u0645\u06d5 \u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643 \u0626\u06d0\u0686\u0649\u0634", "List Properties": "\u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643 \u062e\u0627\u0633\u0644\u0649\u0642\u0644\u0649\u0631\u0649", "List properties...": "\u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643 \u062e\u0627\u0633\u0644\u0649\u0642\u0644\u0649\u0631\u0649...", "Start list at number": "\u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643\u0646\u0649 \u0633\u0627\u0646 \u0628\u0649\u0644\u06d5\u0646 \u0628\u0627\u0634\u0644\u0627\u0634", "Line height": "\u0642\u06c7\u0631 \u0626\u0627\u0631\u0649\u0644\u0649\u0642\u0649", "comments": "\u0626\u0649\u0646\u0643\u0627\u0633\u0644\u0627\u0631", "Format Painter": "\u0641\u0648\u0631\u0645\u0627\u062a \u0643\u06c6\u0686\u06c8\u0631\u06af\u06c8\u0686", "Insert\/edit iframe": "\u0631\u0627\u0645\u0643\u0627 (iframe) \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634 \u064a\u0627\u0643\u0649 \u062a\u06d5\u06be\u0631\u0649\u0631\u0644\u06d5\u0634", "Capitalization": "\u0686\u0648\u06ad \u06be\u06d5\u0631\u067e\u0643\u06d5 \u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "lowercase": "\u0643\u0649\u0686\u0649\u0643 \u06be\u06d5\u0631\u067e", "UPPERCASE": "\u0686\u0648\u06ad \u06be\u06d5\u0631\u067e", "Title Case": "\u062a\u06d0\u0645\u0627 \u0626\u06c7\u0633\u0644\u06c7\u0628\u0649", "permanent pen": "\u062f\u0627\u0626\u0649\u0645\u0644\u0649\u0642 \u0642\u06d5\u0644\u06d5\u0645", "Permanent Pen Properties": "\u062f\u0627\u0626\u0649\u0645\u0644\u0649\u0642 \u0642\u06d5\u0644\u06d5\u0645 \u062e\u0627\u0633\u0644\u0649\u0642\u0644\u0649\u0631\u0649", "Permanent pen properties...": "\u062f\u0627\u0626\u0649\u0645\u0644\u0649\u0642 \u0642\u06d5\u0644\u06d5\u0645 \u062e\u0627\u0633\u0644\u0649\u0642\u0644\u0649\u0631\u0649...", "case change": "\u0686\u0648\u06ad\u0644\u06c7\u0642\u0649\u0646\u0649 \u0626\u06c6\u0632\u06af\u06d5\u0631\u062a\u0649\u0634", "page embed": "\u0642\u0649\u0633\u062a\u06c7\u0631\u0645\u0627 \u0628\u06d5\u062a", "Advanced sort...": "\u0626\u0627\u0644\u0649\u064a \u062a\u0649\u0632\u0649\u0634...", "Advanced Sort": "\u0626\u0627\u0644\u0649\u064a \u062a\u0649\u0632\u0649\u0634", "Sort table by column ascending": "\u062c\u06d5\u062f\u06cb\u06d5\u0644\u0646\u0649 \u0626\u0649\u0633\u062a\u0648\u0646\u0646\u0649\u06ad \u0626\u06d0\u0634\u0649\u0634\u0649 \u0628\u0648\u064a\u0649\u0686\u06d5 \u062a\u0649\u0632\u0649\u0634", "Sort table by column descending": "\u062c\u06d5\u062f\u06cb\u06d5\u0644\u0646\u0649 \u0626\u0649\u0633\u062a\u0648\u0646\u0646\u0649\u06ad \u0643\u06d0\u0645\u0649\u064a\u0649\u0634\u0649 \u0628\u0648\u064a\u0649\u0686\u06d5 \u062a\u0649\u0632\u0649\u0634", "Sort": "\u062a\u0649\u0632\u0649\u0634", "Order": "\u062a\u06d5\u0631\u062a\u0649\u067e\u0649", "Sort by": "\u062a\u0649\u0632\u0649\u0634 \u0634\u06d5\u0643\u0644\u0649", "Ascending": "\u0626\u06d0\u0634\u0649\u0634", "Descending": "\u0643\u06d0\u0645\u0649\u064a\u0649\u0634", "Column {0}": "{0} \u0626\u0649\u0633\u062a\u0648\u0646", "Row {0}": "{0}-\u0642\u06c7\u0631", "Spellcheck...": "\u0626\u0649\u0645\u0644\u0627 \u062a\u06d5\u0643\u0634\u06c8\u0631\u06c8\u0634...", "Misspelled word": "\u062e\u0627\u062a\u0627 \u0633\u06c6\u0632", "Suggestions": "\u062a\u06d5\u06cb\u0633\u0649\u064a\u06d5\u0644\u06d5\u0631", "Change": "\u0626\u06c6\u0632\u06af\u06d5\u0631\u062a\u0649\u0634", "Finding word suggestions": "\u062a\u06d5\u06cb\u0633\u0649\u064a\u06d5 \u0633\u06c6\u0632\u0644\u06d5\u0631\u0646\u0649 \u0626\u0649\u0632\u062f\u06d5\u0634", "Success": "\u0626\u0648\u06ad\u06c7\u0634\u0644\u06c7\u0642 \u0628\u0648\u0644\u062f\u0649", "Repair": "\u0626\u0648\u06ad\u0634\u0627\u0634", "Issue {0} of {1}": "{0}-\u0645\u06d5\u0633\u0649\u0644\u06d5\u060c \u062c\u06d5\u0645\u0626\u0649\u064a {1} \u0645\u06d5\u0633\u0649\u0644\u06d5", "Images must be marked as decorative or have an alternative text description": "\u0631\u06d5\u0633\u0649\u0645\u0644\u06d5\u0631\u0646\u0649\u06ad \u0686\u0648\u0642\u06c7\u0645 \u0628\u06d0\u0632\u06d5\u0643 \u0628\u06d5\u0644\u06af\u0649\u0633\u0649 \u064a\u0627\u0643\u0649 \u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0627 \u062a\u06d0\u0643\u0649\u0633\u062a \u0686\u06c8\u0634\u06d5\u0646\u062f\u06c8\u0631\u06c8\u0634\u0649 \u0628\u0648\u0644\u06c7\u0634\u0649 \u0643\u06d0\u0631\u06d5\u0643", "Images must have an alternative text description. Decorative images are not allowed.": "\u0631\u06d5\u0633\u0649\u0645\u0644\u06d5\u0631\u0646\u0649\u06ad \u0686\u0648\u0642\u06c7\u0645 \u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0627 \u062a\u06d0\u0643\u0649\u0633\u062a \u0686\u06c8\u0634\u06d5\u0646\u062f\u06c8\u0631\u06c8\u0634\u0649 \u0628\u0648\u0644\u06c7\u0634\u0649 \u0643\u06d0\u0631\u06d5\u0643. \u0628\u06d0\u0632\u06d5\u0643 \u0631\u06d5\u0633\u0649\u0645\u0644\u06d5\u0631\u06af\u06d5 \u0631\u06c7\u062e\u0633\u06d5\u062a \u0642\u0649\u0644\u0649\u0646\u0645\u0627\u064a\u062f\u06c7.", "Or provide alternative text:": "\u064a\u0627\u0643\u0649 \u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0627 \u062a\u06d0\u0643\u0649\u0633\u062a\u0646\u0649 \u0643\u0649\u0631\u06af\u06c8\u0632\u06c8\u06ad:", "Make image decorative:": "\u0628\u06d0\u0632\u06d5\u0643 \u0631\u06d5\u0633\u0649\u0645 \u0642\u0649\u0644\u0649\u06ad:", "ID attribute must be unique": "ID \u062e\u0627\u0633\u0644\u0649\u0642\u0649 \u0628\u0649\u0631\u062f\u0649\u0646\u0628\u0649\u0631 \u0628\u0648\u0644\u06c7\u0634\u0649 \u0643\u06d0\u0631\u06d5\u0643", "Make ID unique": "ID \u0646\u0649 \u0628\u0649\u0631\u062f\u0649\u0646\u0628\u0649\u0631 \u0642\u0649\u0644\u0649\u0634", "Keep this ID and remove all others": "\u0628\u06c7 ID \u062f\u0649\u0646 \u0628\u0627\u0634\u0642\u0649\u0644\u0649\u0631\u0649\u0646\u0649 \u0686\u0649\u0642\u0649\u0631\u0649\u06cb\u06d0\u062a\u0649\u0634", "Remove this ID": "\u0628\u06c7 ID \u0646\u0649 \u0686\u0649\u0642\u0649\u0631\u0649\u06cb\u06d0\u062a\u0649\u0634", "Remove all IDs": "\u0628\u0627\u0631\u0644\u0649\u0642 ID \u0646\u0649 \u0686\u0649\u0642\u0649\u0631\u0649\u06cb\u06d0\u062a\u0649\u0634", "Checklist": "\u062a\u0627\u0644\u0644\u0627\u0646\u0645\u0627 \u062a\u0649\u0632\u0649\u0645\u0644\u0649\u0643", "Anchor": "\u0626\u06c7\u0644\u0627\u0646\u0645\u0627", "Special character": "\u0626\u0627\u0644\u0627\u06be\u0649\u062f\u06d5 \u0628\u06d5\u0644\u06af\u0649\u0644\u06d5\u0631", "Code sample": "\u0643\u0648\u062f \u0645\u0649\u0633\u0627\u0644\u0649", "Color": "\u0631\u06d5\u06ad", "Document properties": "\u06be\u06c6\u062c\u062c\u06d5\u062a \u062e\u0627\u0633\u0644\u0649\u0642\u0649", "Image description": "\u0631\u06d5\u0633\u0649\u0645 \u062a\u06d5\u0633\u06cb\u0649\u0631\u0649", "Image": "\u0631\u06d5\u0633\u0649\u0645", "Insert link": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634", "Target": "\u0646\u0649\u0634\u0627\u0646", "Link": "\u0626\u06c7\u0644\u0649\u0646\u0649\u0634", "Poster": "\u064a\u0648\u0644\u0644\u0649\u063a\u06c7\u0686\u0649", "Media": "\u0645\u06d0\u062f\u0649\u064a\u0627", "Print": "\u0628\u06d0\u0633\u0649\u0634", "Prev": "\u0626\u0627\u0644\u062f\u0649\u0646\u0642\u0649\u0633\u0649", "Find and replace": "\u0626\u0649\u0632\u062f\u06d5\u0634 \u06cb\u06d5 \u0626\u0627\u0644\u0645\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Whole words": "\u062a\u0648\u0644\u06c7\u0642 \u0645\u0627\u0633\u0644\u0627\u0634\u062a\u06c7\u0631\u06c7\u0634", "Insert template": "\u0626\u06c8\u0644\u06af\u06d5 \u0642\u0649\u0633\u062a\u06c7\u0631\u06c7\u0634" });
export { default } from './ReactComponent.js';
var cluster = require('cluster'); module.exports = { run: run }; function run(createServer) { if (cluster.isMaster) { console.log('Master pid ', process.pid); startWorker(); } else { createServer(); } } function startWorker() { var worker = cluster.fork(); worker.once('disconnect', function () { worker.process.kill(); }); worker.on('message', function(message) { if (message.type === 'reload') { if (worker.disconnecting) return; console.log('Killing %d', worker.process.pid); worker.process.kill(); worker.disconnecting = true; startWorker(); } }); }
/** * Module dependencies. */ var express = require('express') , passport = require('passport') , nowww = require('nowww') , log = require('debug')('root:config') , MongoStore = require('connect-mongo')(express) , mandrillMailer = require('lib/mailer').mandrillMailer , resolve = require('path').resolve , config = require('lib/config') , auth = require('http-auth') , t = require('t-component'); /** * Expose `Setup` * * @api private */ module.exports = Setup; /** * Configs Express Application with * defaults configs */ function Setup(app) { /** * Set `development` only settings */ app.configure('development', function() { // Log config settigs load log( 'development settings' ); /** * Build */ app.use(require('lib/build').middleware); }); /** * Set `testing` only settings */ app.configure('testing', function() { // Log config settigs load log( 'testing settings' ); }); /** * Set `production` only settings */ app.configure('production', function() { // Log config settigs load log( 'production settings' ); /** * Set `nowww` middleware helper */ app.use( nowww() ); /** * Set `native` express compression middleware */ app.use( express.compress() ); }); /** * Set `common` settings */ app.configure(function() { // Log config settigs load log( 'common settings' ); /** * Save config in app */ app.set('config', config); /** * Config mandrill mailer */ mandrillMailer(app); /** * Basic HTTP-Auth restriction middleware * for production access only. */ if (config.auth.basic && config.auth.basic.username && config.auth.basic.password) { var basic = auth({ authRealm: "Authentication required", authList : [config.auth.basic.username+":"+config.auth.basic.password] }); app.use(function(req, res, next) { basic.apply(req, res, function(username) { return next(); }); }); } /** * Set application http server port from `env` * Defaults to 3005 */ app.set( 'port', config('privatePort') || 3005 ); /** * Set `public-assets` default path */ app.use(express.static(resolve('public'))); /** * Configure native `express` body parser */ // `express.bodyParsers()` uses `connect.multipart()` // check https://github.com/senchalabs/connect/wiki/Connect-3.0 // for more details on the temporal fix. // app.use( express.bodyParser() ); app.use(express.urlencoded()); app.use(express.json()); /** * Configure native `express` cookie parser */ app.use( express.cookieParser('democracyos-cookie') ); /** * Configure native `express` session middleware */ app.use( express.session( { cookie: { maxAge: 1000 * 60 * 60 * 24 * 7 }, secret: 'democracyos-secret', key: "democracyos.org", store: new MongoStore( { url: config('mongoUrl') } ) } ) ); /** * Use `express.csrf` middleware */ app.use(express.csrf()); app.use(function (req, res, next) { res.locals.csrfToken = req.csrfToken(); next(); }); /** * Use `passport` setup & helpers middleware */ app.use(passport.initialize()); /** * Use `passport` sessions middleware */ app.use(passport.session()); /** * Set template local variables */ app.use(function(req, res, next) { // Set user as local var if authenticated if(req.isAuthenticated() && req.user) res.locals.citizen = req.user; res.locals.t = t; // Call next middleware next(); }); /** * Use `twitter-card` and 'facebook-card' middlewares */ app.use(require('lib/twitter-card/middleware')); app.use(require('lib/facebook-card/middleware')); }); }
version https://git-lfs.github.com/spec/v1 oid sha256:2bf80e8c8892a317ece4d9f37fdcc01f7a17be3a31d0459abe4bdee8638dccf9 size 222
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isMediaQuery; function isMediaQuery(property) { return property.substr(0, 6) === '@media'; }
angular .module('cocktailApp') .value('cocktailList', [{ id: 'cf6a9493-cbfe-4d15-90b7-1e730c002e55', source: '4c1c50c3-369d-4eb6-b0a6-f447d7273bea', name: 'Gin and Tonic', equipment: [ {name: 'Highball glass'} ], ingredients: [{ name: 'Gin', quantity: 25, unit: 'ml' }, { name: 'Tonic Water', quantity: 125, unit: 'ml' }, { name: 'Lemon', quantity: 1, unit: 'slice' }, { name: 'Ice', quantity: 6, unit: 'cube' }], method: [ 'Half fill the glass with ice', 'Pour over the gin and tonic water and stir', 'Garnish with a slice of lemon' ] }, { id: '400dc69d-da79-4be7-a363-bb9cb7fb3198', source: '4c1c50c3-369d-4eb6-b0a6-f447d7273bea', name: 'Screwdriver', equipment: [ {name: 'Highball glass'} ], ingredients: [{ name: 'Vodka', quantity: 25, unit: 'ml' }, { name: 'Orange Juice', quantity: 125, unit: 'ml' }, { name: 'Orange', quantity: 1, unit: 'slice' }, { name: 'Ice', quantity: 6, unit: 'cube' }], method: [ 'Half fill the glass with ice', 'Pour over the vodka and orange juice and stir', 'Garnish with a slice of orange' ] }]);
import '../../css/main.scss'; import './materialize';
var arraySome = require('./_arraySome'), baseIteratee = require('./_baseIteratee'), baseSome = require('./_baseSome'), isArray = require('./isArray'), isIterateeCall = require('./_isIterateeCall'); /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function|Object|string} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, baseIteratee(predicate, 3)); } module.exports = some;
var forOwn = require('../object/forOwn'); var isArray = require('./isArray'); function isEmpty(val){ if (val == null) { // typeof null == 'object' so we check it first return false; } else if ( typeof val === 'string' || isArray(val) ) { return !val.length; } else if ( typeof val === 'object' || typeof val === 'function' ) { var result = true; forOwn(val, function(){ result = false; return false; // break loop }); return result; } else { return false; } } module.exports = isEmpty;
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var ImageCollectionsBookmark = React.createClass({ displayName: 'ImageCollectionsBookmark', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zM20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 10l-2.5-1.5L15 12V4h5v8z' }) ); } }); module.exports = ImageCollectionsBookmark;
'use strict'; function mapWithSeparator(items, itemRenderer, spacerRenderer) { var mapped = []; if (items.length > 0) { mapped.push(itemRenderer(items[0], 0, items)); for (var ii = 1; ii < items.length; ii++) { mapped.push(spacerRenderer(ii - 1), itemRenderer(items[ii], ii, items)); } } return mapped; } module.exports = mapWithSeparator;
if(typeof sne == "undefined") sne = { steps: {} }; sne.steps.docchooser = {}; (function () { var docchooserCallback = null; var usernameMap = null; var docs = []; var $docs = $('#docs'); sne.steps.docchooser.show = function (cb) { logNavigation('docchoser'); $('#docChooser').addClass('active'); reloadDocsTable(); docchooserCallback = cb; }; sne.steps.docchooser.hide = function () { $('#docChooser').removeClass('active'); docchooserCallback(); }; function reloadDocsTable () { async.series( [ function (cb) { shownoteseditor.connectors[sne.connectorName].getUsernameMap(sne.connectorOptions, function (err, _usernameMap) { usernameMap = _usernameMap; cb(); } ); }, function (cb) { shownoteseditor.connectors[sne.connectorName].listDocuments(sne.connectorOptions, function (err, _docs) { docs = _docs; tabletools.clear($docs); $('#noDocs').css('display', (docs.length == 0) ? 'block' : 'none'); for (var i = 0; i < docs.length; i++) { var doc = docs[i]; addDocToTable(doc); } } ); } ] ); } function addDocToTable (doc) { var $btns = $('#btnsTemplate').clone(); var accessDate = moment(doc.accessDate).format("DD.MM.YYYY"); var owner = (usernameMap[doc.owner] || {}).name || "Unnamed"; var $td = tabletools.addRow($docs, [ doc.name, accessDate, owner, $btns ]); $btns = $td.find('.btns').parent().addClass('btns'); $td.click( function (e) { var $target = $(e.target); if($target.prop('tagName').toLowerCase() == "button" || $target.parent().prop('tagName').toLowerCase() == "button") { return; } openDoc(doc.id); } ); $td.find('button.download').click( function () { downloadDoc(doc.id, doc.name); } ); $td.find('button.edit').click( function () { if(doc.owner != sne.uid) return alert("You can only edit your own documents."); sne.steps.docedit.show("edit", doc, usernameMap, function (success, doc) { $('#docChooser').addClass('active'); reloadDocsTable(); } ); } ); $td.find('button.delete').click( function () { if(doc.owner != sne.uid) return alert("You can only delete your own documents."); deleteDoc(doc.id, function (err) { reloadDocsTable(); if(err) alert(err); } ); } ); } $('#docsSearch').keyup( function () { $.uiTableFilter($docs, $('#docsSearch').val(), "Name"); } ); $('#createDoc').click(showCreateDoc); function showCreateDoc () { sne.steps.docedit.show("create", null, usernameMap, function (success, doc) { if(success) { docs.push(doc); openDoc(doc.id); } else { $('#docChooser').addClass('active'); } } ); } function openDoc (id) { var doc; for (var i = 0; i < docs.length; i++) { if(docs[i].id == id) doc = docs[i]; } sne.doc = doc; sne.files = doc.urls; logNavigation('doc/' + doc.name); sne.steps.docchooser.hide(); } function downloadDoc (id, name) { shownoteseditor.connectors[sne.connectorName].getDocument(sne.connectorOptions, id, function (err, notes) { var osf = osftools.osfNotes(notes); var parts = [osf]; var blob = new Blob(parts, { "type" : "text/octet-stream" }); var url = window.URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = name + ".osf.txt"; a.style.display = 'none'; document.body.appendChild(a); a.click(); delete a; } ); } function deleteDoc (id, cb) { var res = confirm("Do you really want to delete this document?"); if(!res) return; shownoteseditor.connectors[sne.connectorName].deleteDocument(sne.connectorOptions, id, cb); } })();
import React from 'react'; import { connect } from '../utils/griddleConnect'; import compose from 'recompose/compose'; import { textSelector, classNamesForComponentSelector, stylesForComponentSelector } from '../selectors/dataSelectors'; import { toggleSettings as toggleSettingsAction } from '../actions'; const enhancedSettingsToggle = OriginalComponent => compose( connect((state, props) => ({ text: textSelector(state, { key: 'settingsToggle' }), className: classNamesForComponentSelector(state, 'SettingsToggle'), style: stylesForComponentSelector(state, 'SettingsToggle'), }), { toggleSettings: toggleSettingsAction } ), )(props => <OriginalComponent {...props} onClick={props.toggleSettings} />); export default enhancedSettingsToggle;
(function () { function create(window) { var location, navigator, XMLHttpRequest; window = window || require('jsdom').jsdom().createWindow(); location = window.location || {}; navigator = window.navigator || { userAgent: "Node.js" }; if ('function' !== typeof window.XMLHttpRequest && 'function' !== typeof window.ActiveXObject) { window.XMLHttpRequest = function () {}; // TODO // node-XMLHttpRequest, Zombie, or AHR needs a good XMLHttpRequestneeds to be put on npm }
goog.provide('ol.test.renderer.canvas.Layer'); describe('ol.renderer.canvas.Layer', function() { describe('#composeFrame()', function() { it('clips to layer extent and draws image', function() { var layer = new ol.layer.Image({ extent: [1, 2, 3, 4] }); var renderer = new ol.renderer.canvas.Layer(layer); var image = new Image(); image.width = 3; image.height = 3; renderer.getImage = function() { return image; }; var frameState = { viewState: { center: [2, 3], resolution: 1, rotation: 0 }, size: [10, 10], pixelRatio: 1, coordinateToPixelMatrix: goog.vec.Mat4.createNumber(), pixelToCoordinateMatrix: goog.vec.Mat4.createNumber() }; renderer.getImageTransform = function() { return goog.vec.Mat4.createNumberIdentity(); }; ol.renderer.Map.prototype.calculateMatrices2D(frameState); var layerState = layer.getLayerState(); var context = { save: sinon.spy(), restore: sinon.spy(), translate: sinon.spy(), rotate: sinon.spy(), beginPath: sinon.spy(), moveTo: sinon.spy(), lineTo: sinon.spy(), clip: sinon.spy(), drawImage: sinon.spy() }; renderer.composeFrame(frameState, layerState, context); expect(context.save.callCount).to.be(1); expect(context.translate.callCount).to.be(0); expect(context.rotate.callCount).to.be(0); expect(context.beginPath.callCount).to.be(1); expect(context.moveTo.firstCall.args).to.eql([4, 4]); expect(context.lineTo.firstCall.args).to.eql([6, 4]); expect(context.lineTo.secondCall.args).to.eql([6, 6]); expect(context.lineTo.thirdCall.args).to.eql([4, 6]); expect(context.clip.callCount).to.be(1); expect(context.drawImage.firstCall.args).to.eql( [renderer.getImage(), 0, 0, 3, 3, 0, 0, 3, 3]); expect(context.restore.callCount).to.be(1); }); }); }); goog.require('ol.render.canvas'); goog.require('goog.vec.Mat4'); goog.require('ol.layer.Image'); goog.require('ol.renderer.Map'); goog.require('ol.renderer.canvas.Layer');
/** .setAlign(Blockly.ALIGN_RIGHT) * Visual Blocks Language * * Copyright 2012 Massachusetts Institute of Technology. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Logic blocks for Blockly, modified for App Inventor * @author fraser@google.com (Neil Fraser) * @author andrew.f.mckinney@gmail.com (Andrew F. McKinney) * Due to the frequency of long strings, the 80-column wrap rule need not apply * to language files. */ // TODO(andrew): Change addition, multiplication, min, and max to take multiple arguments. // TODO(andrew): Add appropriate helpurls for each block. if (!Blockly.Language) Blockly.Language = {}; Blockly.Language.math_number = { // Numeric value. category : Blockly.LANG_CATEGORY_MATH, helpUrl : Blockly.LANG_MATH_NUMBER_HELPURL, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.appendDummyInput().appendTitle( new Blockly.FieldTextInput('0', Blockly.Language.math_number.validator), 'NUM'); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.setTooltip(Blockly.LANG_MATH_NUMBER_TOOLTIP); this.appendCollapsedInput().appendTitle('0', 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_MUTATOR_ITEM_INPUT_NUMBER }], prepareCollapsedText: function(){ var textToDisplay = this.getTitleValue('NUM'); if (textToDisplay.length > 8 ) // 8 is a length of 5 plus 3 dots textToDisplay = textToDisplay.substring(0, 5) + '...'; this.getTitle_('COLLAPSED_TEXT').setText(textToDisplay, 'COLLAPSED_TEXT'); } }; Blockly.Language.math_number.validator = function(text) { // Ensure that only a number may be entered. // TODO: Handle cases like 'o', 'ten', '1,234', '3,14', etc. var n = window.parseFloat(text || 0); return window.isNaN(n) ? null : String(n); }; Blockly.Language.math_compare = { // Basic arithmetic operator. // TODO(Andrew): equality block needs to have any on the sockets. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_compare.HELPURLS[mode];}, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT)); this.appendValueInput('A').setCheck(null); this.appendValueInput('B').setCheck(null).appendTitle(new Blockly.FieldDropdown(this.OPERATORS,Blockly.Language.math_compare.onchange), 'OP'); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_compare.TOOLTIPS[mode]; }); this.appendCollapsedInput().appendTitle('=', 'COLLAPSED_TEXT'); }, //TODO (user) compare has not been internationalized yet // Potential clash with logic equal, using '=' for now typeblock: [{ translatedName: '=', dropDown: { titleName: 'OP', value: 'EQ' } },{ translatedName: '\u2260', dropDown: { titleName: 'OP', value: 'NEQ' } },{ translatedName: '<', dropDown: { titleName: 'OP', value: 'LT' } },{ translatedName: '\u2264', dropDown: { titleName: 'OP', value: 'LTE' } },{ translatedName: '>', dropDown: { titleName: 'OP', value: 'GT' } },{ translatedName: '\u2265', dropDown: { titleName: 'OP', value: 'GTE' } }], prepareCollapsedText: function(){ var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP')); this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT'); } }; Blockly.Language.math_compare.onchange = function(value){ if(!this.sourceBlock_){return;} if(value == "EQ" || value == "NEQ") { this.sourceBlock_.getInput("A").setCheck(null); this.sourceBlock_.getInput("B").setCheck(null); } else { this.sourceBlock_.getInput("A").setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); this.sourceBlock_.getInput("B").setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); } }; Blockly.Language.math_compare.OPERATORS = [['=', 'EQ'], ['\u2260', 'NEQ'], ['<', 'LT'], ['\u2264', 'LTE'], ['>', 'GT'], ['\u2265', 'GTE']]; Blockly.Language.math_compare.TOOLTIPS = { EQ: Blockly.LANG_MATH_COMPARE_TOOLTIP_EQ, NEQ: Blockly.LANG_MATH_COMPARE_TOOLTIP_NEQ, LT: Blockly.LANG_MATH_COMPARE_TOOLTIP_LT, LTE: Blockly.LANG_MATH_COMPARE_TOOLTIP_LTE, GT: Blockly.LANG_MATH_COMPARE_TOOLTIP_GT, GTE: Blockly.LANG_MATH_COMPARE_TOOLTIP_GTE }; Blockly.Language.math_compare.HELPURLS = { EQ: Blockly.LANG_MATH_COMPARE_HELPURL_EQ, NEQ: Blockly.LANG_MATH_COMPARE_HELPURL_NEQ, LT: Blockly.LANG_MATH_COMPARE_HELPURL_LT, LTE: Blockly.LANG_MATH_COMPARE_HELPURL_LTE, GT: Blockly.LANG_MATH_COMPARE_HELPURL_GT, GTE: Blockly.LANG_MATH_COMPARE_HELPURL_GTE }; Blockly.Language.math_add = { // Basic arithmetic operator. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_ARITHMETIC_HELPURL_ADD, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM0').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); // append the title on a separate line to avoid overly long lines this.appendValueInput('NUM1').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)) .appendTitle("+"); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_ADD; }); this.setMutator(new Blockly.Mutator(['math_mutator_item'])); this.emptyInputName = 'EMPTY'; this.repeatingInputName = 'NUM'; this.itemCount_ = 2; this.appendCollapsedInput().appendTitle('+', 'COLLAPSED_TEXT'); }, mutationToDom: Blockly.mutationToDom, domToMutation: Blockly.domToMutation, decompose: function(workspace){ return Blockly.decompose(workspace,'math_mutator_item',this); }, compose: Blockly.compose, saveConnections: Blockly.saveConnections, addEmptyInput: function(){ var input = this.appendDummyInput(this.emptyInputName); }, addInput: function(inputNum){ var input = this.appendValueInput(this.repeatingInputName + inputNum).setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); if(inputNum !== 0){ input.appendTitle("+"); } return input; }, updateContainerBlock: function(containerBlock) { containerBlock.setTitleValue("+","CONTAINER_TEXT"); }, //TODO (user) add has not been internationalized yet // Using '+' for now typeblock: [{ translatedName: '+' }] }; Blockly.Language.math_mutator_item = { // Add items. init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.appendDummyInput() //.appendTitle(Blockly.LANG_LISTS_CREATE_WITH_ITEM_TITLE); .appendTitle("number"); this.setPreviousStatement(true); this.setNextStatement(true); //this.setTooltip(Blockly.LANG_LISTS_CREATE_WITH_ITEM_TOOLTIP_1); this.contextMenu = false; } }; Blockly.Language.math_subtract = { // Basic arithmetic operator. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_ARITHMETIC_HELPURL_MINUS , init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)) .appendTitle("-"); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_MINUS; }); this.appendCollapsedInput().appendTitle('-', 'COLLAPSED_TEXT'); }, //TODO (user) subtract has not been internationalized yet // Using '-' for now typeblock: [{ translatedName: '-' }] }; Blockly.Language.math_multiply = { // Basic arithmetic operator. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_ARITHMETIC_HELPURL_MULTIPLY, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM0').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); this.appendValueInput('NUM1').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)) .appendTitle(Blockly.Language.times_symbol); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_MULTIPLY ; }); this.setMutator(new Blockly.Mutator(['math_mutator_item'])); this.emptyInputName = 'EMPTY'; this.repeatingInputName = 'NUM'; this.itemCount_ = 2; this.appendCollapsedInput().appendTitle(Blockly.Language.times_symbol, 'COLLAPSED_TEXT'); }, mutationToDom: Blockly.mutationToDom, domToMutation: Blockly.domToMutation, decompose: function(workspace){ return Blockly.decompose(workspace,'math_mutator_item',this); }, compose: Blockly.compose, saveConnections: Blockly.saveConnections, addEmptyInput: function(){ var input = this.appendDummyInput(this.emptyInputName); }, addInput: function(inputNum){ var input = this.appendValueInput(this.repeatingInputName + inputNum).setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); if(inputNum !== 0){ input.appendTitle(Blockly.Language.times_symbol); } return input; }, updateContainerBlock: function(containerBlock) { containerBlock.setTitleValue(Blockly.Language.times_symbol,"CONTAINER_TEXT"); }, //TODO (user) multiply has not been internationalized yet // Using '*' for now typeblock: [{ translatedName: '*' }] }; Blockly.Language.math_division = { // Basic arithmetic operator. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_ARITHMETIC_HELPURL_DIVIDE, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)) .appendTitle('/'); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { return Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_DIVIDE; }); this.appendCollapsedInput().appendTitle('/', 'COLLAPSED_TEXT'); }, //TODO (user) division has not been internationalized yet // Using '/' for now typeblock: [{ translatedName: '/' }] }; Blockly.Language.math_power = { // Basic arithmetic operator. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_ARITHMETIC_HELPURL_POWER, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('A').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); this.appendValueInput('B').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)) .appendTitle("^"); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { //var mode = thisBlock.getTitleValue('OP'); return Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_POWER; }); this.appendCollapsedInput().appendTitle('^', 'COLLAPSED_TEXT'); }, //TODO (user) power has not been internationalized yet // Using '^' for now typeblock: [{ translatedName: '^' }] }; Blockly.Language.math_random_int = { // Random integer between [X] and [Y]. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_RANDOM_INT_HELPURL, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('FROM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('random integer').appendTitle('from'); this.appendValueInput('TO').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('to'); this.setInputsInline(true); this.setTooltip(Blockly.LANG_MATH_RANDOM_INT_TOOLTIP ); this.appendCollapsedInput().appendTitle(Blockly.LANG_MATH_RANDOM_INT_TITLE_RANDOM, 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_RANDOM_INT_TITLE_RANDOM }] }; Blockly.Language.math_random_float = { // Random fraction between 0 and 1. category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_RANDOM_FLOAT_HELPURL, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendDummyInput().appendTitle('random fraction'); this.setTooltip(Blockly.LANG_MATH_RANDOM_FLOAT_TOOLTIP); this.appendCollapsedInput().appendTitle(Blockly.LANG_MATH_RANDOM_FLOAT_TITLE_RANDOM, 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_RANDOM_FLOAT_TITLE_RANDOM }] }; Blockly.Language.math_random_set_seed = { // Set the seed of the radom number generator category: Blockly.LANG_CATEGORY_MATH, helpUrl: Blockly.LANG_MATH_RANDOM_SEED_HELPURL, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(false, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('random set seed').appendTitle('to'); this.setPreviousStatement(true); this.setNextStatement(true); this.setTooltip(Blockly.LANG_MATH_RANDOM_SEED_TOOLTIP); this.appendCollapsedInput().appendTitle(Blockly.LANG_MATH_RANDOM_SEED_TITLE_RANDOM, 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_RANDOM_SEED_TITLE_RANDOM }] }; Blockly.Language.math_on_list = { // Evaluate a list of numbers to return sum, average, min, max, etc. // Some functions also work on text (min, max, mode, median). category: Blockly.LANG_CATEGORY_MATH, helpUrl: '', init: function() { // Assign 'this' to a variable for use in the closures below. var thisBlock = this; this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM0').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP'); this.appendValueInput('NUM1').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); this.setInputsInline(false); this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_on_list.TOOLTIPS[mode]; }); this.setMutator(new Blockly.Mutator(['math_mutator_item'])); this.itemCount_ = 2; this.valuesToSave = {'OP':null}; this.emptyInputName = 'EMPTY'; this.repeatingInputName = 'NUM'; this.appendCollapsedInput().appendTitle(this.getTitleValue('OP'), 'COLLAPSED_TEXT'); }, mutationToDom: Blockly.mutationToDom, domToMutation: Blockly.domToMutation, decompose: function(workspace){ return Blockly.decompose(workspace,'math_mutator_item',this); }, compose: Blockly.compose, saveConnections: Blockly.saveConnections, addEmptyInput: function(){ var input = this.appendDummyInput(this.emptyInputName); input.appendTitle(new Blockly.FieldDropdown(this.OPERATORS),'OP'); this.setTitleValue(this.valuesToSave['OP'],'OP'); }, addInput: function(inputNum){ var input = this.appendValueInput(this.repeatingInputName + inputNum).setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)); if(inputNum == 0){ input.appendTitle(new Blockly.FieldDropdown(this.OPERATORS),'OP'); this.setTitleValue(this.valuesToSave['OP'],'OP'); } return input; }, updateContainerBlock: function(containerBlock) { for(var i=0;i<Blockly.Language.math_on_list.OPERATORS.length;i++){ if(Blockly.Language.math_on_list.OPERATORS[i][1] == this.getTitleValue("OP") ){ containerBlock.setTitleValue(Blockly.Language.math_on_list.OPERATORS[i][0],"CONTAINER_TEXT"); } } }, typeblock: [{ translatedName: Blockly.LANG_MATH_ONLIST_OPERATOR_MIN, dropDown: { titleName: 'OP', value: 'MIN' } },{ translatedName: Blockly.LANG_MATH_ONLIST_OPERATOR_MAX, dropDown: { titleName: 'OP', value: 'MAX' } }], prepareCollapsedText: function(){ this.getTitle_('COLLAPSED_TEXT').setText(this.getTitleValue('OP').toLowerCase(), 'COLLAPSED_TEXT'); } }; Blockly.Language.math_on_list.OPERATORS = [['min', 'MIN'], ['max', 'MAX']]; Blockly.Language.math_on_list.TOOLTIPS = { MIN: 'Return the smallest of its arguments..', MAX: 'Return the largest of its arguments..' }; Blockly.Language.math_single = { // Advanced math operators with single operand. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_single.HELPURLS[mode]; }, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP'); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_single.TOOLTIPS[mode]; }); this.appendCollapsedInput().appendTitle(this.getTitleValue('OP'), 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_SINGLE_OP_ROOT, dropDown: { titleName: 'OP', value: 'ROOT' } },{ translatedName: Blockly.LANG_MATH_SINGLE_OP_ABSOLUTE, dropDown: { titleName: 'OP', value: 'ABS' } },{ translatedName: 'neg', dropDown: { titleName: 'OP', value: 'NEG' } },{ translatedName: 'log', dropDown: { titleName: 'OP', value: 'LN' } },{ translatedName: 'e^', dropDown: { titleName: 'OP', value: 'EXP' } },{ translatedName: Blockly.LANG_MATH_ROUND_OPERATOR_ROUND, dropDown: { titleName: 'OP', value: 'ROUND' } },{ translatedName: Blockly.LANG_MATH_ROUND_OPERATOR_CEILING, dropDown: { titleName: 'OP', value: 'CEILING' } },{ translatedName: Blockly.LANG_MATH_ROUND_OPERATOR_FLOOR, dropDown: { titleName: 'OP', value: 'FLOOR' } }], prepareCollapsedText: function(){ var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP')); this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT'); } }; Blockly.Language.math_single.OPERATORS = [['sqrt', 'ROOT'], ['abs', 'ABS'], ['-', 'NEG'], ['log', 'LN'], ['e^', 'EXP'], ['round', 'ROUND'], ['ceiling', 'CEILING'], ['floor', 'FLOOR']]; Blockly.Language.math_single.TOOLTIPS = { ROOT: Blockly.LANG_MATH_SINGLE_TOOLTIP_ROOT, ABS: Blockly.LANG_MATH_SINGLE_TOOLTIP_ABS, NEG: Blockly.LANG_MATH_SINGLE_TOOLTIP_NEG, LN: Blockly.LANG_MATH_SINGLE_TOOLTIP_LN, EXP: Blockly.LANG_MATH_SINGLE_TOOLTIP_EXP, ROUND : Blockly.LANG_MATH_ROUND_TOOLTIP_ROUND, CEILING : Blockly.LANG_MATH_ROUND_TOOLTIP_CEILING, FLOOR : Blockly.LANG_MATH_ROUND_TOOLTIP_FLOOR }; Blockly.Language.math_single.HELPURLS = { ROOT: Blockly.LANG_MATH_SINGLE_HELPURL_ROOT, ABS: Blockly.LANG_MATH_SINGLE_HELPURL_ABS, NEG: Blockly.LANG_MATH_SINGLE_HELPURL_NEG, LN: Blockly.LANG_MATH_SINGLE_HELPURL_LN, EXP: Blockly.LANG_MATH_SINGLE_HELPURL_EXP, ROUND : Blockly.LANG_MATH_ROUND_HELPURL_ROUND, CEILING : Blockly.LANG_MATH_ROUND_HELPURL_CEILING, FLOOR : Blockly.LANG_MATH_ROUND_HELPURL_FLOOR }; Blockly.Language.math_abs = { // Advanced math operators with single operand. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_single.HELPURLS[mode]; }, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_single.OPERATORS), 'OP'); this.setTitleValue('ABS',"OP"); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_single.TOOLTIPS[mode]; }); } }; Blockly.Language.math_neg = { // Advanced math operators with single operand. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_single.HELPURLS[mode]; }, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_single.OPERATORS), 'OP'); this.setTitleValue('NEG',"OP"); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_single.TOOLTIPS[mode]; }); } }; Blockly.Language.math_round = { // Advanced math operators with single operand. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_single.HELPURLS[mode]; }, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_single.OPERATORS), 'OP'); this.setTitleValue('ROUND',"OP"); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_single.TOOLTIPS[mode]; }); } }; Blockly.Language.math_ceiling = { // Advanced math operators with single operand. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_single.HELPURLS[mode]; }, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_single.OPERATORS), 'OP'); this.setTitleValue('CEILING',"OP"); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_single.TOOLTIPS[mode]; }); } }; Blockly.Language.math_floor = { // Advanced math operators with single operand. category: Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_single.HELPURLS[mode]; }, init: function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_single.OPERATORS), 'OP'); this.setTitleValue('FLOOR',"OP"); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_single.TOOLTIPS[mode]; }); } }; Blockly.Language.math_divide = { // Remainder or quotient of a division. category : Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_divide.HELPURLS[mode]; }, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('DIVIDEND').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP'); this.appendValueInput('DIVISOR').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('\u00F7'); this.setInputsInline(true); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_divide.TOOLTIPS[mode]; }); this.appendCollapsedInput().appendTitle(this.getTitleValue('OP'), 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_DIVIDE_OPERATOR_MODULO, dropDown: { titleName: 'OP', value: 'MODULO' } },{ translatedName: Blockly.LANG_MATH_DIVIDE_OPERATOR_REMAINDER, dropDown: { titleName: 'OP', value: 'REMAINDER' } },{ translatedName: Blockly.LANG_MATH_DIVIDE_OPERATOR_QUOTIENT, dropDown: { titleName: 'OP', value: 'QUOTIENT' } }], prepareCollapsedText: function(){ this.getTitle_('COLLAPSED_TEXT').setText(this.getTitleValue('OP').toLowerCase(), 'COLLAPSED_TEXT'); } }; Blockly.Language.math_divide.OPERATORS = [['modulo of', 'MODULO'], ['remainder of', 'REMAINDER'], [ 'quotient of', 'QUOTIENT' ]]; Blockly.Language.math_divide.TOOLTIPS = { MODULO: Blockly.LANG_MATH_DIVIDE_TOOLTIP_MODULO, REMAINDER: Blockly.LANG_MATH_DIVIDE_TOOLTIP_REMAINDER, QUOTIENT: Blockly.LANG_MATH_DIVIDE_TOOLTIP_QUOTIENT }; Blockly.Language.math_divide.HELPURLS = { MODULO: Blockly.LANG_MATH_DIVIDE_HELPURL_MODULO, REMAINDER: Blockly.LANG_MATH_DIVIDE_HELPURL_REMAINDER, QUOTIENT: Blockly.LANG_MATH_DIVIDE_HELPURL_QUOTIENT }; Blockly.Language.math_trig = { // Trigonometry operators. category : Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_trig.HELPURLS[mode]; }, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP'); // Assign 'this' to a variable for use in the closures below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_trig.TOOLTIPS[mode]; }); this.appendCollapsedInput().appendTitle(this.getTitleValue('OP'), 'COLLAPSED_TEXT'); }, //TODO (user) sine has not been internationalized yet //Using 'sine' for now typeblock: [{ translatedName: 'sin', dropDown: { titleName: 'OP', value: 'SIN' } },{ translatedName: 'cos', dropDown: { titleName: 'OP', value: 'COS' } },{ translatedName: 'tan', dropDown: { titleName: 'OP', value: 'TAN' } },{ translatedName: 'asin', dropDown: { titleName: 'OP', value: 'ASIN' } },{ translatedName: 'acos', dropDown: { titleName: 'OP', value: 'ACOS' } },{ translatedName: 'atan', dropDown: { titleName: 'OP', value: 'ATAN' } }], prepareCollapsedText: function(){ this.getTitle_('COLLAPSED_TEXT').setText(this.getTitleValue('OP').toLowerCase(), 'COLLAPSED_TEXT'); } }; Blockly.Language.math_trig.OPERATORS = [[ 'sin', 'SIN' ], [ 'cos', 'COS' ], [ 'tan', 'TAN' ], [ 'asin', 'ASIN' ], [ 'acos', 'ACOS' ], [ 'atan', 'ATAN' ]]; Blockly.Language.math_trig.TOOLTIPS = { SIN : Blockly.LANG_MATH_TRIG_TOOLTIP_SIN, COS : Blockly.LANG_MATH_TRIG_TOOLTIP_COS, TAN : Blockly.LANG_MATH_TRIG_TOOLTIP_TAN, ASIN : Blockly.LANG_MATH_TRIG_TOOLTIP_ASIN, ACOS : Blockly.LANG_MATH_TRIG_TOOLTIP_ACOS, ATAN : Blockly.LANG_MATH_TRIG_TOOLTIP_ATAN }; Blockly.Language.math_trig.HELPURLS = { SIN : Blockly.LANG_MATH_TRIG_HELPURL_SIN, COS : Blockly.LANG_MATH_TRIG_HELPURL_COS, TAN : Blockly.LANG_MATH_TRIG_HELPURL_TAN, ASIN : Blockly.LANG_MATH_TRIG_HELPURL_ASIN, ACOS : Blockly.LANG_MATH_TRIG_HELPURL_ACOS, ATAN : Blockly.LANG_MATH_TRIG_HELPURL_ATAN }; Blockly.Language.math_cos = { // Trigonometry operators. category : Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_trig.HELPURLS[mode]; }, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_trig.OPERATORS), 'OP'); this.setTitleValue('COS',"OP"); // Assign 'this' to a variable for use in the closures below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_trig.TOOLTIPS[mode]; }); } }; Blockly.Language.math_tan = { // Trigonometry operators. category : Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_trig.HELPURLS[mode]; }, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle(new Blockly.FieldDropdown(Blockly.Language.math_trig.OPERATORS), 'OP'); this.setTitleValue('TAN',"OP"); // Assign 'this' to a variable for use in the closures below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_trig.TOOLTIPS[mode]; }); } }; Blockly.Language.math_atan2 = { // Trigonometry operators. category : Blockly.LANG_CATEGORY_MATH, helpUrl : Blockly.LANG_MATH_TRIG_HELPURL_ATAN2, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendDummyInput().appendTitle('atan2'); this.appendValueInput('Y').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('y').setAlign(Blockly.ALIGN_RIGHT); this.appendValueInput('X').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('x').setAlign(Blockly.ALIGN_RIGHT); this.setInputsInline(false); this.setTooltip(Blockly.LANG_MATH_TRIG_TOOLTIP_ATAN2); this.appendCollapsedInput().appendTitle('atan2', 'COLLAPSED_TEXT'); }, //TODO (user) atan2 has not been internationalized yet // Using 'atan2' for now typeblock: [{ translatedName: 'atan2' }] }; Blockly.Language.math_convert_angles = { // Trigonometry operators. category : Blockly.LANG_CATEGORY_MATH, helpUrl: function() { var mode = this.getTitleValue('OP'); return Blockly.Language.math_convert_angles.HELPURLS[mode]; }, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('convert').appendTitle(new Blockly.FieldDropdown(this.OPERATORS), 'OP'); // Assign 'this' to a variable for use in the closures below. var thisBlock = this; this.setTooltip(function() { var mode = thisBlock.getTitleValue('OP'); return Blockly.Language.math_convert_angles.TOOLTIPS[mode]; }); this.appendCollapsedInput().appendTitle(this.getTitleValue('OP'), 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_CONVERT_ANGLES_TITLE_CONVERT + ' ' + Blockly.LANG_MATH_CONVERT_ANGLES_OP_RAD_TO_DEG, dropDown: { titleName: 'OP', value: 'RADIANS_TO_DEGREES' } },{ translatedName: Blockly.LANG_MATH_CONVERT_ANGLES_TITLE_CONVERT+ ' ' + Blockly.LANG_MATH_CONVERT_ANGLES_OP_DEG_TO_RAD, dropDown: { titleName: 'OP', value: 'DEGREES_TO_RADIANS' } }], prepareCollapsedText: function(){ var titleFromOperator = Blockly.FieldDropdown.lookupOperator(this.OPERATORS, this.getTitleValue('OP')); this.getTitle_('COLLAPSED_TEXT').setText(titleFromOperator, 'COLLAPSED_TEXT'); } }; Blockly.Language.math_convert_angles.OPERATORS = [[ 'radians to degrees', 'RADIANS_TO_DEGREES' ], [ 'degrees to radians', 'DEGREES_TO_RADIANS' ]]; Blockly.Language.math_convert_angles.TOOLTIPS = { RADIANS_TO_DEGREES : Blockly.LANG_MATH_CONVERT_ANGLES_TOOLTIP_RAD_TO_DEG, DEGREES_TO_RADIANS : Blockly.LANG_MATH_CONVERT_ANGLES_TOOLTIP_DEG_TO_RAD }; Blockly.Language.math_convert_angles.HELPURLS = { RADIANS_TO_DEGREES : Blockly.LANG_MATH_CONVERT_ANGLES_HELPURL_RAD_TO_DEG, DEGREES_TO_RADIANS : Blockly.LANG_MATH_CONVERT_ANGLES_HELPURL_DEG_TO_RAD }; Blockly.Language.math_format_as_decimal = { category : Blockly.LANG_CATEGORY_MATH, helpUrl : Blockly.LANG_MATH_FORMAT_AS_DECIMAL_HELPURL, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.OUTPUT)); this.appendDummyInput().appendTitle('format as decimal'); this.appendValueInput('NUM').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('number').setAlign(Blockly.ALIGN_RIGHT); this.appendValueInput('PLACES').setCheck(Blockly.Language.YailTypeToBlocklyType("number",Blockly.Language.INPUT)).appendTitle('places').setAlign(Blockly.ALIGN_RIGHT); this.setInputsInline(false); this.setTooltip(Blockly.LANG_MATH_FORMAT_AS_DECIMAL_TOOLTIP); this.appendCollapsedInput().appendTitle('format decimal', 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_FORMAT_AS_DECIMAL_TITLE }] }; Blockly.Language.math_is_a_number = { category : Blockly.LANG_CATEGORY_MATH, helpUrl : Blockly.LANG_MATH_IS_A_NUMBER_HELPURL, init : function() { this.setColour(Blockly.MATH_CATEGORY_HUE); this.setOutput(true, Blockly.Language.YailTypeToBlocklyType("boolean",Blockly.Language.OUTPUT)); this.appendValueInput('NUM').appendTitle('is a number?'); this.setTooltip(function() { return Blockly.LANG_MATH_IS_A_NUMBER_TOOLTIP; }); this.appendCollapsedInput().appendTitle('number?', 'COLLAPSED_TEXT'); }, typeblock: [{ translatedName: Blockly.LANG_MATH_IS_A_NUMBER_INPUT_NUM }] };
version https://git-lfs.github.com/spec/v1 oid sha256:c32c7af615c44088fd2201ec0c442e1f7bcba5463b768d6c75ac51417208b915 size 1999
define(['./module'], function(app) { 'use strict'; var communitiesRepository = function($http) { this.getOne = function(key) { return $http.get("/data/" + key + ".json"); }; this.getAll = function() { return $http.get("/data/communities.json"); }; } app.factory('communitiesRepository', ['$http', function($http) { return new communitiesRepository($http); }]); });
var CACHE_NAME = 'morpheus'; var CACHED_FILES = [ 'css/morpheus-latest.min.css', 'fonts/FontAwesome.otf', 'fonts/fontawesome-webfont.eot', 'fonts/fontawesome-webfont.svg', 'fonts/fontawesome-webfont.ttf', 'fonts/fontawesome-webfont.woff', 'fonts/fontawesome-webfont.woff2', 'js/morpheus-external-latest.min.js', 'js/morpheus-latest.min.js', '/', 'index.html', 'favicon.ico' ]; self.addEventListener('install', function (event) { event.waitUntil( caches.open(CACHE_NAME).then(function (cache) { cache.addAll(CACHED_FILES); }) ); }); self.addEventListener('fetch', function (event) { event.respondWith( caches.open(CACHE_NAME).then(function (cache) { return cache.match(event.request).then(function (cachedResponse) { if (cachedResponse) { // try to get an updated version return fetch(event.request.clone()).then(function (response) { cache.put(event.request, response.clone()); return response; }).catch(function () { return cachedResponse; }) } else { return fetch(event.request).then(function (response) { return response; }); } }).catch(function (error) { // This catch() will handle exceptions that arise from the match() or fetch() operations. // Note that a HTTP error response (e.g. 404) will NOT trigger an exception. // It will return a normal response object that has the appropriate error code set. throw error; }); }) ); });
/* eslint-disable padding-line-between-statements,strict */ module.exports.foo = function () { try { } catch (e) { }; };
var test = require('tape'); if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { test('has native Symbol support', function (t) { t.equal(typeof Symbol, 'function'); t.equal(typeof Symbol(), 'symbol'); t.end(); }); return; } var hasSymbols = require('../hasSymbols'); test('polyfilled Symbols', function (t) { t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); require('get-own-property-symbols'); var hasSymbolsAfter = hasSymbols(); t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); if (hasSymbolsAfter) { require('./'); } t.end(); });
Flame.FocusSupport = { // To make text fields/areas behave consistently with our concept of key responder, we have to also // tell the browser to focus/blur the input field didBecomeKeyResponder: function() { this.$().focus(); }, didLoseKeyResponder: function() { this.$().blur(); }, focusIn: function() { if (Flame.keyResponderStack.current() !== this) { this.becomeKeyResponder(); } }, focusOut: function() { if (Flame.keyResponderStack.current() === this) { this.resignKeyResponder(); } } };
"use strict"; var $__ParseTree_46_js__, $__ParseTreeType_46_js__; var ParseTree = ($__ParseTree_46_js__ = require("./ParseTree.js"), $__ParseTree_46_js__ && $__ParseTree_46_js__.__esModule && $__ParseTree_46_js__ || {default: $__ParseTree_46_js__}).ParseTree; var ParseTreeType = ($__ParseTreeType_46_js__ = require("./ParseTreeType.js"), $__ParseTreeType_46_js__ && $__ParseTreeType_46_js__.__esModule && $__ParseTreeType_46_js__ || {default: $__ParseTreeType_46_js__}); var ANNOTATION = ParseTreeType.ANNOTATION; var Annotation = function($__super) { function Annotation(location, name, args) { $traceurRuntime.superConstructor(Annotation).call(this, location); this.name = name; this.args = args; } return ($traceurRuntime.createClass)(Annotation, { transform: function(transformer) { return transformer.transformAnnotation(this); }, visit: function(visitor) { visitor.visitAnnotation(this); }, get type() { return ANNOTATION; } }, {}, $__super); }(ParseTree); var ANON_BLOCK = ParseTreeType.ANON_BLOCK; var AnonBlock = function($__super) { function AnonBlock(location, statements) { $traceurRuntime.superConstructor(AnonBlock).call(this, location); this.statements = statements; } return ($traceurRuntime.createClass)(AnonBlock, { transform: function(transformer) { return transformer.transformAnonBlock(this); }, visit: function(visitor) { visitor.visitAnonBlock(this); }, get type() { return ANON_BLOCK; } }, {}, $__super); }(ParseTree); var ARGUMENT_LIST = ParseTreeType.ARGUMENT_LIST; var ArgumentList = function($__super) { function ArgumentList(location, args) { $traceurRuntime.superConstructor(ArgumentList).call(this, location); this.args = args; } return ($traceurRuntime.createClass)(ArgumentList, { transform: function(transformer) { return transformer.transformArgumentList(this); }, visit: function(visitor) { visitor.visitArgumentList(this); }, get type() { return ARGUMENT_LIST; } }, {}, $__super); }(ParseTree); var ARRAY_COMPREHENSION = ParseTreeType.ARRAY_COMPREHENSION; var ArrayComprehension = function($__super) { function ArrayComprehension(location, comprehensionList, expression) { $traceurRuntime.superConstructor(ArrayComprehension).call(this, location); this.comprehensionList = comprehensionList; this.expression = expression; } return ($traceurRuntime.createClass)(ArrayComprehension, { transform: function(transformer) { return transformer.transformArrayComprehension(this); }, visit: function(visitor) { visitor.visitArrayComprehension(this); }, get type() { return ARRAY_COMPREHENSION; } }, {}, $__super); }(ParseTree); var ARRAY_LITERAL = ParseTreeType.ARRAY_LITERAL; var ArrayLiteral = function($__super) { function ArrayLiteral(location, elements) { $traceurRuntime.superConstructor(ArrayLiteral).call(this, location); this.elements = elements; } return ($traceurRuntime.createClass)(ArrayLiteral, { transform: function(transformer) { return transformer.transformArrayLiteral(this); }, visit: function(visitor) { visitor.visitArrayLiteral(this); }, get type() { return ARRAY_LITERAL; } }, {}, $__super); }(ParseTree); var ARRAY_PATTERN = ParseTreeType.ARRAY_PATTERN; var ArrayPattern = function($__super) { function ArrayPattern(location, elements) { $traceurRuntime.superConstructor(ArrayPattern).call(this, location); this.elements = elements; } return ($traceurRuntime.createClass)(ArrayPattern, { transform: function(transformer) { return transformer.transformArrayPattern(this); }, visit: function(visitor) { visitor.visitArrayPattern(this); }, get type() { return ARRAY_PATTERN; } }, {}, $__super); }(ParseTree); var ARRAY_TYPE = ParseTreeType.ARRAY_TYPE; var ArrayType = function($__super) { function ArrayType(location, elementType) { $traceurRuntime.superConstructor(ArrayType).call(this, location); this.elementType = elementType; } return ($traceurRuntime.createClass)(ArrayType, { transform: function(transformer) { return transformer.transformArrayType(this); }, visit: function(visitor) { visitor.visitArrayType(this); }, get type() { return ARRAY_TYPE; } }, {}, $__super); }(ParseTree); var ARROW_FUNCTION = ParseTreeType.ARROW_FUNCTION; var ArrowFunction = function($__super) { function ArrowFunction(location, functionKind, parameterList, body) { $traceurRuntime.superConstructor(ArrowFunction).call(this, location); this.functionKind = functionKind; this.parameterList = parameterList; this.body = body; } return ($traceurRuntime.createClass)(ArrowFunction, { transform: function(transformer) { return transformer.transformArrowFunction(this); }, visit: function(visitor) { visitor.visitArrowFunction(this); }, get type() { return ARROW_FUNCTION; } }, {}, $__super); }(ParseTree); var ASSIGNMENT_ELEMENT = ParseTreeType.ASSIGNMENT_ELEMENT; var AssignmentElement = function($__super) { function AssignmentElement(location, assignment, initializer) { $traceurRuntime.superConstructor(AssignmentElement).call(this, location); this.assignment = assignment; this.initializer = initializer; } return ($traceurRuntime.createClass)(AssignmentElement, { transform: function(transformer) { return transformer.transformAssignmentElement(this); }, visit: function(visitor) { visitor.visitAssignmentElement(this); }, get type() { return ASSIGNMENT_ELEMENT; } }, {}, $__super); }(ParseTree); var AWAIT_EXPRESSION = ParseTreeType.AWAIT_EXPRESSION; var AwaitExpression = function($__super) { function AwaitExpression(location, expression) { $traceurRuntime.superConstructor(AwaitExpression).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(AwaitExpression, { transform: function(transformer) { return transformer.transformAwaitExpression(this); }, visit: function(visitor) { visitor.visitAwaitExpression(this); }, get type() { return AWAIT_EXPRESSION; } }, {}, $__super); }(ParseTree); var BINARY_EXPRESSION = ParseTreeType.BINARY_EXPRESSION; var BinaryExpression = function($__super) { function BinaryExpression(location, left, operator, right) { $traceurRuntime.superConstructor(BinaryExpression).call(this, location); this.left = left; this.operator = operator; this.right = right; } return ($traceurRuntime.createClass)(BinaryExpression, { transform: function(transformer) { return transformer.transformBinaryExpression(this); }, visit: function(visitor) { visitor.visitBinaryExpression(this); }, get type() { return BINARY_EXPRESSION; } }, {}, $__super); }(ParseTree); var BINDING_ELEMENT = ParseTreeType.BINDING_ELEMENT; var BindingElement = function($__super) { function BindingElement(location, binding, initializer) { $traceurRuntime.superConstructor(BindingElement).call(this, location); this.binding = binding; this.initializer = initializer; } return ($traceurRuntime.createClass)(BindingElement, { transform: function(transformer) { return transformer.transformBindingElement(this); }, visit: function(visitor) { visitor.visitBindingElement(this); }, get type() { return BINDING_ELEMENT; } }, {}, $__super); }(ParseTree); var BINDING_IDENTIFIER = ParseTreeType.BINDING_IDENTIFIER; var BindingIdentifier = function($__super) { function BindingIdentifier(location, identifierToken) { $traceurRuntime.superConstructor(BindingIdentifier).call(this, location); this.identifierToken = identifierToken; } return ($traceurRuntime.createClass)(BindingIdentifier, { transform: function(transformer) { return transformer.transformBindingIdentifier(this); }, visit: function(visitor) { visitor.visitBindingIdentifier(this); }, get type() { return BINDING_IDENTIFIER; } }, {}, $__super); }(ParseTree); var BLOCK = ParseTreeType.BLOCK; var Block = function($__super) { function Block(location, statements) { $traceurRuntime.superConstructor(Block).call(this, location); this.statements = statements; } return ($traceurRuntime.createClass)(Block, { transform: function(transformer) { return transformer.transformBlock(this); }, visit: function(visitor) { visitor.visitBlock(this); }, get type() { return BLOCK; } }, {}, $__super); }(ParseTree); var BREAK_STATEMENT = ParseTreeType.BREAK_STATEMENT; var BreakStatement = function($__super) { function BreakStatement(location, name) { $traceurRuntime.superConstructor(BreakStatement).call(this, location); this.name = name; } return ($traceurRuntime.createClass)(BreakStatement, { transform: function(transformer) { return transformer.transformBreakStatement(this); }, visit: function(visitor) { visitor.visitBreakStatement(this); }, get type() { return BREAK_STATEMENT; } }, {}, $__super); }(ParseTree); var CALL_EXPRESSION = ParseTreeType.CALL_EXPRESSION; var CallExpression = function($__super) { function CallExpression(location, operand, args) { $traceurRuntime.superConstructor(CallExpression).call(this, location); this.operand = operand; this.args = args; } return ($traceurRuntime.createClass)(CallExpression, { transform: function(transformer) { return transformer.transformCallExpression(this); }, visit: function(visitor) { visitor.visitCallExpression(this); }, get type() { return CALL_EXPRESSION; } }, {}, $__super); }(ParseTree); var CALL_SIGNATURE = ParseTreeType.CALL_SIGNATURE; var CallSignature = function($__super) { function CallSignature(location, typeParameters, parameterList, returnType) { $traceurRuntime.superConstructor(CallSignature).call(this, location); this.typeParameters = typeParameters; this.parameterList = parameterList; this.returnType = returnType; } return ($traceurRuntime.createClass)(CallSignature, { transform: function(transformer) { return transformer.transformCallSignature(this); }, visit: function(visitor) { visitor.visitCallSignature(this); }, get type() { return CALL_SIGNATURE; } }, {}, $__super); }(ParseTree); var CASE_CLAUSE = ParseTreeType.CASE_CLAUSE; var CaseClause = function($__super) { function CaseClause(location, expression, statements) { $traceurRuntime.superConstructor(CaseClause).call(this, location); this.expression = expression; this.statements = statements; } return ($traceurRuntime.createClass)(CaseClause, { transform: function(transformer) { return transformer.transformCaseClause(this); }, visit: function(visitor) { visitor.visitCaseClause(this); }, get type() { return CASE_CLAUSE; } }, {}, $__super); }(ParseTree); var CATCH = ParseTreeType.CATCH; var Catch = function($__super) { function Catch(location, binding, catchBody) { $traceurRuntime.superConstructor(Catch).call(this, location); this.binding = binding; this.catchBody = catchBody; } return ($traceurRuntime.createClass)(Catch, { transform: function(transformer) { return transformer.transformCatch(this); }, visit: function(visitor) { visitor.visitCatch(this); }, get type() { return CATCH; } }, {}, $__super); }(ParseTree); var CLASS_DECLARATION = ParseTreeType.CLASS_DECLARATION; var ClassDeclaration = function($__super) { function ClassDeclaration(location, name, superClass, elements, annotations, typeParameters) { $traceurRuntime.superConstructor(ClassDeclaration).call(this, location); this.name = name; this.superClass = superClass; this.elements = elements; this.annotations = annotations; this.typeParameters = typeParameters; } return ($traceurRuntime.createClass)(ClassDeclaration, { transform: function(transformer) { return transformer.transformClassDeclaration(this); }, visit: function(visitor) { visitor.visitClassDeclaration(this); }, get type() { return CLASS_DECLARATION; } }, {}, $__super); }(ParseTree); var CLASS_EXPRESSION = ParseTreeType.CLASS_EXPRESSION; var ClassExpression = function($__super) { function ClassExpression(location, name, superClass, elements, annotations, typeParameters) { $traceurRuntime.superConstructor(ClassExpression).call(this, location); this.name = name; this.superClass = superClass; this.elements = elements; this.annotations = annotations; this.typeParameters = typeParameters; } return ($traceurRuntime.createClass)(ClassExpression, { transform: function(transformer) { return transformer.transformClassExpression(this); }, visit: function(visitor) { visitor.visitClassExpression(this); }, get type() { return CLASS_EXPRESSION; } }, {}, $__super); }(ParseTree); var COMMA_EXPRESSION = ParseTreeType.COMMA_EXPRESSION; var CommaExpression = function($__super) { function CommaExpression(location, expressions) { $traceurRuntime.superConstructor(CommaExpression).call(this, location); this.expressions = expressions; } return ($traceurRuntime.createClass)(CommaExpression, { transform: function(transformer) { return transformer.transformCommaExpression(this); }, visit: function(visitor) { visitor.visitCommaExpression(this); }, get type() { return COMMA_EXPRESSION; } }, {}, $__super); }(ParseTree); var COMPREHENSION_FOR = ParseTreeType.COMPREHENSION_FOR; var ComprehensionFor = function($__super) { function ComprehensionFor(location, left, iterator) { $traceurRuntime.superConstructor(ComprehensionFor).call(this, location); this.left = left; this.iterator = iterator; } return ($traceurRuntime.createClass)(ComprehensionFor, { transform: function(transformer) { return transformer.transformComprehensionFor(this); }, visit: function(visitor) { visitor.visitComprehensionFor(this); }, get type() { return COMPREHENSION_FOR; } }, {}, $__super); }(ParseTree); var COMPREHENSION_IF = ParseTreeType.COMPREHENSION_IF; var ComprehensionIf = function($__super) { function ComprehensionIf(location, expression) { $traceurRuntime.superConstructor(ComprehensionIf).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(ComprehensionIf, { transform: function(transformer) { return transformer.transformComprehensionIf(this); }, visit: function(visitor) { visitor.visitComprehensionIf(this); }, get type() { return COMPREHENSION_IF; } }, {}, $__super); }(ParseTree); var COMPUTED_PROPERTY_NAME = ParseTreeType.COMPUTED_PROPERTY_NAME; var ComputedPropertyName = function($__super) { function ComputedPropertyName(location, expression) { $traceurRuntime.superConstructor(ComputedPropertyName).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(ComputedPropertyName, { transform: function(transformer) { return transformer.transformComputedPropertyName(this); }, visit: function(visitor) { visitor.visitComputedPropertyName(this); }, get type() { return COMPUTED_PROPERTY_NAME; } }, {}, $__super); }(ParseTree); var CONDITIONAL_EXPRESSION = ParseTreeType.CONDITIONAL_EXPRESSION; var ConditionalExpression = function($__super) { function ConditionalExpression(location, condition, left, right) { $traceurRuntime.superConstructor(ConditionalExpression).call(this, location); this.condition = condition; this.left = left; this.right = right; } return ($traceurRuntime.createClass)(ConditionalExpression, { transform: function(transformer) { return transformer.transformConditionalExpression(this); }, visit: function(visitor) { visitor.visitConditionalExpression(this); }, get type() { return CONDITIONAL_EXPRESSION; } }, {}, $__super); }(ParseTree); var CONSTRUCT_SIGNATURE = ParseTreeType.CONSTRUCT_SIGNATURE; var ConstructSignature = function($__super) { function ConstructSignature(location, typeParameters, parameterList, returnType) { $traceurRuntime.superConstructor(ConstructSignature).call(this, location); this.typeParameters = typeParameters; this.parameterList = parameterList; this.returnType = returnType; } return ($traceurRuntime.createClass)(ConstructSignature, { transform: function(transformer) { return transformer.transformConstructSignature(this); }, visit: function(visitor) { visitor.visitConstructSignature(this); }, get type() { return CONSTRUCT_SIGNATURE; } }, {}, $__super); }(ParseTree); var CONSTRUCTOR_TYPE = ParseTreeType.CONSTRUCTOR_TYPE; var ConstructorType = function($__super) { function ConstructorType(location, typeParameters, parameterList, returnType) { $traceurRuntime.superConstructor(ConstructorType).call(this, location); this.typeParameters = typeParameters; this.parameterList = parameterList; this.returnType = returnType; } return ($traceurRuntime.createClass)(ConstructorType, { transform: function(transformer) { return transformer.transformConstructorType(this); }, visit: function(visitor) { visitor.visitConstructorType(this); }, get type() { return CONSTRUCTOR_TYPE; } }, {}, $__super); }(ParseTree); var CONTINUE_STATEMENT = ParseTreeType.CONTINUE_STATEMENT; var ContinueStatement = function($__super) { function ContinueStatement(location, name) { $traceurRuntime.superConstructor(ContinueStatement).call(this, location); this.name = name; } return ($traceurRuntime.createClass)(ContinueStatement, { transform: function(transformer) { return transformer.transformContinueStatement(this); }, visit: function(visitor) { visitor.visitContinueStatement(this); }, get type() { return CONTINUE_STATEMENT; } }, {}, $__super); }(ParseTree); var COVER_FORMALS = ParseTreeType.COVER_FORMALS; var CoverFormals = function($__super) { function CoverFormals(location, expressions) { $traceurRuntime.superConstructor(CoverFormals).call(this, location); this.expressions = expressions; } return ($traceurRuntime.createClass)(CoverFormals, { transform: function(transformer) { return transformer.transformCoverFormals(this); }, visit: function(visitor) { visitor.visitCoverFormals(this); }, get type() { return COVER_FORMALS; } }, {}, $__super); }(ParseTree); var COVER_INITIALIZED_NAME = ParseTreeType.COVER_INITIALIZED_NAME; var CoverInitializedName = function($__super) { function CoverInitializedName(location, name, equalToken, initializer) { $traceurRuntime.superConstructor(CoverInitializedName).call(this, location); this.name = name; this.equalToken = equalToken; this.initializer = initializer; } return ($traceurRuntime.createClass)(CoverInitializedName, { transform: function(transformer) { return transformer.transformCoverInitializedName(this); }, visit: function(visitor) { visitor.visitCoverInitializedName(this); }, get type() { return COVER_INITIALIZED_NAME; } }, {}, $__super); }(ParseTree); var DEBUGGER_STATEMENT = ParseTreeType.DEBUGGER_STATEMENT; var DebuggerStatement = function($__super) { function DebuggerStatement(location) { $traceurRuntime.superConstructor(DebuggerStatement).call(this, location); } return ($traceurRuntime.createClass)(DebuggerStatement, { transform: function(transformer) { return transformer.transformDebuggerStatement(this); }, visit: function(visitor) { visitor.visitDebuggerStatement(this); }, get type() { return DEBUGGER_STATEMENT; } }, {}, $__super); }(ParseTree); var DEFAULT_CLAUSE = ParseTreeType.DEFAULT_CLAUSE; var DefaultClause = function($__super) { function DefaultClause(location, statements) { $traceurRuntime.superConstructor(DefaultClause).call(this, location); this.statements = statements; } return ($traceurRuntime.createClass)(DefaultClause, { transform: function(transformer) { return transformer.transformDefaultClause(this); }, visit: function(visitor) { visitor.visitDefaultClause(this); }, get type() { return DEFAULT_CLAUSE; } }, {}, $__super); }(ParseTree); var DO_WHILE_STATEMENT = ParseTreeType.DO_WHILE_STATEMENT; var DoWhileStatement = function($__super) { function DoWhileStatement(location, body, condition) { $traceurRuntime.superConstructor(DoWhileStatement).call(this, location); this.body = body; this.condition = condition; } return ($traceurRuntime.createClass)(DoWhileStatement, { transform: function(transformer) { return transformer.transformDoWhileStatement(this); }, visit: function(visitor) { visitor.visitDoWhileStatement(this); }, get type() { return DO_WHILE_STATEMENT; } }, {}, $__super); }(ParseTree); var EMPTY_STATEMENT = ParseTreeType.EMPTY_STATEMENT; var EmptyStatement = function($__super) { function EmptyStatement(location) { $traceurRuntime.superConstructor(EmptyStatement).call(this, location); } return ($traceurRuntime.createClass)(EmptyStatement, { transform: function(transformer) { return transformer.transformEmptyStatement(this); }, visit: function(visitor) { visitor.visitEmptyStatement(this); }, get type() { return EMPTY_STATEMENT; } }, {}, $__super); }(ParseTree); var EXPORT_DECLARATION = ParseTreeType.EXPORT_DECLARATION; var ExportDeclaration = function($__super) { function ExportDeclaration(location, declaration, annotations) { $traceurRuntime.superConstructor(ExportDeclaration).call(this, location); this.declaration = declaration; this.annotations = annotations; } return ($traceurRuntime.createClass)(ExportDeclaration, { transform: function(transformer) { return transformer.transformExportDeclaration(this); }, visit: function(visitor) { visitor.visitExportDeclaration(this); }, get type() { return EXPORT_DECLARATION; } }, {}, $__super); }(ParseTree); var EXPORT_DEFAULT = ParseTreeType.EXPORT_DEFAULT; var ExportDefault = function($__super) { function ExportDefault(location, expression) { $traceurRuntime.superConstructor(ExportDefault).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(ExportDefault, { transform: function(transformer) { return transformer.transformExportDefault(this); }, visit: function(visitor) { visitor.visitExportDefault(this); }, get type() { return EXPORT_DEFAULT; } }, {}, $__super); }(ParseTree); var EXPORT_SPECIFIER = ParseTreeType.EXPORT_SPECIFIER; var ExportSpecifier = function($__super) { function ExportSpecifier(location, lhs, rhs) { $traceurRuntime.superConstructor(ExportSpecifier).call(this, location); this.lhs = lhs; this.rhs = rhs; } return ($traceurRuntime.createClass)(ExportSpecifier, { transform: function(transformer) { return transformer.transformExportSpecifier(this); }, visit: function(visitor) { visitor.visitExportSpecifier(this); }, get type() { return EXPORT_SPECIFIER; } }, {}, $__super); }(ParseTree); var EXPORT_SPECIFIER_SET = ParseTreeType.EXPORT_SPECIFIER_SET; var ExportSpecifierSet = function($__super) { function ExportSpecifierSet(location, specifiers) { $traceurRuntime.superConstructor(ExportSpecifierSet).call(this, location); this.specifiers = specifiers; } return ($traceurRuntime.createClass)(ExportSpecifierSet, { transform: function(transformer) { return transformer.transformExportSpecifierSet(this); }, visit: function(visitor) { visitor.visitExportSpecifierSet(this); }, get type() { return EXPORT_SPECIFIER_SET; } }, {}, $__super); }(ParseTree); var EXPORT_STAR = ParseTreeType.EXPORT_STAR; var ExportStar = function($__super) { function ExportStar(location) { $traceurRuntime.superConstructor(ExportStar).call(this, location); } return ($traceurRuntime.createClass)(ExportStar, { transform: function(transformer) { return transformer.transformExportStar(this); }, visit: function(visitor) { visitor.visitExportStar(this); }, get type() { return EXPORT_STAR; } }, {}, $__super); }(ParseTree); var EXPRESSION_STATEMENT = ParseTreeType.EXPRESSION_STATEMENT; var ExpressionStatement = function($__super) { function ExpressionStatement(location, expression) { $traceurRuntime.superConstructor(ExpressionStatement).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(ExpressionStatement, { transform: function(transformer) { return transformer.transformExpressionStatement(this); }, visit: function(visitor) { visitor.visitExpressionStatement(this); }, get type() { return EXPRESSION_STATEMENT; } }, {}, $__super); }(ParseTree); var FINALLY = ParseTreeType.FINALLY; var Finally = function($__super) { function Finally(location, block) { $traceurRuntime.superConstructor(Finally).call(this, location); this.block = block; } return ($traceurRuntime.createClass)(Finally, { transform: function(transformer) { return transformer.transformFinally(this); }, visit: function(visitor) { visitor.visitFinally(this); }, get type() { return FINALLY; } }, {}, $__super); }(ParseTree); var FOR_IN_STATEMENT = ParseTreeType.FOR_IN_STATEMENT; var ForInStatement = function($__super) { function ForInStatement(location, initializer, collection, body) { $traceurRuntime.superConstructor(ForInStatement).call(this, location); this.initializer = initializer; this.collection = collection; this.body = body; } return ($traceurRuntime.createClass)(ForInStatement, { transform: function(transformer) { return transformer.transformForInStatement(this); }, visit: function(visitor) { visitor.visitForInStatement(this); }, get type() { return FOR_IN_STATEMENT; } }, {}, $__super); }(ParseTree); var FOR_OF_STATEMENT = ParseTreeType.FOR_OF_STATEMENT; var ForOfStatement = function($__super) { function ForOfStatement(location, initializer, collection, body) { $traceurRuntime.superConstructor(ForOfStatement).call(this, location); this.initializer = initializer; this.collection = collection; this.body = body; } return ($traceurRuntime.createClass)(ForOfStatement, { transform: function(transformer) { return transformer.transformForOfStatement(this); }, visit: function(visitor) { visitor.visitForOfStatement(this); }, get type() { return FOR_OF_STATEMENT; } }, {}, $__super); }(ParseTree); var FOR_ON_STATEMENT = ParseTreeType.FOR_ON_STATEMENT; var ForOnStatement = function($__super) { function ForOnStatement(location, initializer, observable, body) { $traceurRuntime.superConstructor(ForOnStatement).call(this, location); this.initializer = initializer; this.observable = observable; this.body = body; } return ($traceurRuntime.createClass)(ForOnStatement, { transform: function(transformer) { return transformer.transformForOnStatement(this); }, visit: function(visitor) { visitor.visitForOnStatement(this); }, get type() { return FOR_ON_STATEMENT; } }, {}, $__super); }(ParseTree); var FOR_STATEMENT = ParseTreeType.FOR_STATEMENT; var ForStatement = function($__super) { function ForStatement(location, initializer, condition, increment, body) { $traceurRuntime.superConstructor(ForStatement).call(this, location); this.initializer = initializer; this.condition = condition; this.increment = increment; this.body = body; } return ($traceurRuntime.createClass)(ForStatement, { transform: function(transformer) { return transformer.transformForStatement(this); }, visit: function(visitor) { visitor.visitForStatement(this); }, get type() { return FOR_STATEMENT; } }, {}, $__super); }(ParseTree); var FORMAL_PARAMETER = ParseTreeType.FORMAL_PARAMETER; var FormalParameter = function($__super) { function FormalParameter(location, parameter, typeAnnotation, annotations) { $traceurRuntime.superConstructor(FormalParameter).call(this, location); this.parameter = parameter; this.typeAnnotation = typeAnnotation; this.annotations = annotations; } return ($traceurRuntime.createClass)(FormalParameter, { transform: function(transformer) { return transformer.transformFormalParameter(this); }, visit: function(visitor) { visitor.visitFormalParameter(this); }, get type() { return FORMAL_PARAMETER; } }, {}, $__super); }(ParseTree); var FORMAL_PARAMETER_LIST = ParseTreeType.FORMAL_PARAMETER_LIST; var FormalParameterList = function($__super) { function FormalParameterList(location, parameters) { $traceurRuntime.superConstructor(FormalParameterList).call(this, location); this.parameters = parameters; } return ($traceurRuntime.createClass)(FormalParameterList, { transform: function(transformer) { return transformer.transformFormalParameterList(this); }, visit: function(visitor) { visitor.visitFormalParameterList(this); }, get type() { return FORMAL_PARAMETER_LIST; } }, {}, $__super); }(ParseTree); var FORWARD_DEFAULT_EXPORT = ParseTreeType.FORWARD_DEFAULT_EXPORT; var ForwardDefaultExport = function($__super) { function ForwardDefaultExport(location, name) { $traceurRuntime.superConstructor(ForwardDefaultExport).call(this, location); this.name = name; } return ($traceurRuntime.createClass)(ForwardDefaultExport, { transform: function(transformer) { return transformer.transformForwardDefaultExport(this); }, visit: function(visitor) { visitor.visitForwardDefaultExport(this); }, get type() { return FORWARD_DEFAULT_EXPORT; } }, {}, $__super); }(ParseTree); var FUNCTION_BODY = ParseTreeType.FUNCTION_BODY; var FunctionBody = function($__super) { function FunctionBody(location, statements) { $traceurRuntime.superConstructor(FunctionBody).call(this, location); this.statements = statements; } return ($traceurRuntime.createClass)(FunctionBody, { transform: function(transformer) { return transformer.transformFunctionBody(this); }, visit: function(visitor) { visitor.visitFunctionBody(this); }, get type() { return FUNCTION_BODY; } }, {}, $__super); }(ParseTree); var FUNCTION_DECLARATION = ParseTreeType.FUNCTION_DECLARATION; var FunctionDeclaration = function($__super) { function FunctionDeclaration(location, name, functionKind, parameterList, typeAnnotation, annotations, body) { $traceurRuntime.superConstructor(FunctionDeclaration).call(this, location); this.name = name; this.functionKind = functionKind; this.parameterList = parameterList; this.typeAnnotation = typeAnnotation; this.annotations = annotations; this.body = body; } return ($traceurRuntime.createClass)(FunctionDeclaration, { transform: function(transformer) { return transformer.transformFunctionDeclaration(this); }, visit: function(visitor) { visitor.visitFunctionDeclaration(this); }, get type() { return FUNCTION_DECLARATION; } }, {}, $__super); }(ParseTree); var FUNCTION_EXPRESSION = ParseTreeType.FUNCTION_EXPRESSION; var FunctionExpression = function($__super) { function FunctionExpression(location, name, functionKind, parameterList, typeAnnotation, annotations, body) { $traceurRuntime.superConstructor(FunctionExpression).call(this, location); this.name = name; this.functionKind = functionKind; this.parameterList = parameterList; this.typeAnnotation = typeAnnotation; this.annotations = annotations; this.body = body; } return ($traceurRuntime.createClass)(FunctionExpression, { transform: function(transformer) { return transformer.transformFunctionExpression(this); }, visit: function(visitor) { visitor.visitFunctionExpression(this); }, get type() { return FUNCTION_EXPRESSION; } }, {}, $__super); }(ParseTree); var FUNCTION_TYPE = ParseTreeType.FUNCTION_TYPE; var FunctionType = function($__super) { function FunctionType(location, typeParameters, parameterList, returnType) { $traceurRuntime.superConstructor(FunctionType).call(this, location); this.typeParameters = typeParameters; this.parameterList = parameterList; this.returnType = returnType; } return ($traceurRuntime.createClass)(FunctionType, { transform: function(transformer) { return transformer.transformFunctionType(this); }, visit: function(visitor) { visitor.visitFunctionType(this); }, get type() { return FUNCTION_TYPE; } }, {}, $__super); }(ParseTree); var GENERATOR_COMPREHENSION = ParseTreeType.GENERATOR_COMPREHENSION; var GeneratorComprehension = function($__super) { function GeneratorComprehension(location, comprehensionList, expression) { $traceurRuntime.superConstructor(GeneratorComprehension).call(this, location); this.comprehensionList = comprehensionList; this.expression = expression; } return ($traceurRuntime.createClass)(GeneratorComprehension, { transform: function(transformer) { return transformer.transformGeneratorComprehension(this); }, visit: function(visitor) { visitor.visitGeneratorComprehension(this); }, get type() { return GENERATOR_COMPREHENSION; } }, {}, $__super); }(ParseTree); var GET_ACCESSOR = ParseTreeType.GET_ACCESSOR; var GetAccessor = function($__super) { function GetAccessor(location, isStatic, name, typeAnnotation, annotations, body) { $traceurRuntime.superConstructor(GetAccessor).call(this, location); this.isStatic = isStatic; this.name = name; this.typeAnnotation = typeAnnotation; this.annotations = annotations; this.body = body; } return ($traceurRuntime.createClass)(GetAccessor, { transform: function(transformer) { return transformer.transformGetAccessor(this); }, visit: function(visitor) { visitor.visitGetAccessor(this); }, get type() { return GET_ACCESSOR; } }, {}, $__super); }(ParseTree); var IDENTIFIER_EXPRESSION = ParseTreeType.IDENTIFIER_EXPRESSION; var IdentifierExpression = function($__super) { function IdentifierExpression(location, identifierToken) { $traceurRuntime.superConstructor(IdentifierExpression).call(this, location); this.identifierToken = identifierToken; } return ($traceurRuntime.createClass)(IdentifierExpression, { transform: function(transformer) { return transformer.transformIdentifierExpression(this); }, visit: function(visitor) { visitor.visitIdentifierExpression(this); }, get type() { return IDENTIFIER_EXPRESSION; } }, {}, $__super); }(ParseTree); var IF_STATEMENT = ParseTreeType.IF_STATEMENT; var IfStatement = function($__super) { function IfStatement(location, condition, ifClause, elseClause) { $traceurRuntime.superConstructor(IfStatement).call(this, location); this.condition = condition; this.ifClause = ifClause; this.elseClause = elseClause; } return ($traceurRuntime.createClass)(IfStatement, { transform: function(transformer) { return transformer.transformIfStatement(this); }, visit: function(visitor) { visitor.visitIfStatement(this); }, get type() { return IF_STATEMENT; } }, {}, $__super); }(ParseTree); var IMPORTED_BINDING = ParseTreeType.IMPORTED_BINDING; var ImportedBinding = function($__super) { function ImportedBinding(location, binding) { $traceurRuntime.superConstructor(ImportedBinding).call(this, location); this.binding = binding; } return ($traceurRuntime.createClass)(ImportedBinding, { transform: function(transformer) { return transformer.transformImportedBinding(this); }, visit: function(visitor) { visitor.visitImportedBinding(this); }, get type() { return IMPORTED_BINDING; } }, {}, $__super); }(ParseTree); var IMPORT_CLAUSE_PAIR = ParseTreeType.IMPORT_CLAUSE_PAIR; var ImportClausePair = function($__super) { function ImportClausePair(location, first, second) { $traceurRuntime.superConstructor(ImportClausePair).call(this, location); this.first = first; this.second = second; } return ($traceurRuntime.createClass)(ImportClausePair, { transform: function(transformer) { return transformer.transformImportClausePair(this); }, visit: function(visitor) { visitor.visitImportClausePair(this); }, get type() { return IMPORT_CLAUSE_PAIR; } }, {}, $__super); }(ParseTree); var IMPORT_DECLARATION = ParseTreeType.IMPORT_DECLARATION; var ImportDeclaration = function($__super) { function ImportDeclaration(location, importClause, moduleSpecifier) { $traceurRuntime.superConstructor(ImportDeclaration).call(this, location); this.importClause = importClause; this.moduleSpecifier = moduleSpecifier; } return ($traceurRuntime.createClass)(ImportDeclaration, { transform: function(transformer) { return transformer.transformImportDeclaration(this); }, visit: function(visitor) { visitor.visitImportDeclaration(this); }, get type() { return IMPORT_DECLARATION; } }, {}, $__super); }(ParseTree); var IMPORT_SPECIFIER = ParseTreeType.IMPORT_SPECIFIER; var ImportSpecifier = function($__super) { function ImportSpecifier(location, binding, name) { $traceurRuntime.superConstructor(ImportSpecifier).call(this, location); this.binding = binding; this.name = name; } return ($traceurRuntime.createClass)(ImportSpecifier, { transform: function(transformer) { return transformer.transformImportSpecifier(this); }, visit: function(visitor) { visitor.visitImportSpecifier(this); }, get type() { return IMPORT_SPECIFIER; } }, {}, $__super); }(ParseTree); var IMPORT_SPECIFIER_SET = ParseTreeType.IMPORT_SPECIFIER_SET; var ImportSpecifierSet = function($__super) { function ImportSpecifierSet(location, specifiers) { $traceurRuntime.superConstructor(ImportSpecifierSet).call(this, location); this.specifiers = specifiers; } return ($traceurRuntime.createClass)(ImportSpecifierSet, { transform: function(transformer) { return transformer.transformImportSpecifierSet(this); }, visit: function(visitor) { visitor.visitImportSpecifierSet(this); }, get type() { return IMPORT_SPECIFIER_SET; } }, {}, $__super); }(ParseTree); var IMPORT_TYPE_CLAUSE = ParseTreeType.IMPORT_TYPE_CLAUSE; var ImportTypeClause = function($__super) { function ImportTypeClause(location, clause) { $traceurRuntime.superConstructor(ImportTypeClause).call(this, location); this.clause = clause; } return ($traceurRuntime.createClass)(ImportTypeClause, { transform: function(transformer) { return transformer.transformImportTypeClause(this); }, visit: function(visitor) { visitor.visitImportTypeClause(this); }, get type() { return IMPORT_TYPE_CLAUSE; } }, {}, $__super); }(ParseTree); var INDEX_SIGNATURE = ParseTreeType.INDEX_SIGNATURE; var IndexSignature = function($__super) { function IndexSignature(location, name, indexType, typeAnnotation) { $traceurRuntime.superConstructor(IndexSignature).call(this, location); this.name = name; this.indexType = indexType; this.typeAnnotation = typeAnnotation; } return ($traceurRuntime.createClass)(IndexSignature, { transform: function(transformer) { return transformer.transformIndexSignature(this); }, visit: function(visitor) { visitor.visitIndexSignature(this); }, get type() { return INDEX_SIGNATURE; } }, {}, $__super); }(ParseTree); var INTERFACE_DECLARATION = ParseTreeType.INTERFACE_DECLARATION; var InterfaceDeclaration = function($__super) { function InterfaceDeclaration(location, name, typeParameters, extendsClause, objectType) { $traceurRuntime.superConstructor(InterfaceDeclaration).call(this, location); this.name = name; this.typeParameters = typeParameters; this.extendsClause = extendsClause; this.objectType = objectType; } return ($traceurRuntime.createClass)(InterfaceDeclaration, { transform: function(transformer) { return transformer.transformInterfaceDeclaration(this); }, visit: function(visitor) { visitor.visitInterfaceDeclaration(this); }, get type() { return INTERFACE_DECLARATION; } }, {}, $__super); }(ParseTree); var JSX_ATTRIBUTE = ParseTreeType.JSX_ATTRIBUTE; var JsxAttribute = function($__super) { function JsxAttribute(location, name, value) { $traceurRuntime.superConstructor(JsxAttribute).call(this, location); this.name = name; this.value = value; } return ($traceurRuntime.createClass)(JsxAttribute, { transform: function(transformer) { return transformer.transformJsxAttribute(this); }, visit: function(visitor) { visitor.visitJsxAttribute(this); }, get type() { return JSX_ATTRIBUTE; } }, {}, $__super); }(ParseTree); var JSX_ELEMENT = ParseTreeType.JSX_ELEMENT; var JsxElement = function($__super) { function JsxElement(location, name, attributes, children) { $traceurRuntime.superConstructor(JsxElement).call(this, location); this.name = name; this.attributes = attributes; this.children = children; } return ($traceurRuntime.createClass)(JsxElement, { transform: function(transformer) { return transformer.transformJsxElement(this); }, visit: function(visitor) { visitor.visitJsxElement(this); }, get type() { return JSX_ELEMENT; } }, {}, $__super); }(ParseTree); var JSX_ELEMENT_NAME = ParseTreeType.JSX_ELEMENT_NAME; var JsxElementName = function($__super) { function JsxElementName(location, names) { $traceurRuntime.superConstructor(JsxElementName).call(this, location); this.names = names; } return ($traceurRuntime.createClass)(JsxElementName, { transform: function(transformer) { return transformer.transformJsxElementName(this); }, visit: function(visitor) { visitor.visitJsxElementName(this); }, get type() { return JSX_ELEMENT_NAME; } }, {}, $__super); }(ParseTree); var JSX_PLACEHOLDER = ParseTreeType.JSX_PLACEHOLDER; var JsxPlaceholder = function($__super) { function JsxPlaceholder(location, expression) { $traceurRuntime.superConstructor(JsxPlaceholder).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(JsxPlaceholder, { transform: function(transformer) { return transformer.transformJsxPlaceholder(this); }, visit: function(visitor) { visitor.visitJsxPlaceholder(this); }, get type() { return JSX_PLACEHOLDER; } }, {}, $__super); }(ParseTree); var JSX_TEXT = ParseTreeType.JSX_TEXT; var JsxText = function($__super) { function JsxText(location, value) { $traceurRuntime.superConstructor(JsxText).call(this, location); this.value = value; } return ($traceurRuntime.createClass)(JsxText, { transform: function(transformer) { return transformer.transformJsxText(this); }, visit: function(visitor) { visitor.visitJsxText(this); }, get type() { return JSX_TEXT; } }, {}, $__super); }(ParseTree); var LABELLED_STATEMENT = ParseTreeType.LABELLED_STATEMENT; var LabelledStatement = function($__super) { function LabelledStatement(location, name, statement) { $traceurRuntime.superConstructor(LabelledStatement).call(this, location); this.name = name; this.statement = statement; } return ($traceurRuntime.createClass)(LabelledStatement, { transform: function(transformer) { return transformer.transformLabelledStatement(this); }, visit: function(visitor) { visitor.visitLabelledStatement(this); }, get type() { return LABELLED_STATEMENT; } }, {}, $__super); }(ParseTree); var LITERAL_EXPRESSION = ParseTreeType.LITERAL_EXPRESSION; var LiteralExpression = function($__super) { function LiteralExpression(location, literalToken) { $traceurRuntime.superConstructor(LiteralExpression).call(this, location); this.literalToken = literalToken; } return ($traceurRuntime.createClass)(LiteralExpression, { transform: function(transformer) { return transformer.transformLiteralExpression(this); }, visit: function(visitor) { visitor.visitLiteralExpression(this); }, get type() { return LITERAL_EXPRESSION; } }, {}, $__super); }(ParseTree); var LITERAL_PROPERTY_NAME = ParseTreeType.LITERAL_PROPERTY_NAME; var LiteralPropertyName = function($__super) { function LiteralPropertyName(location, literalToken) { $traceurRuntime.superConstructor(LiteralPropertyName).call(this, location); this.literalToken = literalToken; } return ($traceurRuntime.createClass)(LiteralPropertyName, { transform: function(transformer) { return transformer.transformLiteralPropertyName(this); }, visit: function(visitor) { visitor.visitLiteralPropertyName(this); }, get type() { return LITERAL_PROPERTY_NAME; } }, {}, $__super); }(ParseTree); var MEMBER_EXPRESSION = ParseTreeType.MEMBER_EXPRESSION; var MemberExpression = function($__super) { function MemberExpression(location, operand, memberName) { $traceurRuntime.superConstructor(MemberExpression).call(this, location); this.operand = operand; this.memberName = memberName; } return ($traceurRuntime.createClass)(MemberExpression, { transform: function(transformer) { return transformer.transformMemberExpression(this); }, visit: function(visitor) { visitor.visitMemberExpression(this); }, get type() { return MEMBER_EXPRESSION; } }, {}, $__super); }(ParseTree); var MEMBER_LOOKUP_EXPRESSION = ParseTreeType.MEMBER_LOOKUP_EXPRESSION; var MemberLookupExpression = function($__super) { function MemberLookupExpression(location, operand, memberExpression) { $traceurRuntime.superConstructor(MemberLookupExpression).call(this, location); this.operand = operand; this.memberExpression = memberExpression; } return ($traceurRuntime.createClass)(MemberLookupExpression, { transform: function(transformer) { return transformer.transformMemberLookupExpression(this); }, visit: function(visitor) { visitor.visitMemberLookupExpression(this); }, get type() { return MEMBER_LOOKUP_EXPRESSION; } }, {}, $__super); }(ParseTree); var METHOD = ParseTreeType.METHOD; var Method = function($__super) { function Method(location, isStatic, functionKind, name, parameterList, typeAnnotation, annotations, body, debugName) { $traceurRuntime.superConstructor(Method).call(this, location); this.isStatic = isStatic; this.functionKind = functionKind; this.name = name; this.parameterList = parameterList; this.typeAnnotation = typeAnnotation; this.annotations = annotations; this.body = body; this.debugName = debugName; } return ($traceurRuntime.createClass)(Method, { transform: function(transformer) { return transformer.transformMethod(this); }, visit: function(visitor) { visitor.visitMethod(this); }, get type() { return METHOD; } }, {}, $__super); }(ParseTree); var METHOD_SIGNATURE = ParseTreeType.METHOD_SIGNATURE; var MethodSignature = function($__super) { function MethodSignature(location, name, optional, callSignature) { $traceurRuntime.superConstructor(MethodSignature).call(this, location); this.name = name; this.optional = optional; this.callSignature = callSignature; } return ($traceurRuntime.createClass)(MethodSignature, { transform: function(transformer) { return transformer.transformMethodSignature(this); }, visit: function(visitor) { visitor.visitMethodSignature(this); }, get type() { return METHOD_SIGNATURE; } }, {}, $__super); }(ParseTree); var MODULE = ParseTreeType.MODULE; var Module = function($__super) { function Module(location, scriptItemList, moduleName) { $traceurRuntime.superConstructor(Module).call(this, location); this.scriptItemList = scriptItemList; this.moduleName = moduleName; } return ($traceurRuntime.createClass)(Module, { transform: function(transformer) { return transformer.transformModule(this); }, visit: function(visitor) { visitor.visitModule(this); }, get type() { return MODULE; } }, {}, $__super); }(ParseTree); var MODULE_SPECIFIER = ParseTreeType.MODULE_SPECIFIER; var ModuleSpecifier = function($__super) { function ModuleSpecifier(location, token) { $traceurRuntime.superConstructor(ModuleSpecifier).call(this, location); this.token = token; } return ($traceurRuntime.createClass)(ModuleSpecifier, { transform: function(transformer) { return transformer.transformModuleSpecifier(this); }, visit: function(visitor) { visitor.visitModuleSpecifier(this); }, get type() { return MODULE_SPECIFIER; } }, {}, $__super); }(ParseTree); var NAME_SPACE_EXPORT = ParseTreeType.NAME_SPACE_EXPORT; var NameSpaceExport = function($__super) { function NameSpaceExport(location, name) { $traceurRuntime.superConstructor(NameSpaceExport).call(this, location); this.name = name; } return ($traceurRuntime.createClass)(NameSpaceExport, { transform: function(transformer) { return transformer.transformNameSpaceExport(this); }, visit: function(visitor) { visitor.visitNameSpaceExport(this); }, get type() { return NAME_SPACE_EXPORT; } }, {}, $__super); }(ParseTree); var NAME_SPACE_IMPORT = ParseTreeType.NAME_SPACE_IMPORT; var NameSpaceImport = function($__super) { function NameSpaceImport(location, binding) { $traceurRuntime.superConstructor(NameSpaceImport).call(this, location); this.binding = binding; } return ($traceurRuntime.createClass)(NameSpaceImport, { transform: function(transformer) { return transformer.transformNameSpaceImport(this); }, visit: function(visitor) { visitor.visitNameSpaceImport(this); }, get type() { return NAME_SPACE_IMPORT; } }, {}, $__super); }(ParseTree); var NAMED_EXPORT = ParseTreeType.NAMED_EXPORT; var NamedExport = function($__super) { function NamedExport(location, exportClause, moduleSpecifier) { $traceurRuntime.superConstructor(NamedExport).call(this, location); this.exportClause = exportClause; this.moduleSpecifier = moduleSpecifier; } return ($traceurRuntime.createClass)(NamedExport, { transform: function(transformer) { return transformer.transformNamedExport(this); }, visit: function(visitor) { visitor.visitNamedExport(this); }, get type() { return NAMED_EXPORT; } }, {}, $__super); }(ParseTree); var NEW_EXPRESSION = ParseTreeType.NEW_EXPRESSION; var NewExpression = function($__super) { function NewExpression(location, operand, args) { $traceurRuntime.superConstructor(NewExpression).call(this, location); this.operand = operand; this.args = args; } return ($traceurRuntime.createClass)(NewExpression, { transform: function(transformer) { return transformer.transformNewExpression(this); }, visit: function(visitor) { visitor.visitNewExpression(this); }, get type() { return NEW_EXPRESSION; } }, {}, $__super); }(ParseTree); var OBJECT_LITERAL = ParseTreeType.OBJECT_LITERAL; var ObjectLiteral = function($__super) { function ObjectLiteral(location, propertyNameAndValues) { $traceurRuntime.superConstructor(ObjectLiteral).call(this, location); this.propertyNameAndValues = propertyNameAndValues; } return ($traceurRuntime.createClass)(ObjectLiteral, { transform: function(transformer) { return transformer.transformObjectLiteral(this); }, visit: function(visitor) { visitor.visitObjectLiteral(this); }, get type() { return OBJECT_LITERAL; } }, {}, $__super); }(ParseTree); var OBJECT_PATTERN = ParseTreeType.OBJECT_PATTERN; var ObjectPattern = function($__super) { function ObjectPattern(location, fields) { $traceurRuntime.superConstructor(ObjectPattern).call(this, location); this.fields = fields; } return ($traceurRuntime.createClass)(ObjectPattern, { transform: function(transformer) { return transformer.transformObjectPattern(this); }, visit: function(visitor) { visitor.visitObjectPattern(this); }, get type() { return OBJECT_PATTERN; } }, {}, $__super); }(ParseTree); var OBJECT_PATTERN_FIELD = ParseTreeType.OBJECT_PATTERN_FIELD; var ObjectPatternField = function($__super) { function ObjectPatternField(location, name, element) { $traceurRuntime.superConstructor(ObjectPatternField).call(this, location); this.name = name; this.element = element; } return ($traceurRuntime.createClass)(ObjectPatternField, { transform: function(transformer) { return transformer.transformObjectPatternField(this); }, visit: function(visitor) { visitor.visitObjectPatternField(this); }, get type() { return OBJECT_PATTERN_FIELD; } }, {}, $__super); }(ParseTree); var OBJECT_TYPE = ParseTreeType.OBJECT_TYPE; var ObjectType = function($__super) { function ObjectType(location, typeMembers) { $traceurRuntime.superConstructor(ObjectType).call(this, location); this.typeMembers = typeMembers; } return ($traceurRuntime.createClass)(ObjectType, { transform: function(transformer) { return transformer.transformObjectType(this); }, visit: function(visitor) { visitor.visitObjectType(this); }, get type() { return OBJECT_TYPE; } }, {}, $__super); }(ParseTree); var PAREN_EXPRESSION = ParseTreeType.PAREN_EXPRESSION; var ParenExpression = function($__super) { function ParenExpression(location, expression) { $traceurRuntime.superConstructor(ParenExpression).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(ParenExpression, { transform: function(transformer) { return transformer.transformParenExpression(this); }, visit: function(visitor) { visitor.visitParenExpression(this); }, get type() { return PAREN_EXPRESSION; } }, {}, $__super); }(ParseTree); var POSTFIX_EXPRESSION = ParseTreeType.POSTFIX_EXPRESSION; var PostfixExpression = function($__super) { function PostfixExpression(location, operand, operator) { $traceurRuntime.superConstructor(PostfixExpression).call(this, location); this.operand = operand; this.operator = operator; } return ($traceurRuntime.createClass)(PostfixExpression, { transform: function(transformer) { return transformer.transformPostfixExpression(this); }, visit: function(visitor) { visitor.visitPostfixExpression(this); }, get type() { return POSTFIX_EXPRESSION; } }, {}, $__super); }(ParseTree); var PREDEFINED_TYPE = ParseTreeType.PREDEFINED_TYPE; var PredefinedType = function($__super) { function PredefinedType(location, typeToken) { $traceurRuntime.superConstructor(PredefinedType).call(this, location); this.typeToken = typeToken; } return ($traceurRuntime.createClass)(PredefinedType, { transform: function(transformer) { return transformer.transformPredefinedType(this); }, visit: function(visitor) { visitor.visitPredefinedType(this); }, get type() { return PREDEFINED_TYPE; } }, {}, $__super); }(ParseTree); var SCRIPT = ParseTreeType.SCRIPT; var Script = function($__super) { function Script(location, scriptItemList, moduleName) { $traceurRuntime.superConstructor(Script).call(this, location); this.scriptItemList = scriptItemList; this.moduleName = moduleName; } return ($traceurRuntime.createClass)(Script, { transform: function(transformer) { return transformer.transformScript(this); }, visit: function(visitor) { visitor.visitScript(this); }, get type() { return SCRIPT; } }, {}, $__super); }(ParseTree); var PROPERTY_NAME_ASSIGNMENT = ParseTreeType.PROPERTY_NAME_ASSIGNMENT; var PropertyNameAssignment = function($__super) { function PropertyNameAssignment(location, name, value) { $traceurRuntime.superConstructor(PropertyNameAssignment).call(this, location); this.name = name; this.value = value; } return ($traceurRuntime.createClass)(PropertyNameAssignment, { transform: function(transformer) { return transformer.transformPropertyNameAssignment(this); }, visit: function(visitor) { visitor.visitPropertyNameAssignment(this); }, get type() { return PROPERTY_NAME_ASSIGNMENT; } }, {}, $__super); }(ParseTree); var PROPERTY_NAME_SHORTHAND = ParseTreeType.PROPERTY_NAME_SHORTHAND; var PropertyNameShorthand = function($__super) { function PropertyNameShorthand(location, name) { $traceurRuntime.superConstructor(PropertyNameShorthand).call(this, location); this.name = name; } return ($traceurRuntime.createClass)(PropertyNameShorthand, { transform: function(transformer) { return transformer.transformPropertyNameShorthand(this); }, visit: function(visitor) { visitor.visitPropertyNameShorthand(this); }, get type() { return PROPERTY_NAME_SHORTHAND; } }, {}, $__super); }(ParseTree); var PROPERTY_VARIABLE_DECLARATION = ParseTreeType.PROPERTY_VARIABLE_DECLARATION; var PropertyVariableDeclaration = function($__super) { function PropertyVariableDeclaration(location, isStatic, name, typeAnnotation, annotations, initializer) { $traceurRuntime.superConstructor(PropertyVariableDeclaration).call(this, location); this.isStatic = isStatic; this.name = name; this.typeAnnotation = typeAnnotation; this.annotations = annotations; this.initializer = initializer; } return ($traceurRuntime.createClass)(PropertyVariableDeclaration, { transform: function(transformer) { return transformer.transformPropertyVariableDeclaration(this); }, visit: function(visitor) { visitor.visitPropertyVariableDeclaration(this); }, get type() { return PROPERTY_VARIABLE_DECLARATION; } }, {}, $__super); }(ParseTree); var PROPERTY_SIGNATURE = ParseTreeType.PROPERTY_SIGNATURE; var PropertySignature = function($__super) { function PropertySignature(location, name, optional, typeAnnotation) { $traceurRuntime.superConstructor(PropertySignature).call(this, location); this.name = name; this.optional = optional; this.typeAnnotation = typeAnnotation; } return ($traceurRuntime.createClass)(PropertySignature, { transform: function(transformer) { return transformer.transformPropertySignature(this); }, visit: function(visitor) { visitor.visitPropertySignature(this); }, get type() { return PROPERTY_SIGNATURE; } }, {}, $__super); }(ParseTree); var REST_PARAMETER = ParseTreeType.REST_PARAMETER; var RestParameter = function($__super) { function RestParameter(location, identifier) { $traceurRuntime.superConstructor(RestParameter).call(this, location); this.identifier = identifier; } return ($traceurRuntime.createClass)(RestParameter, { transform: function(transformer) { return transformer.transformRestParameter(this); }, visit: function(visitor) { visitor.visitRestParameter(this); }, get type() { return REST_PARAMETER; } }, {}, $__super); }(ParseTree); var RETURN_STATEMENT = ParseTreeType.RETURN_STATEMENT; var ReturnStatement = function($__super) { function ReturnStatement(location, expression) { $traceurRuntime.superConstructor(ReturnStatement).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(ReturnStatement, { transform: function(transformer) { return transformer.transformReturnStatement(this); }, visit: function(visitor) { visitor.visitReturnStatement(this); }, get type() { return RETURN_STATEMENT; } }, {}, $__super); }(ParseTree); var SET_ACCESSOR = ParseTreeType.SET_ACCESSOR; var SetAccessor = function($__super) { function SetAccessor(location, isStatic, name, parameterList, annotations, body) { $traceurRuntime.superConstructor(SetAccessor).call(this, location); this.isStatic = isStatic; this.name = name; this.parameterList = parameterList; this.annotations = annotations; this.body = body; } return ($traceurRuntime.createClass)(SetAccessor, { transform: function(transformer) { return transformer.transformSetAccessor(this); }, visit: function(visitor) { visitor.visitSetAccessor(this); }, get type() { return SET_ACCESSOR; } }, {}, $__super); }(ParseTree); var SPREAD_EXPRESSION = ParseTreeType.SPREAD_EXPRESSION; var SpreadExpression = function($__super) { function SpreadExpression(location, expression) { $traceurRuntime.superConstructor(SpreadExpression).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(SpreadExpression, { transform: function(transformer) { return transformer.transformSpreadExpression(this); }, visit: function(visitor) { visitor.visitSpreadExpression(this); }, get type() { return SPREAD_EXPRESSION; } }, {}, $__super); }(ParseTree); var SPREAD_PATTERN_ELEMENT = ParseTreeType.SPREAD_PATTERN_ELEMENT; var SpreadPatternElement = function($__super) { function SpreadPatternElement(location, lvalue) { $traceurRuntime.superConstructor(SpreadPatternElement).call(this, location); this.lvalue = lvalue; } return ($traceurRuntime.createClass)(SpreadPatternElement, { transform: function(transformer) { return transformer.transformSpreadPatternElement(this); }, visit: function(visitor) { visitor.visitSpreadPatternElement(this); }, get type() { return SPREAD_PATTERN_ELEMENT; } }, {}, $__super); }(ParseTree); var SUPER_EXPRESSION = ParseTreeType.SUPER_EXPRESSION; var SuperExpression = function($__super) { function SuperExpression(location) { $traceurRuntime.superConstructor(SuperExpression).call(this, location); } return ($traceurRuntime.createClass)(SuperExpression, { transform: function(transformer) { return transformer.transformSuperExpression(this); }, visit: function(visitor) { visitor.visitSuperExpression(this); }, get type() { return SUPER_EXPRESSION; } }, {}, $__super); }(ParseTree); var SWITCH_STATEMENT = ParseTreeType.SWITCH_STATEMENT; var SwitchStatement = function($__super) { function SwitchStatement(location, expression, caseClauses) { $traceurRuntime.superConstructor(SwitchStatement).call(this, location); this.expression = expression; this.caseClauses = caseClauses; } return ($traceurRuntime.createClass)(SwitchStatement, { transform: function(transformer) { return transformer.transformSwitchStatement(this); }, visit: function(visitor) { visitor.visitSwitchStatement(this); }, get type() { return SWITCH_STATEMENT; } }, {}, $__super); }(ParseTree); var SYNTAX_ERROR_TREE = ParseTreeType.SYNTAX_ERROR_TREE; var SyntaxErrorTree = function($__super) { function SyntaxErrorTree(location, nextToken, message) { $traceurRuntime.superConstructor(SyntaxErrorTree).call(this, location); this.nextToken = nextToken; this.message = message; } return ($traceurRuntime.createClass)(SyntaxErrorTree, { transform: function(transformer) { return transformer.transformSyntaxErrorTree(this); }, visit: function(visitor) { visitor.visitSyntaxErrorTree(this); }, get type() { return SYNTAX_ERROR_TREE; } }, {}, $__super); }(ParseTree); var TEMPLATE_LITERAL_EXPRESSION = ParseTreeType.TEMPLATE_LITERAL_EXPRESSION; var TemplateLiteralExpression = function($__super) { function TemplateLiteralExpression(location, operand, elements) { $traceurRuntime.superConstructor(TemplateLiteralExpression).call(this, location); this.operand = operand; this.elements = elements; } return ($traceurRuntime.createClass)(TemplateLiteralExpression, { transform: function(transformer) { return transformer.transformTemplateLiteralExpression(this); }, visit: function(visitor) { visitor.visitTemplateLiteralExpression(this); }, get type() { return TEMPLATE_LITERAL_EXPRESSION; } }, {}, $__super); }(ParseTree); var TEMPLATE_LITERAL_PORTION = ParseTreeType.TEMPLATE_LITERAL_PORTION; var TemplateLiteralPortion = function($__super) { function TemplateLiteralPortion(location, value) { $traceurRuntime.superConstructor(TemplateLiteralPortion).call(this, location); this.value = value; } return ($traceurRuntime.createClass)(TemplateLiteralPortion, { transform: function(transformer) { return transformer.transformTemplateLiteralPortion(this); }, visit: function(visitor) { visitor.visitTemplateLiteralPortion(this); }, get type() { return TEMPLATE_LITERAL_PORTION; } }, {}, $__super); }(ParseTree); var TEMPLATE_SUBSTITUTION = ParseTreeType.TEMPLATE_SUBSTITUTION; var TemplateSubstitution = function($__super) { function TemplateSubstitution(location, expression) { $traceurRuntime.superConstructor(TemplateSubstitution).call(this, location); this.expression = expression; } return ($traceurRuntime.createClass)(TemplateSubstitution, { transform: function(transformer) { return transformer.transformTemplateSubstitution(this); }, visit: function(visitor) { visitor.visitTemplateSubstitution(this); }, get type() { return TEMPLATE_SUBSTITUTION; } }, {}, $__super); }(ParseTree); var THIS_EXPRESSION = ParseTreeType.THIS_EXPRESSION; var ThisExpression = function($__super) { function ThisExpression(location) { $traceurRuntime.superConstructor(ThisExpression).call(this, location); } return ($traceurRuntime.createClass)(ThisExpression, { transform: function(transformer) { return transformer.transformThisExpression(this); }, visit: function(visitor) { visitor.visitThisExpression(this); }, get type() { return THIS_EXPRESSION; } }, {}, $__super); }(ParseTree); var THROW_STATEMENT = ParseTreeType.THROW_STATEMENT; var ThrowStatement = function($__super) { function ThrowStatement(location, value) { $traceurRuntime.superConstructor(ThrowStatement).call(this, location); this.value = value; } return ($traceurRuntime.createClass)(ThrowStatement, { transform: function(transformer) { return transformer.transformThrowStatement(this); }, visit: function(visitor) { visitor.visitThrowStatement(this); }, get type() { return THROW_STATEMENT; } }, {}, $__super); }(ParseTree); var TRY_STATEMENT = ParseTreeType.TRY_STATEMENT; var TryStatement = function($__super) { function TryStatement(location, body, catchBlock, finallyBlock) { $traceurRuntime.superConstructor(TryStatement).call(this, location); this.body = body; this.catchBlock = catchBlock; this.finallyBlock = finallyBlock; } return ($traceurRuntime.createClass)(TryStatement, { transform: function(transformer) { return transformer.transformTryStatement(this); }, visit: function(visitor) { visitor.visitTryStatement(this); }, get type() { return TRY_STATEMENT; } }, {}, $__super); }(ParseTree); var TYPE_ALIAS_DECLARATION = ParseTreeType.TYPE_ALIAS_DECLARATION; var TypeAliasDeclaration = function($__super) { function TypeAliasDeclaration(location, name, value) { $traceurRuntime.superConstructor(TypeAliasDeclaration).call(this, location); this.name = name; this.value = value; } return ($traceurRuntime.createClass)(TypeAliasDeclaration, { transform: function(transformer) { return transformer.transformTypeAliasDeclaration(this); }, visit: function(visitor) { visitor.visitTypeAliasDeclaration(this); }, get type() { return TYPE_ALIAS_DECLARATION; } }, {}, $__super); }(ParseTree); var TYPE_ARGUMENTS = ParseTreeType.TYPE_ARGUMENTS; var TypeArguments = function($__super) { function TypeArguments(location, args) { $traceurRuntime.superConstructor(TypeArguments).call(this, location); this.args = args; } return ($traceurRuntime.createClass)(TypeArguments, { transform: function(transformer) { return transformer.transformTypeArguments(this); }, visit: function(visitor) { visitor.visitTypeArguments(this); }, get type() { return TYPE_ARGUMENTS; } }, {}, $__super); }(ParseTree); var TYPE_NAME = ParseTreeType.TYPE_NAME; var TypeName = function($__super) { function TypeName(location, moduleName, name) { $traceurRuntime.superConstructor(TypeName).call(this, location); this.moduleName = moduleName; this.name = name; } return ($traceurRuntime.createClass)(TypeName, { transform: function(transformer) { return transformer.transformTypeName(this); }, visit: function(visitor) { visitor.visitTypeName(this); }, get type() { return TYPE_NAME; } }, {}, $__super); }(ParseTree); var TYPE_PARAMETER = ParseTreeType.TYPE_PARAMETER; var TypeParameter = function($__super) { function TypeParameter(location, identifierToken, extendsType) { $traceurRuntime.superConstructor(TypeParameter).call(this, location); this.identifierToken = identifierToken; this.extendsType = extendsType; } return ($traceurRuntime.createClass)(TypeParameter, { transform: function(transformer) { return transformer.transformTypeParameter(this); }, visit: function(visitor) { visitor.visitTypeParameter(this); }, get type() { return TYPE_PARAMETER; } }, {}, $__super); }(ParseTree); var TYPE_PARAMETERS = ParseTreeType.TYPE_PARAMETERS; var TypeParameters = function($__super) { function TypeParameters(location, parameters) { $traceurRuntime.superConstructor(TypeParameters).call(this, location); this.parameters = parameters; } return ($traceurRuntime.createClass)(TypeParameters, { transform: function(transformer) { return transformer.transformTypeParameters(this); }, visit: function(visitor) { visitor.visitTypeParameters(this); }, get type() { return TYPE_PARAMETERS; } }, {}, $__super); }(ParseTree); var TYPE_REFERENCE = ParseTreeType.TYPE_REFERENCE; var TypeReference = function($__super) { function TypeReference(location, typeName, args) { $traceurRuntime.superConstructor(TypeReference).call(this, location); this.typeName = typeName; this.args = args; } return ($traceurRuntime.createClass)(TypeReference, { transform: function(transformer) { return transformer.transformTypeReference(this); }, visit: function(visitor) { visitor.visitTypeReference(this); }, get type() { return TYPE_REFERENCE; } }, {}, $__super); }(ParseTree); var UNARY_EXPRESSION = ParseTreeType.UNARY_EXPRESSION; var UnaryExpression = function($__super) { function UnaryExpression(location, operator, operand) { $traceurRuntime.superConstructor(UnaryExpression).call(this, location); this.operator = operator; this.operand = operand; } return ($traceurRuntime.createClass)(UnaryExpression, { transform: function(transformer) { return transformer.transformUnaryExpression(this); }, visit: function(visitor) { visitor.visitUnaryExpression(this); }, get type() { return UNARY_EXPRESSION; } }, {}, $__super); }(ParseTree); var UNION_TYPE = ParseTreeType.UNION_TYPE; var UnionType = function($__super) { function UnionType(location, types) { $traceurRuntime.superConstructor(UnionType).call(this, location); this.types = types; } return ($traceurRuntime.createClass)(UnionType, { transform: function(transformer) { return transformer.transformUnionType(this); }, visit: function(visitor) { visitor.visitUnionType(this); }, get type() { return UNION_TYPE; } }, {}, $__super); }(ParseTree); var VARIABLE_DECLARATION = ParseTreeType.VARIABLE_DECLARATION; var VariableDeclaration = function($__super) { function VariableDeclaration(location, lvalue, typeAnnotation, initializer) { $traceurRuntime.superConstructor(VariableDeclaration).call(this, location); this.lvalue = lvalue; this.typeAnnotation = typeAnnotation; this.initializer = initializer; } return ($traceurRuntime.createClass)(VariableDeclaration, { transform: function(transformer) { return transformer.transformVariableDeclaration(this); }, visit: function(visitor) { visitor.visitVariableDeclaration(this); }, get type() { return VARIABLE_DECLARATION; } }, {}, $__super); }(ParseTree); var VARIABLE_DECLARATION_LIST = ParseTreeType.VARIABLE_DECLARATION_LIST; var VariableDeclarationList = function($__super) { function VariableDeclarationList(location, declarationType, declarations) { $traceurRuntime.superConstructor(VariableDeclarationList).call(this, location); this.declarationType = declarationType; this.declarations = declarations; } return ($traceurRuntime.createClass)(VariableDeclarationList, { transform: function(transformer) { return transformer.transformVariableDeclarationList(this); }, visit: function(visitor) { visitor.visitVariableDeclarationList(this); }, get type() { return VARIABLE_DECLARATION_LIST; } }, {}, $__super); }(ParseTree); var VARIABLE_STATEMENT = ParseTreeType.VARIABLE_STATEMENT; var VariableStatement = function($__super) { function VariableStatement(location, declarations) { $traceurRuntime.superConstructor(VariableStatement).call(this, location); this.declarations = declarations; } return ($traceurRuntime.createClass)(VariableStatement, { transform: function(transformer) { return transformer.transformVariableStatement(this); }, visit: function(visitor) { visitor.visitVariableStatement(this); }, get type() { return VARIABLE_STATEMENT; } }, {}, $__super); }(ParseTree); var WHILE_STATEMENT = ParseTreeType.WHILE_STATEMENT; var WhileStatement = function($__super) { function WhileStatement(location, condition, body) { $traceurRuntime.superConstructor(WhileStatement).call(this, location); this.condition = condition; this.body = body; } return ($traceurRuntime.createClass)(WhileStatement, { transform: function(transformer) { return transformer.transformWhileStatement(this); }, visit: function(visitor) { visitor.visitWhileStatement(this); }, get type() { return WHILE_STATEMENT; } }, {}, $__super); }(ParseTree); var WITH_STATEMENT = ParseTreeType.WITH_STATEMENT; var WithStatement = function($__super) { function WithStatement(location, expression, body) { $traceurRuntime.superConstructor(WithStatement).call(this, location); this.expression = expression; this.body = body; } return ($traceurRuntime.createClass)(WithStatement, { transform: function(transformer) { return transformer.transformWithStatement(this); }, visit: function(visitor) { visitor.visitWithStatement(this); }, get type() { return WITH_STATEMENT; } }, {}, $__super); }(ParseTree); var YIELD_EXPRESSION = ParseTreeType.YIELD_EXPRESSION; var YieldExpression = function($__super) { function YieldExpression(location, expression, isYieldFor) { $traceurRuntime.superConstructor(YieldExpression).call(this, location); this.expression = expression; this.isYieldFor = isYieldFor; } return ($traceurRuntime.createClass)(YieldExpression, { transform: function(transformer) { return transformer.transformYieldExpression(this); }, visit: function(visitor) { visitor.visitYieldExpression(this); }, get type() { return YIELD_EXPRESSION; } }, {}, $__super); }(ParseTree); Object.defineProperties(module.exports, { Annotation: {get: function() { return Annotation; }}, AnonBlock: {get: function() { return AnonBlock; }}, ArgumentList: {get: function() { return ArgumentList; }}, ArrayComprehension: {get: function() { return ArrayComprehension; }}, ArrayLiteral: {get: function() { return ArrayLiteral; }}, ArrayPattern: {get: function() { return ArrayPattern; }}, ArrayType: {get: function() { return ArrayType; }}, ArrowFunction: {get: function() { return ArrowFunction; }}, AssignmentElement: {get: function() { return AssignmentElement; }}, AwaitExpression: {get: function() { return AwaitExpression; }}, BinaryExpression: {get: function() { return BinaryExpression; }}, BindingElement: {get: function() { return BindingElement; }}, BindingIdentifier: {get: function() { return BindingIdentifier; }}, Block: {get: function() { return Block; }}, BreakStatement: {get: function() { return BreakStatement; }}, CallExpression: {get: function() { return CallExpression; }}, CallSignature: {get: function() { return CallSignature; }}, CaseClause: {get: function() { return CaseClause; }}, Catch: {get: function() { return Catch; }}, ClassDeclaration: {get: function() { return ClassDeclaration; }}, ClassExpression: {get: function() { return ClassExpression; }}, CommaExpression: {get: function() { return CommaExpression; }}, ComprehensionFor: {get: function() { return ComprehensionFor; }}, ComprehensionIf: {get: function() { return ComprehensionIf; }}, ComputedPropertyName: {get: function() { return ComputedPropertyName; }}, ConditionalExpression: {get: function() { return ConditionalExpression; }}, ConstructSignature: {get: function() { return ConstructSignature; }}, ConstructorType: {get: function() { return ConstructorType; }}, ContinueStatement: {get: function() { return ContinueStatement; }}, CoverFormals: {get: function() { return CoverFormals; }}, CoverInitializedName: {get: function() { return CoverInitializedName; }}, DebuggerStatement: {get: function() { return DebuggerStatement; }}, DefaultClause: {get: function() { return DefaultClause; }}, DoWhileStatement: {get: function() { return DoWhileStatement; }}, EmptyStatement: {get: function() { return EmptyStatement; }}, ExportDeclaration: {get: function() { return ExportDeclaration; }}, ExportDefault: {get: function() { return ExportDefault; }}, ExportSpecifier: {get: function() { return ExportSpecifier; }}, ExportSpecifierSet: {get: function() { return ExportSpecifierSet; }}, ExportStar: {get: function() { return ExportStar; }}, ExpressionStatement: {get: function() { return ExpressionStatement; }}, Finally: {get: function() { return Finally; }}, ForInStatement: {get: function() { return ForInStatement; }}, ForOfStatement: {get: function() { return ForOfStatement; }}, ForOnStatement: {get: function() { return ForOnStatement; }}, ForStatement: {get: function() { return ForStatement; }}, FormalParameter: {get: function() { return FormalParameter; }}, FormalParameterList: {get: function() { return FormalParameterList; }}, ForwardDefaultExport: {get: function() { return ForwardDefaultExport; }}, FunctionBody: {get: function() { return FunctionBody; }}, FunctionDeclaration: {get: function() { return FunctionDeclaration; }}, FunctionExpression: {get: function() { return FunctionExpression; }}, FunctionType: {get: function() { return FunctionType; }}, GeneratorComprehension: {get: function() { return GeneratorComprehension; }}, GetAccessor: {get: function() { return GetAccessor; }}, IdentifierExpression: {get: function() { return IdentifierExpression; }}, IfStatement: {get: function() { return IfStatement; }}, ImportedBinding: {get: function() { return ImportedBinding; }}, ImportClausePair: {get: function() { return ImportClausePair; }}, ImportDeclaration: {get: function() { return ImportDeclaration; }}, ImportSpecifier: {get: function() { return ImportSpecifier; }}, ImportSpecifierSet: {get: function() { return ImportSpecifierSet; }}, ImportTypeClause: {get: function() { return ImportTypeClause; }}, IndexSignature: {get: function() { return IndexSignature; }}, InterfaceDeclaration: {get: function() { return InterfaceDeclaration; }}, JsxAttribute: {get: function() { return JsxAttribute; }}, JsxElement: {get: function() { return JsxElement; }}, JsxElementName: {get: function() { return JsxElementName; }}, JsxPlaceholder: {get: function() { return JsxPlaceholder; }}, JsxText: {get: function() { return JsxText; }}, LabelledStatement: {get: function() { return LabelledStatement; }}, LiteralExpression: {get: function() { return LiteralExpression; }}, LiteralPropertyName: {get: function() { return LiteralPropertyName; }}, MemberExpression: {get: function() { return MemberExpression; }}, MemberLookupExpression: {get: function() { return MemberLookupExpression; }}, Method: {get: function() { return Method; }}, MethodSignature: {get: function() { return MethodSignature; }}, Module: {get: function() { return Module; }}, ModuleSpecifier: {get: function() { return ModuleSpecifier; }}, NameSpaceExport: {get: function() { return NameSpaceExport; }}, NameSpaceImport: {get: function() { return NameSpaceImport; }}, NamedExport: {get: function() { return NamedExport; }}, NewExpression: {get: function() { return NewExpression; }}, ObjectLiteral: {get: function() { return ObjectLiteral; }}, ObjectPattern: {get: function() { return ObjectPattern; }}, ObjectPatternField: {get: function() { return ObjectPatternField; }}, ObjectType: {get: function() { return ObjectType; }}, ParenExpression: {get: function() { return ParenExpression; }}, PostfixExpression: {get: function() { return PostfixExpression; }}, PredefinedType: {get: function() { return PredefinedType; }}, Script: {get: function() { return Script; }}, PropertyNameAssignment: {get: function() { return PropertyNameAssignment; }}, PropertyNameShorthand: {get: function() { return PropertyNameShorthand; }}, PropertyVariableDeclaration: {get: function() { return PropertyVariableDeclaration; }}, PropertySignature: {get: function() { return PropertySignature; }}, RestParameter: {get: function() { return RestParameter; }}, ReturnStatement: {get: function() { return ReturnStatement; }}, SetAccessor: {get: function() { return SetAccessor; }}, SpreadExpression: {get: function() { return SpreadExpression; }}, SpreadPatternElement: {get: function() { return SpreadPatternElement; }}, SuperExpression: {get: function() { return SuperExpression; }}, SwitchStatement: {get: function() { return SwitchStatement; }}, SyntaxErrorTree: {get: function() { return SyntaxErrorTree; }}, TemplateLiteralExpression: {get: function() { return TemplateLiteralExpression; }}, TemplateLiteralPortion: {get: function() { return TemplateLiteralPortion; }}, TemplateSubstitution: {get: function() { return TemplateSubstitution; }}, ThisExpression: {get: function() { return ThisExpression; }}, ThrowStatement: {get: function() { return ThrowStatement; }}, TryStatement: {get: function() { return TryStatement; }}, TypeAliasDeclaration: {get: function() { return TypeAliasDeclaration; }}, TypeArguments: {get: function() { return TypeArguments; }}, TypeName: {get: function() { return TypeName; }}, TypeParameter: {get: function() { return TypeParameter; }}, TypeParameters: {get: function() { return TypeParameters; }}, TypeReference: {get: function() { return TypeReference; }}, UnaryExpression: {get: function() { return UnaryExpression; }}, UnionType: {get: function() { return UnionType; }}, VariableDeclaration: {get: function() { return VariableDeclaration; }}, VariableDeclarationList: {get: function() { return VariableDeclarationList; }}, VariableStatement: {get: function() { return VariableStatement; }}, WhileStatement: {get: function() { return WhileStatement; }}, WithStatement: {get: function() { return WithStatement; }}, YieldExpression: {get: function() { return YieldExpression; }}, __esModule: {value: true} });
module.exports = require('./lib/release');
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 3.3.1 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { return function () { vertxNext(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = require; var vertx = r('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && typeof require === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); _resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { asap(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { _resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; _reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; _reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { _reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return _resolve(promise, value); }, function (reason) { return _reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable); } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error); } else if (then$$ === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$); } else { fulfill(promise, maybeThenable); } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function _reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { _reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { _resolve(promise, value); } else if (failed) { _reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { _reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value); }, function rejectPromise(reason) { _reject(promise, reason); }); } catch (e) { _reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { _reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._enumerate = function () { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$) { return resolve$$(entry); }), i); } } else { this._willSettleAt(resolve$$(entry), i); } }; Enumerator.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; function polyfill() { var local = undefined; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise; } polyfill(); // Strange compat.. Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise; }))); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":2}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],3:[function(require,module,exports){ "use strict"; var tools = require("../helpers/tools"); var Events = require("../core/Events"); var LikeFormData = require("../helpers/LikeFormData"); /** * This is an Ajax transport. * Supports XDomainRequest for old IE * @param {Object} [options] * @param {Object} [options.headers] Headers to add to the instance * @fires beforeSend event that will be performed before request is send. Event called with one parameter "options", that contains all variables for Ajax * @constructor */ var Ajax = function (options) { this.currentRequests = 0; this.events = new Events(["beforeSend", 'load']); if (options && options.headers) { this.headers = Object.assign(this.headers, options.headers); } }; /** * Default headers. You can overwrite it. Look at the event beforeSend * Please note that on XDomainRequest we can't send any headers. * @type Object */ Ajax.prototype.headers = { 'X-Requested-With': 'XMLHttpRequest' }; /** * Send ajax request to server * Will return promise or array with promise and XMLHttpRequest : {window.Promise|[window.Promise,XMLHttpRequest]} * @since 0.4.0 * @param {Object} options object with options * @param {String} options.url url to send data * @param {Object|String} [options.data] data to send * @param {String} [options.method] * @param {Object} [options.headers] headers to add to the request * @param {Function} [options.onProgress] callback function on progress. Two callback options: current bytes sent,totalBytes * @param {Function} [options.isReturnXHRToo===false] should method return array instead of Promise. Some times is needed to control ajax (abort, etc). If tree then [window.Promise,XMLHttpRequest ] will be returned * @returns {Promise|Array} */ Ajax.prototype.send = function (options) { var that = this; //TODO why we check here if data === null then reassign to null again? if (options.data === null || options.data === void 0 || options.data === 'undefined') { options.data = null; } if (!options.method) { options.method = "POST" } options.headers = options.headers ? Object.assign(options.headers, this.headers, options.headers) : Object.assign({}, this.headers); var xhr; var ajaxPromise = new Promise(function (resolve, reject) { // Return a new promise. if (!options.url) { console.error("You should provide url"); reject("You should provide url"); } that.currentRequests++; var oldIE = false; if ((typeof window !== 'undefined') && window.XDomainRequest && (window.XMLHttpRequest && new XMLHttpRequest().responseType === undefined) && (url.indexOf("http") === 0)) {//old IE CORS //TODO maybe we should use XDomainRequest only for cross domain requests? But Spiral for now works great with XDomainRequest (based on IEJSON) xhr = new XDomainRequest(); //http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx oldIE = true; //http://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment xhr.onprogress = function (e) { //TODO adjust options options.onProgress && options.onProgress(e); }; } else { xhr = new XMLHttpRequest(); if (options.onProgress) { xhr.upload.addEventListener("progress", function (event) { if (event.lengthComputable) { options.onProgress(event.loaded, event.total); } }, false); } } xhr.open(options.method, options.url); xhr.onload = function () {//On loaded that.currentRequests--; var ans = that._parseJSON(xhr); if (ans.status) { if (ans.status > 199 && ans.status < 300) {//200-299 resolve(ans); } else if (ans.status > 399 && ans.status < 600) {//400-599 reject(ans); } else { console.error("unknown status %d. Rejecting", ans.status); reject(ans); } } else if (oldIE) { resolve(ans);//OLD IE + downloading file is producing no status. } else { reject(ans);//reject with the status text } options.response = ans; that.events.trigger("load", options);//for example - used to handle actions }; xhr.onerror = function () {// Handle network errors that.currentRequests--; reject(Error("Network Error"), xhr); }; that.events.trigger("beforeSend", options);//you can modify "options" object inside event (like adding you headers,data,etc) var dataToSend; if (options.data !== null) {//if data to send is not empty if (!oldIE) { if (options.data.toString().indexOf("FormData") !== -1) {//if form data dataToSend = options.data; } else { dataToSend = new LikeFormData(options.data); options.headers["content-type"] = dataToSend.getContentTypeHeader(); } that._setHeaders(xhr, options.headers); } else { dataToSend = "IEJSON" + JSON.stringify(options.data); } } else {//else send empty data dataToSend = null; } // if (!oldIE) { // //xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // dataToSend = new spiral.LikeFormData(data, xhr, oldIE); // } else { // if (data !==null && data !== void 0 && data !== 'undefined'){ // dataToSend = "IEJSON"+JSON.stringify(data); // } else { // dataToSend =data; // } // // } try {//working around FF bug xhr.send(dataToSend);// Make the request } catch (e) { //console.error("error sending trying another method"); xhr.send(dataToSend.toString()); } return xhr; }); if (options.isReturnXHRToo){//return xhr too return [ajaxPromise,xhr] } return ajaxPromise; }; /** * Iterate over headers object and call xhr.setRequestHeader * @param {XMLHttpRequest} xhr * @param {Object} headers object with headers to set */ Ajax.prototype._setHeaders = function (xhr, headers) { for (var header in headers) { xhr.setRequestHeader(header, headers[header]); } }; /** * Try to parse and normalize answer * @param xhr * @returns {*} * @private */ Ajax.prototype._parseJSON = function (xhr) { if (!xhr.response) { xhr.response = xhr.responseText; } var ret = {}; var contentType = false; if (xhr.getResponseHeader) { contentType = xhr.getResponseHeader("Content-Type"); } if (!contentType || contentType.toLowerCase() === 'application/json' || contentType.toLowerCase() === 'text/json' || contentType.toLowerCase() === 'inode/symlink') {//application/json or inode/symlink (AmazonS3 bug? ) try { ret = JSON.parse(xhr.response); } catch (e) { console.error("Not a JSON!", xhr.response); ret = {data: xhr.response}; } } else { ret = {data: xhr.response}; } if (!ret.status) { ret.status = xhr.status; } //Some servers can answer status in JSON as "HTTP/1.1 200 OK" but we need a status number if (typeof ret.status === 'string' && ret.status.indexOf("HTTP/") === 0 && ret.status.match( / (\d\d\d)/ )) { ret.status = parseInt(ret.status.match( / (\d\d\d)/ )[1]);//TODO check this code } if (!ret.statusText) { ret.statusText = xhr.statusText; } if (xhr.status && xhr.status != ret.status) { console.warn("Status from request %d, but response contains status %d", xhr.status, ret.status) } return ret; }; module.exports = Ajax; },{"../core/Events":6,"../helpers/LikeFormData":11,"../helpers/tools":13}],4:[function(require,module,exports){ "use strict"; /** * This a base constructor (class) for any DOM based instance. * This constructor just grab all node attributes and generates options. All processed options stored at this.options * @example * We have html like this: * <div data-test="testValue" data-value="value123">.....</div> * this.options will be: * { * test:"testValue", * value:"value" * } * Note: data-test and data-value should be described in attributesToGrab * @constructor */ var BaseDOMConstructor = function () { }; /** * Init method. Call after construct instance * @param {Object} sf * @param {Object} node DomNode of form * @param {Object} [options] all options to override default */ BaseDOMConstructor.prototype.init = function (sf, node, options) { //TODO data-spiral-JSON this.sf = sf; this.node = node; //if (sf.options && sf.options.instances && sf.options.instances[this.name]) { // options = Object.assign(options || {}, sf.options.instances[this.name]); //} this.options = Object.assign(this.grabOptions(node), options); }; /** * This is a options to generate. * You should provide processor or value. * @type {Object} * @property {Object} propertyKey - object of property * @property {String} propertyKey.value - default value to return * @property {String} [propertyKey.domAttr] - dom attribute to grab data * @property {Function} [propertyKey.processor] - processor to process data before return * @property {Object} ... - Another object of one property * @type {{}} * @example * "someAttribute": {// key * value: true, //default Value * domAttr: "data-some-attribute", // attribute from node to grab * processor: function (node,val,self) { //processor to process values before return * //some calculations * return someValue; * } * }, * "anotherAttribute":{...}, * "..." * * @example * //return node as value * "context": { * "processor": function (node,val,key) { //processor * return node; * } * }, * "Another-key":{...}, * "..." * @example * //Grab attribute "data-attribute" as "MyAttribute" if attribute not provided return "DefaultValue" * // Dom node <div data-attribute="someValue"></div> * "MyAttribute": { * value: "DefaultValue", * domAttr: "data-attribute" * } * //after processing we should have * {"MyAttribute":"someValue"} * * @example * //Grab attribute "data-attribute" as "MyAttribute" and return some value instead * //Dom node <div data-attribute="someValue"></div> * "MyAttribute": { * domAttr: "data-attribute", * processor: function (node,val,self) { * return val+"SomeCalculation"; * } * } * //after processing we should have * {"MyAttribute":"someValueSomeCalculation"} * * @example * //return function as value * processAnswer: { * "value": function (options) { * return "someVal"; * } * //after processing we should have * {"processAnswer":function (options) { * return "someVal"; * } * } * * @example * //return init time as value * initTime: { * "processor": function (node,val,self) { * return new Date().getTime; * } * //after processing we should have * {"initTime":1429808977404} * @example * //return other value instead of real one * processAnswer: { * "processor": function (node,val,self) { * return "someVal"; * } * //after processing we should have * {"processAnswer":"someVal"} */ BaseDOMConstructor.prototype.optionsToGrab = {}; /** * Grab all options that described in optionsToGrab * @param {Object} node domNode * @return {Object} */ BaseDOMConstructor.prototype.grabOptions = function (node) { var options = {}; var currentOptionValue; var currentOption; for (var option in this.optionsToGrab) { currentOptionValue = null; if (this.optionsToGrab.hasOwnProperty(option)) {//if this is own option currentOption = this.optionsToGrab[option]; if (currentOption.hasOwnProperty("value")) {//we have default option. Let's grab it for first currentOptionValue = currentOption.value; } if (this.sf.options.instances[this.name] && this.sf.options.instances[this.name].hasOwnProperty(option)) { currentOptionValue = this.sf.options.instances[this.name][option] } if (currentOption.hasOwnProperty("domAttr") && node.attributes.hasOwnProperty(currentOption.domAttr)) {//we can grab the attribute of node currentOptionValue = node.attributes[currentOption.domAttr].value; } if (currentOption.hasOwnProperty("processor")) {//we have processor. Let's execute it currentOptionValue = currentOption.processor.call(this, node, currentOptionValue, currentOption); } if (currentOptionValue !== null) { options[option] = currentOptionValue; } } } return options; }; /** * Get addon for instance * @param {String} addonType type of addon (message,fill,etc) * @param {String} addonName name of addon */ //depricated //BaseDOMConstructor.prototype.getAddon = function (addonType, addonName) { // return this.spiral.instancesController.getInstanceAddon(this.name, addonType, addonName); //}; module.exports = BaseDOMConstructor; },{}],5:[function(require,module,exports){ "use strict"; /** * Dom mutation. Listening to the DOM and add or remove instances based on classes. * @param {Object} instancesController spiral instancesController. * @param {Function} instancesController.getClasses get all registered modules classes. * @param {Function} instancesController.addInstance add instance method. * @param {Function} instancesController.removeInstance remove instance method * @constructor */ var DomMutations = function (instancesController) { if (!instancesController){ console.error("You should provide instancesController for DOM Mutation. Because DOM Mutation should known all classes and"); return; } if (!this.constructor){ console.error("Please call DomMutations with new - 'new DomMutations()' "); return; } this.instancesController = instancesController; var config = {//config for MutationObserver attributes: true, childList: true, characterData: true, characterDataOldValue: true, subtree: true, attributeOldValue: true, attributeFilter: ["class"] }, that = this; this.observer = new MutationObserver(function () {//call function when dom mutated. that.onDomMutate.apply(that, arguments) }); this.observer.observe(document, config);//start observer }; /** * When dom mutated this function id executed. * @param {Array} mutations array of mutations * @returns {boolean} */ DomMutations.prototype.onDomMutate = function (mutations) { var classArray = this.instancesController.getClasses();//get all registered classes var classSelector = "." + classArray.join(",.");//convert for querySelectorAll() if (classSelector.length === 1) {//if not registered any instanceTypes return false; } mutations.forEach(function (mutation) {//loop over mutation array switch (mutation.type) { case "attributes": this.processMutationAttributes(mutation, classArray); break; case "characterData": break; case "childList": this.processMutationChildList(mutation.addedNodes, "addInstance", classSelector, classArray); this.processMutationChildList(mutation.removedNodes, "removeInstance", classSelector, classArray); break; case "default": console.error("Something wrong. Contact tech support"); } }, this); return true; }; DomMutations.prototype.processMutationAttributes = function (mutation, classArray) { var that = this; var currentClasses = mutation.target.className.split(" "), oldClasses = (mutation.oldValue)?mutation.oldValue.split(" "):[], addedClasses = currentClasses.filter(function (val) { return (oldClasses.indexOf(val) === -1); }), removedClasses = oldClasses.filter(function (val) { return (currentClasses.indexOf(val) === -1); }), addedRegisteredClasses = addedClasses.filter(function (val) { return (classArray.indexOf(val) !== -1); }), removedRegisteredClasses = removedClasses.filter(function (val) { return (classArray.indexOf(val) !== -1); }); removedRegisteredClasses.forEach(function (val) { that.instancesController.removeInstance(that.instancesController.getInstanceNameByCssClass(val), mutation.target); }); addedRegisteredClasses.forEach(function (val) { that.instancesController.addInstance(that.instancesController.getInstanceNameByCssClass(val), mutation.target); }); }; /** * Process mutation on ChildList * @param {NodeList} nodesList array with nodes * @param {String} action action to call (add or remove nodes) * @param {String} classSelector - string selector for querySelectorAll * @param {Array} classArray - array of all registered classes */ DomMutations.prototype.processMutationChildList = function (nodesList, action, classSelector, classArray) { var that =this; /** * Internal function for checking node class * @param {Object} node dom node */ function checkNode(node) { classArray.forEach(function (className) {//loop over registered classes if (node.classList.contains(className)) {//if class match try to add or remove instance for this node that.instancesController[action](that.instancesController.getInstanceNameByCssClass(className), node); } }); } [].forEach.call(nodesList, function (val) {//loop over mutation nodes if (val.nodeType !== 1 || val.nodeName === "SCRIPT" || val.nodeName === "LINK") {//do not process other nodes then ELEMENT_NODE https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType also ignore SCRIPT and LINK tag return false; } checkNode(val);//check mutation node [].forEach.call(val.querySelectorAll(classSelector), checkNode);//query all nodes with required classes and check it return true; }); }; /** * Stop listening the dom changes */ DomMutations.prototype.stopObserve = function () { this.observer.disconnect(); }; module.exports = DomMutations; },{}],6:[function(require,module,exports){ "use strict"; /** * Events system. * @param {Array} allowedEvents array of allowed events. * @constructs Events * @example * //allow to work with all events * var events = new Events(); * events.on("myBestEvent",function(e){console.log(e)}); * @example * //Allow to serve only limited events * var events = new Events(["beforeSubmit","onDataReady"]); * events.on("myBestEvent",function(e){console.log(e)});//will not works * events.on("beforeSubmit",function(e){console.log(e)});//will work */ var Events = function (allowedEvents) { this._storage = {}; this._allowedEvents = allowedEvents; }; /** * Add event(s) * @param {String} events event or space separated event list * @param {Function} callback callback function * @example * var events = new Events(); * events.on("myBestEvent myBestEvent2 myBestEvent3",function(e){console.log(e)}); * events.on("myBestEvent",function(e){console.log(e)}); */ Events.prototype.on = function (events, callback) { var eventArr = events.replace(/\s{2,}/g, " ").split(" "); eventArr.forEach(function(event){ if (this._allowedEvents && this._allowedEvents.indexOf(event) === -1){// event not inside allowed events console.warn("Events. Try to register event %s, but event is not allowed",event); return; } if (!this._storage.hasOwnProperty(events)) { this._storage[event] = []; } this._storage[event].push(callback); },this) }; /** * Add action * @param {String} action * @param {Function} func * @deprecated use "on" instead */ Events.prototype.registerAction = Events.prototype.on; /** * remove event * @param {String} event * @param {Function} callback */ Events.prototype.off = function (event, callback) { alert("You try to remove action. This part is incomplete"); //TODO }; /** * Trigger event. * @param {String} event event name * @param {Object} [options] options to pass to the callback * @example * var events = new Events(); * events.on("myBestEvent",function(e){console.log(e.bestKey)}); * events.trigger("myBestEvent",{bestKey:42}); //will show in log */ Events.prototype.trigger = function (event, options) { if (this._allowedEvents && this._allowedEvents.indexOf(event) === -1){// event not inside allowed events console.warn("Events. Try to trigger event %s, but event is not allowed",event); return; } if (this._storage.hasOwnProperty(event)) { for (var n = 0, l = this._storage[event].length; n < l; n++) { this._storage[event][n](options); } } }; /** * Perform action * @param {String} action * @param {Object} [actionParams] object with all action data from server * @param {Object} [options] ajax options * @deprecated use "trigger" instead */ Events.prototype.performAction = Events.prototype.trigger; module.exports = Events; },{}],7:[function(require,module,exports){ "use strict"; /** * Instance controller * @param spiral * @constructor */ var InstancesController = function (spiral) { this.spiral = spiral; if (!this.constructor){ console.error("Please call InstancesController with new - 'new InstancesController()' "); return; } this._storage = { instancesConstructors: { cssClasses:{}, jsConstructors:{} }, addons: {}, instances: {} }; //todo decide if we need this //["onAddInstance", "onRemoveInstance"] //this.events = new spiral.modules.core.Events(); }; /** * Register new instance type * @param {Function} constructorFunction - constructor function of instance * @param {String} [cssClassName] - css class name of instance. If class not provided that it can't be automatically controlled by DomMutation. But you still can use it from JS. * @param {Boolean} [isSkipInitialization=false] - skip component initialization, just adding, no init nodes. */ InstancesController.prototype.registerInstanceType = function (constructorFunction, cssClassName, isSkipInitialization) { var instanceName = constructorFunction.prototype.name; if (!instanceName){ console.error("Instance constructor should have name inside it"); } if (this._storage.instancesConstructors.jsConstructors.hasOwnProperty(instanceName)){ console.error("Instance Constructor for type '%s' already added. Skipping",instanceName); return; } if (cssClassName){//add link (cssClassName->instanceName) this._storage.instancesConstructors.cssClasses[cssClassName] = instanceName; } this._storage.instancesConstructors.jsConstructors[instanceName] = constructorFunction; // if (this._storage.instancesConstructors.hasOwnProperty(className)){ // console.error("Instance Constructor for type %s already added. Skipping",constructorFunction.prototype.name); // return; //} //this._storage.instancesConstructors[className] = {//init storage fields // "typeName": constructorFunction.prototype.name, // "constructor": constructorFunction //}; this._storage.instances[instanceName] = []; if (!isSkipInitialization){ var nodes = document.getElementsByClassName(cssClassName);//init add nodes with this class for (var i = 0, max = nodes.length; i < max; i++) { this.addInstance(instanceName, nodes[i]); } } }; /** * Old method to register instance type * @param className * @param constructorFunction * @param isSkipInitialization * @deprecated */ InstancesController.prototype.addInstanceType =function(className,constructorFunction, isSkipInitialization){ console.warn("addInstanceType is deprecated. Please use registerInstanceType instead"); return this.registerInstanceType(constructorFunction, isSkipInitialization); }; /** * Add instance * @param {String} instanceName - name of instance * @param {Object} node - dom node * @param {Object} [options] all options for send to the constructor * @returns {boolean} */ InstancesController.prototype.addInstance = function (instanceName, node, options) { var instanceConstructor = this._storage.instancesConstructors.jsConstructors[instanceName], isAlreadyAdded = this.getInstance(instanceName,node); if (!instanceConstructor || isAlreadyAdded) {//if not found this type or already added - return return false; } // console.log("Adding instance for type -",instanceName,". Node - ",node); var instance = new instanceConstructor(this.spiral,node, options); this._storage.instances[instanceName].push({//add new instance of this type "node": node, "instance": instance }); //this.events.trigger("onAddInstance", instance); return instance; }; /** * Remove instance. * @param {String} instanceName - name of instance class * @param {Object|String} node - dom node ID * @returns {boolean} */ InstancesController.prototype.removeInstance = function (instanceName, node) { var instanceObj = this.getInstance(instanceName, node,true), key; if (!instanceObj) { return false; } instanceObj.instance.die();//avoid memory leak key = this._storage.instances[instanceName].indexOf(instanceObj); if (key !== -1){//remove key this._storage.instances[instanceName].splice(key, 1); } return true; }; /** * Get instance. Return instance object of this dom node * @param {String} instanceName - name of instance * @param {Object|String} node - dom node o dome node ID * @param {boolean} [isReturnObject] - return object or instance * @returns {boolean} */ InstancesController.prototype.getInstance = function (instanceName, node, isReturnObject) {//TODO isReturnObject not needed. Refactor and remove var typeArr = this._storage.instances[instanceName], ret = false; if (!typeArr) { return false; } node = (node instanceof HTMLElement) ? node : document.getElementById(node); if (!node) { return false; } for (var key = 0, l = typeArr.length; key < l; key++) {//iterate storage and try to find instance if (typeArr[key].node === node) { ret = (isReturnObject) ? typeArr[key] : typeArr[key].instance; break; } } return ret; }; /** * Get instances. Return array of instances objects * @param {String} instanceName - name of instance * @returns {array|boolean} */ InstancesController.prototype.getInstances = function (instanceName) { return this._storage.instances[instanceName] || false; }; /** * Register addon for instance * @param {Function|Object} addon * @param {String} instanceName name of instance to register addon * @param {String} addonType type of addon (message,fill,etc) * @param {String} addonName name of addon (spiral, bootstrap,etc) */ InstancesController.prototype.registerAddon = function(addon, instanceName, addonType, addonName){ if (!this._storage.addons.hasOwnProperty(instanceName)){ this._storage.addons[instanceName] = {}; } if (!this._storage.addons[instanceName].hasOwnProperty(addonType)){ this._storage.addons[instanceName][addonType] = {}; } if (this._storage.addons[instanceName][addonType].hasOwnProperty(addonName)){ console.error("The %s addon type %s already registered for instance %s! Skipping registration.",addonName,addonType,instanceName); return; } this._storage.addons[instanceName][addonType][addonName]= addon; }; /** * Get registered addon * @param {String} instanceName name of instance to register addon * @param {String} addonType type of addon (message,fill,etc) * @param {String} addonName name of addon (spiral, bootstrap,etc) */ InstancesController.prototype.getInstanceAddon =function(instanceName, addonType, addonName){ if (!this._storage.addons.hasOwnProperty(instanceName) || !this._storage.addons[instanceName].hasOwnProperty(addonType) || !this._storage.addons[instanceName][addonType].hasOwnProperty(addonName)){ return false; } return this._storage.addons[instanceName][addonType][addonName]; }; /** * Get all registered classes * @returns {Array} */ InstancesController.prototype.getClasses = function (){ return Object.keys(this._storage.instancesConstructors.cssClasses); }; /** * For given cssClass return name of instance * @param {String} cssClass * @return {*} */ InstancesController.prototype.getInstanceNameByCssClass = function(cssClass){ return this._storage.instancesConstructors.cssClasses[cssClass]; }; /** * Get constructor by name or class name */ InstancesController.prototype.getInstanceConstructors = function (name){ //TODO }; module.exports = InstancesController; },{}],8:[function(require,module,exports){ "use strict"; /** * This plugin adds ability to perform actions from the server. * "action":"reload" * "action":{"redirect":"/account"} * "action":{"redirect":"/account","delay":3000} * "action":{"name":"redirect","url":"/account","delay":3000} */ module.exports = function (sf) { sf.ajax.events.on('load', function (options) { var response = options.response; if (response.hasOwnProperty('action')) { if (typeof response.action === 'string') {//"action":"reload" sf.events.trigger(response.action); } else if (typeof response.action === 'object') { var keys = Object.keys(response.action); if (keys.indexOf('flash') !== -1){ var flash = response.action['flash'], timestamp = Date.now(), sfFlashMessage = {}; if (typeof response.action['flash'] === 'object'){ sfFlashMessage = flash; sfFlashMessage.timestamp = timestamp; } else { sfFlashMessage = { message: flash, timestamp: timestamp } } sessionStorage.setItem('sfFlashMessage', JSON.stringify(sfFlashMessage)); } if (keys.indexOf('redirect') !== -1){ setTimeout(function () { sf.events.trigger('redirect', response.action['redirect'], options); }, +response.action.delay|0); } else if (keys.indexOf('name') !== -1) { setTimeout(function () { sf.events.trigger(response.action.name, response.action.url); }, +response.action.delay || 0); } //if (keys.length === 1) {//"action":{"redirect":"/account"} // sf.events.trigger(keys[0], response.action[keys[0]], options); //} else if (keys.length === 2 && response.action.delay) {//"action":{"redirect":"/account","delay":3000} // setTimeout(function () { // var action = keys.filter(function (value) { // return value !== 'delay'; // })[0]; // sf.events.trigger(action, response.action[action], options); // }, +response.action.delay); //} else if (keys.length > 1) {//"action":{"name":"redirect","url":"/account","delay":3000} // setTimeout(function () { // sf.events.trigger(response.action.name, response.action, options); // }, +response.action.delay || 0); //} else { // console.error("Action from server. Object doesn't have keys. ", response.action); //} } else { console.error("Action from server. Something wrong. ", response.action); } } }); (function (sfFlashMessage) { if (!sfFlashMessage) return; var message = JSON.parse(sfFlashMessage), timestamp = Date.now(), node, nodeWrapper, flashClass; if (timestamp - message.timestamp > 10000) return; if (message.type === 'debug' || message.type === 'success'){ flashClass = 'debug' } else if (message.type === 'info' || !message.type || message.type === 'notice'){ flashClass = 'info' } else { flashClass = 'danger' } node = document.createElement('div'); nodeWrapper = document.createElement('div'); nodeWrapper.classList.add('flash-wrapper'); node.classList.add('flash', flashClass); node.innerHTML = message.message; document.body.appendChild(nodeWrapper); nodeWrapper.appendChild(node); setTimeout(function(){nodeWrapper.classList.add('show');}, 1); setTimeout(function(){nodeWrapper.classList.remove('show')}, message.timeout||5000); sessionStorage.removeItem('sfFlashMessage'); }(sessionStorage.getItem('sfFlashMessage'))) }; },{}],9:[function(require,module,exports){ module.exports = function(events){ events.on("redirect", function (event) { var url = Object.prototype.toString.call(event) === "[object String]" ? event : event.url; //http://stackoverflow.com/questions/10687099/how-to-test-if-a-url-string-is-absolute-or-relative self.location[/^(?:[a-z]+:)?\/\//i.test(url) ? 'href' : 'pathname'] = url; }); events.on('reload', function () { location.reload(); }); events.on('refresh', function () { events.trigger('reload'); }); events.on('close', function () { self.close(); }); }; },{}],10:[function(require,module,exports){ "use strict"; /** * Helper to manipulate DOM Events. It's a simple wrapper around "addEventListener" but it's store all functions and allow us to remove it all. * It's very helpful for die() method of instances * @TODO add to many nodes * @TODO new method like addEventListener DOMEvents.on(node(s),event,callback,useCapture); * @constructor */ var DOMEvents = function(){ /** * Internal storage for events * @property {Array.<Object>} DOMEvents - dom events array * @property {Object} DOMEvents.DOMNode - DOM node * @property {String} DOMEvents.eventType - Event type * @property {Function} DOMEvents.eventFunction - Function * @property {Boolean} DOMEvents.useCapture=false - useCapture * @property {Object} ... - another object * @private */ this._DOMEventsStorage = []; }; /** * Add event(s) to node(s). * @TODO add to many nodes * @param {Array.<Object>|Object} eventArray - event array or event itself * @param {Object} eventArray.DOMNode - DOM node * @param {String} eventArray.eventType - Event type * @param {Function} eventArray.eventFunction - Function * @param {Boolean} [eventArray.useCapture=false] - useCapture * @example * var DOMEventsInstance = new DOMEvents(); * var eventOne = { * DOMNode: document.getElementById("example"), * eventType: "click", * eventFunction: function (e) { * console.log("Hi there. Native DOM events is:",e); * } * } * var eventTwo = { * DOMNode: document.getElementById("example2"), * eventType: "mousedown", * eventFunction: function (e) { * console.log("Hi there. mousedown event. Native DOM events is:",e); * } * } * DOMEventsInstance.add([eventOne,eventTwo]); */ DOMEvents.prototype.add = function(eventArray){ if (Object.prototype.toString.call([]) !== "[object Array]"){ eventArray = [eventArray]; } eventArray.forEach(function(val){ val.useCapture=!!(val.useCapture); val.DOMNode.addEventListener(val.eventType,val.eventFunction,val.useCapture); this._DOMEventsStorage.push(val); },this) }; /** * Remove events * @param {Array.<Object>} eventArray - event array * @param {Object} eventArray.DOMNode - DOM node * @param {String} eventArray.eventType - Event type * @param {Function} eventArray.eventFunction - Function * @param {Boolean} [eventArray.useCapture=false] - useCapture */ DOMEvents.prototype.remove = function(eventArray){ //TODO IMPLEMENT // TODO не уверен что этот метод необходим. если надо часто убирать какието обработчики, то лучше поставить обработчки на родителя console.warn("TODO IMPLEMENT"); }; /** * Remove all dom events registered with this instance (added by method add) * @example * //look at add method as first part of this code * DOMEventsInstance.removeAll(); */ DOMEvents.prototype.removeAll = function(){ this._DOMEventsStorage.forEach(function(val){ val.DOMNode.removeEventListener(val.eventType,val.eventFunction,val.useCapture); }); this._DOMEventsStorage=[]; }; module.exports = DOMEvents; },{}],11:[function(require,module,exports){ "use strict"; /** * This object try to be easy as FormData. * Please note this is not(!) a shim for Form data, because it's impossible (you should set headers for Ajax by hands) * It take object and can convert it string like FormData do. Then you can send this string by Ajax or do some other staff. * @see https://developer.mozilla.org/en-US/docs/Web/API/FormData * @param {Object} [data] object with data (supports nested objects) * @param {String} [boundary] boundary for Form Data * @constructor * @example * var formData = new LikeFormData({testKey:"testValue"},"testBoundary"); * formData.toString(); * // Returns: * //"--testBoundary * //Content-Disposition: form-data; name=testKey * // * // testValue * //--testBoundary-- * //" * * @example * var formData = new LikeFormData({testKey:"testValue"}); * formData.toString(); * // Returns: * //"--SpiralFormData-4935309085994959 * //Content-Disposition: form-data; name=testKey * // * // testValue * //--SpiralFormData-4935309085994959-- * //" * * @example * var formData = new LikeFormData({testKey:"testValue"}); * formData.append("key2","val2"); * formData.toString(); * // Returns: * //--SpiralFormData-988681384595111 * //Content-Disposition: form-data; name=testKey * // * //testValue * //--SpiralFormData-988681384595111 * //Content-Disposition: form-data; name=key2 * // * //val2 * //--SpiralFormData-988681384595111-- * //" */ var LikeFormData = function (data, boundary) { this.data = {}; if (data) { if (Object.prototype.toString.call(data) !== "[object Object]") {//non object/ Alert developer console.warn("LikeFormData can't accept non Object. Please reefer to documentation. Problem parameter is:", data); } else { this.data = data; } } this.boundary = (boundary) ? boundary : ("SpiralFormData-" + Math.random().toString().substr(2)); //if (!isOldIE) { // this.boundary = "SpiralAjax-" + Math.random().toString().substr(2); // //xhr.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + this.boundary); //} else { // this.boundary = "SpiralAjax-oldIE9876gsloiHGldowu"; //} }; /** * Append data to storage. Like standart FormData do. * @param {String} key * @param {String} val * @example * var formData = new FormData(); * formData.append("key2","val2"); */ LikeFormData.prototype.append = function (key, val) { //https://developer.mozilla.org/en-US/docs/Web/API/FormData //TODO ***Appends a new value**** onto an existing key inside a FormData object, or adds the key if it does not already exist. this.data[key] = val; }; /** * convert to string * @example * var formData = new LikeFormData({testKey:"testValue"}); * formData.toString(); * // Returns: * //"--SpiralFormData-4935309085994959 * //Content-Disposition: form-data; name=testKey * // * // testValue * //--SpiralFormData-4935309085994959-- * //" */ LikeFormData.prototype.toString = function () { var retString = ""; var boundary = this.boundary; var iterate = function (data, partOfKey) { for (var key in data) { if (data.hasOwnProperty(key) && (typeof data[key] !== "undefined" )) { if (typeof data[key] === "object") { iterate(data[key], ((partOfKey.length === 0) ? key : (partOfKey + "[" + key + "]"))); } else { retString += "--" + boundary + "\r\nContent-Disposition: form-data; name=" + ((partOfKey.length === 0) ? key : (partOfKey + "[" + key + "]")) + "\r\n\r\n" + data[key] + "\r\n"; } } } }; if (typeof this.data !== "object") { this.data = { data: this.data } } iterate(this.data, ""); retString += "--" + this.boundary + "--\r\n"; return retString; }; /** * The delete() method of the FormData interface deletes a key/value pair from a FormData object. * @param key */ LikeFormData.prototype.delete = function (key) { return delete(this.data[key]); }; /** *The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. * @param key */ LikeFormData.prototype.get = function (key) { return this.data[key]; }; /** *The getAll() method of the FormData interface returns the first value associated with a given key from within a FormData object. */ LikeFormData.prototype.getAll = function () { return this.data; }; /** * The has() method of the FormData interface returns a boolean stating whether a FormData object contains a certain key/value pair. * @param key */ LikeFormData.prototype.has = function(key){ return this.data.hasOwnProperty(key); }; /** * The difference between set() and FormData.append is that if the specified header does already exist, set() will overwrite the existing value with the new one, whereas FormData.append will append the new value onto the end of the set of values. * @param key * @param val */ LikeFormData.prototype.set = function(key, val){ this.data[key] = val; }; /** * Get content header to set for Ajax. Not a part of standart FormData object. But for sending Like FormData over Ajax you should know header. * @return {string} * @example * var formData = new LikeFormData(); * formData.getContentTypeHeader(); //return "multipart/form-data; charset=utf-8; boundary=SpiralFormData-988681384595111" * @example * var formData = new LikeFormData({key:"val2"},"testBoundary"); * formData.getContentTypeHeader(); //return "multipart/form-data; charset=utf-8; boundary=testBoundary" */ LikeFormData.prototype.getContentTypeHeader = function () { return "multipart/form-data; charset=utf-8; boundary=" + this.boundary; }; module.exports = LikeFormData; },{}],12:[function(require,module,exports){ /** This is a collection of useful DOM tools. */ module.exports = { /** * Found first parent node with matched selector(s) * @param {Object} elem - dom node * @param {String|Array} selectors - selector or array of selectors * @returns {Object| Boolean} - node or false */ closest: function (elem, selectors) { selectors = (typeof selectors === 'string') ? [selectors] : selectors; var key, l = selectors.length, matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector; while (elem && elem.parentNode) { for (key = 0; key < l; key++) { if (matchesSelector.call(elem, selectors[key])) { return elem; } } elem = elem.parentNode; } return false; }, /** * Found first parent node with matched className(s). * TODO Why this? Because old IE.... * TODO It's not good, because it's a copy of closest @see closest. Refactor * @param {Object} elem - dom node * @param {String|Array} className - className or array of classNames * @returns {Object| Boolean} - node or false */ closestByClassName: function (elem, className) { className = (typeof className === 'string') ? [className] : className; var key, l = className.length; //,matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector; while (elem && elem.parentNode) { for (key = 0; key < l; key++) { var reg = new RegExp("(\\s|^)" + className[key] + "(\\s|$)"); if (elem.className.match(reg)) { return elem; } } elem = elem.parentNode; } return false; } }; },{}],13:[function(require,module,exports){ "use strict"; /** * @module tools * @namespace */ var tools = { resolveKeyPath : function(path, obj, safe) { return path.split('.').reduce(function(prev, curr) { return !safe ? prev[curr] : (prev ? prev[curr] : void 0) }, obj||self) } }; module.exports = tools; },{}],14:[function(require,module,exports){ "use strict"; //https://github.com/spiral/sf.js //Add console shim for old IE require("./shim/console"); require("./shim/Object.assign"); if (typeof Promise != 'function') { var Promise = require('es6-promise').Promise; } var _sf; if (typeof sf !== 'undefined' && Object.prototype.toString.call(sf) === "[object Object]") { _sf = Object.assign(sf, require("./sf")); } else { _sf = require("./sf"); } if (!_sf.hasOwnProperty('options')) _sf.options = {instances:{}}; if (!_sf.options.hasOwnProperty('instances')) _sf.options.instances = {}; //todo delete this in future if (!window.hasOwnProperty("sf")) {//bind only if window.sf is empty to avoid conflicts with other libs window.sf = _sf; } _sf.instancesController = new _sf.core.InstancesController(sf); _sf.domMutation = new _sf.core.DomMutations(_sf.instancesController); //Events system _sf.events = new _sf.core.Events(); require("./core/events/baseEvents.js")(_sf.events); //AJAX _sf.ajax = new _sf.core.Ajax(window.csrfToken ? {//TODO move to spiral bindings headers: { "X-CSRF-Token": window.csrfToken } } : null); require("./core/ajax/baseActions.js")(_sf); //API _sf.createModulePrototype = function() { return Object.create(_sf.modules.core.BaseDOMConstructor.prototype)}; _sf.registerInstanceType = _sf.instancesController.registerInstanceType.bind(_sf.instancesController); _sf.addInstance = _sf.instancesController.addInstance.bind(_sf.instancesController); _sf.removeInstance = _sf.instancesController.removeInstance.bind(_sf.instancesController); _sf.getInstance = _sf.instancesController.getInstance.bind(_sf.instancesController); _sf.getInstances = _sf.instancesController.getInstances.bind(_sf.instancesController); _sf.closest = sf.helpers.domTools.closest; _sf.resolveKeyPath = sf.tools.resolveKeyPath; if (typeof exports === "object" && exports) { module.exports = _sf; } },{"./core/ajax/baseActions.js":8,"./core/events/baseEvents.js":9,"./sf":15,"./shim/Object.assign":16,"./shim/console":17,"es6-promise":1}],15:[function(require,module,exports){ var core = { Ajax: require("./core/Ajax"), BaseDOMConstructor: require("./core/BaseDOMConstructor"), DomMutations: require("./core/DomMutations"), Events: require("./core/Events"), InstancesController: require("./core/InstancesController") }; var helpers = { DOMEvents: require("./helpers/DOMEvents"), domTools: require("./helpers/domTools"), LikeFormData: require("./helpers/LikeFormData"), tools: require("./helpers/tools") }; var sf = { core: core, helpers: helpers, tools: helpers.tools, modules: {//todo remove this when removed in dependencies 'WILL_BE_DEPRECATED': true, core: core, helpers: helpers } }; module.exports = sf; },{"./core/Ajax":3,"./core/BaseDOMConstructor":4,"./core/DomMutations":5,"./core/Events":6,"./core/InstancesController":7,"./helpers/DOMEvents":10,"./helpers/LikeFormData":11,"./helpers/domTools":12,"./helpers/tools":13}],16:[function(require,module,exports){ /** * Object.assign polyfill * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign */ if (typeof Object.assign != 'function') { (function () { Object.assign = function (target) { 'use strict'; if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); } var output = Object(target); for (var index = 1; index < arguments.length; index++) { var source = arguments[index]; if (source !== undefined && source !== null) { for (var nextKey in source) { if (source.hasOwnProperty(nextKey)) { output[nextKey] = source[nextKey]; } } } } return output; }; })(); } },{}],17:[function(require,module,exports){ /** * Avoid `console` errors in browsers that lack a console. */ (function () { var method, noop = function () { }, methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ], length = methods.length, console = (window.console = window.console || {}); while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } } }()); },{}]},{},[14]) //# sourceMappingURL=sf.js.map
/* global processWebhookMessage */ RocketChat.API.v1.addRoute('chat.delete', { authRequired: true }, { post: function() { try { check(this.bodyParams, { msgId: String, roomId: String, asUser: Match.Maybe(Boolean) }); const msg = RocketChat.models.Messages.findOneById(this.bodyParams.msgId, { fields: { u: 1, rid: 1 }}); if (!msg) { return RocketChat.API.v1.failure(`No message found with the id of "${this.bodyParams.msgId}".`); } if (this.bodyParams.roomId !== msg.rid) { return RocketChat.API.v1.failure('The room id provided does not match where the message is from.'); } Meteor.runAsUser(this.bodyParams.asUser ? msg.u._id : this.userId, () => { Meteor.call('deleteMessage', { _id: msg._id }); }); return RocketChat.API.v1.success({ _id: msg._id, ts: Date.now() }); } catch (e) { return RocketChat.API.v1.failure(e.name + ': ' + e.message); } } }); RocketChat.API.v1.addRoute('chat.postMessage', { authRequired: true }, { post: function() { try { if (!this.bodyParams.attachments) { check(this.bodyParams, { channel: String, text: String }); } //TODO: Completely rewrite this? Seems too "magical" const messageReturn = processWebhookMessage(this.bodyParams, this.user)[0]; if (!messageReturn) { return RocketChat.API.v1.failure('unknown-error'); } return RocketChat.API.v1.success({ ts: Date.now(), channel: messageReturn.channel, message: messageReturn.message }); } catch (e) { return RocketChat.API.v1.failure(e.name + ': ' + e.message); } } });
/*! Scroller 1.2.2 ©2011-2014 SpryMedia Ltd - datatables.net/license */ (function(m,n,k){var l=function(e){var g=function(a,b){!this instanceof g?alert("Scroller warning: Scroller must be initialised with the 'new' keyword."):("undefined"==typeof b&&(b={}),this.s={dt:a,tableTop:0,tableBottom:0,redrawTop:0,redrawBottom:0,autoHeight:!0,viewportRows:0,stateTO:null,drawTO:null,heights:{jump:null,page:null,virtual:null,scroll:null,row:null,viewport:null},topRowFloat:0,scrollDrawDiff:null,loaderVisible:!1},this.s=e.extend(this.s,g.oDefaults,b),this.s.heights.row=this.s.rowHeight, this.dom={force:n.createElement("div"),scroller:null,table:null,loader:null},this.s.dt.oScroller=this,this._fnConstruct())};g.prototype={fnRowToPixels:function(a,b,c){a=c?this._domain("virtualToPhysical",a*this.s.heights.row):this.s.baseScrollTop+(a-this.s.baseRowTop)*this.s.heights.row;return b||b===k?parseInt(a,10):a},fnPixelsToRow:function(a,b,c){var d=a-this.s.baseScrollTop,a=c?this._domain("physicalToVirtual",a)/this.s.heights.row:d/this.s.heights.row+this.s.baseRowTop;return b||b===k?parseInt(a, 10):a},fnScrollToRow:function(a,b){var c=this,d=!1,f=this.fnRowToPixels(a),h=a-(this.s.displayBuffer-1)/2*this.s.viewportRows;0>h&&(h=0);if((f>this.s.redrawBottom||f<this.s.redrawTop)&&this.s.dt._iDisplayStart!==h)d=!0,f=this.fnRowToPixels(a,!1,!0);"undefined"==typeof b||b?(this.s.ani=d,e(this.dom.scroller).animate({scrollTop:f},function(){setTimeout(function(){c.s.ani=!1},25)})):e(this.dom.scroller).scrollTop(f)},fnMeasure:function(a){this.s.autoHeight&&this._fnCalcRowHeight();var b=this.s.heights; b.viewport=e(this.dom.scroller).height();this.s.viewportRows=parseInt(b.viewport/b.row,10)+1;this.s.dt._iDisplayLength=this.s.viewportRows*this.s.displayBuffer;(a===k||a)&&this.s.dt.oInstance.fnDraw()},_fnConstruct:function(){var a=this;if(this.s.dt.oFeatures.bPaginate){this.dom.force.style.position="absolute";this.dom.force.style.top="0px";this.dom.force.style.left="0px";this.dom.force.style.width="1px";this.dom.scroller=e("div."+this.s.dt.oClasses.sScrollBody,this.s.dt.nTableWrapper)[0];this.dom.scroller.appendChild(this.dom.force); this.dom.scroller.style.position="relative";this.dom.table=e(">table",this.dom.scroller)[0];this.dom.table.style.position="absolute";this.dom.table.style.top="0px";this.dom.table.style.left="0px";e(this.s.dt.nTableWrapper).addClass("DTS");this.s.loadingIndicator&&(this.dom.loader=e('<div class="DTS_Loading">'+this.s.dt.oLanguage.sLoadingRecords+"</div>").css("display","none"),e(this.dom.scroller.parentNode).css("position","relative").append(this.dom.loader));this.s.heights.row&&"auto"!=this.s.heights.row&& (this.s.autoHeight=!1);this.fnMeasure(!1);this.s.ingnoreScroll=!0;this.s.stateSaveThrottle=this.s.dt.oApi._fnThrottle(function(){a.s.dt.oApi._fnSaveState(a.s.dt)},500);e(this.dom.scroller).on("scroll.DTS",function(){a._fnScroll.call(a)});e(this.dom.scroller).on("touchstart.DTS",function(){a._fnScroll.call(a)});this.s.dt.aoDrawCallback.push({fn:function(){a.s.dt.bInitialised&&a._fnDrawCallback.call(a)},sName:"Scroller"});e(m).on("resize.DTS",function(){a.fnMeasure(false);a._fnInfo()});var b=!0;this.s.dt.oApi._fnCallbackReg(this.s.dt, "aoStateSaveParams",function(c,d){if(b&&a.s.dt.oLoadedState){d.iScroller=a.s.dt.oLoadedState.iScroller;d.iScrollerTopRow=a.s.dt.oLoadedState.iScrollerTopRow;b=false}else{d.iScroller=a.dom.scroller.scrollTop;d.iScrollerTopRow=a.s.topRowFloat}},"Scroller_State");this.s.dt.oLoadedState&&(this.s.topRowFloat=this.s.dt.oLoadedState.iScrollerTopRow||0);this.s.dt.aoDestroyCallback.push({sName:"Scroller",fn:function(){e(m).off("resize.DTS");e(a.dom.scroller).off("touchstart.DTS scroll.DTS");e(a.s.dt.nTableWrapper).removeClass("DTS"); e("div.DTS_Loading",a.dom.scroller.parentNode).remove();a.dom.table.style.position="";a.dom.table.style.top="";a.dom.table.style.left=""}})}else this.s.dt.oApi._fnLog(this.s.dt,0,"Pagination must be enabled for Scroller")},_fnScroll:function(){var a=this,b=this.s.heights,c=this.dom.scroller.scrollTop,d;if(!this.s.skip&&!this.s.ingnoreScroll)if(this.s.dt.bFiltered||this.s.dt.bSorted)this.s.lastScrollTop=0;else{this._fnInfo();clearTimeout(this.s.stateTO);this.s.stateTO=setTimeout(function(){a.s.dt.oApi._fnSaveState(a.s.dt)}, 250);if(c<this.s.redrawTop||c>this.s.redrawBottom){var f=Math.ceil((this.s.displayBuffer-1)/2*this.s.viewportRows);Math.abs(c-this.s.lastScrollTop)>b.viewport||this.s.ani?(d=parseInt(this._domain("physicalToVirtual",c)/b.row,10)-f,this.s.topRowFloat=this._domain("physicalToVirtual",c)/b.row):(d=this.fnPixelsToRow(c)-f,this.s.topRowFloat=this.fnPixelsToRow(c,!1));0>=d?d=0:d+this.s.dt._iDisplayLength>this.s.dt.fnRecordsDisplay()?(d=this.s.dt.fnRecordsDisplay()-this.s.dt._iDisplayLength,0>d&&(d=0)): 0!==d%2&&d++;if(d!=this.s.dt._iDisplayStart&&(this.s.tableTop=e(this.s.dt.nTable).offset().top,this.s.tableBottom=e(this.s.dt.nTable).height()+this.s.tableTop,b=function(){if(a.s.scrollDrawReq===null)a.s.scrollDrawReq=c;a.s.dt._iDisplayStart=d;a.s.dt.oApi._fnCalculateEnd&&a.s.dt.oApi._fnCalculateEnd(a.s.dt);a.s.dt.oApi._fnDraw(a.s.dt)},this.s.dt.oFeatures.bServerSide?(clearTimeout(this.s.drawTO),this.s.drawTO=setTimeout(b,this.s.serverWait)):b(),this.dom.loader&&!this.s.loaderVisible))this.dom.loader.css("display", "block"),this.s.loaderVisible=!0}this.s.lastScrollTop=c;this.s.stateSaveThrottle()}},_domain:function(a,b){var c=this.s.heights,d;if(c.virtual===c.scroll){d=(c.virtual-c.viewport)/(c.scroll-c.viewport);if("virtualToPhysical"===a)return b/d;if("physicalToVirtual"===a)return b*d}var e=(c.scroll-c.viewport)/2,h=(c.virtual-c.viewport)/2;d=h/(e*e);if("virtualToPhysical"===a){if(b<h)return Math.pow(b/d,0.5);b=2*h-b;return 0>b?c.scroll:2*e-Math.pow(b/d,0.5)}if("physicalToVirtual"===a){if(b<e)return b*b* d;b=2*e-b;return 0>b?c.virtual:2*h-b*b*d}},_fnDrawCallback:function(){var a=this,b=this.s.heights,c=this.dom.scroller.scrollTop,d=e(this.s.dt.nTable).height(),f=this.s.dt._iDisplayStart,h=this.s.dt._iDisplayLength,g=this.s.dt.fnRecordsDisplay();this.s.skip=!0;this._fnScrollForce();c=0===f?this.s.topRowFloat*b.row:f+h>=g?b.scroll-(g-this.s.topRowFloat)*b.row:this._domain("virtualToPhysical",this.s.topRowFloat*b.row);this.dom.scroller.scrollTop=c;this.s.baseScrollTop=c;this.s.baseRowTop=this.s.topRowFloat; var j=c-(this.s.topRowFloat-f)*b.row;0===f?j=0:f+h>=g&&(j=b.scroll-d);this.dom.table.style.top=j+"px";this.s.tableTop=j;this.s.tableBottom=d+this.s.tableTop;d=(c-this.s.tableTop)*this.s.boundaryScale;this.s.redrawTop=c-d;this.s.redrawBottom=c+d;this.s.skip=!1;this.s.dt.oFeatures.bStateSave&&null!==this.s.dt.oLoadedState&&"undefined"!=typeof this.s.dt.oLoadedState.iScroller?((c=(this.s.dt.sAjaxSource||a.s.dt.ajax)&&!this.s.dt.oFeatures.bServerSide?!0:!1)&&2==this.s.dt.iDraw||!c&&1==this.s.dt.iDraw)&& setTimeout(function(){e(a.dom.scroller).scrollTop(a.s.dt.oLoadedState.iScroller);a.s.redrawTop=a.s.dt.oLoadedState.iScroller-b.viewport/2;setTimeout(function(){a.s.ingnoreScroll=!1},0)},0):a.s.ingnoreScroll=!1;setTimeout(function(){a._fnInfo.call(a)},0);this.dom.loader&&this.s.loaderVisible&&(this.dom.loader.css("display","none"),this.s.loaderVisible=!1)},_fnScrollForce:function(){var a=this.s.heights;a.virtual=a.row*this.s.dt.fnRecordsDisplay();a.scroll=a.virtual;1E6<a.scroll&&(a.scroll=1E6);this.dom.force.style.height= a.scroll+"px"},_fnCalcRowHeight:function(){var a=this.s.dt,b=a.nTable,c=b.cloneNode(!1),d=e("<tbody/>").appendTo(c),f=e('<div class="'+a.oClasses.sWrapper+' DTS"><div class="'+a.oClasses.sScrollWrapper+'"><div class="'+a.oClasses.sScrollBody+'"></div></div></div>');for(e("tbody tr:lt(4)",b).clone().appendTo(d);3>e("tr",d).length;)d.append("<tr><td>&nbsp;</td></tr>");e("div."+a.oClasses.sScrollBody,f).append(c);a._bInitComplete?a=b.parentNode:(this.s.dt.nHolding||(this.s.dt.nHolding=e("<div></div>").insertBefore(this.s.dt.nTable)), a=this.s.dt.nHolding);f.appendTo(a);this.s.heights.row=e("tr",d).eq(1).outerHeight();f.remove()},_fnInfo:function(){if(this.s.dt.oFeatures.bInfo){var a=this.s.dt,b=a.oLanguage,c=this.dom.scroller.scrollTop,d=Math.floor(this.fnPixelsToRow(c,!1,this.s.ani)+1),f=a.fnRecordsTotal(),h=a.fnRecordsDisplay(),c=Math.ceil(this.fnPixelsToRow(c+this.s.heights.viewport,!1,this.s.ani)),c=h<c?h:c,g=a.fnFormatNumber(d),j=a.fnFormatNumber(c),i=a.fnFormatNumber(f),k=a.fnFormatNumber(h),g=0===a.fnRecordsDisplay()&& a.fnRecordsDisplay()==a.fnRecordsTotal()?b.sInfoEmpty+b.sInfoPostFix:0===a.fnRecordsDisplay()?b.sInfoEmpty+" "+b.sInfoFiltered.replace("_MAX_",i)+b.sInfoPostFix:a.fnRecordsDisplay()==a.fnRecordsTotal()?b.sInfo.replace("_START_",g).replace("_END_",j).replace("_MAX_",i).replace("_TOTAL_",k)+b.sInfoPostFix:b.sInfo.replace("_START_",g).replace("_END_",j).replace("_MAX_",i).replace("_TOTAL_",k)+" "+b.sInfoFiltered.replace("_MAX_",a.fnFormatNumber(a.fnRecordsTotal()))+b.sInfoPostFix;(b=b.fnInfoCallback)&& (g=b.call(a.oInstance,a,d,c,f,h,g));a=a.aanFeatures.i;if("undefined"!=typeof a){d=0;for(f=a.length;d<f;d++)e(a[d]).html(g)}}}};g.defaults={trace:!1,rowHeight:"auto",serverWait:200,displayBuffer:9,boundaryScale:0.5,loadingIndicator:!1};g.oDefaults=g.defaults;g.version="1.2.2";"function"==typeof e.fn.dataTable&&"function"==typeof e.fn.dataTableExt.fnVersionCheck&&e.fn.dataTableExt.fnVersionCheck("1.9.0")?e.fn.dataTableExt.aoFeatures.push({fnInit:function(a){var b=a.oInit;return(new g(a,b.scroller|| b.oScroller||{})).dom.wrapper},cFeature:"S",sFeature:"Scroller"}):alert("Warning: Scroller requires DataTables 1.9.0 or greater - www.datatables.net/download");e.fn.dataTable.Scroller=g;e.fn.DataTable.Scroller=g;if(e.fn.dataTable.Api){var i=e.fn.dataTable.Api;i.register("scroller()",function(){return this});i.register("scroller().rowToPixels()",function(a,b,c){var d=this.context;if(d.length&&d[0].oScroller)return d[0].oScroller.fnRowToPixels(a,b,c)});i.register("scroller().pixelsToRow()",function(a, b,c){var d=this.context;if(d.length&&d[0].oScroller)return d[0].oScroller.fnPixelsToRow(a,b,c)});i.register("scroller().scrollToRow()",function(a,b){this.iterator("table",function(c){c.oScroller&&c.oScroller.fnScrollToRow(a,b)});return this});i.register("scroller().measure()",function(a){this.iterator("table",function(b){b.oScroller&&b.oScroller.fnMeasure(a)});return this})}return g};"function"===typeof define&&define.amd?define(["jquery","datatables"],l):"object"===typeof exports?l(require("jquery"), require("datatables")):jQuery&&!jQuery.fn.dataTable.Scroller&&l(jQuery,jQuery.fn.dataTable)})(window,document);
var _ = require('lodash'); var GraphQL = require('./GraphQL'); var GraphQLFilter = require('./GraphQLFilter'); var Util = require('./Util'); var MetaStore = function() { this._rawData = {}; }; MetaStore.prototype.export = function () { return JSON.stringify(this._rawData, null, 2); } MetaStore.prototype.import = function (data) { this._rawData = JSON.parse(data); this._resetCompile(); } MetaStore.prototype.addData = function (extractorName, fileName, data) { if (this._rawData[extractorName] === undefined) { this._rawData[extractorName] = {}; } this._rawData[extractorName][fileName] = data; this._resetCompile(); }; MetaStore.prototype.getData = function (extractorName, fileName) { if (!this._rawData[extractorName]) return [] return this._rawData[extractorName][fileName] || []; }; MetaStore.prototype.getExtractors = function () { return Object.keys(this._rawData); }; MetaStore.prototype.getFiles = function () { var fileNameMap = {}; for (var key in this._rawData) { for (var fileName in this._rawData[key]) { if (fileName !== '__metadata') { fileNameMap[fileName] = true; } } } return Object.keys(fileNameMap); }; MetaStore.prototype.removeExtractor = function (extractorName) { delete this._rawData[extractorName]; this._resetCompile(); }; MetaStore.prototype.removeFile = function (fileName) { for (var key in this._rawData) { delete this._rawData[key][fileName]; } this._resetCompile(); }; MetaStore.prototype.query = function (queryString, isParsed) { var compiled = this._getCompiled(); var query = isParsed ? queryString : GraphQL.parse(queryString); return GraphQLFilter.filter(compiled[query.getType()], query); }; MetaStore.prototype._getCompiled = function () { if (this._compiled === undefined) { this._compiled = Util.compressData(this._rawData); } return this._compiled; }; MetaStore.prototype._resetCompile = function () { this._compiled = undefined; }; module.exports = MetaStore;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the FileGetNodeFilePropertiesFromComputeNodeOptions class. * @constructor * Additional parameters for the File_getNodeFilePropertiesFromComputeNode * operation. * * @member {number} [timeout] The maximum time that the server can spend * processing the request, in seconds. The default is 30 seconds. Default * value: 30 . * * @member {string} [clientRequestId] The caller-generated request identity, * in the form of a GUID with no decoration such as curly braces, e.g. * 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @member {boolean} [returnClientRequestId] Whether the server should return * the client-request-id identifier in the response. * * @member {date} [ocpDate] The time the request was issued. If not specified, * this header will be automatically populated with the current system clock * time. * * @member {date} [ifModifiedSince] Specify this header to perform the * operation only if the resource has been modified since the specified * date/time. * * @member {date} [ifUnmodifiedSince] Specify this header to perform the * operation only if the resource has not been modified since the specified * date/time. * */ function FileGetNodeFilePropertiesFromComputeNodeOptions() { } /** * Defines the metadata of FileGetNodeFilePropertiesFromComputeNodeOptions * * @returns {object} metadata of FileGetNodeFilePropertiesFromComputeNodeOptions * */ FileGetNodeFilePropertiesFromComputeNodeOptions.prototype.mapper = function () { return { required: false, type: { name: 'Composite', className: 'FileGetNodeFilePropertiesFromComputeNodeOptions', modelProperties: { timeout: { required: false, defaultValue: 30, type: { name: 'Number' } }, clientRequestId: { required: false, type: { name: 'String' } }, returnClientRequestId: { required: false, type: { name: 'Boolean' } }, ocpDate: { required: false, type: { name: 'DateTimeRfc1123' } }, ifModifiedSince: { required: false, type: { name: 'DateTimeRfc1123' } }, ifUnmodifiedSince: { required: false, type: { name: 'DateTimeRfc1123' } } } } }; }; module.exports = FileGetNodeFilePropertiesFromComputeNodeOptions;
var response_lib = require('../../lib/response_lib'); var reql = require('../../lib/request_lib'); var base = '/svc/elections/us/v3/finances'; var keyName = 'campaign-finance'; function electioneeringCommunications (keys) { this.myKeys = keys; } /* Electioneering Communications */ electioneeringCommunications.prototype.recentCommunications = function (args, callback) { var specific = reql.buildPath(args['cycle'], 'electioneering_communications'); reql.createRequest(args, callback, this.myKeys, base, specific, keyName); } electioneeringCommunications.prototype.communicationsByCommittee = function (args, callback) { var specific = reql.buildPath(args['cycle'], 'committees', args['FEC-ID'], 'electioneering_communications'); reql.createRequest(args, callback, this.myKeys, base, specific, keyName); } electioneeringCommunications.prototype.communicationsByDate = function (args, callback) { var specific = reql.buildPath(args['cycle'], 'committees', 'electioneering_communications', args['year'], args['month'], args['day']); reql.createRequest(args, callback, this.myKeys, base, specific, keyName); } module.exports = electioneeringCommunications;
import { userList } from './elements'; import itemForUser from './itemForUser'; export default function renderList(users) { userList.innerHTML = ''; users.forEach((user) => { userList.appendChild(itemForUser(user)); }); }
'use strict'; var expect = require('chai').expect; var Backbone = require('backbone'); var sinon = require('sinon'); var screen = require('./fake_screen'); var SplitLogPanel = require('../../lib/reporters/dev/split_log_panel'); var Chars = require('../../lib/chars'); var TestResults = require('../../lib/reporters/dev/test_results'); var isWin = /^win/.test(process.platform); describe('SplitLogPanel', !isWin ? function() { var runner, panel, appview, results, messages, sandbox; beforeEach(function() { sandbox = sinon.sandbox.create(); screen.$setSize(10, 20); results = new TestResults(); messages = new Backbone.Collection(); runner = new Backbone.Model({ results: results, messages: messages }); appview = new Backbone.Model({ cols: 10, lines: 20 }); runner.hasMessages = function() { return true; }; runner.hasResults = function() { return true; }; panel = new SplitLogPanel({ runner: runner, appview: appview, visible: true, screen: screen }); }); afterEach(function() { sandbox.restore(); }); describe('getResultsDisplayText', function() { it.skip('gets topLevelError', function() { expect(panel.getResultsDisplayText().unstyled()).to.equal(''); results.set('topLevelError', 'Shit happened.'); expect(panel.getResultsDisplayText().unstyled()).to.equal('Top Level:\n Shit happened.\n\n'); }); it('says "Please be patient" if not all results are in', function() { var tests = new Backbone.Collection(); results.set('tests', tests); expect(panel.getResultsDisplayText().unstyled()).to.equal('Please be patient :)'); }); it('says "No tests were run :(" when no tests but all is true', function() { var tests = new Backbone.Collection(); results.set('tests', tests); results.set('all', true); expect(panel.getResultsDisplayText().unstyled()).to.equal('No tests were run :('); }); it('gives result when has results and all is true', function() { results.set('total', 1); results.set('pending', 0); var tests = new Backbone.Collection([ new Backbone.Model({ name: 'blah', passed: true }) ]); results.set('tests', tests); results.set('all', true); expect(panel.getResultsDisplayText().unstyled()).to.equal(Chars.success + ' 1 tests complete.'); }); it('shows pending tests in yellow when has results, all is true, no tests failed and there are pending tests', function() { results.set('total', 1); results.set('pending', 1); var tests = new Backbone.Collection([ new Backbone.Model({ name: 'blah', pending: true }) ]); results.set('tests', tests); results.set('all', true); var text = panel.getResultsDisplayText(); expect(text.children).to.have.length(2); var resultText = text.children[0]; var pendingText = text.children[1]; expect(resultText.str).to.equal(Chars.success + ' 1 tests complete (1 pending).'); expect(resultText.attrs.foreground).to.equal('cyan'); expect(pendingText.str).to.equal('\n\n[PENDING] blah'); expect(pendingText.attrs.foreground).to.equal('yellow'); }); it('shows "failed" when failure', function() { results.set('total', 1); results.addResult({ name: 'blah', passed: false, failed: 1, items: [ { passed: false } ] }); results.set('all', true); expect(panel.getResultsDisplayText().unstyled()).to.match(/blah\n {4}[x✘] failed/); }); it('shows "failed" without items when failure', function() { results.set('total', 1); results.addResult({ name: 'blah', passed: false, failed: 1 }); results.set('all', true); expect(panel.getResultsDisplayText().unstyled()).to.match(/blah\n {4}/); }); it('shows the error message', function() { results.set('total', 1); var tests = new Backbone.Collection([ new Backbone.Model({ name: 'blah', passed: false, failed: 1, items: [ { message: 'should not be null', passed: false } ] }) ]); results.set('tests', tests); results.set('all', true); expect(panel.getResultsDisplayText().unstyled()).to.match(/blah\n {4}[x✘] should not be null/); }); it('shows the stacktrace', function() { results.set('total', 1); var tests = new Backbone.Collection([ new Backbone.Model({ name: 'blah', passed: false, failed: 1, items: [ { message: 'should not be null', passed: false, stack: [ 'AssertionError: ', ' at Module._compile (module.js:437:25)', ' at Object.Module._extensions..js (module.js:467:10)' ].join('\n') } ] }) ]); results.set('tests', tests); results.set('all', true); expect(panel.getResultsDisplayText().unstyled()).to.equal('blah\n ' + Chars.fail + ' should not be null\n AssertionError: \n at Module._compile (module.js:437:25)\n at Object.Module._extensions..js (module.js:467:10)'); }); it('says "Looking good..." if all is false but all passed so far', function() { results.set('total', 1); var tests = new Backbone.Collection([ new Backbone.Model({ name: 'blah', passed: true }) ]); results.set('tests', tests); expect(panel.getResultsDisplayText().unstyled()).to.equal('Looking good...'); }); }); describe('getMessagesText', function() { it('returns "" with no messages', function() { expect(panel.getMessagesText().unstyled()).to.equal(''); }); it('returns "" with empty collection', function() { var messages = new Backbone.Collection(); runner.set('messages', messages); expect(panel.getMessagesText().unstyled()).to.equal(''); }); it('returns the messages', function() { var messages = new Backbone.Collection([ new Backbone.Model({type: 'log', text: 'hello world'}) ]); runner.set('messages', messages); expect(panel.getMessagesText().unstyled()).to.equal('hello world'); messages.add(new Backbone.Model({type: 'error', text: 'crap happens'})); expect(panel.getMessagesText().unstyled()).to.equal('hello worldcrap happens'); }); }); describe('targetPanel', function() { it('is the top if only has test results', function() { sandbox.stub(runner, 'hasResults').returns(true); sandbox.stub(runner, 'hasMessages').returns(false); expect(panel.targetPanel()).to.equal(panel.topPanel); }); it('is the bottom if only has messages', function() { sandbox.stub(runner, 'hasResults').returns(false); sandbox.stub(runner, 'hasMessages').returns(true); expect(panel.targetPanel()).to.equal(panel.bottomPanel); }); context('has both results and messages', function() { beforeEach(function() { sandbox.stub(runner, 'hasResults').returns(true); sandbox.stub(runner, 'hasMessages').returns(true); }); it('is the top if focused on top', function() { panel.set('focus', 'top'); expect(panel.targetPanel()).to.equal(panel.topPanel); }); it('is the bottom if focused on bottom', function() { panel.set('focus', 'bottom'); expect(panel.targetPanel()).to.equal(panel.bottomPanel); }); }); it('is the top if has neither', function() { sandbox.stub(runner, 'hasResults').returns(false); sandbox.stub(runner, 'hasMessages').returns(false); expect(panel.targetPanel()).to.equal(panel.topPanel); }); }); describe('scrolling', function() { 'scrollUp scrollDown pageUp pageDown halfPageUp halfPageDown'.split(' ').forEach(function(method) { it('delegates ' + method + ' to the target Panel', function() { var targetPanel = {}; targetPanel[method] = sandbox.spy(); sandbox.stub(panel, 'targetPanel').returns(targetPanel); panel[method](); expect(targetPanel[method]).to.have.been.called(); }); }); }); describe('syncDimensions', function() { it('shows both panels if has both results and messages', function() { sandbox.stub(runner, 'hasResults').returns(true); sandbox.stub(runner, 'hasMessages').returns(true); panel.syncDimensions(); expect(panel.topPanel.get('height')).to.equal(6); expect(panel.bottomPanel.get('height')).to.equal(6); }); it('show top panel only if only has results', function() { sandbox.stub(runner, 'hasResults').returns(true); sandbox.stub(runner, 'hasMessages').returns(false); panel.syncDimensions(); expect(panel.topPanel.get('height')).to.equal(12); expect(panel.bottomPanel.get('height')).to.equal(0); }); it('show bottom panel only if only has messages', function() { sandbox.stub(runner, 'hasResults').returns(false); sandbox.stub(runner, 'hasMessages').returns(true); panel.syncDimensions(); expect(panel.topPanel.get('height')).to.equal(0); expect(panel.bottomPanel.get('height')).to.equal(12); }); }); describe('render', function() { it('renders', function() { sandbox.stub(panel, 'getResultsDisplayText').returns('1 tests passed.'); sandbox.stub(panel, 'getMessagesText').returns('This is a message.'); panel.syncResultsDisplay(); panel.syncMessages(); panel.render(); expect(screen.buffer).to.deep.equal([ ' ', ' ', ' ', ' ', ' ', ' ', ' ', '1 tests pa', 'ssed. ', ' ', ' ', ' ', ' ', 'This is a ', 'message. ', ' ', ' ', ' ', ' ', ' ']); }); }); } : function() { xit('TODO: Fix and re-enable for windows'); });
/** * @file 字符串相关的函数 * @author mengke01(kekee000@gmail.com) */ define( function (require) { var string = { /** * HTML解码字符串 * * @param {string} source 源字符串 * @return {string} */ decodeHTML: function (source) { var str = String(source) .replace(/&quot;/g, '"') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&'); // 处理转义的中文和实体字符 return str.replace(/&#([\d]+);/g, function ($0, $1) { return String.fromCharCode(parseInt($1, 10)); }); }, /** * HTML编码字符串 * * @param {string} source 源字符串 * @return {string} */ encodeHTML: function (source) { return String(source) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); }, /** * 获取string字节长度 * * @param {string} source 源字符串 * @return {number} 长度 */ getLength: function (source) { return String(source).replace(/[^\x00-\xff]/g, '11').length; }, /** * 字符串格式化,支持如 ${xxx.xxx} 的语法 * @param {string} source 模板字符串 * @param {Object} data 数据 * @return {string} 格式化后字符串 */ format: function (source, data) { return source.replace(/\$\{([\w.]+)\}/g, function ($0, $1) { var ref = $1.split('.'); var refObject = data; var level; while (refObject != null && (level = ref.shift())) { refObject = refObject[level]; } return refObject != null ? refObject : ''; }); }, /** * 使用指定字符填充字符串,默认`0` * * @param {string} str 字符串 * @param {number} size 填充到的大小 * @param {string=} ch 填充字符 * @return {string} 字符串 */ pad: function (str, size, ch) { str = String(str); if (str.length > size) { return str.slice(str.length - size); } return new Array(size - str.length + 1).join(ch || '0') + str; }, /** * 获取字符串哈希编码 * @param {string} str 字符串 * @return {number} 哈希值 */ hashcode: function (str) { if (!str) { return 0; } var hash = 0; for (var i = 0, l = str.length; i < l; i++) { hash = 0x7FFFFFFFF & (hash * 31 + str.charCodeAt(i)); } return hash; } }; return string; } );
var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') var config = require('./webpack.base.config.js') // Use webpack dev server config.entry = [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './assets/js/index' ] // override django's STATIC_URL for webpack bundles config.output.publicPath = 'http://localhost:3000/assets/bundles/' // Add HotModuleReplacementPlugin and BundleTracker plugins config.plugins = config.plugins.concat([ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new BundleTracker({filename: './webpack-stats.json'}), ]) // Add a loader for JSX files with react-hot enabled config.module.loaders.push( { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['react-hot', 'babel'] } ) module.exports = config
var spdy = require('spdy'); var http = require('http'); var assert = require('assert'); describe('SPDY Proxy', function() { var spdyAgent; before(function(done) { var i = 2; process.argv[i++] = '--key'; process.argv[i++] = __dirname + '/../keys/mykey.pem'; process.argv[i++] = '--cert'; process.argv[i++] = __dirname + '/../keys/mycert.pem'; require('../bin/spdyproxy'); spdyAgent = spdy.createAgent({ host: '127.0.0.1', port: 44300, rejectUnauthorized: false }); done(); }); it('should be able to fetch www.google.com over spdy via GET', function(done) { var options = { method: 'GET', host: 'www.google.com', agent: spdyAgent }; var req = http.request(options, function(res) { var googlePage = ""; assert.equal(res.statusCode, 200); res.on('data', function(chunk) { googlePage += chunk.toString(); }); res.on('end', function() { assert.notEqual(googlePage.search('google'), -1, "Google page should contain string 'google'"); done(); }); }); req.end(); }); it('should be able to fetch www.google.com over spdy via CONNECT', function(done) { var options = { method: 'CONNECT', path: 'www.google.com:80', agent: spdyAgent }; var req = http.request(options); req.end(); req.on('connect', function(res, socket) { var googlePage = ""; socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', function(chunk) { googlePage = googlePage + chunk.toString(); }); socket.on('end', function() { assert.notEqual(googlePage.search('google'), -1, "Google page should contain string 'google'"); done(); }); }); }); after(function(done) { spdyAgent.close(function() { done(); }); }); });
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Guest disk signature based disk exclusion option when doing enable * protection of virtual machine in InMage provider. * */ class InMageVolumeExclusionOptions { /** * Create a InMageVolumeExclusionOptions. * @member {string} [volumeLabel] The volume label. The disk having any * volume with this label will be excluded from replication. * @member {string} [onlyExcludeIfSingleVolume] The value indicating whether * to exclude multi volume disk or not. If a disk has multiple volumes and * one of the volume has label matching with VolumeLabel this disk will be * excluded from replication if OnlyExcludeIfSingleVolume is false. */ constructor() { } /** * Defines the metadata of InMageVolumeExclusionOptions * * @returns {object} metadata of InMageVolumeExclusionOptions * */ mapper() { return { required: false, serializedName: 'InMageVolumeExclusionOptions', type: { name: 'Composite', className: 'InMageVolumeExclusionOptions', modelProperties: { volumeLabel: { required: false, serializedName: 'volumeLabel', type: { name: 'String' } }, onlyExcludeIfSingleVolume: { required: false, serializedName: 'OnlyExcludeIfSingleVolume', type: { name: 'String' } } } } }; } } module.exports = InMageVolumeExclusionOptions;
var fireworks = (function() { var canvasEl = document.querySelector('.fireworks'); var ctx = canvasEl.getContext('2d'); var numberOfParticules = Number(location.href.split('?')[1]) || 40; var pointerX = 0; var pointerY = 0; var tap = ('ontouchstart' in window || navigator.msMaxTouchPoints) ? 'touchstart' : 'mousedown'; var colors = ['#FF1461', '#18FF92', '#5A87FF', '#FBF38C']; function setCanvasSize() { canvasEl.width = window.innerWidth * 2; canvasEl.height = window.innerHeight * 2; canvasEl.style.width = window.innerWidth + 'px'; canvasEl.style.height = window.innerHeight + 'px'; canvasEl.getContext('2d').scale(2, 2); } function updateCoords(e) { pointerX = e.clientX || e.touches[0].clientX; pointerY = e.clientY || e.touches[0].clientY; } function setParticuleDirection(p) { var angle = anime.random(0, 360) * Math.PI / 180; var value = anime.random(50, 180); var radius = [-1, 1][anime.random(0, 1)] * value; return { x: p.x + radius * Math.cos(angle), y: p.y + radius * Math.sin(angle) } } function createParticule(x,y) { var p = {}; p.x = x; p.y = y; p.color = colors[anime.random(0, colors.length - 1)]; p.radius = anime.random(16, 32); p.endPos = setParticuleDirection(p); p.draw = function() { ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true); ctx.fillStyle = p.color; ctx.fill(); } return p; } function createCircle(x,y) { var p = {}; p.x = x; p.y = y; p.color = '#FFF'; p.radius = 0.1; p.alpha = .5; p.lineWidth = 6; p.draw = function() { ctx.globalAlpha = p.alpha; ctx.beginPath(); ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true); ctx.lineWidth = p.lineWidth; ctx.strokeStyle = p.color; ctx.stroke(); ctx.globalAlpha = 1; } return p; } function renderParticule(anim) { for (var i = 0; i < anim.animatables.length; i++) { anim.animatables[i].target.draw(); } } function animateParticules(x, y) { var circle = createCircle(x, y); var particules = []; for (var i = 0; i < numberOfParticules; i++) { particules.push(createParticule(x, y)); } anime.timeline().add({ targets: particules, x: function(p) { return p.endPos.x; }, y: function(p) { return p.endPos.y; }, radius: 0.1, duration: anime.random(1200, 1800), easing: 'easeOutExpo', update: renderParticule }) .add({ targets: circle, radius: anime.random(80, 160), lineWidth: 0, alpha: { value: 0, easing: 'linear', duration: anime.random(600, 800), }, duration: anime.random(1200, 1800), easing: 'easeOutExpo', update: renderParticule, offset: 0 }); } var render = anime({ duration: Infinity, update: function() { ctx.clearRect(0, 0, canvasEl.width, canvasEl.height); } }); document.addEventListener(tap, function(e) { window.human = true; render.play(); updateCoords(e); animateParticules(pointerX, pointerY); ga('send', 'event', 'Fireworks', 'Click'); }, false); window.addEventListener('resize', setCanvasSize, false); return { render: render, setCanvasSize: setCanvasSize, animateParticules: animateParticules } })();
import events from './events' import hed from './hed' import validate from './validate' export default { events: events, hed: hed, validateEvents: validate, }
var testcase = require('nodeunit').testCase; var jsdom = require("../.."); var EventMonitor = function() { self = this; self.atEvents = []; self.bubbledEvents = []; self.capturedEvents = []; self.allEvents = []; self.handleEvent = function(event) { self.allEvents.push(event); switch(event.eventPhase) { case event.CAPTURING_PHASE: self.capturedEvents.push(event); break; case event.AT_TARGET: self.atEvents.push(event); break; case event.BUBBLING_PHASE: self.bubbledEvents.push(event); break; default: throw new Error("Unspecified event phase"); } }; }; var _setUp = function() { var doc = require('../level1/core/files/hc_staff.xml').hc_staff(); var monitor = this.monitor = new EventMonitor(); this.win = doc.defaultView; this.title = doc.getElementsByTagName("title").item(0); this.body = doc.getElementsByTagName("body").item(0); this.plist = doc.getElementsByTagName("p").item(0); this.event = doc.createEvent("Events"); this._handleEvent = function(type) { return(function(event) { event[type](); monitor.handleEvent(event) }); } } var _tearDown = function(xs) { xs = ['monitor', 'title', 'body', 'plist', 'event', '_handleEvent'].concat(xs ? xs : []); var self = this; xs.forEach(function(x){ self[x] = undefined; delete(self[x]); }) } // A document is created using implementation.createDocument and cast to a DocumentEvent interface. // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent exports['DocumentEvent interface'] = function (test) { var doc = require('../level1/core/files/hc_staff.xml').hc_staff(); test.ok((doc.createEvent instanceof Function), "should have createEvent function"); test.done(); } // A document is created using implementation.createDocument and cast to a EventTarget interface. // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget exports['EventTarget interface'] = function (test) { var doc = require('../level1/core/files/hc_staff.xml').hc_staff(); test.ok((doc instanceof doc.defaultView.EventTarget), 'should be an instance of EventTarget'); test.done(); } // An object implementing the Event interface is created by using DocumentEvent.createEvent method with an eventType // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-DocumentEvent-createEvent exports['create event with each event type'] = function(test){ var doc = require('../level1/core/files/hc_staff.xml').hc_staff(), event_types = {'Events': doc.defaultView.Event, 'MutationEvents': doc.defaultView.MutationEvent, 'UIEvents': doc.defaultView.UIEvent, 'MouseEvents': doc.defaultView.MouseEvent , 'HTMLEvents': doc.defaultView.Event}; test.expect(10); for (var type in event_types) { var event = doc.createEvent(type); test.notEqual(event, null, "should not be null for " + type); test.ok((event instanceof event_types[type]),"should be instanceof " + type); } test.done(); } // @see https://dom.spec.whatwg.org/#interface-event exports['event interface eventInit parameter'] = function (test) { var doc = jsdom.jsdom(); testEventConstructor(doc.defaultView.Event); testEventConstructor(doc.defaultView.UIEvent); testEventConstructor(doc.defaultView.MouseEvent); testEventConstructor(doc.defaultView.MutationEvent); test.done(); function testEventConstructor(Constructor) { test.throws(function () { new Constructor('myevent', 'not a dictionary'); }, TypeError); var event = new Constructor('myevent'); test.equal(event.bubbles, false); test.equal(event.cancelable, false); event = new Constructor('myevent', null); test.equal(event.bubbles, false); test.equal(event.cancelable, false); event = new Constructor('myevent', { bubbles: true }); test.equal(event.bubbles, true); test.equal(event.cancelable, false); event = new Constructor('myevent', { cancelable: true }); test.equal(event.bubbles, false); test.equal(event.cancelable, true); event = new Constructor('myevent', { bubbles: true, cancelable: true }); test.equal(event.bubbles, true); test.equal(event.cancelable, true); event = new Constructor('myevent', {}); test.equal(event.bubbles, false); test.equal(event.cancelable, false); event = new Constructor('myevent', { bubbles: null, cancelable: null }); test.equal(event.bubbles, false); test.equal(event.cancelable, false); event = new Constructor('myevent', { bubbles: 0, cancelable: 0 }); test.equal(event.bubbles, false); test.equal(event.cancelable, false); // values > 0 are considered true event = new Constructor('myevent', { bubbles: 1, cancelable: 1 }); test.equal(event.bubbles, true); test.equal(event.cancelable, true); // values > 0 are considered true event = new Constructor('myevent', { bubbles: 10, cancelable: 10 }); test.equal(event.bubbles, true); test.equal(event.cancelable, true); // empty string is considered false event = new Constructor('myevent', { bubbles: "", cancelable: "" }); test.equal(event.bubbles, false); test.equal(event.cancelable, false); // non empty string is considered true event = new Constructor('myevent', { bubbles: "false", cancelable: "false" }); test.equal(event.bubbles, true); test.equal(event.cancelable, true); // non empty string is considered true event = new Constructor('myevent', { bubbles: "true", cancelable: "true" }); test.equal(event.bubbles, true); test.equal(event.cancelable, true); } } // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-EventTarget-dispatchEvent // @see http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-17189187 exports['dispatch event'] = testcase({ setUp: function(cb){ this.doc = require('../level1/core/files/hc_staff.xml').hc_staff(); cb(); }, tearDown: function(cb){ _tearDown.call(this, 'doc'); cb(); }, 'a null reference passed to dispatchEvent': function (test) { var doc = this.doc; test.throws(function(){ doc.dispatchEvent(null) }, TypeError, 'should throw an exception'); // TODO: figure out the best way to test (exception.code == 0) and (exception.message == 'Null event') test.done(); }, 'a created but not initialized event passed to dispatchEvent': function (test) { var doc = this.doc, event_types = ['Events', 'MutationEvents', 'UIEvents', 'MouseEvents', 'HTMLEvents']; test.expect(event_types.length); event_types.forEach(function(type){ test.throws(function(){ doc.dispatchEvent(doc.createEvent(type)) }, doc.defaultView.DOMException, 'should throw an exception for ' + type); }) test.done(); }, 'an Event initialized with a empty name passed to dispatchEvent': function (test) { var doc = this.doc, event = doc.createEvent("Events"); event.initEvent("",false,false); test.throws(function(){ doc.dispatchEvent(event) }, doc.defaultView.DOMException, 'should throw an exception'); test.done(); }, // An EventListener registered on the target node with capture false, should receive any event fired on that node. 'EventListener with capture false': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); test.expect(7); test.strictEqual(event.eventPhase, 0); test.strictEqual(event.currentTarget, null); this.doc.dispatchEvent(event); test.equal(monitor.atEvents.length, 1, 'should receive atEvent'); test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase'); test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase'); test.strictEqual(event.eventPhase, 0); test.strictEqual(event.currentTarget, null); test.done(); }, // An EventListener registered on the target node with capture true, should receive any event fired on that node. 'EventListener with capture true': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, true); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); test.expect(7); test.strictEqual(event.eventPhase, 0); test.strictEqual(event.currentTarget, null); this.doc.dispatchEvent(event); test.equal(monitor.atEvents.length, 1, 'should receive atEvent'); test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase'); test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase'); test.strictEqual(event.eventPhase, 0); test.strictEqual(event.currentTarget, null); test.done(); }, // The same monitor is registered twice and an event is dispatched. The monitor should receive only one handleEvent call. 'EventListener is registered twice': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.addEventListener("foo", monitor.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.expect(3); test.equal(monitor.atEvents.length, 1, 'should receive atEvent only once'); test.equal(monitor.bubbledEvents.length, 0, 'should not receive at bubble phase'); test.equal(monitor.capturedEvents.length, 0, 'should not receive at capture phase'); test.done(); }, // The same monitor is registered twice, removed once, and an event is dispatched. The monitor should receive only no handleEvent calls. 'EventListener is registered twice, removed once': function (test) { var monitor = new EventMonitor(); this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.removeEventListener("foo", monitor.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.equal(monitor.allEvents.length, 0, 'should not receive any handleEvent calls'); test.done(); }, // A monitor is added, multiple calls to removeEventListener are made with similar but not identical arguments, and an event is dispatched. // The monitor should receive handleEvent calls. 'EventListener is registered, other listeners (similar but not identical) are removed': function (test) { var monitor = new EventMonitor(); var other = {handleEvent: function(){}} this.doc.addEventListener("foo", monitor.handleEvent, false); this.doc.removeEventListener("foo", monitor.handleEvent, true); this.doc.removeEventListener("food", monitor.handleEvent, false); this.doc.removeEventListener("foo", other.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.equal(monitor.allEvents.length, 1, 'should still receive the handleEvent call'); test.done(); }, // Two listeners are registered on the same target, each of which will remove both itself and the other on the first event. Only one should see the event since event listeners can never be invoked after being removed. 'two EventListeners which both handle by unregistering itself and the other': function (test) { // setup var es = []; var ls = []; var EventListener1 = function() { ls.push(this); } var EventListener2 = function() { ls.push(this); } EventListener1.prototype.handleEvent = function(event) { _handleEvent(event); } EventListener2.prototype.handleEvent = function(event) { _handleEvent(event); } var _handleEvent = function(event) { es.push(event); ls.forEach(function(l){ event.currentTarget.removeEventListener("foo", l.handleEvent, false); }) } // test var listener1 = new EventListener1(); var listener2 = new EventListener2(); this.doc.addEventListener("foo", listener1.handleEvent, false); this.doc.addEventListener("foo", listener2.handleEvent, false); var event = this.doc.createEvent("Events"); event.initEvent("foo",true,false); this.doc.dispatchEvent(event); test.equal(es.length, 1, 'should only be handled by one EventListener'); test.done(); } }) // The Event.initEvent method is called for event returned by DocumentEvent.createEvent("Events") and DocumentEvent.createEvent("MutationEvents") // The state is checked to see if it reflects the parameters. // @author Curt Arnold // @see http://www.w3.org/TR/DOM-Level-2-Events/events#Events-Event-initEvent exports['init event'] = testcase({ setUp: function(cb){ var doc = require('../level1/core/files/hc_staff.xml').hc_staff(); this._events = ['Events', 'MutationEvents'].map(function(t){ return(doc.createEvent(t)); }) cb(); }, tearDown: function(cb){ _tearDown.call(this, '_events'); cb(); }, 'set state from params, bubble no cancel': function (test) { test.expect(8); this._events.forEach(function(event){ test.notEqual(event, null, 'event should not be null for ' + event.eventType); event.initEvent('rotate', true, false); test.equal(event.type, 'rotate', 'event type should be \"rotate\" for ' + event.eventType); test.equal(event.bubbles, true, 'event should bubble for ' + event.eventType); test.equal(event.cancelable, false, 'event should not be cancelable for ' + event.eventType); }) test.done(); }, 'set state from params, cancel no bubble': function (test) { test.expect(8); this._events.forEach(function(event){ test.notEqual(event, null, 'event should not be null for' + event.eventType); event.initEvent('rotate', false, true); test.equal(event.type, 'rotate', 'event type should be \"rotate\" for ' + event.eventType); test.equal(event.bubbles, false, 'event should not bubble for ' + event.eventType); test.equal(event.cancelable, true, 'event should be cancelable for ' + event.eventType); }) test.done(); }, 'initEvent called multiple times, final time is definitive': function (test) { test.expect(14); this._events.forEach(function(event){ test.notEqual(event, null, 'event should not be null for ' + event.eventType); // rotate event.initEvent("rotate", true, true); test.equal(event.type, 'rotate', 'event type should be \"rotate\" for ' + event.eventType); test.equal(event.bubbles, true, 'event should bubble for ' + event.eventType); test.equal(event.cancelable, true, 'event should be cancelable for ' + event.eventType); // shear event.initEvent("shear", false, false); test.equal(event.type, 'shear', 'event type should be \"shear\" for ' + event.eventType); test.equal(event.bubbles, false, 'event should not bubble for ' + event.eventType); test.equal(event.cancelable, false, 'event should not be cancelable for ' + event.eventType); }) test.done(); }, }) exports['capture event'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,false); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'all capturing listeners in a direct line from dispatched node will receive the event': function(test) { this.plist.addEventListener("foo", this.monitor.handleEvent, true); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 0, 'should not have any bubbled events'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); }, 'only capture listeners in a direct line from target to the document node should receive the event': function(test) { var self = this; this.title.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", function(event) { event.preventDefault(); self.monitor.handleEvent(event) }, false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, true, 'dispatchEvent should return *true*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have bubbled 1 event'); test.equal(this.monitor.capturedEvents.length, 0, 'should not have captured any events'); test.done(); } }) exports['bubble event'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,false); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'all non-capturing listeners in a direct line from dispatched node will receive a bubbling event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 2, 'should have 2 bubbled events'); test.equal(this.monitor.capturedEvents.length, 0, 'should not have any captured events'); test.done(); }, 'only bubble listeners in a direct line from target to the document node should receive the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.title.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), true); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, true, 'dispatchEvent should return *true*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have 1 bubbled event'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); }, 'if an event does not bubble, bubble listeners should not receive the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.body.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.event.initEvent("foo",false,false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, true, 'dispatchEvent should return *true*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 0, 'should not have any bubbled events'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); } }) exports['stop propagation'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,false); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'should prevent the target from receiving the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('stopPropagation'), true); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 0, 'should be at 0 events'); test.equal(this.monitor.bubbledEvents.length, 0, 'should have no bubbled events'); test.equal(this.monitor.capturedEvents.length, 1, 'should have 1 captured event'); test.done(); }, 'should prevent all listeners from receiving the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.body.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('stopPropagation'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.plist.firstChild.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have 1 bubbled event'); test.equal(this.monitor.capturedEvents.length, 0, 'should have no captured events'); test.done(); }, 'stopPropagation should not prevent listeners on the same element from receiving the event': function(test) { this.win.addEventListener("foo", this.monitor.handleEvent, false); this.body.addEventListener("foo", this.monitor.handleEvent, false); this.plist.addEventListener("foo", this._handleEvent('stopPropagation'), true); this.plist.addEventListener("foo", this._handleEvent('stopPropagation'), false); this.plist.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this.monitor.handleEvent, false); this.plist.dispatchEvent(this.event); test.expect(3); test.equal(this.monitor.atEvents.length, 4, 'should be at 4 events'); test.equal(this.monitor.bubbledEvents.length, 0, 'should have no bubbled events'); test.equal(this.monitor.capturedEvents.length, 0, 'should have no captured events'); test.done(); } }) exports['prevent default'] = testcase({ setUp: function(cb){ _setUp.call(this); this.event.initEvent("foo",true,true); cb(); }, tearDown: function(cb){ _tearDown.call(this); cb(); }, 'the defaultPrevented flag is set when the event is prevented': function(test) { this.title.addEventListener("foo", function(event) { event.preventDefault();}, false); var return_val = this.title.dispatchEvent(this.event); test.equal(this.event.defaultPrevented, true, 'the defaultPrevented flag should be true when the event is prevented'); test.done(); }, 'the defaultPrevented flag is not set when the event is not prevented': function(test) { this.title.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.title.dispatchEvent(this.event); test.equal(this.event.defaultPrevented, false, 'the defaultPrevented flag should be false when the event is not prevented'); test.done(); }, 'a cancelable event can have its default event disabled': function(test) { this.body.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, false, 'dispatchEvent should return *false*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have bubbled 1 event'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); }, 'a non-cancelable event cannot have its default event disabled': function(test) { this.body.addEventListener("foo", this.monitor.handleEvent, true); this.plist.addEventListener("foo", this._handleEvent('preventDefault'), false); this.plist.firstChild.addEventListener("foo", this.monitor.handleEvent, false); this.event.initEvent("foo",true,false); var return_val = this.plist.firstChild.dispatchEvent(this.event); test.expect(4); test.equal(return_val, true, 'dispatchEvent should return *true*'); test.equal(this.monitor.atEvents.length, 1, 'should be at 1 event'); test.equal(this.monitor.bubbledEvents.length, 1, 'should have bubbled 1 event'); test.equal(this.monitor.capturedEvents.length, 1, 'should have captured 1 event'); test.done(); } })
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _unstyled = require("@material-ui/unstyled"); var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled")); var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps")); var _Typography = _interopRequireDefault(require("../Typography")); var _alertTitleClasses = require("./alertTitleClasses"); var _jsxRuntime = require("react/jsx-runtime"); const useUtilityClasses = styleProps => { const { classes } = styleProps; const slots = { root: ['root'] }; return (0, _unstyled.unstable_composeClasses)(slots, _alertTitleClasses.getAlertTitleUtilityClass, classes); }; const AlertTitleRoot = (0, _experimentalStyled.default)(_Typography.default, {}, { name: 'MuiAlertTitle', slot: 'Root', overridesResolver: (props, styles) => styles.root })(({ theme }) => { /* Styles applied to the root element. */ return { fontWeight: theme.typography.fontWeightMedium, marginTop: -2 }; }); const AlertTitle = /*#__PURE__*/React.forwardRef(function AlertTitle(inProps, ref) { const props = (0, _useThemeProps.default)({ props: inProps, name: 'MuiAlertTitle' }); const { className } = props, other = (0, _objectWithoutPropertiesLoose2.default)(props, ["className"]); // TODO: convert to simple assignment after the type error in defaultPropsHandler.js:60:6 is fixed const styleProps = (0, _extends2.default)({}, props); const classes = useUtilityClasses(styleProps); return /*#__PURE__*/(0, _jsxRuntime.jsx)(AlertTitleRoot, (0, _extends2.default)({ gutterBottom: true, component: "div", styleProps: styleProps, ref: ref, className: (0, _clsx.default)(classes.root, className) }, other)); }); process.env.NODE_ENV !== "production" ? AlertTitle.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. */ classes: _propTypes.default.object, /** * @ignore */ className: _propTypes.default.string, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: _propTypes.default.object } : void 0; var _default = AlertTitle; exports.default = _default;
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.styles = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _withStyles = _interopRequireDefault(require("../styles/withStyles")); var _ListContext = _interopRequireDefault(require("./ListContext")); var styles = { /* Styles applied to the root element. */ root: { listStyle: 'none', margin: 0, padding: 0, position: 'relative' }, /* Styles applied to the root element if `disablePadding={false}`. */ padding: { paddingTop: 8, paddingBottom: 8 }, /* Styles applied to the root element if dense. */ dense: {}, /* Styles applied to the root element if a `subheader` is provided. */ subheader: { paddingTop: 0 } }; exports.styles = styles; var List = React.forwardRef(function List(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$component = props.component, Component = _props$component === void 0 ? 'ul' : _props$component, _props$dense = props.dense, dense = _props$dense === void 0 ? false : _props$dense, _props$disablePadding = props.disablePadding, disablePadding = _props$disablePadding === void 0 ? false : _props$disablePadding, subheader = props.subheader, other = (0, _objectWithoutProperties2.default)(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]); var context = React.useMemo(function () { return { dense: dense }; }, [dense]); return React.createElement(_ListContext.default.Provider, { value: context }, React.createElement(Component, (0, _extends2.default)({ className: (0, _clsx.default)(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader), ref: ref }, other), subheader, children)); }); process.env.NODE_ENV !== "production" ? List.propTypes = { /** * The content of the component. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object.isRequired, /** * @ignore */ className: _propTypes.default.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: _propTypes.default.elementType, /** * If `true`, compact vertical padding designed for keyboard and mouse input will be used for * the list and list items. * The prop is available to descendant components as the `dense` context. */ dense: _propTypes.default.bool, /** * If `true`, vertical padding will be removed from the list. */ disablePadding: _propTypes.default.bool, /** * The content of the subheader, normally `ListSubheader`. */ subheader: _propTypes.default.node } : void 0; var _default = (0, _withStyles.default)(styles, { name: 'MuiList' })(List); exports.default = _default;
"use strict";"production"===process.env.NODE_ENV?module.exports=require("./oidc-client-ts.cjs.production.min.js"):module.exports=require("./oidc-client-ts.cjs.development.js");
import Vue from 'vue'; import ErrorTrackingSettings from './components/app.vue'; import createStore from './store'; export default () => { const formContainerEl = document.querySelector('.js-error-tracking-form'); const { dataset: { apiHost, enabled, project, token, listProjectsEndpoint, operationsSettingsEndpoint }, } = formContainerEl; return new Vue({ el: formContainerEl, store: createStore(), render(createElement) { return createElement(ErrorTrackingSettings, { props: { initialApiHost: apiHost, initialEnabled: enabled, initialProject: project, initialToken: token, listProjectsEndpoint, operationsSettingsEndpoint, }, }); }, }); };
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import invariant from 'shared/invariant'; // Renderers that don't support microtasks // can re-export everything from this module. function shim(...args: any) { invariant( false, 'The current renderer does not support microtasks. ' + 'This error is likely caused by a bug in React. ' + 'Please file an issue.', ); } // Test selectors (when unsupported) export const supportsMicrotasks = false; export const scheduleMicrotask = shim;
define(function() { var ctor = function () { }; return ctor; });
/** @module ember @submodule ember-views */ import { inspect } from 'ember-utils'; import { Mixin, get, isNone, assert } from 'ember-metal'; import { MUTABLE_CELL } from '../compat/attrs'; function validateAction(component, actionName) { if (actionName && actionName[MUTABLE_CELL]) { actionName = actionName.value; } assert( 'The default action was triggered on the component ' + component.toString() + ', but the action name (' + actionName + ') was not a string.', isNone(actionName) || typeof actionName === 'string' || typeof actionName === 'function' ); return actionName; } /** @class ActionSupport @namespace Ember @private */ export default Mixin.create({ /** Calls an action passed to a component. For example a component for playing or pausing music may translate click events into action notifications of "play" or "stop" depending on some internal state of the component: ```javascript // app/components/play-button.js export default Ember.Component.extend({ click() { if (this.get('isPlaying')) { this.sendAction('play'); } else { this.sendAction('stop'); } } }); ``` The actions "play" and "stop" must be passed to this `play-button` component: ```handlebars {{! app/templates/application.hbs }} {{play-button play=(action "musicStarted") stop=(action "musicStopped")}} ``` When the component receives a browser `click` event it translate this interaction into application-specific semantics ("play" or "stop") and calls the specified action. ```javascript // app/controller/application.js export default Ember.Controller.extend({ actions: { musicStarted() { // called when the play button is clicked // and the music started playing }, musicStopped() { // called when the play button is clicked // and the music stopped playing } } }); ``` If no action is passed to `sendAction` a default name of "action" is assumed. ```javascript // app/components/next-button.js export default Ember.Component.extend({ click() { this.sendAction(); } }); ``` ```handlebars {{! app/templates/application.hbs }} {{next-button action=(action "playNextSongInAlbum")}} ``` ```javascript // app/controllers/application.js App.ApplicationController = Ember.Controller.extend({ actions: { playNextSongInAlbum() { ... } } }); ``` @method sendAction @param [action] {String} the action to call @param [params] {*} arguments for the action @public */ sendAction(action, ...contexts) { let actionName; // Send the default action if (action === undefined) { action = 'action'; } actionName = get(this, `attrs.${action}`) || get(this, action); actionName = validateAction(this, actionName); // If no action name for that action could be found, just abort. if (actionName === undefined) { return; } if (typeof actionName === 'function') { actionName(...contexts); } else { this.triggerAction({ action: actionName, actionContext: contexts }); } }, send(actionName, ...args) { let target; let action = this.actions && this.actions[actionName]; if (action) { let shouldBubble = action.apply(this, args) === true; if (!shouldBubble) { return; } } target = get(this, 'target'); if (target) { assert( 'The `target` for ' + this + ' (' + target + ') does not have a `send` method', typeof target.send === 'function' ); target.send(...arguments); } else { assert(`${inspect(this)} had no action handler for: ${actionName}`, action); } } });
// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010. // Author Larry Kuhns 2011 import { StaveModifier } from './stavemodifier'; export class StaveSection extends StaveModifier { static get CATEGORY() { return 'stavesection'; } constructor(section, x, shift_y) { super(); this.setAttribute('type', 'StaveSection'); this.setWidth(16); this.section = section; this.x = x; this.shift_x = 0; this.shift_y = shift_y; this.font = { family: 'sans-serif', size: 12, weight: 'bold', }; } getCategory() { return StaveSection.CATEGORY; } setStaveSection(section) { this.section = section; return this; } setShiftX(x) { this.shift_x = x; return this; } setShiftY(y) { this.shift_y = y; return this; } draw(stave, shift_x) { const ctx = stave.checkContext(); this.setRendered(); ctx.save(); ctx.lineWidth = 2; ctx.setFont(this.font.family, this.font.size, this.font.weight); const text_width = ctx.measureText('' + this.section).width; let width = text_width + 6; // add left & right padding if (width < 18) width = 18; const height = 20; // Seems to be a good default y const y = stave.getYForTopText(3) + this.shift_y; let x = this.x + shift_x; ctx.beginPath(); ctx.lineWidth = 2; ctx.rect(x, y, width, height); ctx.stroke(); x += (width - text_width) / 2; ctx.fillText('' + this.section, x, y + 16); ctx.restore(); return this; } }
module.exports = adduser var uuid = require("node-uuid") , crypto try { } catch (ex) {} function sha (s) { return crypto.createHash("sha1").update(s).digest("hex") } function adduser (username, password, email, cb) { if (!crypto) crypto = require("crypto") password = ("" + (password || "")).trim() if (!password) return cb(new Error("No password supplied.")) email = ("" + (email || "")).trim() if (!email) return cb(new Error("No email address supplied.")) if (!email.match(/^[^@]+@[^\.]+\.[^\.]+/)) { return cb(new Error("Please use a real email address.")) } if (password.indexOf(":") !== -1) return cb(new Error( "Sorry, ':' chars are not allowed in passwords.\n"+ "See <https://issues.apache.org/jira/browse/COUCHDB-969> for why.")) var salt = uuid() , userobj = { name : username , salt : salt , password_sha : sha(password + salt) , email : email , _id : 'org.couchdb.user:'+username , type : "user" , roles : [] , date: new Date().toISOString() } cb = done.call(this, cb) this.log.verbose("adduser", "before first PUT", userobj) this.request('PUT' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) , userobj , function (error, data, json, response) { // if it worked, then we just created a new user, and all is well. // but if we're updating a current record, then it'll 409 first if (error && !this.auth) { // must be trying to re-auth on a new machine. // use this info as auth var b = new Buffer(username + ":" + password) this.auth = b.toString("base64") } if (!error || !response || response.statusCode !== 409) { return cb(error, data, json, response) } this.log.verbose("adduser", "update existing user") return this.request('GET' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) , function (er, data, json, response) { if (er || data.error) { return cb(er, data, json, response) } Object.keys(data).forEach(function (k) { if (!userobj[k]) { userobj[k] = data[k] } }) this.log.verbose("adduser", "userobj", userobj) this.request('PUT' , '/-/user/org.couchdb.user:'+encodeURIComponent(username) + "/-rev/" + userobj._rev , userobj , cb ) }.bind(this)) }.bind(this)) } function done (cb) { return function (error, data, json, response) { if (!error && (!response || response.statusCode === 201)) { return cb(error, data, json, response) } this.log.verbose("adduser", "back", [error, data, json]) if (!error) { error = new Error( (response && response.statusCode || "") + " "+ "Could not create user\n"+JSON.stringify(data)) } if (response && (response.statusCode === 401 || response.statusCode === 403)) { this.log.warn("adduser", "Incorrect username or password\n" +"You can reset your account by visiting:\n" +"\n" +" http://admin.npmjs.org/reset\n") } return cb(error) }.bind(this) }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<a4fd2ef174e1953094da46d80d9685b7>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ConcreteRequest, Query } from 'relay-runtime'; type useRefetchableFragmentNodeTestUserFragmentWithArgs$fragmentType = any; export type useRefetchableFragmentNodeTestUserQueryWithArgsQuery$variables = {| id: string, scale: number, |}; export type useRefetchableFragmentNodeTestUserQueryWithArgsQuery$data = {| +node: ?{| +$fragmentSpreads: useRefetchableFragmentNodeTestUserFragmentWithArgs$fragmentType, |}, |}; export type useRefetchableFragmentNodeTestUserQueryWithArgsQuery = {| variables: useRefetchableFragmentNodeTestUserQueryWithArgsQuery$variables, response: useRefetchableFragmentNodeTestUserQueryWithArgsQuery$data, |}; */ var node/*: ConcreteRequest*/ = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "id" }, { "defaultValue": null, "kind": "LocalArgument", "name": "scale" } ], v1 = [ { "kind": "Variable", "name": "id", "variableName": "id" } ]; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "useRefetchableFragmentNodeTestUserQueryWithArgsQuery", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "args": [ { "kind": "Variable", "name": "scaleLocal", "variableName": "scale" } ], "kind": "FragmentSpread", "name": "useRefetchableFragmentNodeTestUserFragmentWithArgs" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "useRefetchableFragmentNodeTestUserQueryWithArgsQuery", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, { "alias": null, "args": [ { "kind": "Variable", "name": "scale", "variableName": "scale" } ], "concreteType": "Image", "kind": "LinkedField", "name": "profile_picture", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "uri", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "username", "storageKey": null } ], "type": "User", "abstractKey": null } ], "storageKey": null } ] }, "params": { "cacheID": "076b06ded4fb8062510f564341b2af97", "id": null, "metadata": {}, "name": "useRefetchableFragmentNodeTestUserQueryWithArgsQuery", "operationKind": "query", "text": "query useRefetchableFragmentNodeTestUserQueryWithArgsQuery(\n $id: ID!\n $scale: Float!\n) {\n node(id: $id) {\n __typename\n ...useRefetchableFragmentNodeTestUserFragmentWithArgs_3FMcZQ\n id\n }\n}\n\nfragment useRefetchableFragmentNodeTestNestedUserFragment on User {\n username\n}\n\nfragment useRefetchableFragmentNodeTestUserFragmentWithArgs_3FMcZQ on User {\n id\n name\n profile_picture(scale: $scale) {\n uri\n }\n ...useRefetchableFragmentNodeTestNestedUserFragment\n}\n" } }; })(); if (__DEV__) { (node/*: any*/).hash = "eb3a8dd67a24e472e2e18e80041d344a"; } module.exports = ((node/*: any*/)/*: Query< useRefetchableFragmentNodeTestUserQueryWithArgsQuery$variables, useRefetchableFragmentNodeTestUserQueryWithArgsQuery$data, >*/);
// // The Box module defines algorithms for dealing with css boxes // module.exports = (function(window, document) { // Original code licensed by Adobe Systems Incorporated under the Apache License 2.0. // https://github.com/adobe-webplatform/brackets-css-shapes-editor/blob/master/thirdparty/CSSShapesEditor.js#L442 var cssBox = cssBox || {}; cssBox.getBox = // returns {top/left/bottom/right} for 'content/padding/border/margin-box' relative to the border box top-left corner. function getBox(element, boxType){ var width = element.offsetWidth, height = element.offsetHeight, style = getComputedStyle(element), leftBorder = parseFloat(style.borderLeftWidth), rightBorder = parseFloat(style.borderRightWidth), topBorder = parseFloat(style.borderTopWidth), bottomBorder = parseFloat(style.borderBottomWidth), leftPadding = parseFloat(style.paddingLeft), rightPadding = parseFloat(style.paddingRight), topPadding = parseFloat(style.paddingTop), bottomPadding = parseFloat(style.paddingBottom), leftMargin = parseFloat(style.marginLeft), rightMargin = parseFloat(style.marginRight), topMargin = parseFloat(style.marginTop), bottomMargin = parseFloat(style.marginBottom); var box = { top: 0, left: 0, width: 0, height: 0 }; switch (boxType||'border-box'){ case 'content-box': box.top = topBorder + topPadding; box.left = leftBorder + leftPadding; box.width = width - leftBorder - leftPadding - rightPadding - rightBorder; box.height = height - topBorder - topPadding - bottomPadding - bottomBorder; break; case 'padding-box': box.top = topPadding; box.left = leftPadding; box.width = width - leftBorder - rightBorder; box.height = height - topBorder - bottomBorder; break; case 'border-box': box.top = 0; box.left = 0; box.width = width; box.height = height; break; case 'margin-box': box.top = 0 - topMargin; box.left = 0 - leftMargin; box.width = width + leftMargin + rightMargin; box.height = height + topMargin + bottomMargin; break; default: throw new TypeError('Invalid parameter, boxType: ' + boxType); } return box; }; return cssBox; })(window, document);
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from 'react-reconciler/src/ReactInternalTypes'; import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type {Instance, TextInstance} from './ReactTestHostConfig'; import * as Scheduler from 'scheduler/unstable_mock'; import { getPublicRootInstance, createContainer, updateContainer, flushSync, injectIntoDevTools, batchedUpdates, act, } from 'react-reconciler/src/ReactFiberReconciler'; import {findCurrentFiberUsingSlowPath} from 'react-reconciler/src/ReactFiberTreeReflection'; import { Fragment, FunctionComponent, ClassComponent, HostComponent, HostPortal, HostText, HostRoot, ContextConsumer, ContextProvider, Mode, ForwardRef, Profiler, MemoComponent, SimpleMemoComponent, Block, IncompleteClassComponent, ScopeComponent, } from 'react-reconciler/src/ReactWorkTags'; import invariant from 'shared/invariant'; import getComponentName from 'shared/getComponentName'; import ReactVersion from 'shared/ReactVersion'; import {getPublicInstance} from './ReactTestHostConfig'; import {ConcurrentRoot, LegacyRoot} from 'react-reconciler/src/ReactRootTags'; type TestRendererOptions = { createNodeMock: (element: React$Element<any>) => any, unstable_isConcurrent: boolean, ... }; type ReactTestRendererJSON = {| type: string, props: {[propName: string]: any, ...}, children: null | Array<ReactTestRendererNode>, $$typeof?: Symbol, // Optional because we add it with defineProperty(). |}; type ReactTestRendererNode = ReactTestRendererJSON | string; type FindOptions = $Shape<{ // performs a "greedy" search: if a matching node is found, will continue // to search within the matching node's children. (default: true) deep: boolean, ... }>; export type Predicate = (node: ReactTestInstance) => ?boolean; const defaultTestOptions = { createNodeMock: function() { return null; }, }; function toJSON(inst: Instance | TextInstance): ReactTestRendererNode | null { if (inst.isHidden) { // Omit timed out children from output entirely. This seems like the least // surprising behavior. We could perhaps add a separate API that includes // them, if it turns out people need it. return null; } switch (inst.tag) { case 'TEXT': return inst.text; case 'INSTANCE': { /* eslint-disable no-unused-vars */ // We don't include the `children` prop in JSON. // Instead, we will include the actual rendered children. const {children, ...props} = inst.props; /* eslint-enable */ let renderedChildren = null; if (inst.children && inst.children.length) { for (let i = 0; i < inst.children.length; i++) { const renderedChild = toJSON(inst.children[i]); if (renderedChild !== null) { if (renderedChildren === null) { renderedChildren = [renderedChild]; } else { renderedChildren.push(renderedChild); } } } } const json: ReactTestRendererJSON = { type: inst.type, props: props, children: renderedChildren, }; Object.defineProperty(json, '$$typeof', { value: Symbol.for('react.test.json'), }); return json; } default: throw new Error(`Unexpected node type in toJSON: ${inst.tag}`); } } function childrenToTree(node) { if (!node) { return null; } const children = nodeAndSiblingsArray(node); if (children.length === 0) { return null; } else if (children.length === 1) { return toTree(children[0]); } return flatten(children.map(toTree)); } function nodeAndSiblingsArray(nodeWithSibling) { const array = []; let node = nodeWithSibling; while (node != null) { array.push(node); node = node.sibling; } return array; } function flatten(arr) { const result = []; const stack = [{i: 0, array: arr}]; while (stack.length) { const n = stack.pop(); while (n.i < n.array.length) { const el = n.array[n.i]; n.i += 1; if (Array.isArray(el)) { stack.push(n); stack.push({i: 0, array: el}); break; } result.push(el); } } return result; } function toTree(node: ?Fiber) { if (node == null) { return null; } switch (node.tag) { case HostRoot: return childrenToTree(node.child); case HostPortal: return childrenToTree(node.child); case ClassComponent: return { nodeType: 'component', type: node.type, props: {...node.memoizedProps}, instance: node.stateNode, rendered: childrenToTree(node.child), }; case FunctionComponent: case SimpleMemoComponent: return { nodeType: 'component', type: node.type, props: {...node.memoizedProps}, instance: null, rendered: childrenToTree(node.child), }; case Block: return { nodeType: 'block', type: node.type, props: {...node.memoizedProps}, instance: null, rendered: childrenToTree(node.child), }; case HostComponent: { return { nodeType: 'host', type: node.type, props: {...node.memoizedProps}, instance: null, // TODO: use createNodeMock here somehow? rendered: flatten(nodeAndSiblingsArray(node.child).map(toTree)), }; } case HostText: return node.stateNode.text; case Fragment: case ContextProvider: case ContextConsumer: case Mode: case Profiler: case ForwardRef: case MemoComponent: case IncompleteClassComponent: case ScopeComponent: return childrenToTree(node.child); default: invariant( false, 'toTree() does not yet know how to handle nodes with tag=%s', node.tag, ); } } const validWrapperTypes = new Set([ FunctionComponent, ClassComponent, HostComponent, ForwardRef, MemoComponent, SimpleMemoComponent, Block, // Normally skipped, but used when there's more than one root child. HostRoot, ]); function getChildren(parent: Fiber) { const children = []; const startingNode = parent; let node: Fiber = startingNode; if (node.child === null) { return children; } node.child.return = node; node = node.child; outer: while (true) { let descend = false; if (validWrapperTypes.has(node.tag)) { children.push(wrapFiber(node)); } else if (node.tag === HostText) { children.push('' + node.memoizedProps); } else { descend = true; } if (descend && node.child !== null) { node.child.return = node; node = node.child; continue; } while (node.sibling === null) { if (node.return === startingNode) { break outer; } node = (node.return: any); } (node.sibling: any).return = node.return; node = (node.sibling: any); } return children; } class ReactTestInstance { _fiber: Fiber; _currentFiber(): Fiber { // Throws if this component has been unmounted. const fiber = findCurrentFiberUsingSlowPath(this._fiber); invariant( fiber !== null, "Can't read from currently-mounting component. This error is likely " + 'caused by a bug in React. Please file an issue.', ); return fiber; } constructor(fiber: Fiber) { invariant( validWrapperTypes.has(fiber.tag), 'Unexpected object passed to ReactTestInstance constructor (tag: %s). ' + 'This is probably a bug in React.', fiber.tag, ); this._fiber = fiber; } get instance() { if (this._fiber.tag === HostComponent) { return getPublicInstance(this._fiber.stateNode); } else { return this._fiber.stateNode; } } get type() { return this._fiber.type; } get props(): Object { return this._currentFiber().memoizedProps; } get parent(): ?ReactTestInstance { let parent = this._fiber.return; while (parent !== null) { if (validWrapperTypes.has(parent.tag)) { if (parent.tag === HostRoot) { // Special case: we only "materialize" instances for roots // if they have more than a single child. So we'll check that now. if (getChildren(parent).length < 2) { return null; } } return wrapFiber(parent); } parent = parent.return; } return null; } get children(): Array<ReactTestInstance | string> { return getChildren(this._currentFiber()); } // Custom search functions find(predicate: Predicate): ReactTestInstance { return expectOne( this.findAll(predicate, {deep: false}), `matching custom predicate: ${predicate.toString()}`, ); } findByType(type: any): ReactTestInstance { return expectOne( this.findAllByType(type, {deep: false}), `with node type: "${getComponentName(type) || 'Unknown'}"`, ); } findByProps(props: Object): ReactTestInstance { return expectOne( this.findAllByProps(props, {deep: false}), `with props: ${JSON.stringify(props)}`, ); } findAll( predicate: Predicate, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll(this, predicate, options); } findAllByType( type: any, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll(this, node => node.type === type, options); } findAllByProps( props: Object, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll( this, node => node.props && propsMatch(node.props, props), options, ); } } function findAll( root: ReactTestInstance, predicate: Predicate, options: ?FindOptions, ): Array<ReactTestInstance> { const deep = options ? options.deep : true; const results = []; if (predicate(root)) { results.push(root); if (!deep) { return results; } } root.children.forEach(child => { if (typeof child === 'string') { return; } results.push(...findAll(child, predicate, options)); }); return results; } function expectOne( all: Array<ReactTestInstance>, message: string, ): ReactTestInstance { if (all.length === 1) { return all[0]; } const prefix = all.length === 0 ? 'No instances found ' : `Expected 1 but found ${all.length} instances `; throw new Error(prefix + message); } function propsMatch(props: Object, filter: Object): boolean { for (const key in filter) { if (props[key] !== filter[key]) { return false; } } return true; } function create(element: React$Element<any>, options: TestRendererOptions) { let createNodeMock = defaultTestOptions.createNodeMock; let isConcurrent = false; if (typeof options === 'object' && options !== null) { if (typeof options.createNodeMock === 'function') { createNodeMock = options.createNodeMock; } if (options.unstable_isConcurrent === true) { isConcurrent = true; } } let container = { children: [], createNodeMock, tag: 'CONTAINER', }; let root: FiberRoot | null = createContainer( container, isConcurrent ? ConcurrentRoot : LegacyRoot, false, null, ); invariant(root != null, 'something went wrong'); updateContainer(element, root, null, null); const entry = { _Scheduler: Scheduler, root: undefined, // makes flow happy // we define a 'getter' for 'root' below using 'Object.defineProperty' toJSON(): Array<ReactTestRendererNode> | ReactTestRendererNode | null { if (root == null || root.current == null || container == null) { return null; } if (container.children.length === 0) { return null; } if (container.children.length === 1) { return toJSON(container.children[0]); } if ( container.children.length === 2 && container.children[0].isHidden === true && container.children[1].isHidden === false ) { // Omit timed out children from output entirely, including the fact that we // temporarily wrap fallback and timed out children in an array. return toJSON(container.children[1]); } let renderedChildren = null; if (container.children && container.children.length) { for (let i = 0; i < container.children.length; i++) { const renderedChild = toJSON(container.children[i]); if (renderedChild !== null) { if (renderedChildren === null) { renderedChildren = [renderedChild]; } else { renderedChildren.push(renderedChild); } } } } return renderedChildren; }, toTree() { if (root == null || root.current == null) { return null; } return toTree(root.current); }, update(newElement: React$Element<any>) { if (root == null || root.current == null) { return; } updateContainer(newElement, root, null, null); }, unmount() { if (root == null || root.current == null) { return; } updateContainer(null, root, null, null); container = null; root = null; }, getInstance() { if (root == null || root.current == null) { return null; } return getPublicRootInstance(root); }, unstable_flushSync<T>(fn: () => T): T { return flushSync(fn); }, }; Object.defineProperty( entry, 'root', ({ configurable: true, enumerable: true, get: function() { if (root === null) { throw new Error("Can't access .root on unmounted test renderer"); } const children = getChildren(root.current); if (children.length === 0) { throw new Error("Can't access .root on unmounted test renderer"); } else if (children.length === 1) { // Normally, we skip the root and just give you the child. return children[0]; } else { // However, we give you the root if there's more than one root child. // We could make this the behavior for all cases but it would be a breaking change. return wrapFiber(root.current); } }, }: Object), ); return entry; } const fiberToWrapper = new WeakMap(); function wrapFiber(fiber: Fiber): ReactTestInstance { let wrapper = fiberToWrapper.get(fiber); if (wrapper === undefined && fiber.alternate !== null) { wrapper = fiberToWrapper.get(fiber.alternate); } if (wrapper === undefined) { wrapper = new ReactTestInstance(fiber); fiberToWrapper.set(fiber, wrapper); } return wrapper; } // Enable ReactTestRenderer to be used to test DevTools integration. injectIntoDevTools({ findFiberByHostInstance: (() => { throw new Error('TestRenderer does not support findFiberByHostInstance()'); }: any), bundleType: __DEV__ ? 1 : 0, version: ReactVersion, rendererPackageName: 'react-test-renderer', }); export { Scheduler as _Scheduler, create, /* eslint-disable-next-line camelcase */ batchedUpdates as unstable_batchedUpdates, act, };
var nixt = require('nixt') var should = require('should') var pkg = require('../package.json') var endpoint = typeof process.env.ENDPOINT !== 'undefined' ? ' -e ' + process.env.ENDPOINT + ' ' : ' ' var surge = 'node ' + pkg.bin + endpoint var opts = { colors: false, newlines: false } describe('surge', function () { it('should be cool', function (done) { done() }) it('should provide an error message when the command isn’t valid', function (done) { nixt({ colors: false }) .run(surge + '--deploy') .expect(function (result) { // Something like… // `--deploy` is not a surge command should(result.stdout).match(/--deploy/) should(result.stdout).match(/not/) }) .end(done) }) describe('version', function (done) { it('`surge --version`', function (done) { nixt(opts) .run(surge + '--version') .expect(function(result) { should(result.stdout).be.equal(pkg.version) }) .end(done) }) it('`surge -V`', function (done) { nixt(opts) .run(surge + '-V') .expect(function(result) { should(result.stdout).be.equal(pkg.version) }) .end(done) }) }) // TODO Endpoint tests // describe('endpoint', function (done) { // // it('`surge --endpoint`', function (done) { // nixt(opts) // .run(surge + '--endpoint locahost:5001') // .expect(function(result) { // }) // .end(done) // }) // // it('`surge -e` without protocol', function (done) { // nixt(opts) // .run(surge + '-e localhost:5001') // .expect(function(result) { // }) // .end(done) // }) // // it('`surge -e` with protocol', function (done) { // nixt(opts) // .run(surge + '-e http://localhost:5001') // .expect(function(result) { // }) // .end(done) // }) // // it('`surge -e` with IP', function (done) { // nixt(opts) // .run(surge + '-e 192.168.1.107:5001') // .expect(function(result) { // }) // .end(done) // }) // }) describe('login', function (done) { this.timeout(2500) it('`surge login`', function (done) { nixt({ colors: false }) .exec(surge + 'logout') // Logout before the test starts .run(surge + 'login') .on(/.*email:.*/).respond('kenneth+test@chloi.io\n') .on(/.*password:.*/).respond('12345\n') .expect(function (result) { should(result.stdout).match(/Logged in as kenneth/) // Possibly not returning the right codes right now? // should(result.code).equal(1) }) .end(done) }) it('`surge whoami`', function (done) { nixt({ colors: false }) .run(surge + 'whoami') .expect(function (result) { should(result.stdout).match(/Logged in as kenneth/) }) .end(done) }) it('`surge logout`', function (done) { nixt({ colors: false }) .run(surge + 'logout') // Logout again afterwards .expect(function (result) { should(result.stdout).match(/Token removed from /) }) .end(done) }) }) describe('list', function () { this.timeout(5000) it('`surge list`', function (done) { nixt({ colors: false, newlines: true }) .exec(surge + 'logout') // Logout before the test starts .run(surge + 'list') .on(/.*email:.*/).respond('kenneth+test@chloi.io\n') .on(/.*password:.*/).respond('12345\n') .expect(function (result) { should(result.stdout).match(/cli-test-2\.surge\.sh/) should(result.stdout).match(/cli-test-3\.surge\.sh/) should(result.stdout).not.match(/www\.cli-test-3\.surge\.sh/) should(result.stdout).match(/www\.cli-test-4\.surge\.sh/) should(result.stdout).not.match(/cli-test-0\.surge\.sh/) }) .end(done) }) }) describe('token', function () { before(function (done) { nixt(opts) .exec(surge + 'logout') // Logout before the test starts .run(surge + 'login') .on(/.*email:.*/).respond('kenneth+test@chloi.io\n') .on(/.*password:.*/).respond('12345\n') .end(done) }) it('`surge token`', function (done) { this.timeout(5000) nixt(opts) .run(surge + 'token') .expect(function (result) { should(result.stdout).match(/.*email: kenneth\+test@chloi\.io/) should(result.stdout).match(/.*token:*./) }) .end(done) }) // Failing // it('should not list the token twice', function (done) { // this.timeout(5000) // // nixt(opts) // .run(surge + 'token') // .expect(function (result) { // should(result.stdout).not.match(/.*token: (\**)*./) // }) // .end(done) // }) }) })
'use strict'; 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; } var React = require('react'); var StylePropable = require('./mixins/style-propable'); var TextField = require('./text-field'); var DropDownMenu = require('./drop-down-menu'); var SelectField = React.createClass({ displayName: 'SelectField', mixins: [StylePropable], contextTypes: { muiTheme: React.PropTypes.object }, propTypes: { errorText: React.PropTypes.string, floatingLabelText: React.PropTypes.string, selectFieldRoot: React.PropTypes.string, underlineStyle: React.PropTypes.object, labelStyle: React.PropTypes.object, errorStyle: React.PropTypes.object, hintText: React.PropTypes.string, id: React.PropTypes.string, multiLine: React.PropTypes.bool, onBlur: React.PropTypes.func, onChange: React.PropTypes.func, onFocus: React.PropTypes.func, onKeyDown: React.PropTypes.func, onEnterKeyDown: React.PropTypes.func, type: React.PropTypes.string, rows: React.PropTypes.number, inputStyle: React.PropTypes.object, iconStyle: React.PropTypes.object, floatingLabelStyle: React.PropTypes.object, autoWidth: React.PropTypes.bool, menuItems: React.PropTypes.array.isRequired, menuItemStyle: React.PropTypes.object, selectedIndex: React.PropTypes.number }, getDefaultProps: function getDefaultProps() { return { fullWidth: false }; }, getStyles: function getStyles() { var styles = { root: { height: 46, position: 'relative', width: '100%', top: 16, fontSize: 16 }, label: { paddingLeft: 0, top: 4, width: '100%' }, icon: { top: 20, right: 0 }, underline: { borderTop: 'none' }, input: {}, error: {} }; if (!this.props.floatingLabelText) { if (this.props.hintText) { styles.root.top = -5; styles.label.top = 1; styles.icon.top = 17; } else { styles.root.top = -8; } } else { styles.error.bottom = -15; } return styles; }, render: function render() { var styles = this.getStyles(); var _props = this.props; var style = _props.style; var labelStyle = _props.labelStyle; var iconStyle = _props.iconStyle; var underlineStyle = _props.underlineStyle; var errorStyle = _props.errorStyle; var selectFieldRoot = _props.selectFieldRoot; var menuItems = _props.menuItems; var disabled = _props.disabled; var floatingLabelText = _props.floatingLabelText; var floatingLabelStyle = _props.floatingLabelStyle; var hintText = _props.hintText; var fullWidth = _props.fullWidth; var errorText = _props.errorText; var other = _objectWithoutProperties(_props, ['style', 'labelStyle', 'iconStyle', 'underlineStyle', 'errorStyle', 'selectFieldRoot', 'menuItems', 'disabled', 'floatingLabelText', 'floatingLabelStyle', 'hintText', 'fullWidth', 'errorText']); var textFieldProps = { style: this.mergeAndPrefix(styles.input, style), floatingLabelText: floatingLabelText, floatingLabelStyle: floatingLabelStyle, hintText: !hintText && !floatingLabelText ? ' ' : hintText, fullWidth: fullWidth, errorText: errorText, errorStyle: this.mergeAndPrefix(styles.error, errorStyle) }; var dropDownMenuProps = { menuItems: menuItems, disabled: disabled, style: this.mergeAndPrefix(styles.root, selectFieldRoot), labelStyle: this.mergeAndPrefix(styles.label, labelStyle), iconStyle: this.mergeAndPrefix(styles.icon, iconStyle), underlineStyle: this.mergeAndPrefix(styles.underline), autoWidth: false }; return React.createElement( TextField, textFieldProps, React.createElement(DropDownMenu, _extends({}, dropDownMenuProps, other)) ); } }); module.exports = SelectField;
;(function(){ 'use strict'; angular .module('<%= slugifiedAppName %>', [ 'ngCookies', 'ngResource', 'ngSanitize', 'restangular', 'btford.socket-io', 'ui.router', 'ui.bootstrap', 'core', 'authentication', 'administration' ]) .run( run ); /* @inject */ function run($rootScope, $location, Auth) { // Redirect to login if route requires auth and you're not logged in $rootScope.$on('$stateChangeStart', function (event, next) { Auth.isLoggedInAsync(function(loggedIn) { if (next.authenticate && !loggedIn) { $location.path('/signin'); } }); }); } }).call(this);
var encoding; (function (encoding) { // TODO: encoding.ISO_8859_1 = System.Text.Encoding.Default; encoding.US_ASCII = System.Text.Encoding.ASCII; encoding.UTF_16 = System.Text.Encoding.Unicode; encoding.UTF_16BE = System.Text.Encoding.BigEndianUnicode; // TODO: encoding.UTF_16LE = System.Text.Encoding.Default; encoding.UTF_8 = System.Text.Encoding.UTF8; })(encoding = exports.encoding || (exports.encoding = {}));
'use strict'; module.exports = function(kbox, drupal, appName) { var _ = require('lodash'); var taskOpts = { name: 'drush-version', kind: 'string', description: 'The version of drush that you want.' }; var drushVersions = _.pluck(drupal, 'drush'); // Add an option kbox.create.add(appName, { option: { name: 'drush-version', task: taskOpts, inquire: { type: 'list', message: 'Major Drush version?', default: function(answers) { if (answers['drupal-version']) { return drupal[answers['drupal-version']].drush; } else { return '6'; } }, choices: drushVersions }, conf: { type: 'plugin', plugin: 'kalabox-plugin-drush', key: 'drush-version' } } }); };
import Stylis from 'stylis/stylis.min'; import _insertRulePlugin from 'stylis-rule-sheet'; import React, { cloneElement, createContext, Component, createElement } from 'react'; import { isElement, isValidElementType, ForwardRef } from 'react-is'; import memoize from 'memoize-one'; import stream from 'stream'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import validAttr from '@emotion/is-prop-valid'; import { createMacro, MacroError } from 'babel-plugin-macros'; import babelPlugin from 'babel-plugin-styled-components'; // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (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; }; var possibleConstructorReturn = function (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; }; // var isPlainObject = (function (x) { return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return target.displayName || target.name || 'Component'; } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_STREAM_ATTR = 'data-styled-streamed'; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n" } : {}; /** * super basic version of sprintf */ function format() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var a = args[0]; var b = []; var c = void 0; for (c = 1; c < args.length; c += 1) { b.push(args[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = function (_Error) { inherits(StyledComponentsError, _Error); function StyledComponentsError(code) { classCallCheck(this, StyledComponentsError); for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { interpolations[_key2 - 1] = arguments[_key2]; } if (process.env.NODE_ENV === 'production') { var _this = possibleConstructorReturn(this, _Error.call(this, 'An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#' + code + ' for more information. ' + (interpolations ? 'Additional arguments: ' + interpolations.join(', ') : ''))); } else { var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim())); } return possibleConstructorReturn(_this); } return StyledComponentsError; }(Error); // var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm; var extractComps = (function (maybeCSS) { var css = '' + (maybeCSS || ''); // Definitely a string, and a clone var existingComponents = []; css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) { existingComponents.push({ componentId: componentId, matchIndex: matchIndex }); return match; }); return existingComponents.map(function (_ref, i) { var componentId = _ref.componentId, matchIndex = _ref.matchIndex; var nextComp = existingComponents[i + 1]; var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex); return { componentId: componentId, cssFromDOM: cssFromDOM }; }); }); // var COMMENT_REGEX = /^\s*\/\/.*$/gm; var SELF_REFERENTIAL_COMBINATOR = /(&(?! *[+~>])([^&{][^{]+)[^+~>]*)?([+~>] *)&/g; // NOTE: This stylis instance is only used to split rules from SSR'd style tags var stylisSplitter = new Stylis({ global: false, cascade: true, keyframe: false, prefix: false, compress: false, semicolon: true }); var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); stylis.use([parseRulesPlugin, returnRulesPlugin]); stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]); var stringifyRules = function stringifyRules(rules, selector, prefix) { var componentId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '&'; var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments var cssStr = (selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS).replace(SELF_REFERENTIAL_COMBINATOR, '$1$3.' + componentId + '$2'); return stylis(prefix || !selector ? '' : selector, cssStr); }; var splitByRules = function splitByRules(css) { return stylisSplitter('', css); }; // /* eslint-disable camelcase, no-undef */ var getNonce = (function () { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }); // // Helper to call a given function, only once var once = (function (cb) { var called = false; return function () { if (!called) { called = true; cb(); } }; }); // /* These are helpers for the StyleTags to keep track of the injected * rule names for each (component) ID that they're keeping track of. * They're crucial for detecting whether a name has already been * injected. * (This excludes rehydrated names) */ /* adds a new ID:name pairing to a names dictionary */ var addNameForId = function addNameForId(names, id, name) { if (name) { // eslint-disable-next-line no-param-reassign var namesForId = names[id] || (names[id] = Object.create(null)); namesForId[name] = true; } }; /* resets an ID entirely by overwriting it in the dictionary */ var resetIdNames = function resetIdNames(names, id) { // eslint-disable-next-line no-param-reassign names[id] = Object.create(null); }; /* factory for a names dictionary checking the existance of an ID:name pairing */ var hasNameForId = function hasNameForId(names) { return function (id, name) { return names[id] !== undefined && names[id][name]; }; }; /* stringifies names for the html/element output */ var stringifyNames = function stringifyNames(names) { var str = ''; // eslint-disable-next-line guard-for-in for (var id in names) { str += Object.keys(names[id]).join(' ') + ' '; } return str.trim(); }; /* clones the nested names dictionary */ var cloneNames = function cloneNames(names) { var clone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in names) { clone[id] = _extends({}, names[id]); } return clone; }; // /* These are helpers that deal with the insertRule (aka speedy) API * They are used in the StyleTags and specifically the speedy tag */ /* retrieve a sheet for a given style tag */ var sheetForTag = function sheetForTag(tag) { // $FlowFixMe if (tag.sheet) return tag.sheet; /* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */ var size = document.styleSheets.length; for (var i = 0; i < size; i += 1) { var sheet = document.styleSheets[i]; // $FlowFixMe if (sheet.ownerNode === tag) return sheet; } /* we should always be able to find a tag */ throw new StyledComponentsError(10); }; /* insert a rule safely and return whether it was actually injected */ var safeInsertRule = function safeInsertRule(sheet, cssRule, index) { /* abort early if cssRule string is falsy */ if (!cssRule) return false; var maxIndex = sheet.cssRules.length; try { /* use insertRule and cap passed index with maxIndex (no of cssRules) */ sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex); } catch (err) { /* any error indicates an invalid rule */ return false; } return true; }; /* deletes `size` rules starting from `removalIndex` */ var deleteRules = function deleteRules(sheet, removalIndex, size) { var lowerBound = removalIndex - size; for (var i = removalIndex; i > lowerBound; i -= 1) { sheet.deleteRule(i); } }; // /* this marker separates component styles and is important for rehydration */ var makeTextMarker = function makeTextMarker(id) { return '\n/* sc-component-id: ' + id + ' */\n'; }; /* add up all numbers in array up until and including the index */ var addUpUntilIndex = function addUpUntilIndex(sizes, index) { var totalUpToIndex = 0; for (var i = 0; i <= index; i += 1) { totalUpToIndex += sizes[i]; } return totalUpToIndex; }; /* create a new style tag after lastEl */ var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) { var el = document.createElement('style'); el.setAttribute(SC_ATTR, ''); el.setAttribute(SC_VERSION_ATTR, "4.0.0-beta.11.3"); var nonce = getNonce(); if (nonce) { el.setAttribute('nonce', nonce); } /* Work around insertRule quirk in EdgeHTML */ el.appendChild(document.createTextNode('')); if (target && !tagEl) { /* Append to target when no previous element was passed */ target.appendChild(el); } else { if (!tagEl || !target || !tagEl.parentNode) { throw new StyledComponentsError(6); } /* Insert new style tag after the previous one */ tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling); } return el; }; /* takes a css factory function and outputs an html styled tag factory */ var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) { return function (additionalAttrs) { var nonce = getNonce(); var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.0-beta.11.3" + '"', additionalAttrs]; var htmlAttr = attrs.filter(Boolean).join(' '); return '<style ' + htmlAttr + '>' + css() + '</style>'; }; }; /* takes a css factory function and outputs an element factory */ var wrapAsElement = function wrapAsElement(css, names) { return function () { var _props; var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.0-beta.11.3", _props); var nonce = getNonce(); if (nonce) { // $FlowFixMe props.nonce = nonce; } // eslint-disable-next-line react/no-danger return React.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } })); }; }; var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) { return function () { return Object.keys(markers); }; }; /* speedy tags utilise insertRule */ var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var sizes = []; var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = sizes.length; sizes.push(0); resetIdNames(names, id); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var sheet = sheetForTag(el); var insertIndex = addUpUntilIndex(sizes, marker); var injectedRules = 0; var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var cssRule = cssRules[i]; var mayHaveImport = extractImport; /* @import rules are reordered to appear first */ if (mayHaveImport && cssRule.indexOf('@import') !== -1) { importRules.push(cssRule); } else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) { mayHaveImport = false; injectedRules += 1; } } if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } sizes[marker] += injectedRules; /* add up no of injected rules */ addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; var size = sizes[marker]; var sheet = sheetForTag(el); var removalIndex = addUpUntilIndex(sizes, marker) - 1; deleteRules(sheet, removalIndex, size); sizes[marker] = 0; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var _sheetForTag = sheetForTag(el), cssRules = _sheetForTag.cssRules; var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += makeTextMarker(id); var marker = markers[id]; var end = addUpUntilIndex(sizes, marker); var size = sizes[marker]; for (var i = end - size; i < end; i += 1) { var rule = cssRules[i]; if (rule !== undefined) { str += rule.cssText; } } } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeTextNode = function makeTextNode(id) { return document.createTextNode(makeTextMarker(id)); }; var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = makeTextNode(id); el.appendChild(markers[id]); names[id] = Object.create(null); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var rule = cssRules[i]; var mayHaveImport = extractImport; if (mayHaveImport && rule.indexOf('@import') !== -1) { importRules.push(rule); } else { mayHaveImport = false; var separator = i === cssRulesSize - 1 ? '' : ' '; marker.appendData('' + rule + separator); } } addNameForId(names, id, name); if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; /* create new empty text node and replace the current one */ var newMarker = makeTextNode(id); el.replaceChild(newMarker, marker); markers[id] = newMarker; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += markers[id].data; } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeServerTag = function makeServerTag(namesArg, markersArg) { var names = namesArg === undefined ? Object.create(null) : namesArg; var markers = markersArg === undefined ? Object.create(null) : markersArg; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } return markers[id] = ['']; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); marker[0] += cssRules.join(' '); addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; marker[0] = ''; resetIdNames(names, id); }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { var cssForId = markers[id][0]; if (cssForId) { str += makeTextMarker(id) + cssForId; } } return str; }; var clone = function clone() { var namesClone = cloneNames(names); var markersClone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in markers) { markersClone[id] = [markers[id][0]]; } return makeServerTag(namesClone, markersClone); }; var tag = { clone: clone, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: null, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; return tag; }; var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) { if (IS_BROWSER && !forceServer) { var el = makeStyleTag(target, tagEl, insertBefore); if (DISABLE_SPEEDY) { return makeBrowserTag(el, getImportRuleTag); } else { return makeSpeedyTag(el, getImportRuleTag); } } return makeServerTag(); }; /* wraps a given tag so that rehydration is performed once when necessary */ var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) { /* rehydration function that adds all rules to the new tag */ var rehydrate = once(function () { /* add all extracted components to the new tag */ for (var i = 0, len = extracted.length; i < len; i += 1) { var _extracted$i = extracted[i], componentId = _extracted$i.componentId, cssFromDOM = _extracted$i.cssFromDOM; var cssRules = splitByRules(cssFromDOM); tag.insertRules(componentId, cssRules); } /* remove old HTMLStyleElements, since they have been rehydrated */ for (var _i = 0, _len = els.length; _i < _len; _i += 1) { var el = els[_i]; if (el.parentNode) { el.parentNode.removeChild(el); } } }); if (immediateRehydration) rehydrate(); return _extends({}, tag, { /* add rehydration hook to methods */ insertMarker: function insertMarker(id) { rehydrate(); return tag.insertMarker(id); }, insertRules: function insertRules(id, cssRules, name) { rehydrate(); return tag.insertRules(id, cssRules, name); }, removeRules: function removeRules(id) { rehydrate(); return tag.removeRules(id); } }); }; // var SPLIT_REGEX = /\s+/; /* determine the maximum number of components before tags are sharded */ var MAX_SIZE = void 0; if (IS_BROWSER) { /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */ MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000; } else { /* for servers we do not need to shard at all */ MAX_SIZE = -1; } var sheetRunningId = 0; var master = void 0; var StyleSheet = function () { /* a map from ids to tags */ /* deferred rules for a given id */ /* this is used for not reinjecting rules via hasNameForId() */ /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */ /* a list of tags belonging to this StyleSheet */ /* a tag for import rules */ /* current capacity until a new tag must be created */ /* children (aka clones) of this StyleSheet inheriting all and future injections */ function StyleSheet() { var _this = this; var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null; var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; classCallCheck(this, StyleSheet); this.getImportRuleTag = function () { var importRuleTag = _this.importRuleTag; if (importRuleTag !== undefined) { return importRuleTag; } var firstTag = _this.tags[0]; var insertBefore = true; return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore); }; sheetRunningId += 1; this.id = sheetRunningId; this.forceServer = forceServer; this.target = forceServer ? null : target; this.tagMap = {}; this.deferred = {}; this.rehydratedNames = {}; this.ignoreRehydratedNames = {}; this.tags = []; this.capacity = 1; this.clones = []; } /* rehydrate all SSR'd style tags */ StyleSheet.prototype.rehydrate = function rehydrate() { if (!IS_BROWSER || this.forceServer) { return this; } var els = []; var extracted = []; var isStreamed = false; /* retrieve all of our SSR style elements from the DOM */ var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.0-beta.11.3" + '"]'); var nodesSize = nodes.length; /* abort rehydration if no previous style tags were found */ if (nodesSize === 0) { return this; } for (var i = 0; i < nodesSize; i += 1) { // $FlowFixMe: We can trust that all elements in this query are style elements var el = nodes[i]; /* check if style tag is a streamed tag */ if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR); /* retrieve all component names */ var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX); var elNamesSize = elNames.length; for (var j = 0; j < elNamesSize; j += 1) { var name = elNames[j]; /* add rehydrated name to sheet to avoid readding styles */ this.rehydratedNames[name] = true; } /* extract all components and their CSS */ extracted.push.apply(extracted, extractComps(el.textContent)); /* store original HTMLStyleElement */ els.push(el); } /* abort rehydration if nothing was extracted */ var extractedSize = extracted.length; if (extractedSize === 0) { return this; } /* create a tag to be used for rehydration */ var tag = this.makeTag(null); var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed); /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */ this.capacity = Math.max(1, MAX_SIZE - extractedSize); this.tags.push(rehydrationTag); /* retrieve all component ids */ for (var _j = 0; _j < extractedSize; _j += 1) { this.tagMap[extracted[_j].componentId] = rehydrationTag; } return this; }; /* retrieve a "master" instance of StyleSheet which is typically used when no other is available * The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any * StyleSheetManager's context */ /* reset the internal "master" instance */ StyleSheet.reset = function reset() { var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; master = new StyleSheet(undefined, forceServer).rehydrate(); }; /* adds "children" to the StyleSheet that inherit all of the parents' rules * while their own rules do not affect the parent */ StyleSheet.prototype.clone = function clone() { var sheet = new StyleSheet(this.target, this.forceServer); /* add to clone array */ this.clones.push(sheet); /* clone all tags */ sheet.tags = this.tags.map(function (tag) { var ids = tag.getIds(); var newTag = tag.clone(); /* reconstruct tagMap */ for (var i = 0; i < ids.length; i += 1) { sheet.tagMap[ids[i]] = newTag; } return newTag; }); /* clone other maps */ sheet.rehydratedNames = _extends({}, this.rehydratedNames); sheet.deferred = _extends({}, this.deferred); return sheet; }; /* force StyleSheet to create a new tag on the next injection */ StyleSheet.prototype.sealAllTags = function sealAllTags() { this.capacity = 1; this.tags.forEach(function (tag) { // eslint-disable-next-line no-param-reassign tag.sealed = true; }); }; StyleSheet.prototype.makeTag = function makeTag$$1(tag) { var lastEl = tag ? tag.styleTag : null; var insertBefore = false; return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag); }; /* get a tag for a given componentId, assign the componentId to one, or shard */ StyleSheet.prototype.getTagForId = function getTagForId(id) { /* simply return a tag, when the componentId was already assigned one */ var prev = this.tagMap[id]; if (prev !== undefined && !prev.sealed) { return prev; } var tag = this.tags[this.tags.length - 1]; /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */ this.capacity -= 1; if (this.capacity === 0) { this.capacity = MAX_SIZE; tag = this.makeTag(tag); this.tags.push(tag); } return this.tagMap[id] = tag; }; /* mainly for createGlobalStyle to check for its id */ StyleSheet.prototype.hasId = function hasId(id) { return this.tagMap[id] !== undefined; }; /* caching layer checking id+name to already have a corresponding tag and injected rules */ StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) { /* exception for rehydrated names which are checked separately */ if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) { return true; } var tag = this.tagMap[id]; return tag !== undefined && tag.hasNameForId(id, name); }; /* registers a componentId and registers it on its tag */ StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) { /* don't inject when the id is already registered */ if (this.tagMap[id] !== undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].deferredInject(id, cssRules); } this.getTagForId(id).insertMarker(id); this.deferred[id] = cssRules; }; /* injects rules for a given id with a name that will need to be cached */ StyleSheet.prototype.inject = function inject(id, cssRules, name) { var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].inject(id, cssRules, name); } var tag = this.getTagForId(id); /* add deferred rules for component */ if (this.deferred[id] !== undefined) { // Combine passed cssRules with previously deferred CSS rules // NOTE: We cannot mutate the deferred array itself as all clones // do the same (see clones[i].inject) var rules = this.deferred[id].concat(cssRules); tag.insertRules(id, rules, name); this.deferred[id] = undefined; } else { tag.insertRules(id, cssRules, name); } }; /* removes all rules for a given id, which doesn't remove its marker but resets it */ StyleSheet.prototype.remove = function remove(id) { var tag = this.tagMap[id]; if (tag === undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].remove(id); } /* remove all rules from the tag */ tag.removeRules(id); /* ignore possible rehydrated names */ this.ignoreRehydratedNames[id] = true; /* delete possible deferred rules */ this.deferred[id] = undefined; }; StyleSheet.prototype.toHTML = function toHTML() { return this.tags.map(function (tag) { return tag.toHTML(); }).join(''); }; StyleSheet.prototype.toReactElements = function toReactElements() { var id = this.id; return this.tags.map(function (tag, i) { var key = 'sc-' + id + '-' + i; return cloneElement(tag.toElement(), { key: key }); }); }; createClass(StyleSheet, null, [{ key: 'master', get: function get$$1() { return master || (master = new StyleSheet().rehydrate()); } /* NOTE: This is just for backwards-compatibility with jest-styled-components */ }, { key: 'instance', get: function get$$1() { return StyleSheet.master; } }]); return StyleSheet; }(); // var Keyframes = function () { function Keyframes(name, rules) { var _this = this; classCallCheck(this, Keyframes); this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.inject(_this.id, _this.rules, _this.name); } }; this.name = name; this.rules = rules; this.id = 'sc-keyframes-' + name; } Keyframes.prototype.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { var chunk = obj[key]; return chunk !== undefined && chunk !== null && chunk !== false && chunk !== ''; }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return null; } /* Handle other components */ if (isStyledComponent(chunk)) { return '.' + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (executionContext) { if (process.env.NODE_ENV !== 'production') { /* Warn if not referring styled component */ try { // eslint-disable-next-line new-cap if (isElement(new chunk(executionContext))) { console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.'); } // eslint-disable-next-line no-empty } catch (e) {} } return flatten(chunk(executionContext), executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } // function constructWithOptions(componentConstructor, tag) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; if (!isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(undefined, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs) })); }; return templateFunction; } // // Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js function murmurhash(c) { for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) { b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d; } switch (e) { case 3: a ^= (c.charCodeAt(d + 2) & 255) << 16; case 2: a ^= (c.charCodeAt(d + 1) & 255) << 8; case 1: a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); } a ^= a >>> 13; a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); return (a ^ a >>> 15) >>> 0; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x = void 0; /* get a char and divide by alphabet-length */ for (x = code; x > charsLength; x = Math.floor(x / charsLength)) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs !== undefined) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in attrs) { var value = attrs[key]; if (isFunction(value)) { return false; } } } return true; } // // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* combines hashStr (murmurhash) and nameGenerator for convenience */ var hasher = function hasher(str) { return generateAlphabeticName(murmurhash(str)); }; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = function () { function ComponentStyle(rules, attrs, componentId) { classCallCheck(this, ComponentStyle); this.rules = rules; this.isStatic = !isHMREnabled && isStaticRules(rules, attrs); this.componentId = componentId; if (!StyleSheet.master.hasId(componentId)) { var placeholder = process.env.NODE_ENV !== 'production' ? ['.' + componentId + ' {}'] : []; StyleSheet.master.deferredInject(componentId, placeholder); } } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var isStatic = this.isStatic, componentId = this.componentId, lastClassName = this.lastClassName; if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) { return lastClassName; } var flatCSS = flatten(this.rules, executionContext, styleSheet); var name = hasher(this.componentId + flatCSS.join('')); if (!styleSheet.hasNameForId(componentId, name)) { styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name, undefined, componentId), name); } this.lastClassName = name; return name; }; ComponentStyle.generateName = function generateName(str) { return hasher(str); }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme) { var defaultProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) /* : %checks */{ return typeof target === 'string'; } // function generateDisplayName(target) { return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')'; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty$1 = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === undefined ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor = void 0; var key = void 0; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty$1(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // var ThemeContext = createContext(); var ThemeConsumer = ThemeContext.Consumer; /** * Provide a theme to an entire react component tree via context */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider(props) { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext.bind(_this)); _this.renderInner = _this.renderInner.bind(_this); return _this; } ThemeProvider.prototype.render = function render() { if (!this.props.children) return null; return React.createElement( ThemeContext.Consumer, null, this.renderInner ); }; ThemeProvider.prototype.renderInner = function renderInner(outerTheme) { var context = this.getContext(this.props.theme, outerTheme); return React.createElement( ThemeContext.Provider, { value: context }, React.Children.only(this.props.children) ); }; /** * Get the theme from the props, supporting both (outerTheme) => {} * as well as object notation */ ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') { throw new StyledComponentsError(8); } return _extends({}, outerTheme, theme); }; ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) { return this.getTheme(theme, outerTheme); }; return ThemeProvider; }(Component); // var ServerStyleSheet = function () { function ServerStyleSheet() { classCallCheck(this, ServerStyleSheet); /* The master sheet might be reset, so keep a reference here */ this.masterSheet = StyleSheet.master; this.instance = this.masterSheet.clone(); this.sealed = false; } /** * Mark the ServerStyleSheet as being fully emitted and manually GC it from the * StyleSheet singleton. */ ServerStyleSheet.prototype.seal = function seal() { if (!this.sealed) { /* Remove sealed StyleSheets from the master sheet */ var index = this.masterSheet.clones.indexOf(this.instance); this.masterSheet.clones.splice(index, 1); this.sealed = true; } }; ServerStyleSheet.prototype.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } return React.createElement( StyleSheetManager, { sheet: this.instance }, children ); }; ServerStyleSheet.prototype.getStyleTags = function getStyleTags() { this.seal(); return this.instance.toHTML(); }; ServerStyleSheet.prototype.getStyleElement = function getStyleElement() { this.seal(); return this.instance.toReactElements(); }; ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) { var _this = this; if (!__SERVER__ || IS_BROWSER) { throw new StyledComponentsError(3); } /* the tag index keeps track of which tags have already been emitted */ var instance = this.instance; var instanceTagIndex = 0; var streamAttr = SC_STREAM_ATTR + '="true"'; var transformer = new stream.Transform({ transform: function appendStyleChunks(chunk, /* encoding */_, callback) { var tags = instance.tags; var html = ''; /* retrieve html for each new style tag */ for (; instanceTagIndex < tags.length; instanceTagIndex += 1) { var tag = tags[instanceTagIndex]; html += tag.toHTML(streamAttr); } /* force our StyleSheets to emit entirely new tags */ instance.sealAllTags(); /* prepend style html to chunk */ this.push(html + chunk); callback(); } }); readableStream.on('end', function () { return _this.seal(); }); readableStream.on('error', function (err) { _this.seal(); // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // var StyleSheetContext = createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var StyleSheetManager = function (_Component) { inherits(StyleSheetManager, _Component); function StyleSheetManager(props) { classCallCheck(this, StyleSheetManager); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext); return _this; } StyleSheetManager.prototype.getContext = function getContext(sheet, target) { if (sheet) { return sheet; } else if (target) { return new StyleSheet(target); } else { throw new StyledComponentsError(4); } }; StyleSheetManager.prototype.render = function render() { var _props = this.props, children = _props.children, sheet = _props.sheet, target = _props.target; var context = this.getContext(sheet, target); return React.createElement( StyleSheetContext.Provider, { value: context }, React.Children.only(children) ); }; return StyleSheetManager; }(Component); process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.oneOfType([PropTypes.instanceOf(StyleSheet), PropTypes.instanceOf(ServerStyleSheet)]), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; // var classNameUseCheckInjector = (function (target) { var elementClassName = ''; var targetCDM = target.componentDidMount; // eslint-disable-next-line no-param-reassign target.componentDidMount = function componentDidMount() { if (typeof targetCDM === 'function') { targetCDM.call(this); } var classNames = elementClassName.replace(/ +/g, ' ').trim().split(' '); // eslint-disable-next-line react/no-find-dom-node var node = ReactDOM.findDOMNode(this); var selector = classNames.map(function (s) { return '.' + s; }).join(''); if (node && node.nodeType === 1 && !classNames.every(function (className) { return node.classList && node.classList.contains(className); }) && !node.querySelector(selector)) { console.warn('It looks like you\'ve wrapped styled() around your React component (' + getComponentName(this.props.forwardedClass.target) + '), but the className prop is not being passed down to a child. No styles will be rendered unless className is composed within your React component.'); } }; var prevRenderInner = target.renderInner; // eslint-disable-next-line no-param-reassign target.renderInner = function renderInner() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var element = prevRenderInner.apply(this, args); elementClassName = element.props.className; return element; }; }); // var identifiers = {}; /* We depend on components having unique IDs */ function generateId(_ComponentStyle, _displayName, parentComponentId) { var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName); /** * This ensures uniqueness if two components happen to share * the same displayName. */ var nr = (identifiers[displayName] || 0) + 1; identifiers[displayName] = nr; var componentId = displayName + '-' + _ComponentStyle.generateName(displayName + nr); return parentComponentId ? parentComponentId + '-' + componentId : componentId; } var warnInnerRef = once(function () { return ( // eslint-disable-next-line no-console console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.') ); }); // $FlowFixMe var StyledComponent = function (_Component) { inherits(StyledComponent, _Component); function StyledComponent() { classCallCheck(this, StyledComponent); var _this = possibleConstructorReturn(this, _Component.call(this)); _this.attrs = {}; _this.renderOuter = _this.renderOuter.bind(_this); _this.renderInner = _this.renderInner.bind(_this); if (process.env.NODE_ENV !== 'production' && IS_BROWSER) { classNameUseCheckInjector(_this); } return _this; } StyledComponent.prototype.render = function render() { return React.createElement( StyleSheetConsumer, null, this.renderOuter ); }; StyledComponent.prototype.renderOuter = function renderOuter(styleSheet) { this.styleSheet = styleSheet; return React.createElement( ThemeConsumer, null, this.renderInner ); }; StyledComponent.prototype.renderInner = function renderInner(theme) { var _props$forwardedClass = this.props.forwardedClass, componentStyle = _props$forwardedClass.componentStyle, defaultProps = _props$forwardedClass.defaultProps, styledComponentId = _props$forwardedClass.styledComponentId, target = _props$forwardedClass.target; var generatedClassName = void 0; if (componentStyle.isStatic) { generatedClassName = this.generateAndInjectStyles(EMPTY_OBJECT, this.props, this.styleSheet); } else if (theme !== undefined) { generatedClassName = this.generateAndInjectStyles(determineTheme(this.props, theme, defaultProps), this.props, this.styleSheet); } else { generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet); } var elementToBeCreated = this.props.as || this.attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var propsForElement = _extends({}, this.attrs); var key = void 0; // eslint-disable-next-line guard-for-in for (key in this.props) { if (process.env.NODE_ENV !== 'production' && key === 'innerRef') { warnInnerRef(); } if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'forwardedRef') propsForElement.ref = this.props[key];else if (!isTargetTag || validAttr(key)) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key]; } } propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' '); return createElement(elementToBeCreated, propsForElement); }; StyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) { var context = _extends({}, props, { theme: theme }); if (attrs === undefined) return context; this.attrs = {}; var attr = void 0; var key = void 0; /* eslint-disable guard-for-in */ for (key in attrs) { attr = attrs[key]; this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr; } /* eslint-enable */ return _extends({}, context, this.attrs); }; StyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) { var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master; var _props$forwardedClass2 = props.forwardedClass, attrs = _props$forwardedClass2.attrs, componentStyle = _props$forwardedClass2.componentStyle, warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses; // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names if (componentStyle.isStatic && attrs === undefined) { return componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet); } var className = componentStyle.generateAndInjectStyles(this.buildExecutionContext(theme, props, props.forwardedClass.attrs), styleSheet); if (warnTooManyClasses) { warnTooManyClasses(className); } return className; }; return StyledComponent; }(Component); function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isClass = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId, _options$ParentCompon = options.ParentComponent, ParentComponent = _options$ParentCompon === undefined ? StyledComponent : _options$ParentCompon, attrs = options.attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ var WrappedStyledComponent = React.forwardRef(function (props, ref) { return React.createElement(ParentComponent, _extends({}, props, { forwardedClass: WrappedStyledComponent, forwardedRef: ref })); }); // $FlowFixMe WrappedStyledComponent.attrs = finalAttrs; // $FlowFixMe WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; // $FlowFixMe WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles // $FlowFixMe WrappedStyledComponent.target = isTargetStyledComp ? target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['componentId']); var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId, ParentComponent: ParentComponent }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { // $FlowFixMe WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } if (isClass) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, styledComponentId: true, target: true, warnTooManyClasses: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = function () { function GlobalStyle(rules, componentId) { classCallCheck(this, GlobalStyle); this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules); if (!StyleSheet.master.hasId(componentId)) { StyleSheet.master.deferredInject(componentId, []); } } GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS, ''); styleSheet.inject(this.componentId, css); }; GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) { var componentId = this.componentId; if (styleSheet.hasId(componentId)) { styleSheet.remove(componentId); } }; // TODO: overwrite in-place instead of remove+create? GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) { this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); // // place our cache into shared context so it'll persist between HMRs if (IS_BROWSER) { window.scCGSHMRCache = {}; } function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var id = 'sc-global-' + murmurhash(JSON.stringify(rules)); var style = new GlobalStyle(rules, id); var GlobalStyleComponent = function (_React$Component) { inherits(GlobalStyleComponent, _React$Component); function GlobalStyleComponent() { classCallCheck(this, GlobalStyleComponent); var _this = possibleConstructorReturn(this, _React$Component.call(this)); var _this$constructor = _this.constructor, globalStyle = _this$constructor.globalStyle, styledComponentId = _this$constructor.styledComponentId; if (IS_BROWSER) { window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1; } /** * This fixes HMR compatiblility. Don't ask me why, but this combination of * caching the closure variables via statics and then persisting the statics in * state works across HMR where no other combination did. ¯\_(ツ)_/¯ */ _this.state = { globalStyle: globalStyle, styledComponentId: styledComponentId }; return _this; } GlobalStyleComponent.prototype.componentDidMount = function componentDidMount() { if (process.env.NODE_ENV !== 'production' && IS_BROWSER && window.scCGSHMRCache[this.state.styledComponentId] > 1) { console.warn('The global style component ' + this.state.styledComponentId + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head> (or your StyleSheetManager target.)'); } }; GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() { if (window.scCGSHMRCache[this.state.styledComponentId]) { window.scCGSHMRCache[this.state.styledComponentId] -= 1; } /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (window.scCGSHMRCache[this.state.styledComponentId] === 0) { this.state.globalStyle.removeStyles(this.styleSheet); } }; GlobalStyleComponent.prototype.render = function render() { var _this2 = this; if (process.env.NODE_ENV !== 'production' && React.Children.count(this.props.children)) { console.warn('The global style component ' + this.state.styledComponentId + ' was given child JSX. createGlobalStyle does not render children.'); } return React.createElement( StyleSheetConsumer, null, function (styleSheet) { _this2.styleSheet = styleSheet || StyleSheet.master; var globalStyle = _this2.state.globalStyle; if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet); return null; } else { return React.createElement( ThemeConsumer, null, function (theme) { var defaultProps = _this2.constructor.defaultProps; var context = _extends({}, _this2.props); if (typeof theme !== 'undefined') { context.theme = determineTheme(_this2.props, theme, defaultProps); } globalStyle.renderStyles(context, _this2.styleSheet); return null; } ); } } ); }; return GlobalStyleComponent; }(React.Component); GlobalStyleComponent.globalStyle = style; GlobalStyleComponent.styledComponentId = id; return GlobalStyleComponent; } // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var name = generateAlphabeticName(murmurhash(replaceWhitespace(JSON.stringify(rules)))); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // var withTheme = (function (Component$$1) { var WithTheme = React.forwardRef(function (props, ref) { return React.createElement( ThemeConsumer, null, function (theme) { // $FlowFixMe var defaultProps = Component$$1.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component$$1)); } return React.createElement(Component$$1, _extends({}, props, { theme: themeProp, ref: ref })); } ); }); hoistNonReactStatics(WithTheme, Component$$1); WithTheme.displayName = 'WithTheme(' + getComponentName(Component$$1) + ')'; return WithTheme; }); // /* eslint-disable */ var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // var styled$1 = /*#__PURE__*/Object.freeze({ default: styled, css: css, keyframes: keyframes, createGlobalStyle: createGlobalStyle, isStyledComponent: isStyledComponent, ThemeConsumer: ThemeConsumer, ThemeProvider: ThemeProvider, withTheme: withTheme, ServerStyleSheet: ServerStyleSheet, StyleSheetManager: StyleSheetManager, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS: __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS }); // var allowedImports = Object.keys(styled$1).filter(function (helper) { return helper !== '__esModule'; }); function styledComponentsMacro(_ref) { var references = _ref.references, state = _ref.state, t = _ref.babel.types, _ref$config = _ref.config, config = _ref$config === undefined ? {} : _ref$config; var program = state.file.path; // replace `styled-components/macro` by `styled-components` // create a node for styled-components's imports var imports = t.importDeclaration([], t.stringLiteral('styled-components')); // and add it to top of the document program.node.body.unshift(imports); // references looks like this // { default: [path, path], css: [path], ... } Object.keys(references).forEach(function (refName) { if (!allowedImports.includes(refName)) { throw new MacroError('Invalid import: ' + refName + '. You can only import ' + allowedImports.join(', ') + ' from \'styled-components/macro\'.'); } // generate new identifier and add to imports var id = void 0; if (refName === 'default') { id = program.scope.generateUidIdentifier('styled'); imports.specifiers.push(t.importDefaultSpecifier(id)); } else { id = program.scope.generateUidIdentifier(refName); imports.specifiers.push(t.importSpecifier(id, t.identifier(refName))); } // update references with the new identifiers references[refName].forEach(function (referencePath) { // eslint-disable-next-line no-param-reassign referencePath.node.name = id.name; }); }); // apply babel-plugin-styled-components to the file var stateWithOpts = _extends({}, state, { opts: config }); program.traverse(babelPlugin({ types: t }).visitor, stateWithOpts); } var configName = 'styledComponents'; var index = createMacro(styledComponentsMacro, { configName: configName }); export default index; //# sourceMappingURL=styled-components-macro.esm.js.map
/*! * jQuery JavaScript Library v1.10.0 -wrap,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-26T21:54Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.0 -wrap,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-15 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( doc.createElement("div") ) & 1; }); // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined ); return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { tween.unit = unit; tween.start = +start || +target || 0; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
/* 7. Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime. */ taskName = "7. Prime number"; function Main(bufferElement) { var integer = ReadLine("Enter a integer: ", GetRandomInt(1, 100)); SetSolveButton(function() { ConsoleClear(); isPrime(integer.value); }); } function isPrime(number) { var number = parseInt(number); if (!IsNumber(number)) { WriteLine("Error! Incorrect input value!"); return; } if (!number || number < 0 || number > 100) { WriteLine("Number must be positive and less than 100!"); return; } for (var i = 2; i <= Math.sqrt(number); i++) { if ((number % i) === 0) { WriteLine(Format("Number {0} is NOT prime!", number)); return; } } WriteLine(Format("Number {0} is prime!", number)); }
var Fiber = Npm.require('fibers'); var Future = Npm.require('fibers/future'); var PHASE = { QUERYING: "QUERYING", FETCHING: "FETCHING", STEADY: "STEADY" }; // Exception thrown by _needToPollQuery which unrolls the stack up to the // enclosing call to finishIfNeedToPollQuery. var SwitchedToQuery = function () {}; var finishIfNeedToPollQuery = function (f) { return function () { try { f.apply(this, arguments); } catch (e) { if (!(e instanceof SwitchedToQuery)) throw e; } }; }; // OplogObserveDriver is an alternative to PollingObserveDriver which follows // the Mongo operation log instead of just re-polling the query. It obeys the // same simple interface: constructing it starts sending observeChanges // callbacks (and a ready() invocation) to the ObserveMultiplexer, and you stop // it by calling the stop() method. OplogObserveDriver = function (options) { var self = this; self._usesOplog = true; // tests look at this self._cursorDescription = options.cursorDescription; self._mongoHandle = options.mongoHandle; self._multiplexer = options.multiplexer; if (options.ordered) { throw Error("OplogObserveDriver only supports unordered observeChanges"); } var sorter = options.sorter; // We don't support $near and other geo-queries so it's OK to initialize the // comparator only once in the constructor. var comparator = sorter && sorter.getComparator(); if (options.cursorDescription.options.limit) { // There are several properties ordered driver implements: // - _limit is a positive number // - _comparator is a function-comparator by which the query is ordered // - _unpublishedBuffer is non-null Min/Max Heap, // the empty buffer in STEADY phase implies that the // everything that matches the queries selector fits // into published set. // - _published - Min Heap (also implements IdMap methods) var heapOptions = { IdMap: LocalCollection._IdMap }; self._limit = self._cursorDescription.options.limit; self._comparator = comparator; self._sorter = sorter; self._unpublishedBuffer = new MinMaxHeap(comparator, heapOptions); // We need something that can find Max value in addition to IdMap interface self._published = new MaxHeap(comparator, heapOptions); } else { self._limit = 0; self._comparator = null; self._sorter = null; self._unpublishedBuffer = null; self._published = new LocalCollection._IdMap; } // Indicates if it is safe to insert a new document at the end of the buffer // for this query. i.e. it is known that there are no documents matching the // selector those are not in published or buffer. self._safeAppendToBuffer = false; self._stopped = false; self._stopHandles = []; Package.facts && Package.facts.Facts.incrementServerFact( "mongo-livedata", "observe-drivers-oplog", 1); self._registerPhaseChange(PHASE.QUERYING); var selector = self._cursorDescription.selector; self._matcher = options.matcher; var projection = self._cursorDescription.options.fields || {}; self._projectionFn = LocalCollection._compileProjection(projection); // Projection function, result of combining important fields for selector and // existing fields projection self._sharedProjection = self._matcher.combineIntoProjection(projection); if (sorter) self._sharedProjection = sorter.combineIntoProjection(self._sharedProjection); self._sharedProjectionFn = LocalCollection._compileProjection( self._sharedProjection); self._needToFetch = new LocalCollection._IdMap; self._currentlyFetching = null; self._fetchGeneration = 0; self._requeryWhenDoneThisQuery = false; self._writesToCommitWhenWeReachSteady = []; // If the oplog handle tells us that it skipped some entries (because it got // behind, say), re-poll. self._stopHandles.push(self._mongoHandle._oplogHandle.onSkippedEntries( finishIfNeedToPollQuery(function () { self._needToPollQuery(); }) )); forEachTrigger(self._cursorDescription, function (trigger) { self._stopHandles.push(self._mongoHandle._oplogHandle.onOplogEntry( trigger, function (notification) { Meteor._noYieldsAllowed(finishIfNeedToPollQuery(function () { var op = notification.op; if (notification.dropCollection || notification.dropDatabase) { // Note: this call is not allowed to block on anything (especially // on waiting for oplog entries to catch up) because that will block // onOplogEntry! self._needToPollQuery(); } else { // All other operators should be handled depending on phase if (self._phase === PHASE.QUERYING) self._handleOplogEntryQuerying(op); else self._handleOplogEntrySteadyOrFetching(op); } })); } )); }); // XXX ordering w.r.t. everything else? self._stopHandles.push(listenAll( self._cursorDescription, function (notification) { // If we're not in a write fence, we don't have to do anything. var fence = DDPServer._CurrentWriteFence.get(); if (!fence) return; var write = fence.beginWrite(); // This write cannot complete until we've caught up to "this point" in the // oplog, and then made it back to the steady state. Meteor.defer(function () { self._mongoHandle._oplogHandle.waitUntilCaughtUp(); if (self._stopped) { // We're stopped, so just immediately commit. write.committed(); } else if (self._phase === PHASE.STEADY) { // Make sure that all of the callbacks have made it through the // multiplexer and been delivered to ObserveHandles before committing // writes. self._multiplexer.onFlush(function () { write.committed(); }); } else { self._writesToCommitWhenWeReachSteady.push(write); } }); } )); // When Mongo fails over, we need to repoll the query, in case we processed an // oplog entry that got rolled back. self._stopHandles.push(self._mongoHandle._onFailover(finishIfNeedToPollQuery( function () { self._needToPollQuery(); }))); // Give _observeChanges a chance to add the new ObserveHandle to our // multiplexer, so that the added calls get streamed. Meteor.defer(finishIfNeedToPollQuery(function () { self._runInitialQuery(); })); }; _.extend(OplogObserveDriver.prototype, { _addPublished: function (id, doc) { var self = this; Meteor._noYieldsAllowed(function () { var fields = _.clone(doc); delete fields._id; self._published.set(id, self._sharedProjectionFn(doc)); self._multiplexer.added(id, self._projectionFn(fields)); // After adding this document, the published set might be overflowed // (exceeding capacity specified by limit). If so, push the maximum // element to the buffer, we might want to save it in memory to reduce the // amount of Mongo lookups in the future. if (self._limit && self._published.size() > self._limit) { // XXX in theory the size of published is no more than limit+1 if (self._published.size() !== self._limit + 1) { throw new Error("After adding to published, " + (self._published.size() - self._limit) + " documents are overflowing the set"); } var overflowingDocId = self._published.maxElementId(); var overflowingDoc = self._published.get(overflowingDocId); if (EJSON.equals(overflowingDocId, id)) { throw new Error("The document just added is overflowing the published set"); } self._published.remove(overflowingDocId); self._multiplexer.removed(overflowingDocId); self._addBuffered(overflowingDocId, overflowingDoc); } }); }, _removePublished: function (id) { var self = this; Meteor._noYieldsAllowed(function () { self._published.remove(id); self._multiplexer.removed(id); if (! self._limit || self._published.size() === self._limit) return; if (self._published.size() > self._limit) throw Error("self._published got too big"); // OK, we are publishing less than the limit. Maybe we should look in the // buffer to find the next element past what we were publishing before. if (!self._unpublishedBuffer.empty()) { // There's something in the buffer; move the first thing in it to // _published. var newDocId = self._unpublishedBuffer.minElementId(); var newDoc = self._unpublishedBuffer.get(newDocId); self._removeBuffered(newDocId); self._addPublished(newDocId, newDoc); return; } // There's nothing in the buffer. This could mean one of a few things. // (a) We could be in the middle of re-running the query (specifically, we // could be in _publishNewResults). In that case, _unpublishedBuffer is // empty because we clear it at the beginning of _publishNewResults. In // this case, our caller already knows the entire answer to the query and // we don't need to do anything fancy here. Just return. if (self._phase === PHASE.QUERYING) return; // (b) We're pretty confident that the union of _published and // _unpublishedBuffer contain all documents that match selector. Because // _unpublishedBuffer is empty, that means we're confident that _published // contains all documents that match selector. So we have nothing to do. if (self._safeAppendToBuffer) return; // (c) Maybe there are other documents out there that should be in our // buffer. But in that case, when we emptied _unpublishedBuffer in // _removeBuffered, we should have called _needToPollQuery, which will // either put something in _unpublishedBuffer or set _safeAppendToBuffer // (or both), and it will put us in QUERYING for that whole time. So in // fact, we shouldn't be able to get here. throw new Error("Buffer inexplicably empty"); }); }, _changePublished: function (id, oldDoc, newDoc) { var self = this; Meteor._noYieldsAllowed(function () { self._published.set(id, self._sharedProjectionFn(newDoc)); var projectedNew = self._projectionFn(newDoc); var projectedOld = self._projectionFn(oldDoc); var changed = LocalCollection._makeChangedFields( projectedNew, projectedOld); if (!_.isEmpty(changed)) self._multiplexer.changed(id, changed); }); }, _addBuffered: function (id, doc) { var self = this; Meteor._noYieldsAllowed(function () { self._unpublishedBuffer.set(id, self._sharedProjectionFn(doc)); // If something is overflowing the buffer, we just remove it from cache if (self._unpublishedBuffer.size() > self._limit) { var maxBufferedId = self._unpublishedBuffer.maxElementId(); self._unpublishedBuffer.remove(maxBufferedId); // Since something matching is removed from cache (both published set and // buffer), set flag to false self._safeAppendToBuffer = false; } }); }, // Is called either to remove the doc completely from matching set or to move // it to the published set later. _removeBuffered: function (id) { var self = this; Meteor._noYieldsAllowed(function () { self._unpublishedBuffer.remove(id); // To keep the contract "buffer is never empty in STEADY phase unless the // everything matching fits into published" true, we poll everything as // soon as we see the buffer becoming empty. if (! self._unpublishedBuffer.size() && ! self._safeAppendToBuffer) self._needToPollQuery(); }); }, // Called when a document has joined the "Matching" results set. // Takes responsibility of keeping _unpublishedBuffer in sync with _published // and the effect of limit enforced. _addMatching: function (doc) { var self = this; Meteor._noYieldsAllowed(function () { var id = doc._id; if (self._published.has(id)) throw Error("tried to add something already published " + id); if (self._limit && self._unpublishedBuffer.has(id)) throw Error("tried to add something already existed in buffer " + id); var limit = self._limit; var comparator = self._comparator; var maxPublished = (limit && self._published.size() > 0) ? self._published.get(self._published.maxElementId()) : null; var maxBuffered = (limit && self._unpublishedBuffer.size() > 0) ? self._unpublishedBuffer.get(self._unpublishedBuffer.maxElementId()) : null; // The query is unlimited or didn't publish enough documents yet or the // new document would fit into published set pushing the maximum element // out, then we need to publish the doc. var toPublish = ! limit || self._published.size() < limit || comparator(doc, maxPublished) < 0; // Otherwise we might need to buffer it (only in case of limited query). // Buffering is allowed if the buffer is not filled up yet and all // matching docs are either in the published set or in the buffer. var canAppendToBuffer = !toPublish && self._safeAppendToBuffer && self._unpublishedBuffer.size() < limit; // Or if it is small enough to be safely inserted to the middle or the // beginning of the buffer. var canInsertIntoBuffer = !toPublish && maxBuffered && comparator(doc, maxBuffered) <= 0; var toBuffer = canAppendToBuffer || canInsertIntoBuffer; if (toPublish) { self._addPublished(id, doc); } else if (toBuffer) { self._addBuffered(id, doc); } else { // dropping it and not saving to the cache self._safeAppendToBuffer = false; } }); }, // Called when a document leaves the "Matching" results set. // Takes responsibility of keeping _unpublishedBuffer in sync with _published // and the effect of limit enforced. _removeMatching: function (id) { var self = this; Meteor._noYieldsAllowed(function () { if (! self._published.has(id) && ! self._limit) throw Error("tried to remove something matching but not cached " + id); if (self._published.has(id)) { self._removePublished(id); } else if (self._unpublishedBuffer.has(id)) { self._removeBuffered(id); } }); }, _handleDoc: function (id, newDoc) { var self = this; Meteor._noYieldsAllowed(function () { var matchesNow = newDoc && self._matcher.documentMatches(newDoc).result; var publishedBefore = self._published.has(id); var bufferedBefore = self._limit && self._unpublishedBuffer.has(id); var cachedBefore = publishedBefore || bufferedBefore; if (matchesNow && !cachedBefore) { self._addMatching(newDoc); } else if (cachedBefore && !matchesNow) { self._removeMatching(id); } else if (cachedBefore && matchesNow) { var oldDoc = self._published.get(id); var comparator = self._comparator; var minBuffered = self._limit && self._unpublishedBuffer.size() && self._unpublishedBuffer.get(self._unpublishedBuffer.minElementId()); if (publishedBefore) { // Unlimited case where the document stays in published once it // matches or the case when we don't have enough matching docs to // publish or the changed but matching doc will stay in published // anyways. // // XXX: We rely on the emptiness of buffer. Be sure to maintain the // fact that buffer can't be empty if there are matching documents not // published. Notably, we don't want to schedule repoll and continue // relying on this property. var staysInPublished = ! self._limit || self._unpublishedBuffer.size() === 0 || comparator(newDoc, minBuffered) <= 0; if (staysInPublished) { self._changePublished(id, oldDoc, newDoc); } else { // after the change doc doesn't stay in the published, remove it self._removePublished(id); // but it can move into buffered now, check it var maxBuffered = self._unpublishedBuffer.get( self._unpublishedBuffer.maxElementId()); var toBuffer = self._safeAppendToBuffer || (maxBuffered && comparator(newDoc, maxBuffered) <= 0); if (toBuffer) { self._addBuffered(id, newDoc); } else { // Throw away from both published set and buffer self._safeAppendToBuffer = false; } } } else if (bufferedBefore) { oldDoc = self._unpublishedBuffer.get(id); // remove the old version manually instead of using _removeBuffered so // we don't trigger the querying immediately. if we end this block // with the buffer empty, we will need to trigger the query poll // manually too. self._unpublishedBuffer.remove(id); var maxPublished = self._published.get( self._published.maxElementId()); var maxBuffered = self._unpublishedBuffer.size() && self._unpublishedBuffer.get( self._unpublishedBuffer.maxElementId()); // the buffered doc was updated, it could move to published var toPublish = comparator(newDoc, maxPublished) < 0; // or stays in buffer even after the change var staysInBuffer = (! toPublish && self._safeAppendToBuffer) || (!toPublish && maxBuffered && comparator(newDoc, maxBuffered) <= 0); if (toPublish) { self._addPublished(id, newDoc); } else if (staysInBuffer) { // stays in buffer but changes self._unpublishedBuffer.set(id, newDoc); } else { // Throw away from both published set and buffer self._safeAppendToBuffer = false; // Normally this check would have been done in _removeBuffered but // we didn't use it, so we need to do it ourself now. if (! self._unpublishedBuffer.size()) { self._needToPollQuery(); } } } else { throw new Error("cachedBefore implies either of publishedBefore or bufferedBefore is true."); } } }); }, _fetchModifiedDocuments: function () { var self = this; Meteor._noYieldsAllowed(function () { self._registerPhaseChange(PHASE.FETCHING); // Defer, because nothing called from the oplog entry handler may yield, // but fetch() yields. Meteor.defer(finishIfNeedToPollQuery(function () { while (!self._stopped && !self._needToFetch.empty()) { if (self._phase === PHASE.QUERYING) { // While fetching, we decided to go into QUERYING mode, and then we // saw another oplog entry, so _needToFetch is not empty. But we // shouldn't fetch these documents until AFTER the query is done. break; } // Being in steady phase here would be surprising. if (self._phase !== PHASE.FETCHING) throw new Error("phase in fetchModifiedDocuments: " + self._phase); self._currentlyFetching = self._needToFetch; var thisGeneration = ++self._fetchGeneration; self._needToFetch = new LocalCollection._IdMap; var waiting = 0; var fut = new Future; // This loop is safe, because _currentlyFetching will not be updated // during this loop (in fact, it is never mutated). self._currentlyFetching.forEach(function (cacheKey, id) { waiting++; self._mongoHandle._docFetcher.fetch( self._cursorDescription.collectionName, id, cacheKey, finishIfNeedToPollQuery(function (err, doc) { try { if (err) { Meteor._debug("Got exception while fetching documents: " + err); // If we get an error from the fetcher (eg, trouble // connecting to Mongo), let's just abandon the fetch phase // altogether and fall back to polling. It's not like we're // getting live updates anyway. if (self._phase !== PHASE.QUERYING) { self._needToPollQuery(); } } else if (!self._stopped && self._phase === PHASE.FETCHING && self._fetchGeneration === thisGeneration) { // We re-check the generation in case we've had an explicit // _pollQuery call (eg, in another fiber) which should // effectively cancel this round of fetches. (_pollQuery // increments the generation.) self._handleDoc(id, doc); } } finally { waiting--; // Because fetch() never calls its callback synchronously, // this is safe (ie, we won't call fut.return() before the // forEach is done). if (waiting === 0) fut.return(); } })); }); fut.wait(); // Exit now if we've had a _pollQuery call (here or in another fiber). if (self._phase === PHASE.QUERYING) return; self._currentlyFetching = null; } // We're done fetching, so we can be steady, unless we've had a // _pollQuery call (here or in another fiber). if (self._phase !== PHASE.QUERYING) self._beSteady(); })); }); }, _beSteady: function () { var self = this; Meteor._noYieldsAllowed(function () { self._registerPhaseChange(PHASE.STEADY); var writes = self._writesToCommitWhenWeReachSteady; self._writesToCommitWhenWeReachSteady = []; self._multiplexer.onFlush(function () { _.each(writes, function (w) { w.committed(); }); }); }); }, _handleOplogEntryQuerying: function (op) { var self = this; Meteor._noYieldsAllowed(function () { self._needToFetch.set(idForOp(op), op.ts.toString()); }); }, _handleOplogEntrySteadyOrFetching: function (op) { var self = this; Meteor._noYieldsAllowed(function () { var id = idForOp(op); // If we're already fetching this one, or about to, we can't optimize; // make sure that we fetch it again if necessary. if (self._phase === PHASE.FETCHING && ((self._currentlyFetching && self._currentlyFetching.has(id)) || self._needToFetch.has(id))) { self._needToFetch.set(id, op.ts.toString()); return; } if (op.op === 'd') { if (self._published.has(id) || (self._limit && self._unpublishedBuffer.has(id))) self._removeMatching(id); } else if (op.op === 'i') { if (self._published.has(id)) throw new Error("insert found for already-existing ID in published"); if (self._unpublishedBuffer && self._unpublishedBuffer.has(id)) throw new Error("insert found for already-existing ID in buffer"); // XXX what if selector yields? for now it can't but later it could // have $where if (self._matcher.documentMatches(op.o).result) self._addMatching(op.o); } else if (op.op === 'u') { // Is this a modifier ($set/$unset, which may require us to poll the // database to figure out if the whole document matches the selector) or // a replacement (in which case we can just directly re-evaluate the // selector)? var isReplace = !_.has(op.o, '$set') && !_.has(op.o, '$unset'); // If this modifier modifies something inside an EJSON custom type (ie, // anything with EJSON$), then we can't try to use // LocalCollection._modify, since that just mutates the EJSON encoding, // not the actual object. var canDirectlyModifyDoc = !isReplace && modifierCanBeDirectlyApplied(op.o); var publishedBefore = self._published.has(id); var bufferedBefore = self._limit && self._unpublishedBuffer.has(id); if (isReplace) { self._handleDoc(id, _.extend({_id: id}, op.o)); } else if ((publishedBefore || bufferedBefore) && canDirectlyModifyDoc) { // Oh great, we actually know what the document is, so we can apply // this directly. var newDoc = self._published.has(id) ? self._published.get(id) : self._unpublishedBuffer.get(id); newDoc = EJSON.clone(newDoc); newDoc._id = id; try { LocalCollection._modify(newDoc, op.o); } catch (e) { if (e.name !== "MinimongoError") throw e; // We didn't understand the modifier. Re-fetch. self._needToFetch.set(id, op.ts.toString()); if (self._phase === PHASE.STEADY) { self._fetchModifiedDocuments(); } return; } self._handleDoc(id, self._sharedProjectionFn(newDoc)); } else if (!canDirectlyModifyDoc || self._matcher.canBecomeTrueByModifier(op.o) || (self._sorter && self._sorter.affectedByModifier(op.o))) { self._needToFetch.set(id, op.ts.toString()); if (self._phase === PHASE.STEADY) self._fetchModifiedDocuments(); } } else { throw Error("XXX SURPRISING OPERATION: " + op); } }); }, // Yields! _runInitialQuery: function () { var self = this; if (self._stopped) throw new Error("oplog stopped surprisingly early"); self._runQuery({initial: true}); // yields if (self._stopped) return; // can happen on queryError // Allow observeChanges calls to return. (After this, it's possible for // stop() to be called.) self._multiplexer.ready(); self._doneQuerying(); // yields }, // In various circumstances, we may just want to stop processing the oplog and // re-run the initial query, just as if we were a PollingObserveDriver. // // This function may not block, because it is called from an oplog entry // handler. // // XXX We should call this when we detect that we've been in FETCHING for "too // long". // // XXX We should call this when we detect Mongo failover (since that might // mean that some of the oplog entries we have processed have been rolled // back). The Node Mongo driver is in the middle of a bunch of huge // refactorings, including the way that it notifies you when primary // changes. Will put off implementing this until driver 1.4 is out. _pollQuery: function () { var self = this; Meteor._noYieldsAllowed(function () { if (self._stopped) return; // Yay, we get to forget about all the things we thought we had to fetch. self._needToFetch = new LocalCollection._IdMap; self._currentlyFetching = null; ++self._fetchGeneration; // ignore any in-flight fetches self._registerPhaseChange(PHASE.QUERYING); // Defer so that we don't yield. We don't need finishIfNeedToPollQuery // here because SwitchedToQuery is not thrown in QUERYING mode. Meteor.defer(function () { self._runQuery(); self._doneQuerying(); }); }); }, // Yields! _runQuery: function (options) { var self = this; options = options || {}; var newResults, newBuffer; // This while loop is just to retry failures. while (true) { // If we've been stopped, we don't have to run anything any more. if (self._stopped) return; newResults = new LocalCollection._IdMap; newBuffer = new LocalCollection._IdMap; // Query 2x documents as the half excluded from the original query will go // into unpublished buffer to reduce additional Mongo lookups in cases // when documents are removed from the published set and need a // replacement. // XXX needs more thought on non-zero skip // XXX 2 is a "magic number" meaning there is an extra chunk of docs for // buffer if such is needed. var cursor = self._cursorForQuery({ limit: self._limit * 2 }); try { cursor.forEach(function (doc, i) { // yields if (!self._limit || i < self._limit) newResults.set(doc._id, doc); else newBuffer.set(doc._id, doc); }); break; } catch (e) { if (options.initial && typeof(e.code) === 'number') { // This is an error document sent to us by mongod, not a connection // error generated by the client. And we've never seen this query work // successfully. Probably it's a bad selector or something, so we // should NOT retry. Instead, we should halt the observe (which ends // up calling `stop` on us). self._multiplexer.queryError(e); return; } // During failover (eg) if we get an exception we should log and retry // instead of crashing. Meteor._debug("Got exception while polling query: " + e); Meteor._sleepForMs(100); } } if (self._stopped) return; self._publishNewResults(newResults, newBuffer); }, // Transitions to QUERYING and runs another query, or (if already in QUERYING) // ensures that we will query again later. // // This function may not block, because it is called from an oplog entry // handler. However, if we were not already in the QUERYING phase, it throws // an exception that is caught by the closest surrounding // finishIfNeedToPollQuery call; this ensures that we don't continue running // close that was designed for another phase inside PHASE.QUERYING. // // (It's also necessary whenever logic in this file yields to check that other // phases haven't put us into QUERYING mode, though; eg, // _fetchModifiedDocuments does this.) _needToPollQuery: function () { var self = this; Meteor._noYieldsAllowed(function () { if (self._stopped) return; // If we're not already in the middle of a query, we can query now // (possibly pausing FETCHING). if (self._phase !== PHASE.QUERYING) { self._pollQuery(); throw new SwitchedToQuery; } // We're currently in QUERYING. Set a flag to ensure that we run another // query when we're done. self._requeryWhenDoneThisQuery = true; }); }, // Yields! _doneQuerying: function () { var self = this; if (self._stopped) return; self._mongoHandle._oplogHandle.waitUntilCaughtUp(); // yields if (self._stopped) return; if (self._phase !== PHASE.QUERYING) throw Error("Phase unexpectedly " + self._phase); Meteor._noYieldsAllowed(function () { if (self._requeryWhenDoneThisQuery) { self._requeryWhenDoneThisQuery = false; self._pollQuery(); } else if (self._needToFetch.empty()) { self._beSteady(); } else { self._fetchModifiedDocuments(); } }); }, _cursorForQuery: function (optionsOverwrite) { var self = this; return Meteor._noYieldsAllowed(function () { // The query we run is almost the same as the cursor we are observing, // with a few changes. We need to read all the fields that are relevant to // the selector, not just the fields we are going to publish (that's the // "shared" projection). And we don't want to apply any transform in the // cursor, because observeChanges shouldn't use the transform. var options = _.clone(self._cursorDescription.options); // Allow the caller to modify the options. Useful to specify different // skip and limit values. _.extend(options, optionsOverwrite); options.fields = self._sharedProjection; delete options.transform; // We are NOT deep cloning fields or selector here, which should be OK. var description = new CursorDescription( self._cursorDescription.collectionName, self._cursorDescription.selector, options); return new Cursor(self._mongoHandle, description); }); }, // Replace self._published with newResults (both are IdMaps), invoking observe // callbacks on the multiplexer. // Replace self._unpublishedBuffer with newBuffer. // // XXX This is very similar to LocalCollection._diffQueryUnorderedChanges. We // should really: (a) Unify IdMap and OrderedDict into Unordered/OrderedDict // (b) Rewrite diff.js to use these classes instead of arrays and objects. _publishNewResults: function (newResults, newBuffer) { var self = this; Meteor._noYieldsAllowed(function () { // If the query is limited and there is a buffer, shut down so it doesn't // stay in a way. if (self._limit) { self._unpublishedBuffer.clear(); } // First remove anything that's gone. Be careful not to modify // self._published while iterating over it. var idsToRemove = []; self._published.forEach(function (doc, id) { if (!newResults.has(id)) idsToRemove.push(id); }); _.each(idsToRemove, function (id) { self._removePublished(id); }); // Now do adds and changes. // If self has a buffer and limit, the new fetched result will be // limited correctly as the query has sort specifier. newResults.forEach(function (doc, id) { self._handleDoc(id, doc); }); // Sanity-check that everything we tried to put into _published ended up // there. // XXX if this is slow, remove it later if (self._published.size() !== newResults.size()) { throw Error( "The Mongo server and the Meteor query disagree on how " + "many documents match your query. Maybe it is hitting a Mongo " + "edge case? The query is: " + EJSON.stringify(self._cursorDescription.selector)); } self._published.forEach(function (doc, id) { if (!newResults.has(id)) throw Error("_published has a doc that newResults doesn't; " + id); }); // Finally, replace the buffer newBuffer.forEach(function (doc, id) { self._addBuffered(id, doc); }); self._safeAppendToBuffer = newBuffer.size() < self._limit; }); }, // This stop function is invoked from the onStop of the ObserveMultiplexer, so // it shouldn't actually be possible to call it until the multiplexer is // ready. // // It's important to check self._stopped after every call in this file that // can yield! stop: function () { var self = this; if (self._stopped) return; self._stopped = true; _.each(self._stopHandles, function (handle) { handle.stop(); }); // Note: we *don't* use multiplexer.onFlush here because this stop // callback is actually invoked by the multiplexer itself when it has // determined that there are no handles left. So nothing is actually going // to get flushed (and it's probably not valid to call methods on the // dying multiplexer). _.each(self._writesToCommitWhenWeReachSteady, function (w) { w.committed(); // maybe yields? }); self._writesToCommitWhenWeReachSteady = null; // Proactively drop references to potentially big things. self._published = null; self._unpublishedBuffer = null; self._needToFetch = null; self._currentlyFetching = null; self._oplogEntryHandle = null; self._listenersHandle = null; Package.facts && Package.facts.Facts.incrementServerFact( "mongo-livedata", "observe-drivers-oplog", -1); }, _registerPhaseChange: function (phase) { var self = this; Meteor._noYieldsAllowed(function () { var now = new Date; if (self._phase) { var timeDiff = now - self._phaseStartTime; Package.facts && Package.facts.Facts.incrementServerFact( "mongo-livedata", "time-spent-in-" + self._phase + "-phase", timeDiff); } self._phase = phase; self._phaseStartTime = now; }); } }); // Does our oplog tailing code support this cursor? For now, we are being very // conservative and allowing only simple queries with simple options. // (This is a "static method".) OplogObserveDriver.cursorSupported = function (cursorDescription, matcher) { // First, check the options. var options = cursorDescription.options; // Did the user say no explicitly? if (options._disableOplog) return false; // skip is not supported: to support it we would need to keep track of all // "skipped" documents or at least their ids. // limit w/o a sort specifier is not supported: current implementation needs a // deterministic way to order documents. if (options.skip || (options.limit && !options.sort)) return false; // If a fields projection option is given check if it is supported by // minimongo (some operators are not supported). if (options.fields) { try { LocalCollection._checkSupportedProjection(options.fields); } catch (e) { if (e.name === "MinimongoError") return false; else throw e; } } // We don't allow the following selectors: // - $where (not confident that we provide the same JS environment // as Mongo, and can yield!) // - $near (has "interesting" properties in MongoDB, like the possibility // of returning an ID multiple times, though even polling maybe // have a bug there) // XXX: once we support it, we would need to think more on how we // initialize the comparators when we create the driver. return !matcher.hasWhere() && !matcher.hasGeoQuery(); }; var modifierCanBeDirectlyApplied = function (modifier) { return _.all(modifier, function (fields, operation) { return _.all(fields, function (value, field) { return !/EJSON\$/.test(field); }); }); }; MongoInternals.OplogObserveDriver = OplogObserveDriver;
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLeakRemove = (props) => ( <SvgIcon {...props}> <path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97C7.14 11.24 5.16 12 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5C10.99 15.81 10 18.29 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43C14.55 17.91 14 19.39 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46C18.09 12.37 19.5 12 21 12v-2c-2.06 0-3.98.58-5.62 1.56z"/> </SvgIcon> ); ImageLeakRemove = pure(ImageLeakRemove); ImageLeakRemove.displayName = 'ImageLeakRemove'; export default ImageLeakRemove;
var EventEmitter = require('events').EventEmitter, inherits = require('util').inherits; var StreamSearch = require('streamsearch'); var B_DCRLF = Buffer.from('\r\n\r\n'), RE_CRLF = /\r\n/g, RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/, MAX_HEADER_PAIRS = 2000, // from node's http.js MAX_HEADER_SIZE = 80 * 1024; // from node's http_parser function HeaderParser(cfg) { EventEmitter.call(this); var self = this; this.nread = 0; this.maxed = false; this.npairs = 0; this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number' ? cfg.maxHeaderPairs : MAX_HEADER_PAIRS); this.buffer = ''; this.header = {}; this.finished = false; this.ss = new StreamSearch(B_DCRLF); this.ss.on('info', function(isMatch, data, start, end) { if (data && !self.maxed) { if (self.nread + (end - start) > MAX_HEADER_SIZE) { end = (MAX_HEADER_SIZE - self.nread); self.nread = MAX_HEADER_SIZE; } else self.nread += (end - start); if (self.nread === MAX_HEADER_SIZE) self.maxed = true; self.buffer += data.toString('binary', start, end); } if (isMatch) self._finish(); }); } inherits(HeaderParser, EventEmitter); HeaderParser.prototype.push = function(data) { var r = this.ss.push(data); if (this.finished) return r; }; HeaderParser.prototype.reset = function() { this.finished = false; this.buffer = ''; this.header = {}; this.ss.reset(); }; HeaderParser.prototype._finish = function() { if (this.buffer) this._parseHeader(); this.ss.matches = this.ss.maxMatches; var header = this.header; this.header = {}; this.buffer = ''; this.finished = true; this.nread = this.npairs = 0; this.maxed = false; this.emit('header', header); }; HeaderParser.prototype._parseHeader = function() { if (this.npairs === this.maxHeaderPairs) return; var lines = this.buffer.split(RE_CRLF), len = lines.length, m, h, modded = false; for (var i = 0; i < len; ++i) { if (lines[i].length === 0) continue; if (lines[i][0] === '\t' || lines[i][0] === ' ') { // folded header content // RFC2822 says to just remove the CRLF and not the whitespace following // it, so we follow the RFC and include the leading whitespace ... this.header[h][this.header[h].length - 1] += lines[i]; } else { m = RE_HDR.exec(lines[i]); if (m) { h = m[1].toLowerCase(); if (m[2]) { if (this.header[h] === undefined) this.header[h] = [m[2]]; else this.header[h].push(m[2]); } else this.header[h] = ['']; if (++this.npairs === this.maxHeaderPairs) break; } else { this.buffer = lines[i]; modded = true; break; } } } if (!modded) this.buffer = ''; }; module.exports = HeaderParser;
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'contextmenu', 'bn', { options: 'Context Menu Options' // MISSING });
/** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: js/tinymce/plugins/spellchecker/classes/DomTextMatcher.js /** * DomTextMatcher.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class logic for filtering text and matching words. * * @class tinymce.spellcheckerplugin.TextFilter * @private */ define("tinymce/spellcheckerplugin/DomTextMatcher", [], function() { // Based on work developed by: James Padolsey http://james.padolsey.com // released under UNLICENSE that is compatible with LGPL // TODO: Handle contentEditable edgecase: // <p>text<span contentEditable="false">text<span contentEditable="true">text</span>text</span>text</p> return function(regex, node, schema) { var m, matches = [], text, count = 0, doc; var blockElementsMap, hiddenTextElementsMap, shortEndedElementsMap; doc = node.ownerDocument; blockElementsMap = schema.getBlockElements(); // H1-H6, P, TD etc hiddenTextElementsMap = schema.getWhiteSpaceElements(); // TEXTAREA, PRE, STYLE, SCRIPT shortEndedElementsMap = schema.getShortEndedElements(); // BR, IMG, INPUT function getMatchIndexes(m) { if (!m[0]) { throw 'findAndReplaceDOMText cannot handle zero-length matches'; } var index = m.index; return [index, index + m[0].length, [m[0]]]; } function getText(node) { var txt; if (node.nodeType === 3) { return node.data; } if (hiddenTextElementsMap[node.nodeName]) { return ''; } txt = ''; if (blockElementsMap[node.nodeName] || shortEndedElementsMap[node.nodeName]) { txt += '\n'; } if ((node = node.firstChild)) { do { txt += getText(node); } while ((node = node.nextSibling)); } return txt; } function stepThroughMatches(node, matches, replaceFn) { var startNode, endNode, startNodeIndex, endNodeIndex, innerNodes = [], atIndex = 0, curNode = node, matchLocation = matches.shift(), matchIndex = 0; out: while (true) { if (blockElementsMap[curNode.nodeName] || shortEndedElementsMap[curNode.nodeName]) { atIndex++; } if (curNode.nodeType === 3) { if (!endNode && curNode.length + atIndex >= matchLocation[1]) { // We've found the ending endNode = curNode; endNodeIndex = matchLocation[1] - atIndex; } else if (startNode) { // Intersecting node innerNodes.push(curNode); } if (!startNode && curNode.length + atIndex > matchLocation[0]) { // We've found the match start startNode = curNode; startNodeIndex = matchLocation[0] - atIndex; } atIndex += curNode.length; } if (startNode && endNode) { curNode = replaceFn({ startNode: startNode, startNodeIndex: startNodeIndex, endNode: endNode, endNodeIndex: endNodeIndex, innerNodes: innerNodes, match: matchLocation[2], matchIndex: matchIndex }); // replaceFn has to return the node that replaced the endNode // and then we step back so we can continue from the end of the // match: atIndex -= (endNode.length - endNodeIndex); startNode = null; endNode = null; innerNodes = []; matchLocation = matches.shift(); matchIndex++; if (!matchLocation) { break; // no more matches } } else if (!hiddenTextElementsMap[curNode.nodeName] && curNode.firstChild) { // Move down curNode = curNode.firstChild; continue; } else if (curNode.nextSibling) { // Move forward: curNode = curNode.nextSibling; continue; } // Move forward or up: while (true) { if (curNode.nextSibling) { curNode = curNode.nextSibling; break; } else if (curNode.parentNode !== node) { curNode = curNode.parentNode; } else { break out; } } } } /** * Generates the actual replaceFn which splits up text nodes * and inserts the replacement element. */ function genReplacer(nodeName) { var makeReplacementNode; if (typeof nodeName != 'function') { var stencilNode = nodeName.nodeType ? nodeName : doc.createElement(nodeName); makeReplacementNode = function(fill, matchIndex) { var clone = stencilNode.cloneNode(false); clone.setAttribute('data-mce-index', matchIndex); if (fill) { clone.appendChild(doc.createTextNode(fill)); } return clone; }; } else { makeReplacementNode = nodeName; } return function replace(range) { var before, after, parentNode, startNode = range.startNode, endNode = range.endNode, matchIndex = range.matchIndex; if (startNode === endNode) { var node = startNode; parentNode = node.parentNode; if (range.startNodeIndex > 0) { // Add `before` text node (before the match) before = doc.createTextNode(node.data.substring(0, range.startNodeIndex)); parentNode.insertBefore(before, node); } // Create the replacement node: var el = makeReplacementNode(range.match[0], matchIndex); parentNode.insertBefore(el, node); if (range.endNodeIndex < node.length) { // Add `after` text node (after the match) after = doc.createTextNode(node.data.substring(range.endNodeIndex)); parentNode.insertBefore(after, node); } node.parentNode.removeChild(node); return el; } else { // Replace startNode -> [innerNodes...] -> endNode (in that order) before = doc.createTextNode(startNode.data.substring(0, range.startNodeIndex)); after = doc.createTextNode(endNode.data.substring(range.endNodeIndex)); var elA = makeReplacementNode(startNode.data.substring(range.startNodeIndex), matchIndex); var innerEls = []; for (var i = 0, l = range.innerNodes.length; i < l; ++i) { var innerNode = range.innerNodes[i]; var innerEl = makeReplacementNode(innerNode.data, matchIndex); innerNode.parentNode.replaceChild(innerEl, innerNode); innerEls.push(innerEl); } var elB = makeReplacementNode(endNode.data.substring(0, range.endNodeIndex), matchIndex); parentNode = startNode.parentNode; parentNode.insertBefore(before, startNode); parentNode.insertBefore(elA, startNode); parentNode.removeChild(startNode); parentNode = endNode.parentNode; parentNode.insertBefore(elB, endNode); parentNode.insertBefore(after, endNode); parentNode.removeChild(endNode); return elB; } }; } text = getText(node); if (text && regex.global) { while ((m = regex.exec(text))) { matches.push(getMatchIndexes(m)); } } function filter(callback) { var filteredMatches = []; each(function(match, i) { if (callback(match, i)) { filteredMatches.push(match); } }); matches = filteredMatches; /*jshint validthis:true*/ return this; } function each(callback) { for (var i = 0, l = matches.length; i < l; i++) { if (callback(matches[i], i) === false) { break; } } /*jshint validthis:true*/ return this; } function mark(replacementNode) { if (matches.length) { count = matches.length; stepThroughMatches(node, matches, genReplacer(replacementNode)); } /*jshint validthis:true*/ return this; } return { text: text, count: count, matches: matches, each: each, filter: filter, mark: mark }; }; }); // Included from: js/tinymce/plugins/spellchecker/classes/Plugin.js /** * Plugin.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*jshint camelcase:false */ /** * This class contains all core logic for the spellchecker plugin. * * @class tinymce.spellcheckerplugin.Plugin * @private */ define("tinymce/spellcheckerplugin/Plugin", [ "tinymce/spellcheckerplugin/DomTextMatcher", "tinymce/PluginManager", "tinymce/util/Tools", "tinymce/ui/Menu", "tinymce/dom/DOMUtils", "tinymce/util/JSONRequest" ], function(DomTextMatcher, PluginManager, Tools, Menu, DOMUtils, JSONRequest) { PluginManager.add('spellchecker', function(editor) { var lastSuggestions, started; function isEmpty(obj) { /*jshint unused:false*/ for (var name in obj) { return false; } return true; } function showSuggestions(target, word) { var items = [], suggestions = lastSuggestions[word]; Tools.each(suggestions, function(suggestion) { items.push({ text: suggestion, onclick: function() { editor.insertContent(suggestion); checkIfFinished(); } }); }); items.push.apply(items, [ {text: '-'}, {text: 'Ignore', onclick: function() { ignoreWord(target, word); }}, {text: 'Ignore all', onclick: function() { ignoreWord(target, word, true); }}, {text: 'Finish', onclick: finish} ]); // Render menu var menu = new Menu({ items: items, context: 'contextmenu', onhide: function() { menu.remove(); } }); menu.renderTo(document.body); // Position menu var pos = DOMUtils.DOM.getPos(editor.getContentAreaContainer()); var targetPos = editor.dom.getPos(target); pos.x += targetPos.x; pos.y += targetPos.y; menu.moveTo(pos.x, pos.y + target.offsetHeight); } function spellcheck() { var textFilter, words = [], uniqueWords = {}; if (started) { finish(); return; } started = true; function doneCallback(suggestions) { editor.setProgressState(false); if (isEmpty(suggestions)) { editor.windowManager.alert('No misspellings found'); return; } lastSuggestions = suggestions; textFilter.filter(function(match) { return !!suggestions[match[2][0]]; }).mark(editor.dom.create('span', { "class": 'mce-spellchecker-word', "data-mce-bogus": 1 })); textFilter = null; editor.fire('SpellcheckStart'); } // Find all words and make an unique words array textFilter = new DomTextMatcher(/\w+/g, editor.getBody(), editor.schema).each(function(match) { if (!uniqueWords[match[2][0]]) { words.push(match[2][0]); uniqueWords[match[2][0]] = true; } }); editor.settings.spellcheck_callback = function(method, words, doneCallback) { JSONRequest.sendRPC({ url: editor.settings.spellchecker_rpc_url, method: method, params: { lang: "en", words: words }, success: function(result) { doneCallback(result); }, error: function(result, xhr) { editor.windowManager.alert("Error: " + result + "\nData:" + xhr.responseText); editor.setProgressState(false); textFilter = null; } }); }; editor.setProgressState(true); editor.settings.spellcheck_callback("spellcheck", words, doneCallback); } function checkIfFinished() { if (!editor.dom.select('span.mce-spellchecker-word').length) { finish(); } } function unwrap(node) { var parentNode = node.parentNode; parentNode.insertBefore(node.firstChild, node); node.parentNode.removeChild(node); } function ignoreWord(target, word, all) { if (all) { Tools.each(editor.dom.select('span.mce-spellchecker-word'), function(item) { var text = item.innerText || item.textContent; if (text == word) { unwrap(item); } }); } else { unwrap(target); } checkIfFinished(); } function finish() { var i, nodes, node; started = false; node = editor.getBody(); nodes = node.getElementsByTagName('span'); i = nodes.length; while (i--) { node = nodes[i]; if (node.getAttribute('data-mce-index')) { unwrap(node); } } editor.fire('SpellcheckEnd'); } function selectMatch(index) { var nodes, i, spanElm, spanIndex = -1, startContainer, endContainer; index = "" + index; nodes = editor.getBody().getElementsByTagName("span"); for (i = 0; i < nodes.length; i++) { spanElm = nodes[i]; if (spanElm.className == "mce-spellchecker-word") { spanIndex = spanElm.getAttribute('data-mce-index'); if (spanIndex === index) { spanIndex = index; if (!startContainer) { startContainer = spanElm.firstChild; } endContainer = spanElm.firstChild; } if (spanIndex !== index && endContainer) { break; } } } var rng = editor.dom.createRng(); rng.setStart(startContainer, 0); rng.setEnd(endContainer, endContainer.length); editor.selection.setRng(rng); return rng; } editor.on('click', function(e) { if (e.target.className == "mce-spellchecker-word") { e.preventDefault(); var rng = selectMatch(e.target.getAttribute('data-mce-index')); showSuggestions(e.target, rng.toString()); } }); editor.addMenuItem('spellchecker', { text: 'Spellcheck', context: 'tools', onclick: spellcheck, selectable: true, onPostRender: function() { var self = this; editor.on('SpellcheckStart SpellcheckEnd', function() { self.active(started); }); } }); editor.addButton('spellchecker', { tooltip: 'Spellcheck', onclick: spellcheck, onPostRender: function() { var self = this; editor.on('SpellcheckStart SpellcheckEnd', function() { self.active(started); }); } }); }); }); expose(["tinymce/spellcheckerplugin/DomTextMatcher","tinymce/spellcheckerplugin/Plugin"]); })(this);
"use strict"; var Trait = require("traits").Trait, tBodyArguments = require("./tBodyArguments"); module.exports = function (withAlert, withScene) { var values = [ { name: "on", type: "bool", optional: true }, { name: "bri", type: "uint8", minValue: 0, maxValue: 255, optional: true }, { name: "hue", type: "uint16", minValue: 0, maxValue: 65535, optional: true }, { name: "sat", type: "uint8", minValue: 0, maxValue: 255, optional: true }, { name: "xy", type: "list", listType: { name: "xyValue", type: "float", minValue: 0, maxValue: 1, optional: false }, optional: true }, { name: "ct", type: "uint8", minValue: 153, maxValue: 500, optional: true }, { name: "effect", type: "string", defaultValue: "none", validValues: ["none", "colorloop"], optional: true }, { name: "transitiontime", type: "uint16", defaultValue: 4, minValue: 0, maxValue: 65535, optional: true } ]; if (withAlert) { values.push({ name: "alert", type: "string", defaultValue: "none", validValues: ["none", "select", "lselect"], optional: true }); } if (withScene) { values.push({ name: "scene", type: "string", optional: true }); } return tBodyArguments("application/json", values); };
/*! @name videojs-contrib-ads @version 6.7.0 @license Apache-2.0 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('video.js'), require('global/window'), require('global/document')) : typeof define === 'function' && define.amd ? define(['video.js', 'global/window', 'global/document'], factory) : (global = global || self, global.videojsContribAds = factory(global.videojs, global.window, global.document)); }(this, function (videojs, window, document) { 'use strict'; videojs = videojs && videojs.hasOwnProperty('default') ? videojs['default'] : videojs; window = window && window.hasOwnProperty('default') ? window['default'] : window; document = document && document.hasOwnProperty('default') ? document['default'] : document; var version = "6.7.0"; /* * Implements the public API available in `player.ads` as well as application state. */ function getAds(player) { return { disableNextSnapshotRestore: false, // This is true if we have finished actual content playback but haven't // dealt with postrolls and officially ended yet _contentEnding: false, // This is set to true if the content has officially ended at least once. // After that, the user can seek backwards and replay content, but _contentHasEnded // remains true. _contentHasEnded: false, // Tracks if loadstart has happened yet for the initial source. It is not reset // on source changes because loadstart is the event that signals to the ad plugin // that the source has changed. Therefore, no special signaling is needed to know // that there has been one for subsequent sources. _hasThereBeenALoadStartDuringPlayerLife: false, // Tracks if loadeddata has happened yet for the current source. _hasThereBeenALoadedData: false, // Tracks if loadedmetadata has happened yet for the current source. _hasThereBeenALoadedMetaData: false, // Are we after startLinearAdMode and before endLinearAdMode? _inLinearAdMode: false, // Should we block calls to play on the content player? _shouldBlockPlay: false, // Was play blocked by the plugin's playMiddleware feature? _playBlocked: false, // Tracks whether play has been requested for this source, // either by the play method or user interaction _playRequested: false, // This is an estimation of the current ad type being played // This is experimental currently. Do not rely on its presence or behavior! adType: null, VERSION: version, reset: function reset() { player.ads.disableNextSnapshotRestore = false; player.ads._contentEnding = false; player.ads._contentHasEnded = false; player.ads.snapshot = null; player.ads.adType = null; player.ads._hasThereBeenALoadedData = false; player.ads._hasThereBeenALoadedMetaData = false; player.ads._cancelledPlay = false; player.ads._shouldBlockPlay = false; player.ads._playBlocked = false; player.ads.nopreroll_ = false; player.ads.nopostroll_ = false; player.ads._playRequested = false; }, // Call this when an ad response has been received and there are // linear ads ready to be played. startLinearAdMode: function startLinearAdMode() { player.ads._state.startLinearAdMode(); }, // Call this when a linear ad pod has finished playing. endLinearAdMode: function endLinearAdMode() { player.ads._state.endLinearAdMode(); }, // Call this when an ad response has been received but there are no // linear ads to be played (i.e. no ads available, or overlays). // This has no effect if we are already in an ad break. Always // use endLinearAdMode() to exit from linear ad-playback state. skipLinearAdMode: function skipLinearAdMode() { player.ads._state.skipLinearAdMode(); }, // With no arguments, returns a boolean value indicating whether or not // contrib-ads is set to treat ads as stitched with content in a single // stream. With arguments, treated as a setter, but this behavior is // deprecated. stitchedAds: function stitchedAds(arg) { if (arg !== undefined) { videojs.log.warn('Using player.ads.stitchedAds() as a setter is deprecated, ' + 'it should be set as an option upon initialization of contrib-ads.'); // Keep the private property and the settings in sync. When this // setter is removed, we can probably stop using the private property. this.settings.stitchedAds = !!arg; } return this.settings.stitchedAds; }, // Returns whether the video element has been modified since the // snapshot was taken. // We test both src and currentSrc because changing the src attribute to a URL that // AdBlocker is intercepting doesn't update currentSrc. videoElementRecycled: function videoElementRecycled() { if (player.ads.shouldPlayContentBehindAd(player)) { return false; } if (!this.snapshot) { throw new Error('You cannot use videoElementRecycled while there is no snapshot.'); } var srcChanged = player.tech_.src() !== this.snapshot.src; var currentSrcChanged = player.currentSrc() !== this.snapshot.currentSrc; return srcChanged || currentSrcChanged; }, // Returns a boolean indicating if given player is in live mode. // One reason for this: https://github.com/videojs/video.js/issues/3262 // Also, some live content can have a duration. isLive: function isLive(somePlayer) { if (somePlayer === void 0) { somePlayer = player; } if (typeof somePlayer.ads.settings.contentIsLive === 'boolean') { return somePlayer.ads.settings.contentIsLive; } else if (somePlayer.duration() === Infinity) { return true; } else if (videojs.browser.IOS_VERSION === '8' && somePlayer.duration() === 0) { return true; } return false; }, // Return true if content playback should mute and continue during ad breaks. // This is only done during live streams on platforms where it's supported. // This improves speed and accuracy when returning from an ad break. shouldPlayContentBehindAd: function shouldPlayContentBehindAd(somePlayer) { if (somePlayer === void 0) { somePlayer = player; } if (!somePlayer) { throw new Error('shouldPlayContentBehindAd requires a player as a param'); } else if (!somePlayer.ads.settings.liveCuePoints) { return false; } else { return !videojs.browser.IS_IOS && !videojs.browser.IS_ANDROID && somePlayer.duration() === Infinity; } }, // Return true if the ads plugin should save and restore snapshots of the // player state when moving into and out of ad mode. shouldTakeSnapshots: function shouldTakeSnapshots(somePlayer) { if (somePlayer === void 0) { somePlayer = player; } return !this.shouldPlayContentBehindAd(somePlayer) && !this.stitchedAds(); }, // Returns true if player is in ad mode. // // Ad mode definition: // If content playback is blocked by the ad plugin. // // Examples of ad mode: // // * Waiting to find out if an ad is going to play while content would normally be // playing. // * Waiting for an ad to start playing while content would normally be playing. // * An ad is playing (even if content is also playing) // * An ad has completed and content is about to resume, but content has not resumed // yet. // // Examples of not ad mode: // // * Content playback has not been requested // * Content playback is paused // * An asynchronous ad request is ongoing while content is playing // * A non-linear ad is active isInAdMode: function isInAdMode() { return this._state.isAdState(); }, // Returns true if in ad mode but an ad break hasn't started yet. isWaitingForAdBreak: function isWaitingForAdBreak() { return this._state.isWaitingForAdBreak(); }, // Returns true if content is resuming after an ad. This is part of ad mode. isContentResuming: function isContentResuming() { return this._state.isContentResuming(); }, // Deprecated because the name was misleading. Use inAdBreak instead. isAdPlaying: function isAdPlaying() { return this._state.inAdBreak(); }, // Returns true if an ad break is ongoing. This is part of ad mode. // An ad break is the time between startLinearAdMode and endLinearAdMode. inAdBreak: function inAdBreak() { return this._state.inAdBreak(); }, /* * Remove the poster attribute from the video element tech, if present. When * reusing a video element for multiple videos, the poster image will briefly * reappear while the new source loads. Removing the attribute ahead of time * prevents the poster from showing up between videos. * * @param {Object} player The videojs player object */ removeNativePoster: function removeNativePoster() { var tech = player.$('.vjs-tech'); if (tech) { tech.removeAttribute('poster'); } }, debug: function debug() { if (this.settings.debug) { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 1 && typeof args[0] === 'string') { videojs.log('ADS: ' + args[0]); } else { videojs.log.apply(videojs, ['ADS:'].concat(args)); } } } }; } /* The goal of this feature is to make player events work as an integrator would expect despite the presense of ads. For example, an integrator would expect an `ended` event to happen once the content is ended. If an `ended` event is sent as a result of a preroll ending, that is a bug. The `redispatch` method should recognize such `ended` events and prefix them so they are sent as `adended`, and so on with all other player events. */ // Cancel an event. // Video.js wraps native events. This technique stops propagation for the Video.js event // (AKA player event or wrapper event) while native events continue propagating. var cancelEvent = function cancelEvent(player, event) { event.isImmediatePropagationStopped = function () { return true; }; event.cancelBubble = true; event.isPropagationStopped = function () { return true; }; }; // Redispatch an event with a prefix. // Cancels the event, then sends a new event with the type of the original // event with the given prefix added. // The inclusion of the "state" property should be removed in a future // major version update with instructions to migrate any code that relies on it. // It is an implementation detail and relying on it creates fragility. var prefixEvent = function prefixEvent(player, prefix, event) { cancelEvent(player, event); player.trigger({ type: prefix + event.type, originalEvent: event }); }; // Playing event // Requirements: // * Normal playing event when there is no preroll // * No playing event before preroll // * At least one playing event after preroll var handlePlaying = function handlePlaying(player, event) { if (player.ads.isInAdMode()) { if (player.ads.isContentResuming()) { // Prefix playing event when switching back to content after postroll. if (player.ads._contentEnding) { prefixEvent(player, 'content', event); } // Prefix all other playing events during ads. } else { prefixEvent(player, 'ad', event); } } }; // Ended event // Requirements: // * A single ended event when there is no postroll // * No ended event before postroll // * A single ended event after postroll var handleEnded = function handleEnded(player, event) { if (player.ads.isInAdMode()) { // Cancel ended events during content resuming. Normally we would // prefix them, but `contentended` has a special meaning. In the // future we'd like to rename the existing `contentended` to // `readyforpostroll`, then we could remove the special `resumeended` // and do a conventional content prefix here. if (player.ads.isContentResuming()) { cancelEvent(player, event); // Important: do not use this event outside of videojs-contrib-ads. // It will be removed and your code will break. // Ideally this would simply be `contentended`, but until // `contentended` no longer has a special meaning it cannot be // changed. player.trigger('resumeended'); // Ad prefix in ad mode } else { prefixEvent(player, 'ad', event); } // Prefix ended due to content ending before postroll check } else if (!player.ads._contentHasEnded && !player.ads.stitchedAds()) { // This will change to cancelEvent after the contentended deprecation // period (contrib-ads 7) prefixEvent(player, 'content', event); // Content ended for the first time, time to check for postrolls player.trigger('readyforpostroll'); } }; // handleLoadEvent is used for loadstart, loadeddata, and loadedmetadata // Requirements: // * Initial event is not prefixed // * Event due to ad loading is prefixed // * Event due to content source change is not prefixed // * Event due to content resuming is prefixed var handleLoadEvent = function handleLoadEvent(player, event) { // Initial event if (event.type === 'loadstart' && !player.ads._hasThereBeenALoadStartDuringPlayerLife || event.type === 'loadeddata' && !player.ads._hasThereBeenALoadedData || event.type === 'loadedmetadata' && !player.ads._hasThereBeenALoadedMetaData) { return; // Ad playing } else if (player.ads.inAdBreak()) { prefixEvent(player, 'ad', event); // Source change } else if (player.currentSrc() !== player.ads.contentSrc) { return; // Content resuming } else { prefixEvent(player, 'content', event); } }; // Play event // Requirements: // * Play events have the "ad" prefix when an ad is playing // * Play events have the "content" prefix when content is resuming // Play requests are unique because they represent user intention to play. They happen // because the user clicked play, or someone called player.play(), etc. It could happen // multiple times during ad loading, regardless of where we are in the process. With our // current architecture, this could cause the content to start playing. // Therefore, contrib-ads must always either: // - cancelContentPlay if there is any possible chance the play caused the // content to start playing, even if we are technically in ad mode. In order for // that to happen, play events need to be unprefixed until the last possible moment. // - use playMiddleware to stop the play from reaching the Tech so there is no risk // of the content starting to play. // Currently, playMiddleware is only supported on desktop browsers with // video.js after version 6.7.1. var handlePlay = function handlePlay(player, event) { if (player.ads.inAdBreak()) { prefixEvent(player, 'ad', event); // Content resuming } else if (player.ads.isContentResuming()) { prefixEvent(player, 'content', event); } }; // Handle a player event, either by redispatching it with a prefix, or by // letting it go on its way without any meddling. function redispatch(event) { // Events with special treatment if (event.type === 'playing') { handlePlaying(this, event); } else if (event.type === 'ended') { handleEnded(this, event); } else if (event.type === 'loadstart' || event.type === 'loadeddata' || event.type === 'loadedmetadata') { handleLoadEvent(this, event); } else if (event.type === 'play') { handlePlay(this, event); // Standard handling for all other events } else if (this.ads.isInAdMode()) { if (this.ads.isContentResuming()) { // Event came from snapshot restore after an ad, use "content" prefix prefixEvent(this, 'content', event); } else { // Event came from ad playback, use "ad" prefix prefixEvent(this, 'ad', event); } } } /* This feature sends a `contentupdate` event when the player source changes. */ // Start sending contentupdate events function initializeContentupdate(player) { // Keep track of the current content source // If you want to change the src of the video without triggering // the ad workflow to restart, you can update this variable before // modifying the player's source player.ads.contentSrc = player.currentSrc(); player.ads._seenInitialLoadstart = false; // Check if a new src has been set, if so, trigger contentupdate var checkSrc = function checkSrc() { if (!player.ads.inAdBreak()) { var src = player.currentSrc(); if (src !== player.ads.contentSrc) { if (player.ads._seenInitialLoadstart) { player.trigger({ type: 'contentchanged' }); } player.trigger({ type: 'contentupdate', oldValue: player.ads.contentSrc, newValue: src }); player.ads.contentSrc = src; } player.ads._seenInitialLoadstart = true; } }; // loadstart reliably indicates a new src has been set player.on('loadstart', checkSrc); } /* This feature provides an optional method for ad plugins to insert run-time values into an ad server URL or configuration. */ var uriEncodeIfNeeded = function uriEncodeIfNeeded(value, uriEncode) { if (uriEncode) { return encodeURIComponent(value); } return value; }; // Add custom field macros to macros object // based on given name for custom fields property of mediainfo object. var customFields = function customFields(mediainfo, macros, customFieldsName) { if (mediainfo && mediainfo[customFieldsName]) { var fields = mediainfo[customFieldsName]; var fieldNames = Object.keys(fields); for (var i = 0; i < fieldNames.length; i++) { var tag = '{mediainfo.' + customFieldsName + '.' + fieldNames[i] + '}'; macros[tag] = fields[fieldNames[i]]; } } }; // Public method that ad plugins use for ad macros. // "string" is any string with macros to be replaced // "uriEncode" if true will uri encode macro values when replaced // "customMacros" is a object with custom macros and values to map them to // - For example: {'{five}': 5} // Return value is is "string" with macros replaced // - For example: adMacroReplacement('{player.id}') returns a string of the player id function adMacroReplacement(string, uriEncode, customMacros) { var _this = this; var defaults = {}; // Get macros with defaults e.g. {x=y}, store values and replace with standard macros string = string.replace(/{([^}=]+)=([^}]+)}/g, function (match, name, defaultVal) { defaults["{" + name + "}"] = defaultVal; return "{" + name + "}"; }); if (uriEncode === undefined) { uriEncode = false; } var macros = {}; if (customMacros !== undefined) { macros = customMacros; } // Static macros macros['{player.id}'] = this.options_['data-player']; macros['{player.height}'] = this.currentHeight(); macros['{player.width}'] = this.currentWidth(); macros['{mediainfo.id}'] = this.mediainfo ? this.mediainfo.id : ''; macros['{mediainfo.name}'] = this.mediainfo ? this.mediainfo.name : ''; macros['{mediainfo.duration}'] = this.mediainfo ? this.mediainfo.duration : ''; macros['{player.duration}'] = this.duration(); macros['{player.pageUrl}'] = videojs.dom.isInFrame() ? document.referrer : window.location.href; macros['{playlistinfo.id}'] = this.playlistinfo ? this.playlistinfo.id : ''; macros['{playlistinfo.name}'] = this.playlistinfo ? this.playlistinfo.name : ''; macros['{timestamp}'] = new Date().getTime(); macros['{document.referrer}'] = document.referrer; macros['{window.location.href}'] = window.location.href; macros['{random}'] = Math.floor(Math.random() * 1000000000000); ['description', 'tags', 'reference_id', 'ad_keys'].forEach(function (prop) { if (_this.mediainfo && _this.mediainfo[prop]) { macros["{mediainfo." + prop + "}"] = _this.mediainfo[prop]; } else if (defaults["{mediainfo." + prop + "}"]) { macros["{mediainfo." + prop + "}"] = defaults["{mediainfo." + prop + "}"]; } else { macros["{mediainfo." + prop + "}"] = ''; } }); // Custom fields in mediainfo customFields(this.mediainfo, macros, 'custom_fields'); customFields(this.mediainfo, macros, 'customFields'); // Go through all the replacement macros and apply them to the string. // This will replace all occurrences of the replacement macros. for (var i in macros) { string = string.split(i).join(uriEncodeIfNeeded(macros[i], uriEncode)); } // Page variables string = string.replace(/{pageVariable\.([^}]+)}/g, function (match, name) { var value; var context = window; var names = name.split('.'); // Iterate down multiple levels of selector without using eval // This makes things like pageVariable.foo.bar work for (var _i = 0; _i < names.length; _i++) { if (_i === names.length - 1) { value = context[names[_i]]; } else { context = context[names[_i]]; } } var type = typeof value; // Only allow certain types of values. Anything else is probably a mistake. if (value === null) { return 'null'; } else if (value === undefined) { if (defaults["{pageVariable." + name + "}"]) { return defaults["{pageVariable." + name + "}"]; } videojs.log.warn("Page variable \"" + name + "\" not found"); return ''; } else if (type !== 'string' && type !== 'number' && type !== 'boolean') { videojs.log.warn("Page variable \"" + name + "\" is not a supported type"); return ''; } return uriEncodeIfNeeded(String(value), uriEncode); }); // Replace defaults for (var defaultVal in defaults) { string = string.replace(defaultVal, defaults[defaultVal]); } return string; } /* * This feature allows metadata text tracks to be manipulated once available * @see processMetadataTracks. * It also allows ad implementations to leverage ad cues coming through * text tracks, @see processAdTrack **/ var cueTextTracks = {}; /* * This feature allows metadata text tracks to be manipulated once they are available, * usually after the 'loadstart' event is observed on the player * @param player A reference to a player * @param processMetadataTrack A callback that performs some operations on a * metadata text track **/ cueTextTracks.processMetadataTracks = function (player, processMetadataTrack) { var tracks = player.textTracks(); var setModeAndProcess = function setModeAndProcess(track) { if (track.kind === 'metadata') { player.ads.cueTextTracks.setMetadataTrackMode(track); processMetadataTrack(player, track); } }; // Text tracks are available for (var i = 0; i < tracks.length; i++) { setModeAndProcess(tracks[i]); } // Wait until text tracks are added tracks.addEventListener('addtrack', function (event) { setModeAndProcess(event.track); }); }; /* * Sets the track mode to one of 'disabled', 'hidden' or 'showing' * @see https://github.com/videojs/video.js/blob/master/docs/guides/text-tracks.md * Default behavior is to do nothing, @override if this is not desired * @param track The text track to set the mode on */ cueTextTracks.setMetadataTrackMode = function (track) { return; }; /* * Determines whether cue is an ad cue and returns the cue data. * @param player A reference to the player * @param cue The full cue object * Returns the given cue by default @override if futher processing is required * @return {Object} a useable ad cue or null if not supported **/ cueTextTracks.getSupportedAdCue = function (player, cue) { return cue; }; /* * Defines whether a cue is supported or not, potentially * based on the player settings * @param player A reference to the player * @param cue The cue to be checked * Default behavior is to return true, @override if this is not desired * @return {Boolean} */ cueTextTracks.isSupportedAdCue = function (player, cue) { return true; }; /* * Gets the id associated with a cue. * @param cue The cue to extract an ID from * @returns The first occurance of 'id' in the object, * @override if this is not the desired cue id **/ cueTextTracks.getCueId = function (player, cue) { return cue.id; }; /* * Checks whether a cue has already been used * @param cueId The Id associated with a cue **/ var cueAlreadySeen = function cueAlreadySeen(player, cueId) { return cueId !== undefined && player.ads.includedCues[cueId]; }; /* * Indicates that a cue has been used * @param cueId The Id associated with a cue **/ var setCueAlreadySeen = function setCueAlreadySeen(player, cueId) { if (cueId !== undefined && cueId !== '') { player.ads.includedCues[cueId] = true; } }; /* * This feature allows ad metadata tracks to be manipulated in ad implementations * @param player A reference to the player * @param cues The set of cues to work with * @param processCue A method that uses a cue to make some * ad request in the ad implementation * @param [cancelAdsHandler] A method that dynamically cancels ads in the ad implementation **/ cueTextTracks.processAdTrack = function (player, cues, processCue, cancelAdsHandler) { player.ads.includedCues = {}; // loop over set of cues for (var i = 0; i < cues.length; i++) { var cue = cues[i]; var cueData = this.getSupportedAdCue(player, cue); // Exit if this is not a supported cue if (!this.isSupportedAdCue(player, cue)) { videojs.log.warn('Skipping as this is not a supported ad cue.', cue); return; } // Continue processing supported cue var cueId = this.getCueId(player, cue); var startTime = cue.startTime; // Skip ad if cue was already used if (cueAlreadySeen(player, cueId)) { videojs.log('Skipping ad already seen with ID ' + cueId); return; } // Optional dynamic ad cancellation if (cancelAdsHandler) { cancelAdsHandler(player, cueData, cueId, startTime); } // Process cue as an ad cue processCue(player, cueData, cueId, startTime); // Indicate that this cue has been used setCueAlreadySeen(player, cueId); } }; function initCancelContentPlay(player, debug) { if (debug) { videojs.log('Using cancelContentPlay to block content playback'); } // Listen to play events to "cancel" them afterward player.on('play', cancelContentPlay); } /* This feature makes sure the player is paused during ad loading. It does this by pausing the player immediately after a "play" where ads will be requested, then signalling that we should play after the ad is done. */ function cancelContentPlay() { // this function is in the player's context if (this.ads._shouldBlockPlay === false) { // Only block play if the ad plugin is in a state when content // playback should be blocked. This currently means during // BeforePrerollState and PrerollState. return; } // pause playback so ads can be handled. if (!this.paused()) { this.ads.debug('Playback was canceled by cancelContentPlay'); this.pause(); } // When the 'content-playback' state is entered, this will let us know to play. // This is needed if there is no preroll or if it errors, times out, etc. this.ads._cancelledPlay = true; } var obj = {}; // This reference allows videojs to be mocked in unit tests // while still using the available videojs import in the source code // @see obj.testHook var videojsReference = videojs; /** * Checks if middleware mediators are available and * can be used on this platform. * Currently we can only use mediators on desktop platforms. */ obj.isMiddlewareMediatorSupported = function () { if (videojsReference.browser.IS_IOS || videojsReference.browser.IS_ANDROID) { return false; } else if ( // added when middleware was introduced in video.js videojsReference.use && // added when mediators were introduced in video.js videojsReference.middleware && videojsReference.middleware.TERMINATOR) { return true; } return false; }; obj.playMiddleware = function (player) { return { setSource: function setSource(srcObj, next) { next(null, srcObj); }, callPlay: function callPlay() { // Block play calls while waiting for an ad, only if this is an // ad supported player if (player.ads && player.ads._shouldBlockPlay === true) { player.ads.debug('Using playMiddleware to block content playback'); player.ads._playBlocked = true; return videojsReference.middleware.TERMINATOR; } }, play: function play(terminated, playPromise) { if (player.ads && player.ads._playBlocked && terminated) { player.ads.debug('Play call to Tech was terminated.'); // Trigger play event to match the user's intent to play. // The call to play on the Tech has been blocked, so triggering // the event on the Player will not affect the Tech's playback state. player.trigger('play'); // At this point the player has technically started player.addClass('vjs-has-started'); // Reset playBlocked player.ads._playBlocked = false; // Safari issues a pause event when autoplay is blocked but other browsers // do not, so we send a pause for consistency in those cases. This keeps the // play button in the correct state if play is rejected. } else if (playPromise && playPromise.catch) { playPromise.catch(function (e) { if (e.name === 'NotAllowedError' && !videojs.browser.IS_SAFARI) { player.trigger('pause'); } }); } } }; }; obj.testHook = function (testVjs) { videojsReference = testVjs; }; var playMiddleware = obj.playMiddleware, isMiddlewareMediatorSupported = obj.isMiddlewareMediatorSupported; /** * Whether or not this copy of Video.js has the ads plugin. * * @return {boolean} * If `true`, has the plugin. `false` otherwise. */ var hasAdsPlugin = function hasAdsPlugin() { // Video.js 6 and 7 have a getPlugin method. if (videojs.getPlugin) { return Boolean(videojs.getPlugin('ads')); } // Video.js 5 does not have a getPlugin method, so check the player prototype. var Player = videojs.getComponent('Player'); return Boolean(Player && Player.prototype.ads); }; /** * Register contrib-ads with Video.js, but provide protection for duplicate * copies of the plugin. This could happen if, for example, a stitched ads * plugin and a client-side ads plugin are included simultaneously with their * own copies of contrib-ads. * * If contrib-ads detects a pre-existing duplicate, it will not register * itself. * * Ad plugins using contrib-ads and anticipating that this could come into * effect should verify that the contrib-ads they are using is of a compatible * version. * * @param {Function} contribAdsPlugin * The plugin function. * * @return {boolean} * When `true`, the plugin was registered. When `false`, the plugin * was not registered. */ function register(contribAdsPlugin) { // If the ads plugin already exists, do not overwrite it. if (hasAdsPlugin(videojs)) { return false; } // Cross-compatibility with Video.js 6/7 and 5. var registerPlugin = videojs.registerPlugin || videojs.plugin; // Register this plugin with Video.js. registerPlugin('ads', contribAdsPlugin); // Register the play middleware with Video.js on script execution, // to avoid a new playMiddleware factory being added for each player. // The `usingContribAdsMiddleware_` flag is used to ensure that we only ever // register the middleware once - despite the ability to de-register and // re-register the plugin itself. if (isMiddlewareMediatorSupported() && !videojs.usingContribAdsMiddleware_) { // Register the play middleware videojs.use('*', playMiddleware); videojs.usingContribAdsMiddleware_ = true; videojs.log.debug('Play middleware has been registered with videojs'); } return true; } var States = /*#__PURE__*/ function () { function States() {} States.getState = function getState(name) { if (!name) { return; } if (States.states_ && States.states_[name]) { return States.states_[name]; } }; States.registerState = function registerState(name, StateToRegister) { if (typeof name !== 'string' || !name) { throw new Error("Illegal state name, \"" + name + "\"; must be a non-empty string."); } if (!States.states_) { States.states_ = {}; } States.states_[name] = StateToRegister; return StateToRegister; }; return States; }(); var State = /*#__PURE__*/ function () { State._getName = function _getName() { return 'Anonymous State'; }; function State(player) { this.player = player; } /* * This is the only allowed way to perform state transitions. State transitions usually * happen in player event handlers. They can also happen recursively in `init`. They * should _not_ happen in `cleanup`. */ var _proto = State.prototype; _proto.transitionTo = function transitionTo(NewState) { var player = this.player; // Since State is an abstract class, this will refer to // the state that is extending this class this.cleanup(player); var newState = new NewState(player); player.ads._state = newState; player.ads.debug(this.constructor._getName() + ' -> ' + newState.constructor._getName()); for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } newState.init.apply(newState, [player].concat(args)); } /* * Implemented by subclasses to provide initialization logic when transitioning * to a new state. */ ; _proto.init = function init() {} /* * Implemented by subclasses to provide cleanup logic when transitioning * to a new state. */ ; _proto.cleanup = function cleanup() {} /* * Default event handlers. Different states can override these to provide behaviors. */ ; _proto.onPlay = function onPlay() {}; _proto.onPlaying = function onPlaying() {}; _proto.onEnded = function onEnded() {}; _proto.onAdEnded = function onAdEnded() {}; _proto.onAdsReady = function onAdsReady() { videojs.log.warn('Unexpected adsready event'); }; _proto.onAdsError = function onAdsError() {}; _proto.onAdsCanceled = function onAdsCanceled() {}; _proto.onAdTimeout = function onAdTimeout() {}; _proto.onAdStarted = function onAdStarted() {}; _proto.onContentChanged = function onContentChanged() {}; _proto.onContentResumed = function onContentResumed() {}; _proto.onReadyForPostroll = function onReadyForPostroll() { videojs.log.warn('Unexpected readyforpostroll event'); }; _proto.onNoPreroll = function onNoPreroll() {}; _proto.onNoPostroll = function onNoPostroll() {} /* * Method handlers. Different states can override these to provide behaviors. */ ; _proto.startLinearAdMode = function startLinearAdMode() { videojs.log.warn('Unexpected startLinearAdMode invocation ' + '(State via ' + this.constructor._getName() + ')'); }; _proto.endLinearAdMode = function endLinearAdMode() { videojs.log.warn('Unexpected endLinearAdMode invocation ' + '(State via ' + this.constructor._getName() + ')'); }; _proto.skipLinearAdMode = function skipLinearAdMode() { videojs.log.warn('Unexpected skipLinearAdMode invocation ' + '(State via ' + this.constructor._getName() + ')'); } /* * Overridden by ContentState and AdState. Should not be overriden elsewhere. */ ; _proto.isAdState = function isAdState() { throw new Error('isAdState unimplemented for ' + this.constructor._getName()); } /* * Overridden by Preroll and Postroll. Midrolls jump right into the ad break * so there is no "waiting" state for them. */ ; _proto.isWaitingForAdBreak = function isWaitingForAdBreak() { return false; } /* * Overridden by Preroll, Midroll, and Postroll. */ ; _proto.isContentResuming = function isContentResuming() { return false; }; _proto.inAdBreak = function inAdBreak() { return false; } /* * Invoke event handler methods when events come in. */ ; _proto.handleEvent = function handleEvent(type) { var player = this.player; if (type === 'play') { this.onPlay(player); } else if (type === 'adsready') { this.onAdsReady(player); } else if (type === 'adserror') { this.onAdsError(player); } else if (type === 'adscanceled') { this.onAdsCanceled(player); } else if (type === 'adtimeout') { this.onAdTimeout(player); } else if (type === 'ads-ad-started') { this.onAdStarted(player); } else if (type === 'contentchanged') { this.onContentChanged(player); } else if (type === 'contentresumed') { this.onContentResumed(player); } else if (type === 'readyforpostroll') { this.onReadyForPostroll(player); } else if (type === 'playing') { this.onPlaying(player); } else if (type === 'ended') { this.onEnded(player); } else if (type === 'nopreroll') { this.onNoPreroll(player); } else if (type === 'nopostroll') { this.onNoPostroll(player); } else if (type === 'adended') { this.onAdEnded(player); } }; return State; }(); States.registerState('State', State); function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /* * This class contains logic for all ads, be they prerolls, midrolls, or postrolls. * Primarily, this involves handling startLinearAdMode and endLinearAdMode. * It also handles content resuming. */ var AdState = /*#__PURE__*/ function (_State) { _inheritsLoose(AdState, _State); function AdState(player) { var _this; _this = _State.call(this, player) || this; _this.contentResuming = false; _this.waitingForAdBreak = false; return _this; } /* * Overrides State.isAdState */ var _proto = AdState.prototype; _proto.isAdState = function isAdState() { return true; } /* * We end the content-resuming process on the playing event because this is the exact * moment that content playback is no longer blocked by ads. */ ; _proto.onPlaying = function onPlaying() { var ContentPlayback = States.getState('ContentPlayback'); if (this.contentResuming) { this.transitionTo(ContentPlayback); } } /* * If the ad plugin does not result in a playing event when resuming content after an * ad, they should instead trigger a contentresumed event to signal that content should * resume. The main use case for this is when ads are stitched into the content video. */ ; _proto.onContentResumed = function onContentResumed() { var ContentPlayback = States.getState('ContentPlayback'); if (this.contentResuming) { this.transitionTo(ContentPlayback); } } /* * Check if we are in an ad state waiting for the ad plugin to start * an ad break. */ ; _proto.isWaitingForAdBreak = function isWaitingForAdBreak() { return this.waitingForAdBreak; } /* * Allows you to check if content is currently resuming after an ad break. */ ; _proto.isContentResuming = function isContentResuming() { return this.contentResuming; } /* * Allows you to check if an ad break is in progress. */ ; _proto.inAdBreak = function inAdBreak() { return this.player.ads._inLinearAdMode === true; }; return AdState; }(State); States.registerState('AdState', AdState); var ContentState = /*#__PURE__*/ function (_State) { _inheritsLoose(ContentState, _State); function ContentState() { return _State.apply(this, arguments) || this; } var _proto = ContentState.prototype; /* * Overrides State.isAdState */ _proto.isAdState = function isAdState() { return false; } /* * Source change sends you back to preroll checks. contentchanged does not * fire during ad breaks, so we don't need to worry about that. */ ; _proto.onContentChanged = function onContentChanged(player) { var BeforePreroll = States.getState('BeforePreroll'); var Preroll = States.getState('Preroll'); player.ads.debug('Received contentchanged event (ContentState)'); if (player.paused()) { this.transitionTo(BeforePreroll); } else { this.transitionTo(Preroll, false); player.pause(); player.ads._pausedOnContentupdate = true; } }; return ContentState; }(State); States.registerState('ContentState', ContentState); var ContentState$1 = States.getState('ContentState'); var AdsDone = /*#__PURE__*/ function (_ContentState) { _inheritsLoose(AdsDone, _ContentState); function AdsDone() { return _ContentState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ AdsDone._getName = function _getName() { return 'AdsDone'; } /* * For state transitions to work correctly, initialization should * happen here, not in a constructor. */ ; var _proto = AdsDone.prototype; _proto.init = function init(player) { // From now on, `ended` events won't be redispatched player.ads._contentHasEnded = true; player.trigger('ended'); } /* * Midrolls do not play after ads are done. */ ; _proto.startLinearAdMode = function startLinearAdMode() { videojs.log.warn('Unexpected startLinearAdMode invocation (AdsDone)'); }; return AdsDone; }(ContentState$1); States.registerState('AdsDone', AdsDone); /* The snapshot feature is responsible for saving the player state before an ad, then restoring the player state after an ad. */ var tryToResumeTimeout_; /* * Returns an object that captures the portions of player state relevant to * video playback. The result of this function can be passed to * restorePlayerSnapshot with a player to return the player to the state it * was in when this function was invoked. * @param {Object} player The videojs player object */ function getPlayerSnapshot(player) { var currentTime; if (videojs.browser.IS_IOS && player.ads.isLive(player)) { // Record how far behind live we are if (player.seekable().length > 0) { currentTime = player.currentTime() - player.seekable().end(0); } else { currentTime = player.currentTime(); } } else { currentTime = player.currentTime(); } var tech = player.$('.vjs-tech'); var tracks = player.textTracks ? player.textTracks() : []; var suppressedTracks = []; var snapshotObject = { ended: player.ended(), currentSrc: player.currentSrc(), sources: player.currentSources(), src: player.tech_.src(), currentTime: currentTime, type: player.currentType() }; if (tech) { snapshotObject.style = tech.getAttribute('style'); } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; suppressedTracks.push({ track: track, mode: track.mode }); track.mode = 'disabled'; } snapshotObject.suppressedTracks = suppressedTracks; return snapshotObject; } /* * Attempts to modify the specified player so that its state is equivalent to * the state of the snapshot. * @param {Object} player - the videojs player object * @param {Object} snapshotObject - the player state to apply */ function restorePlayerSnapshot(player, callback) { var snapshotObject = player.ads.snapshot; if (callback === undefined) { callback = function callback() {}; } if (player.ads.disableNextSnapshotRestore === true) { player.ads.disableNextSnapshotRestore = false; delete player.ads.snapshot; callback(); return; } // The playback tech var tech = player.$('.vjs-tech'); // the number of[ remaining attempts to restore the snapshot var attempts = 20; var suppressedTracks = snapshotObject.suppressedTracks; var trackSnapshot; var restoreTracks = function restoreTracks() { for (var i = 0; i < suppressedTracks.length; i++) { trackSnapshot = suppressedTracks[i]; trackSnapshot.track.mode = trackSnapshot.mode; } }; // Finish restoring the playback state. // This only happens if the content video element was reused for ad playback. var resume = function resume() { var currentTime; // Live video on iOS has special logic to try to seek to the right place after // an ad. if (videojs.browser.IS_IOS && player.ads.isLive(player)) { if (snapshotObject.currentTime < 0) { // Playback was behind real time, so seek backwards to match if (player.seekable().length > 0) { currentTime = player.seekable().end(0) + snapshotObject.currentTime; } else { currentTime = player.currentTime(); } player.currentTime(currentTime); } // iOS live play after restore if player was paused (would not be paused if // ad played muted behind ad) if (player.paused()) { var playPromise = player.play(); if (playPromise && playPromise.catch) { playPromise.catch(function (error) { videojs.log.warn('Play promise rejected in IOS snapshot resume', error); }); } } // Restore the video position after an ad. // We check snapshotObject.ended because the content starts at the beginning again // after being restored. } else if (snapshotObject.ended) { // For postrolls, seek to the player's current duration. // It could be different from the snapshot's currentTime due to // inaccuracy in HLS. player.currentTime(player.duration()); } else { // Prerolls and midrolls, just seek to the player time before the ad. player.currentTime(snapshotObject.currentTime); var _playPromise = player.play(); if (_playPromise && _playPromise.catch) { _playPromise.catch(function (error) { videojs.log.warn('Play promise rejected in snapshot resume', error); }); } } // if we added autoplay to force content loading on iOS, remove it now // that it has served its purpose if (player.ads.shouldRemoveAutoplay_) { player.autoplay(false); player.ads.shouldRemoveAutoplay_ = false; } }; // Determine if the video element has loaded enough of the snapshot source // to be ready to apply the rest of the state. // This only happens if the content video element was reused for ad playback. var tryToResume = function tryToResume() { // tryToResume can either have been called through the `contentcanplay` // event or fired through setTimeout. // When tryToResume is called, we should make sure to clear out the other // way it could've been called by removing the listener and clearing out // the timeout. player.off('contentcanplay', tryToResume); if (tryToResumeTimeout_) { player.clearTimeout(tryToResumeTimeout_); } // Tech may have changed depending on the differences in sources of the // original video and that of the ad tech = player.el().querySelector('.vjs-tech'); if (tech.readyState > 1) { // some browsers and media aren't "seekable". // readyState greater than 1 allows for seeking without exceptions return resume(); } if (tech.seekable === undefined) { // if the tech doesn't expose the seekable time ranges, try to // resume playback immediately return resume(); } if (tech.seekable.length > 0) { // if some period of the video is seekable, resume playback return resume(); } // delay a bit and then check again unless we're out of attempts if (attempts--) { player.setTimeout(tryToResume, 50); } else { try { resume(); } catch (e) { videojs.log.warn('Failed to resume the content after an advertisement', e); } } }; if ('style' in snapshotObject) { // overwrite all css style properties to restore state precisely tech.setAttribute('style', snapshotObject.style || ''); } // Determine whether the player needs to be restored to its state // before ad playback began. With a custom ad display or burned-in // ads, the content player state hasn't been modified and so no // restoration is required if (player.ads.videoElementRecycled()) { // Snapshot restore is done, so now we're really finished. player.one('resumeended', function () { delete player.ads.snapshot; callback(); }); // on ios7, fiddling with textTracks too early will cause safari to crash player.one('contentloadedmetadata', restoreTracks); // adding autoplay guarantees that Safari will load the content so we can // seek back to the correct time after ads if (videojs.browser.IS_IOS && !player.autoplay()) { player.autoplay(true); // if we get here, the player was not originally configured to autoplay, // so we should remove it after it has served its purpose player.ads.shouldRemoveAutoplay_ = true; } // if the src changed for ad playback, reset it player.src(snapshotObject.sources); // and then resume from the snapshots time once the original src has loaded // in some browsers (firefox) `canplay` may not fire correctly. // Reace the `canplay` event with a timeout. player.one('contentcanplay', tryToResume); tryToResumeTimeout_ = player.setTimeout(tryToResume, 2000); } else { // if we didn't change the src, just restore the tracks restoreTracks(); // we don't need to check snapshotObject.ended here because the content video // element wasn't recycled if (!player.ended()) { // the src didn't change and this wasn't a postroll // just resume playback at the current time. var playPromise = player.play(); if (playPromise && playPromise.catch) { playPromise.catch(function (error) { videojs.log.warn('Play promise rejected in snapshot restore', error); }); } } // snapshot restore is complete delete player.ads.snapshot; callback(); } } /* * Encapsulates logic for starting and ending ad breaks. An ad break * is the time between startLinearAdMode and endLinearAdMode. The ad * plugin may play 0 or more ads during this time. */ function start(player) { player.ads.debug('Starting ad break'); player.ads._inLinearAdMode = true; // No longer does anything, used to move us to ad-playback player.trigger('adstart'); // Capture current player state snapshot if (player.ads.shouldTakeSnapshots()) { player.ads.snapshot = getPlayerSnapshot(player); } // Mute the player behind the ad if (player.ads.shouldPlayContentBehindAd(player)) { player.ads.preAdVolume_ = player.volume(); player.volume(0); } // Add css to the element to indicate and ad is playing. player.addClass('vjs-ad-playing'); // We should remove the vjs-live class if it has been added in order to // show the adprogress control bar on Android devices for falsely // determined LIVE videos due to the duration incorrectly reported as Infinity if (player.hasClass('vjs-live')) { player.removeClass('vjs-live'); } // This removes the native poster so the ads don't show the content // poster if content element is reused for ad playback. player.ads.removeNativePoster(); } function end(player, callback) { player.ads.debug('Ending ad break'); if (callback === undefined) { callback = function callback() {}; } player.ads.adType = null; player.ads._inLinearAdMode = false; // Signals the end of the ad break to anyone listening. player.trigger('adend'); player.removeClass('vjs-ad-playing'); // We should add the vjs-live class back if the video is a LIVE video // If we dont do this, then for a LIVE Video, we will get an incorrect // styled control, which displays the time for the video if (player.ads.isLive(player)) { player.addClass('vjs-live'); } // Restore snapshot if (player.ads.shouldTakeSnapshots()) { restorePlayerSnapshot(player, callback); // Reset the volume to pre-ad levels } else { player.volume(player.ads.preAdVolume_); callback(); } } var obj$1 = { start: start, end: end }; var AdState$1 = States.getState('AdState'); /* * This state encapsulates waiting for prerolls, preroll playback, and * content restoration after a preroll. */ var Preroll = /*#__PURE__*/ function (_AdState) { _inheritsLoose(Preroll, _AdState); function Preroll() { return _AdState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ Preroll._getName = function _getName() { return 'Preroll'; } /* * For state transitions to work correctly, initialization should * happen here, not in a constructor. */ ; var _proto = Preroll.prototype; _proto.init = function init(player, adsReady, shouldResumeToContent) { this.waitingForAdBreak = true; // Loading spinner from now until ad start or end of ad break. player.addClass('vjs-ad-loading'); // If adserror, adscanceled, nopreroll or skipLinearAdMode already // ocurred, resume to content immediately if (shouldResumeToContent || player.ads.nopreroll_) { return this.resumeAfterNoPreroll(player); } // Determine preroll timeout based on plugin settings var timeout = player.ads.settings.timeout; if (typeof player.ads.settings.prerollTimeout === 'number') { timeout = player.ads.settings.prerollTimeout; } // Start the clock ticking for ad timeout this._timeout = player.setTimeout(function () { player.trigger('adtimeout'); }, timeout); // If adsready already happened, lets get started. Otherwise, // wait until onAdsReady. if (adsReady) { this.handleAdsReady(); } else { this.adsReady = false; } } /* * Adsready event after play event. */ ; _proto.onAdsReady = function onAdsReady(player) { if (!player.ads.inAdBreak()) { player.ads.debug('Received adsready event (Preroll)'); this.handleAdsReady(); } else { videojs.log.warn('Unexpected adsready event (Preroll)'); } } /* * Ad plugin is ready. Let's get started on this preroll. */ ; _proto.handleAdsReady = function handleAdsReady() { this.adsReady = true; this.readyForPreroll(); } /* * Helper to call a callback only after a loadstart event. * If we start content or ads before loadstart, loadstart * will not be prefixed correctly. */ ; _proto.afterLoadStart = function afterLoadStart(callback) { var player = this.player; if (player.ads._hasThereBeenALoadStartDuringPlayerLife) { callback(); } else { player.ads.debug('Waiting for loadstart...'); player.one('loadstart', function () { player.ads.debug('Received loadstart event'); callback(); }); } } /* * If there is no preroll, play content instead. */ ; _proto.noPreroll = function noPreroll() { var _this = this; this.afterLoadStart(function () { _this.player.ads.debug('Skipping prerolls due to nopreroll event (Preroll)'); _this.resumeAfterNoPreroll(_this.player); }); } /* * Fire the readyforpreroll event. If loadstart hasn't happened yet, * wait until loadstart first. */ ; _proto.readyForPreroll = function readyForPreroll() { var player = this.player; this.afterLoadStart(function () { player.ads.debug('Triggered readyforpreroll event (Preroll)'); player.trigger('readyforpreroll'); }); } /* * adscanceled cancels all ads for the source. Play content now. */ ; _proto.onAdsCanceled = function onAdsCanceled(player) { var _this2 = this; player.ads.debug('adscanceled (Preroll)'); this.afterLoadStart(function () { _this2.resumeAfterNoPreroll(player); }); } /* * An ad error occured. Play content instead. */ ; _proto.onAdsError = function onAdsError(player) { var _this3 = this; videojs.log('adserror (Preroll)'); // In the future, we may not want to do this automatically. // Ad plugins should be able to choose to continue the ad break // if there was an error. if (this.inAdBreak()) { player.ads.endLinearAdMode(); } else { this.afterLoadStart(function () { _this3.resumeAfterNoPreroll(player); }); } } /* * Ad plugin invoked startLinearAdMode, the ad break starts now. */ ; _proto.startLinearAdMode = function startLinearAdMode() { var player = this.player; if (this.adsReady && !player.ads.inAdBreak() && !this.isContentResuming()) { this.clearTimeout(player); player.ads.adType = 'preroll'; this.waitingForAdBreak = false; obj$1.start(player); // We don't need to block play calls anymore player.ads._shouldBlockPlay = false; } else { videojs.log.warn('Unexpected startLinearAdMode invocation (Preroll)'); } } /* * An ad has actually started playing. * Remove the loading spinner. */ ; _proto.onAdStarted = function onAdStarted(player) { player.removeClass('vjs-ad-loading'); } /* * Ad plugin invoked endLinearAdMode, the ad break ends now. */ ; _proto.endLinearAdMode = function endLinearAdMode() { var player = this.player; if (this.inAdBreak()) { player.removeClass('vjs-ad-loading'); player.addClass('vjs-ad-content-resuming'); this.contentResuming = true; obj$1.end(player); } } /* * Ad skipped by ad plugin. Play content instead. */ ; _proto.skipLinearAdMode = function skipLinearAdMode() { var _this4 = this; var player = this.player; if (player.ads.inAdBreak() || this.isContentResuming()) { videojs.log.warn('Unexpected skipLinearAdMode invocation'); } else { this.afterLoadStart(function () { player.trigger('adskip'); player.ads.debug('skipLinearAdMode (Preroll)'); _this4.resumeAfterNoPreroll(player); }); } } /* * Prerolls took too long! Play content instead. */ ; _proto.onAdTimeout = function onAdTimeout(player) { var _this5 = this; this.afterLoadStart(function () { player.ads.debug('adtimeout (Preroll)'); _this5.resumeAfterNoPreroll(player); }); } /* * Check if nopreroll event was too late before handling it. */ ; _proto.onNoPreroll = function onNoPreroll(player) { if (player.ads.inAdBreak() || this.isContentResuming()) { videojs.log.warn('Unexpected nopreroll event (Preroll)'); } else { this.noPreroll(); } }; _proto.resumeAfterNoPreroll = function resumeAfterNoPreroll(player) { // Resume to content and unblock play as there is no preroll ad this.contentResuming = true; player.ads._shouldBlockPlay = false; this.cleanupPartial(player); // Play the content if we had requested play or we paused on 'contentupdate' // and we haven't played yet. This happens if there was no preroll or if it // errored, timed out, etc. Otherwise snapshot restore would play. if (player.paused() && (player.ads._playRequested || player.ads._pausedOnContentupdate)) { var playPromise = player.play(); if (playPromise && playPromise.then) { playPromise.then(null, function (e) {}); } } } /* * Cleanup timeouts and spinner. */ ; _proto.cleanup = function cleanup(player) { if (!player.ads._hasThereBeenALoadStartDuringPlayerLife) { videojs.log.warn('Leaving Preroll state before loadstart event can cause issues.'); } this.cleanupPartial(player); } /* * Performs cleanup tasks without depending on a state transition. This is * used mainly in cases where a preroll failed. */ ; _proto.cleanupPartial = function cleanupPartial(player) { player.removeClass('vjs-ad-loading'); player.removeClass('vjs-ad-content-resuming'); this.clearTimeout(player); } /* * Clear the preroll timeout and nulls out the pointer. */ ; _proto.clearTimeout = function clearTimeout(player) { player.clearTimeout(this._timeout); this._timeout = null; }; return Preroll; }(AdState$1); States.registerState('Preroll', Preroll); var ContentState$2 = States.getState('ContentState'); /* * This is the initial state for a player with an ad plugin. Normally, it remains in this * state until a "play" event is seen. After that, we enter the Preroll state to check for * prerolls. This happens regardless of whether or not any prerolls ultimately will play. * Errors and other conditions may lead us directly from here to ContentPlayback. */ var BeforePreroll = /*#__PURE__*/ function (_ContentState) { _inheritsLoose(BeforePreroll, _ContentState); function BeforePreroll() { return _ContentState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ BeforePreroll._getName = function _getName() { return 'BeforePreroll'; } /* * For state transitions to work correctly, initialization should * happen here, not in a constructor. */ ; var _proto = BeforePreroll.prototype; _proto.init = function init(player) { this.adsReady = false; this.shouldResumeToContent = false; // Content playback should be blocked until we are done // playing ads or we know there are no ads to play player.ads._shouldBlockPlay = true; } /* * The ad plugin may trigger adsready before the play request. If so, * we record that adsready already happened so the Preroll state will know. */ ; _proto.onAdsReady = function onAdsReady(player) { player.ads.debug('Received adsready event (BeforePreroll)'); this.adsReady = true; } /* * Ad mode officially begins on the play request, because at this point * content playback is blocked by the ad plugin. */ ; _proto.onPlay = function onPlay(player) { var Preroll = States.getState('Preroll'); player.ads.debug('Received play event (BeforePreroll)'); // Check for prerolls this.transitionTo(Preroll, this.adsReady, this.shouldResumeToContent); } /* * All ads for the entire video are canceled. */ ; _proto.onAdsCanceled = function onAdsCanceled(player) { player.ads.debug('adscanceled (BeforePreroll)'); this.shouldResumeToContent = true; } /* * An ad error occured. Play content instead. */ ; _proto.onAdsError = function onAdsError() { this.player.ads.debug('adserror (BeforePreroll)'); this.shouldResumeToContent = true; } /* * If there is no preroll, don't wait for a play event to move forward. */ ; _proto.onNoPreroll = function onNoPreroll() { this.player.ads.debug('Skipping prerolls due to nopreroll event (BeforePreroll)'); this.shouldResumeToContent = true; } /* * Prerolls skipped by ad plugin. Play content instead. */ ; _proto.skipLinearAdMode = function skipLinearAdMode() { var player = this.player; player.trigger('adskip'); player.ads.debug('skipLinearAdMode (BeforePreroll)'); this.shouldResumeToContent = true; }; _proto.onContentChanged = function onContentChanged() { this.init(this.player); }; return BeforePreroll; }(ContentState$2); States.registerState('BeforePreroll', BeforePreroll); var AdState$2 = States.getState('AdState'); var Midroll = /*#__PURE__*/ function (_AdState) { _inheritsLoose(Midroll, _AdState); function Midroll() { return _AdState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ Midroll._getName = function _getName() { return 'Midroll'; } /* * Midroll breaks happen when the ad plugin calls startLinearAdMode, * which can happen at any time during content playback. */ ; var _proto = Midroll.prototype; _proto.init = function init(player) { player.ads.adType = 'midroll'; obj$1.start(player); player.addClass('vjs-ad-loading'); } /* * An ad has actually started playing. * Remove the loading spinner. */ ; _proto.onAdStarted = function onAdStarted(player) { player.removeClass('vjs-ad-loading'); } /* * Midroll break is done. */ ; _proto.endLinearAdMode = function endLinearAdMode() { var player = this.player; if (this.inAdBreak()) { this.contentResuming = true; player.addClass('vjs-ad-content-resuming'); player.removeClass('vjs-ad-loading'); obj$1.end(player); } } /* * End midroll break if there is an error. */ ; _proto.onAdsError = function onAdsError(player) { // In the future, we may not want to do this automatically. // Ad plugins should be able to choose to continue the ad break // if there was an error. if (this.inAdBreak()) { player.ads.endLinearAdMode(); } } /* * Cleanup CSS classes. */ ; _proto.cleanup = function cleanup(player) { player.removeClass('vjs-ad-loading'); player.removeClass('vjs-ad-content-resuming'); }; return Midroll; }(AdState$2); States.registerState('Midroll', Midroll); var AdState$3 = States.getState('AdState'); var Postroll = /*#__PURE__*/ function (_AdState) { _inheritsLoose(Postroll, _AdState); function Postroll() { return _AdState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ Postroll._getName = function _getName() { return 'Postroll'; } /* * For state transitions to work correctly, initialization should * happen here, not in a constructor. */ ; var _proto = Postroll.prototype; _proto.init = function init(player) { this.waitingForAdBreak = true; // Legacy name that now simply means "handling postrolls". player.ads._contentEnding = true; // Start postroll process. if (!player.ads.nopostroll_) { player.addClass('vjs-ad-loading'); // Determine postroll timeout based on plugin settings var timeout = player.ads.settings.timeout; if (typeof player.ads.settings.postrollTimeout === 'number') { timeout = player.ads.settings.postrollTimeout; } this._postrollTimeout = player.setTimeout(function () { player.trigger('adtimeout'); }, timeout); // No postroll, ads are done } else { this.resumeContent(player); var AdsDone = States.getState('AdsDone'); this.transitionTo(AdsDone); } } /* * Start the postroll if it's not too late. */ ; _proto.startLinearAdMode = function startLinearAdMode() { var player = this.player; if (!player.ads.inAdBreak() && !this.isContentResuming()) { player.ads.adType = 'postroll'; player.clearTimeout(this._postrollTimeout); this.waitingForAdBreak = false; obj$1.start(player); } else { videojs.log.warn('Unexpected startLinearAdMode invocation (Postroll)'); } } /* * An ad has actually started playing. * Remove the loading spinner. */ ; _proto.onAdStarted = function onAdStarted(player) { player.removeClass('vjs-ad-loading'); } /* * Ending a postroll triggers the ended event. */ ; _proto.endLinearAdMode = function endLinearAdMode() { var _this = this; var player = this.player; var AdsDone = States.getState('AdsDone'); if (this.inAdBreak()) { player.removeClass('vjs-ad-loading'); this.resumeContent(player); obj$1.end(player, function () { _this.transitionTo(AdsDone); }); } } /* * Postroll skipped, time to clean up. */ ; _proto.skipLinearAdMode = function skipLinearAdMode() { var player = this.player; if (player.ads.inAdBreak() || this.isContentResuming()) { videojs.log.warn('Unexpected skipLinearAdMode invocation'); } else { player.ads.debug('Postroll abort (skipLinearAdMode)'); player.trigger('adskip'); this.abort(player); } } /* * Postroll timed out, time to clean up. */ ; _proto.onAdTimeout = function onAdTimeout(player) { player.ads.debug('Postroll abort (adtimeout)'); this.abort(player); } /* * Postroll errored out, time to clean up. */ ; _proto.onAdsError = function onAdsError(player) { player.ads.debug('Postroll abort (adserror)'); // In the future, we may not want to do this automatically. // Ad plugins should be able to choose to continue the ad break // if there was an error. if (player.ads.inAdBreak()) { player.ads.endLinearAdMode(); } else { this.abort(player); } } /* * Handle content change if we're not in an ad break. */ ; _proto.onContentChanged = function onContentChanged(player) { // Content resuming after Postroll. Content is paused // at this point, since it is done playing. if (this.isContentResuming()) { var BeforePreroll = States.getState('BeforePreroll'); this.transitionTo(BeforePreroll); // Waiting for postroll to start. Content is considered playing // at this point, since it had to be playing to start the postroll. } else if (!this.inAdBreak()) { var Preroll = States.getState('Preroll'); this.transitionTo(Preroll); } } /* * Wrap up if there is no postroll. */ ; _proto.onNoPostroll = function onNoPostroll(player) { if (!this.isContentResuming() && !this.inAdBreak()) { this.abort(player); } else { videojs.log.warn('Unexpected nopostroll event (Postroll)'); } }; _proto.resumeContent = function resumeContent(player) { this.contentResuming = true; player.addClass('vjs-ad-content-resuming'); } /* * Helper for ending Postrolls. In the future we may want to * refactor this class so that `cleanup` handles all of this. */ ; _proto.abort = function abort(player) { var AdsDone = States.getState('AdsDone'); this.resumeContent(player); player.removeClass('vjs-ad-loading'); this.transitionTo(AdsDone); } /* * Cleanup timeouts and state. */ ; _proto.cleanup = function cleanup(player) { player.removeClass('vjs-ad-content-resuming'); player.clearTimeout(this._postrollTimeout); player.ads._contentEnding = false; }; return Postroll; }(AdState$3); States.registerState('Postroll', Postroll); var ContentState$3 = States.getState('ContentState'); /* * This state represents content playback the first time through before * content ends. After content has ended once, we check for postrolls and * move on to the AdsDone state rather than returning here. */ var ContentPlayback = /*#__PURE__*/ function (_ContentState) { _inheritsLoose(ContentPlayback, _ContentState); function ContentPlayback() { return _ContentState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ ContentPlayback._getName = function _getName() { return 'ContentPlayback'; } /* * For state transitions to work correctly, initialization should * happen here, not in a constructor. */ ; var _proto = ContentPlayback.prototype; _proto.init = function init(player) { // Don't block calls to play in content playback player.ads._shouldBlockPlay = false; } /* * In the case of a timeout, adsready might come in late. This assumes the behavior * that if an ad times out, it could still interrupt the content and start playing. * An ad plugin could behave otherwise by ignoring this event. */ ; _proto.onAdsReady = function onAdsReady(player) { player.ads.debug('Received adsready event (ContentPlayback)'); if (!player.ads.nopreroll_) { player.ads.debug('Triggered readyforpreroll event (ContentPlayback)'); player.trigger('readyforpreroll'); } } /* * Content ended before postroll checks. */ ; _proto.onReadyForPostroll = function onReadyForPostroll(player) { var Postroll = States.getState('Postroll'); player.ads.debug('Received readyforpostroll event'); this.transitionTo(Postroll); } /* * This is how midrolls start. */ ; _proto.startLinearAdMode = function startLinearAdMode() { var Midroll = States.getState('Midroll'); this.transitionTo(Midroll); }; return ContentPlayback; }(ContentState$3); States.registerState('ContentPlayback', ContentPlayback); var ContentState$4 = States.getState('ContentState'); /* * This state represents content playback when stitched ads are in play. */ var StitchedContentPlayback = /*#__PURE__*/ function (_ContentState) { _inheritsLoose(StitchedContentPlayback, _ContentState); function StitchedContentPlayback() { return _ContentState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ StitchedContentPlayback._getName = function _getName() { return 'StitchedContentPlayback'; } /* * For state transitions to work correctly, initialization should * happen here, not in a constructor. */ ; var _proto = StitchedContentPlayback.prototype; _proto.init = function init() { // Don't block calls to play in stitched ad players, ever. this.player.ads._shouldBlockPlay = false; } /* * Source change does not do anything for stitched ad players. * contentchanged does not fire during ad breaks, so we don't need to * worry about that. */ ; _proto.onContentChanged = function onContentChanged() { this.player.ads.debug("Received contentchanged event (" + this.constructor._getName() + ")"); } /* * This is how stitched ads start. */ ; _proto.startLinearAdMode = function startLinearAdMode() { var StitchedAdRoll = States.getState('StitchedAdRoll'); this.transitionTo(StitchedAdRoll); }; return StitchedContentPlayback; }(ContentState$4); States.registerState('StitchedContentPlayback', StitchedContentPlayback); var AdState$4 = States.getState('AdState'); var StitchedAdRoll = /*#__PURE__*/ function (_AdState) { _inheritsLoose(StitchedAdRoll, _AdState); function StitchedAdRoll() { return _AdState.apply(this, arguments) || this; } /* * Allows state name to be logged even after minification. */ StitchedAdRoll._getName = function _getName() { return 'StitchedAdRoll'; } /* * StitchedAdRoll breaks happen when the ad plugin calls startLinearAdMode, * which can happen at any time during content playback. */ ; var _proto = StitchedAdRoll.prototype; _proto.init = function init() { this.waitingForAdBreak = false; this.contentResuming = false; this.player.ads.adType = 'stitched'; obj$1.start(this.player); } /* * For stitched ads, there is no "content resuming" scenario, so a "playing" * event is not relevant. */ ; _proto.onPlaying = function onPlaying() {} /* * For stitched ads, there is no "content resuming" scenario, so a * "contentresumed" event is not relevant. */ ; _proto.onContentResumed = function onContentResumed() {} /* * When we see an "adended" event, it means that we are in a postroll that * has ended (because the media ended and we are still in an ad state). * * In these cases, we transition back to content mode and fire ended. */ ; _proto.onAdEnded = function onAdEnded() { this.endLinearAdMode(); this.player.trigger('ended'); } /* * StitchedAdRoll break is done. */ ; _proto.endLinearAdMode = function endLinearAdMode() { var StitchedContentPlayback = States.getState('StitchedContentPlayback'); obj$1.end(this.player); this.transitionTo(StitchedContentPlayback); }; return StitchedAdRoll; }(AdState$4); States.registerState('StitchedAdRoll', StitchedAdRoll); /* This main plugin file is responsible for the public API and enabling the features that live in in separate files. */ var isMiddlewareMediatorSupported$1 = obj.isMiddlewareMediatorSupported; var VIDEO_EVENTS = videojs.getTech('Html5').Events; // Default settings var defaults = { // Maximum amount of time in ms to wait to receive `adsready` from the ad // implementation after play has been requested. Ad implementations are // expected to load any dynamic libraries and make any requests to determine // ad policies for a video during this time. timeout: 5000, // Maximum amount of time in ms to wait for the ad implementation to start // linear ad mode after `readyforpreroll` has fired. This is in addition to // the standard timeout. prerollTimeout: undefined, // Maximum amount of time in ms to wait for the ad implementation to start // linear ad mode after `readyforpostroll` has fired. postrollTimeout: undefined, // When truthy, instructs the plugin to output additional information about // plugin state to the video.js log. On most devices, the video.js log is // the same as the developer console. debug: false, // Set this to true when using ads that are part of the content video stitchedAds: false, // Force content to be treated as live or not live // if not defined, the code will try to infer if content is live, // which can have limitations. contentIsLive: undefined, // If set to true, content will play muted behind ads on supported platforms. This is // to support ads on video metadata cuepoints during a live stream. It also results in // more precise resumes after ads during a live stream. liveCuePoints: true }; var contribAdsPlugin = function contribAdsPlugin(options) { var player = this; // eslint-disable-line consistent-this var settings = videojs.mergeOptions(defaults, options); // Prefix all video element events during ad playback // if the video element emits ad-related events directly, // plugins that aren't ad-aware will break. prefixing allows // plugins that wish to handle ad events to do so while // avoiding the complexity for common usage var videoEvents = []; // dedupe event names VIDEO_EVENTS.concat(['firstplay', 'loadedalldata']).forEach(function (eventName) { if (videoEvents.indexOf(eventName) === -1) { videoEvents.push(eventName); } }); // Set up redispatching of player events player.on(videoEvents, redispatch); // Set up features to block content playback while waiting for ads. // Play middleware is only supported on later versions of video.js // and on desktop currently(as the user-gesture requirement on mobile // will disallow calling play once play blocking is lifted) // The middleware must also be registered outside of the plugin, // to avoid a middleware factory being created for each player if (!isMiddlewareMediatorSupported$1()) { initCancelContentPlay(player, settings.debug); } // If we haven't seen a loadstart after 5 seconds, the plugin was not initialized // correctly. player.setTimeout(function () { if (!player.ads._hasThereBeenALoadStartDuringPlayerLife && player.src() !== '') { videojs.log.error('videojs-contrib-ads has not seen a loadstart event 5 seconds ' + 'after being initialized, but a source is present. This indicates that ' + 'videojs-contrib-ads was initialized too late. It must be initialized ' + 'immediately after video.js in the same tick. As a result, some ads will not ' + 'play and some media events will be incorrect. For more information, see ' + 'http://videojs.github.io/videojs-contrib-ads/integrator/getting-started.html'); } }, 5000); // "vjs-has-started" should be present at the end of a video. This makes sure it's // always there. player.on('ended', function () { if (!player.hasClass('vjs-has-started')) { player.addClass('vjs-has-started'); } }); // video.js removes the vjs-waiting class on timeupdate. We want // to make sure this still happens during content restoration. player.on('contenttimeupdate', function () { player.removeClass('vjs-waiting'); }); // We now auto-play when an ad gets loaded if we're playing ads in the same video // element as the content. // The problem is that in IE11, we cannot play in addurationchange but in iOS8, we // cannot play from adcanplay. // This will prevent ad plugins from needing to do this themselves. player.on(['addurationchange', 'adcanplay'], function () { // We don't need to handle this for stitched ads because // linear ads in such cases are stitched into the content. if (player.ads.settings.stitchedAds) { return; } // Some techs may retrigger canplay after playback has begun. // So we want to procceed only if playback hasn't started. if (player.hasStarted()) { return; } if (player.ads.snapshot && player.currentSrc() === player.ads.snapshot.currentSrc) { return; } // If an ad isn't playing, don't try to play an ad. This could result from prefixed // events when the player is blocked by a preroll check, but there is no preroll. if (!player.ads.inAdBreak()) { return; } var playPromise = player.play(); if (playPromise && playPromise.catch) { playPromise.catch(function (error) { videojs.log.warn('Play promise rejected when playing ad', error); }); } }); player.on('nopreroll', function () { player.ads.debug('Received nopreroll event'); player.ads.nopreroll_ = true; }); player.on('nopostroll', function () { player.ads.debug('Received nopostroll event'); player.ads.nopostroll_ = true; }); // Restart the cancelContentPlay process. player.on('playing', function () { player.ads._cancelledPlay = false; player.ads._pausedOnContentupdate = false; }); // Keep track of whether a play event has happened player.on('play', function () { player.ads._playRequested = true; }); player.one('loadstart', function () { player.ads._hasThereBeenALoadStartDuringPlayerLife = true; }); player.on('loadeddata', function () { player.ads._hasThereBeenALoadedData = true; }); player.on('loadedmetadata', function () { player.ads._hasThereBeenALoadedMetaData = true; }); // Replace the plugin constructor with the ad namespace player.ads = getAds(player); player.ads.settings = settings; // Set the stitched ads state. This needs to happen before the `_state` is // initialized below - BeforePreroll needs to know whether contrib-ads is // playing stitched ads or not. // The setter is deprecated, so this does not use it. // But first, cast to boolean. settings.stitchedAds = !!settings.stitchedAds; if (settings.stitchedAds) { player.ads._state = new (States.getState('StitchedContentPlayback'))(player); } else { player.ads._state = new (States.getState('BeforePreroll'))(player); } player.ads._state.init(player); player.ads.cueTextTracks = cueTextTracks; player.ads.adMacroReplacement = adMacroReplacement.bind(player); // Start sending contentupdate and contentchanged events for this player initializeContentupdate(player); // Global contentchanged handler for resetting plugin state player.on('contentchanged', player.ads.reset); // A utility method for textTrackChangeHandler to define the conditions // when text tracks should be disabled. // Currently this includes: // - on iOS with native text tracks, during an ad playing var shouldDisableTracks = function shouldDisableTracks() { // If the platform matches iOS with native text tracks // and this occurs during ad playback, we should disable tracks again. // If shouldPlayContentBehindAd, no special handling is needed. return !player.ads.shouldPlayContentBehindAd(player) && player.ads.inAdBreak() && player.tech_.featuresNativeTextTracks && videojs.browser.IS_IOS && // older versions of video.js did not use an emulated textTrackList !Array.isArray(player.textTracks()); }; /* * iOS Safari will change caption mode to 'showing' if a user previously * turned captions on manually for that video source, so this TextTrackList * 'change' event handler will re-disable them in case that occurs during ad playback */ var textTrackChangeHandler = function textTrackChangeHandler() { var textTrackList = player.textTracks(); if (shouldDisableTracks()) { // We must double check all tracks for (var i = 0; i < textTrackList.length; i++) { var track = textTrackList[i]; if (track.mode === 'showing') { track.mode = 'disabled'; } } } }; // Add the listener to the text track list player.ready(function () { player.textTracks().addEventListener('change', textTrackChangeHandler); }); // Event handling for the current state. player.on(['play', 'playing', 'ended', 'adsready', 'adscanceled', 'adskip', 'adserror', 'adtimeout', 'adended', 'ads-ad-started', 'contentchanged', 'dispose', 'contentresumed', 'readyforpostroll', 'nopreroll', 'nopostroll'], function (e) { player.ads._state.handleEvent(e.type); }); // Clear timeouts and handlers when player is disposed player.on('dispose', function () { player.ads.reset(); player.textTracks().removeEventListener('change', textTrackChangeHandler); }); }; // Expose the contrib-ads version before it is initialized. Will be replaced // after initialization in ads.js contribAdsPlugin.VERSION = version; // Attempt to register the plugin, if we can. register(contribAdsPlugin); return contribAdsPlugin; }));
// Copyright Joyent, Inc. and other Node contributors. // // 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. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream services. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. module.exports = Transform; var Duplex = require('./_stream_duplex'); /*<replacement>*/ var util = require('core-util-is'); util.inherits = require('inherits'); /*</replacement>*/ util.inherits(Transform, Duplex); function TransformState(options, stream) { this.afterTransform = function(er, data) { return afterTransform(stream, er, data); }; this.needTransform = false; this.transforming = false; this.writecb = null; this.writechunk = null; } function afterTransform(stream, er, data) { var ts = stream._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); ts.writechunk = null; ts.writecb = null; if (!util.isNullOrUndefined(data)) stream.push(data); if (cb) cb(er); var rs = stream._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { stream._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = new TransformState(options, this); // when the writable side finishes, then flush out anything remaining. var stream = this; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; this.once('prefinish', function() { if (util.isFunction(this._flush)) this._flush(function(er) { done(stream, er); }); else done(stream); }); } Transform.prototype.push = function(chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation services. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function(chunk, encoding, cb) { throw new Error('not implemented'); }; Transform.prototype._write = function(chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function(n) { var ts = this._transformState; if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; function done(stream, er) { if (er) return stream.emit('error', er); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided var ws = stream._writableState; var ts = stream._transformState; if (ws.length) throw new Error('calling transform done when ws.length != 0'); if (ts.transforming) throw new Error('calling transform done when still transforming'); return stream.push(null); }
/** * Error codes used by Apple * @see <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW4">The Binary Interface and Notification Formats</a> */ var Errors = { 'noErrorsEncountered': 0, 'processingError': 1, 'missingDeviceToken': 2, 'missingTopic': 3, 'missingPayload': 4, 'invalidTokenSize': 5, 'invalidTopicSize': 6, 'invalidPayloadSize': 7, 'invalidToken': 8, 'apnsShutdown': 10, 'none': 255, 'retryLimitExceeded': 512, 'moduleInitialisationFailed': 513 }; module.exports = Errors;
// Copyright 2018 Mathias Bynens. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- author: Mathias Bynens description: > Some binary properties used to be part of the Unicode property escapes proposal but were later removed. They must not be supported. esid: sec-static-semantics-unicodematchproperty-p negative: phase: parse type: SyntaxError features: [regexp-unicode-property-escapes] ---*/ $DONOTEVALUATE(); /\P{Hyphen}/u;
// XXX should check error codes var failure = function (test, code, reason) { return function (error, result) { test.equal(result, undefined); test.isTrue(error && typeof error === "object"); if (error && typeof error === "object") { if (typeof code === "number") { test.instanceOf(error, Meteor.Error); code && test.equal(error.error, code); reason && test.equal(error.reason, reason); // XXX should check that other keys aren't present.. should // probably use something like the Matcher we used to have } else { // for normal Javascript errors test.instanceOf(error, Error); test.equal(error.message, code); } } }; }; var failureOnStopped = function (test, code, reason) { var f = failure(test, code, reason); return function (error) { if (error) { f(error); } } }; Tinytest.add("livedata - Meteor.Error", function (test) { var error = new Meteor.Error(123, "kittens", "puppies"); test.instanceOf(error, Meteor.Error); test.instanceOf(error, Error); test.equal(error.error, 123); test.equal(error.reason, "kittens"); test.equal(error.details, "puppies"); }); if (Meteor.isServer) { Tinytest.add("livedata - version negotiation", function (test) { var versionCheck = function (clientVersions, serverVersions, expected) { test.equal( LivedataTest.calculateVersion(clientVersions, serverVersions), expected); }; versionCheck(["A", "B", "C"], ["A", "B", "C"], "A"); versionCheck(["B", "C"], ["A", "B", "C"], "B"); versionCheck(["A", "B", "C"], ["B", "C"], "B"); versionCheck(["foo", "bar", "baz"], ["A", "B", "C"], "A"); }); } Tinytest.add("livedata - methods with colliding names", function (test) { var x = Random.id(); var m = {}; m[x] = function () {}; Meteor.methods(m); test.throws(function () { Meteor.methods(m); }); }); var echoTest = function (item) { return function (test, expect) { if (Meteor.isServer) { test.equal(Meteor.call("echo", item), [item]); test.equal(Meteor.call("echoOne", item), item); } if (Meteor.isClient) test.equal(Meteor.call("echo", item), undefined); test.equal(Meteor.call("echo", item, expect(undefined, [item])), undefined); test.equal(Meteor.call("echoOne", item, expect(undefined, item)), undefined); }; }; testAsyncMulti("livedata - basic method invocation", [ // Unknown methods function (test, expect) { if (Meteor.isServer) { // On server, with no callback, throws exception try { var ret = Meteor.call("unknown method"); } catch (e) { test.equal(e.error, 404); var threw = true; } test.isTrue(threw); test.equal(ret, undefined); } if (Meteor.isClient) { // On client, with no callback, just returns undefined var ret = Meteor.call("unknown method"); test.equal(ret, undefined); } // On either, with a callback, calls the callback and does not throw var ret = Meteor.call("unknown method", expect(failure(test, 404, "Method not found"))); test.equal(ret, undefined); }, function (test, expect) { // make sure 'undefined' is preserved as such, instead of turning // into null (JSON does not have 'undefined' so there is special // code for this) if (Meteor.isServer) test.equal(Meteor.call("nothing"), undefined); if (Meteor.isClient) test.equal(Meteor.call("nothing"), undefined); test.equal(Meteor.call("nothing", expect(undefined, undefined)), undefined); }, function (test, expect) { if (Meteor.isServer) test.equal(Meteor.call("echo"), []); if (Meteor.isClient) test.equal(Meteor.call("echo"), undefined); test.equal(Meteor.call("echo", expect(undefined, [])), undefined); }, echoTest(new Date()), echoTest({d: new Date(), s: "foobarbaz"}), echoTest([new Date(), "foobarbaz"]), echoTest(new Mongo.ObjectID()), echoTest({o: new Mongo.ObjectID()}), echoTest({$date: 30}), // literal echoTest({$literal: {$date: 30}}), echoTest(12), echoTest(Infinity), echoTest(-Infinity), function (test, expect) { if (Meteor.isServer) test.equal(Meteor.call("echo", 12, {x: 13}), [12, {x: 13}]); if (Meteor.isClient) test.equal(Meteor.call("echo", 12, {x: 13}), undefined); test.equal(Meteor.call("echo", 12, {x: 13}, expect(undefined, [12, {x: 13}])), undefined); }, // test that `wait: false` is respected function (test, expect) { if (Meteor.isClient) { // For test isolation var token = Random.id(); Meteor.apply( "delayedTrue", [token], {wait: false}, expect(function(err, res) { test.equal(res, false); })); Meteor.apply("makeDelayedTrueImmediatelyReturnFalse", [token]); } }, // test that `wait: true` is respected function(test, expect) { if (Meteor.isClient) { var token = Random.id(); Meteor.apply( "delayedTrue", [token], {wait: true}, expect(function(err, res) { test.equal(res, true); })); Meteor.apply("makeDelayedTrueImmediatelyReturnFalse", [token]); } }, function (test, expect) { // No callback if (Meteor.isServer) { test.throws(function () { Meteor.call("exception", "both"); }); test.throws(function () { Meteor.call("exception", "server"); }); // No exception, because no code will run on the client test.equal(Meteor.call("exception", "client"), undefined); } if (Meteor.isClient) { // The client exception is thrown away because it's in the // stub. The server exception is throw away because we didn't // give a callback. test.equal(Meteor.call("exception", "both"), undefined); test.equal(Meteor.call("exception", "server"), undefined); test.equal(Meteor.call("exception", "client"), undefined); } // With callback if (Meteor.isClient) { test.equal( Meteor.call("exception", "both", expect(failure(test, 500, "Internal server error"))), undefined); test.equal( Meteor.call("exception", "server", expect(failure(test, 500, "Internal server error"))), undefined); test.equal(Meteor.call("exception", "client"), undefined); } if (Meteor.isServer) { test.equal( Meteor.call("exception", "both", expect(failure(test, "Test method throwing an exception"))), undefined); test.equal( Meteor.call("exception", "server", expect(failure(test, "Test method throwing an exception"))), undefined); test.equal(Meteor.call("exception", "client"), undefined); } }, function (test, expect) { if (Meteor.isServer) { var threw = false; try { Meteor.call("exception", "both", {intended: true}); } catch (e) { threw = true; test.equal(e.error, 999); test.equal(e.reason, "Client-visible test exception"); } test.isTrue(threw); threw = false; try { Meteor.call("exception", "both", {intended: true, throwThroughFuture: true}); } catch (e) { threw = true; test.equal(e.error, 999); test.equal(e.reason, "Client-visible test exception"); } test.isTrue(threw); } if (Meteor.isClient) { test.equal( Meteor.call("exception", "both", {intended: true}, expect(failure(test, 999, "Client-visible test exception"))), undefined); test.equal( Meteor.call("exception", "server", {intended: true}, expect(failure(test, 999, "Client-visible test exception"))), undefined); test.equal( Meteor.call("exception", "server", {intended: true, throwThroughFuture: true}, expect(failure(test, 999, "Client-visible test exception"))), undefined); } } ]); var checkBalances = function (test, a, b) { var alice = Ledger.findOne({name: "alice", world: test.runId()}); var bob = Ledger.findOne({name: "bob", world: test.runId()}); test.equal(alice.balance, a); test.equal(bob.balance, b); }; // would be nice to have a database-aware test harness of some kind -- // this is a big hack (and XXX pollutes the global test namespace) testAsyncMulti("livedata - compound methods", [ function (test, expect) { if (Meteor.isClient) Meteor.subscribe("ledger", test.runId(), expect()); Ledger.insert({name: "alice", balance: 100, world: test.runId()}, expect(function () {})); Ledger.insert({name: "bob", balance: 50, world: test.runId()}, expect(function () {})); }, function (test, expect) { Meteor.call('ledger/transfer', test.runId(), "alice", "bob", 10, expect(function(err, result) { test.equal(err, undefined); test.equal(result, undefined); checkBalances(test, 90, 60); })); checkBalances(test, 90, 60); }, function (test, expect) { Meteor.call('ledger/transfer', test.runId(), "alice", "bob", 100, true, expect(function (err, result) { failure(test, 409)(err, result); // Balances are reverted back to pre-stub values. checkBalances(test, 90, 60); })); if (Meteor.isClient) // client can fool itself by cheating, but only until the sync // finishes checkBalances(test, -10, 160); else checkBalances(test, 90, 60); } ]); // Replaces the Connection's `_livedata_data` method to push incoming // messages on a given collection to an array. This can be used to // verify that the right data is sent on the wire // // @param messages {Array} The array to which to append the messages // @return {Function} A function to call to undo the eavesdropping var eavesdropOnCollection = function(livedata_connection, collection_name, messages) { var old_livedata_data = _.bind( livedata_connection._livedata_data, livedata_connection); // Kind of gross since all tests past this one will run with this // hook set up. That's probably fine since we only check a specific // collection but still... // // Should we consider having a separate connection per Tinytest or // some similar scheme? livedata_connection._livedata_data = function(msg) { if (msg.collection && msg.collection === collection_name) { messages.push(msg); } old_livedata_data(msg); }; return function() { livedata_connection._livedata_data = old_livedata_data; }; }; if (Meteor.isClient) { testAsyncMulti("livedata - changing userid reruns subscriptions without flapping data on the wire", [ function(test, expect) { var messages = []; var undoEavesdrop = eavesdropOnCollection( Meteor.connection, "objectsWithUsers", messages); // A helper for testing incoming set and unset messages // XXX should this be extracted as a general helper together with // eavesdropOnCollection? var expectMessages = function(expectedAddedMessageCount, expectedRemovedMessageCount, expectedNamesInCollection) { var actualAddedMessageCount = 0; var actualRemovedMessageCount = 0; _.each(messages, function (msg) { if (msg.msg === 'added') ++actualAddedMessageCount; else if (msg.msg === 'removed') ++actualRemovedMessageCount; else test.fail({unexpected: JSON.stringify(msg)}); }); test.equal(actualAddedMessageCount, expectedAddedMessageCount); test.equal(actualRemovedMessageCount, expectedRemovedMessageCount); expectedNamesInCollection.sort(); test.equal(_.pluck(objectsWithUsers.find({}, {sort: ['name']}).fetch(), 'name'), expectedNamesInCollection); messages.length = 0; // clear messages without creating a new object }; // make sure we're not already logged in. can happen if accounts // tests fail oddly. Meteor.apply("setUserId", [null], {wait: true}, expect(function () {})); Meteor.subscribe("objectsWithUsers", expect(function() { expectMessages(1, 0, ["owned by none"]); Meteor.apply("setUserId", ["1"], {wait: true}, afterFirstSetUserId); })); var afterFirstSetUserId = expect(function() { expectMessages(3, 1, [ "owned by one - a", "owned by one/two - a", "owned by one/two - b"]); Meteor.apply("setUserId", ["2"], {wait: true}, afterSecondSetUserId); }); var afterSecondSetUserId = expect(function() { expectMessages(2, 1, [ "owned by one/two - a", "owned by one/two - b", "owned by two - a", "owned by two - b"]); Meteor.apply("setUserId", ["2"], {wait: true}, afterThirdSetUserId); }); var afterThirdSetUserId = expect(function() { // Nothing should have been sent since the results of the // query are the same ("don't flap data on the wire") expectMessages(0, 0, [ "owned by one/two - a", "owned by one/two - b", "owned by two - a", "owned by two - b"]); undoEavesdrop(); }); }, function(test, expect) { var key = Random.id(); Meteor.subscribe("recordUserIdOnStop", key); Meteor.apply("setUserId", ["100"], {wait: true}, expect(function () {})); Meteor.apply("setUserId", ["101"], {wait: true}, expect(function () {})); Meteor.call("userIdWhenStopped", key, expect(function (err, result) { test.isFalse(err); test.equal(result, "100"); })); // clean up Meteor.apply("setUserId", [null], {wait: true}, expect(function () {})); } ]); } Tinytest.add("livedata - setUserId error when called from server", function(test) { if (Meteor.isServer) { test.equal(errorThrownWhenCallingSetUserIdDirectlyOnServer.message, "Can't call setUserId on a server initiated method call"); } }); if (Meteor.isServer) { var pubHandles = {}; }; Meteor.methods({ "livedata/setup" : function (id) { check(id, String); if (Meteor.isServer) { pubHandles[id] = {}; Meteor.publish("pub1"+id, function () { pubHandles[id].pub1 = this; this.ready(); }); Meteor.publish("pub2"+id, function () { pubHandles[id].pub2 = this; this.ready(); }); } }, "livedata/pub1go" : function (id) { check(id, String); if (Meteor.isServer) { pubHandles[id].pub1.added("MultiPubCollection" + id, "foo", {a: "aa"}); return 1; } return 0; }, "livedata/pub2go" : function (id) { check(id, String); if (Meteor.isServer) { pubHandles[id].pub2.added("MultiPubCollection" + id , "foo", {b: "bb"}); return 2; } return 0; } }); if (Meteor.isClient) { (function () { var MultiPub; var id = Random.id(); testAsyncMulti("livedata - added from two different subs", [ function (test, expect) { Meteor.call('livedata/setup', id, expect(function () {})); }, function (test, expect) { MultiPub = new Mongo.Collection("MultiPubCollection" + id); var sub1 = Meteor.subscribe("pub1"+id, expect(function () {})); var sub2 = Meteor.subscribe("pub2"+id, expect(function () {})); }, function (test, expect) { Meteor.call("livedata/pub1go", id, expect(function (err, res) {test.equal(res, 1);})); }, function (test, expect) { test.equal(MultiPub.findOne("foo"), {_id: "foo", a: "aa"}); }, function (test, expect) { Meteor.call("livedata/pub2go", id, expect(function (err, res) {test.equal(res, 2);})); }, function (test, expect) { test.equal(MultiPub.findOne("foo"), {_id: "foo", a: "aa", b: "bb"}); } ]); })(); }; if (Meteor.isClient) { testAsyncMulti("livedata - overlapping universal subs", [ function (test, expect) { var coll = new Mongo.Collection("overlappingUniversalSubs"); var token = Random.id(); test.isFalse(coll.findOne(token)); Meteor.call("testOverlappingSubs", token, expect(function (err) { test.isFalse(err); test.isTrue(coll.findOne(token)); })); } ]); testAsyncMulti("livedata - runtime universal sub creation", [ function (test, expect) { var coll = new Mongo.Collection("runtimeSubCreation"); var token = Random.id(); test.isFalse(coll.findOne(token)); Meteor.call("runtimeUniversalSubCreation", token, expect(function (err) { test.isFalse(err); test.isTrue(coll.findOne(token)); })); } ]); testAsyncMulti("livedata - no setUserId after unblock", [ function (test, expect) { Meteor.call("setUserIdAfterUnblock", expect(function (err, result) { test.isFalse(err); test.isTrue(result); })); } ]); testAsyncMulti("livedata - publisher errors with onError callback", (function () { var conn, collName, coll; var errorFromRerun; var gotErrorFromStopper = false; return [ function (test, expect) { // Use a separate connection so that we can safely check to see if // conn._subscriptions is empty. conn = new LivedataTest.Connection('/', {reloadWithOutstanding: true}); collName = Random.id(); coll = new Mongo.Collection(collName, {connection: conn}); var testSubError = function (options) { conn.subscribe("publisherErrors", collName, options, { onReady: expect(), onError: expect( failure(test, options.internalError ? 500 : 412, options.internalError ? "Internal server error" : "Explicit error")) }); }; testSubError({throwInHandler: true}); testSubError({throwInHandler: true, internalError: true}); testSubError({errorInHandler: true}); testSubError({errorInHandler: true, internalError: true}); testSubError({errorLater: true}); testSubError({errorLater: true, internalError: true}); }, function (test, expect) { test.equal(coll.find().count(), 0); test.equal(_.size(conn._subscriptions), 0); // white-box test conn.subscribe("publisherErrors", collName, {throwWhenUserIdSet: true}, { onReady: expect(), onError: function (error) { errorFromRerun = error; } }); }, function (test, expect) { // Because the last subscription is ready, we should have a document. test.equal(coll.find().count(), 1); test.isFalse(errorFromRerun); test.equal(_.size(conn._subscriptions), 1); // white-box test conn.call('setUserId', 'bla', expect(function(){})); }, function (test, expect) { // Now that we've re-run, we should have stopped the subscription, // gotten a error, and lost the document. test.equal(coll.find().count(), 0); test.isTrue(errorFromRerun); test.instanceOf(errorFromRerun, Meteor.Error); test.equal(errorFromRerun.error, 412); test.equal(errorFromRerun.reason, "Explicit error"); test.equal(_.size(conn._subscriptions), 0); // white-box test conn.subscribe("publisherErrors", collName, {stopInHandler: true}, { onError: function() { gotErrorFromStopper = true; } }); // Call a method. This method won't be processed until the publisher's // function returns, so blocking on it being done ensures that we've // gotten the removed/nosub/etc. conn.call('nothing', expect(function(){})); }, function (test, expect) { test.equal(coll.find().count(), 0); // sub.stop does NOT call onError. test.isFalse(gotErrorFromStopper); test.equal(_.size(conn._subscriptions), 0); // white-box test conn._stream.disconnect({_permanent: true}); } ];})()); testAsyncMulti("livedata - publisher errors with onStop callback", (function () { var conn, collName, coll; var errorFromRerun; var gotErrorFromStopper = false; return [ function (test, expect) { // Use a separate connection so that we can safely check to see if // conn._subscriptions is empty. conn = new LivedataTest.Connection('/', {reloadWithOutstanding: true}); collName = Random.id(); coll = new Mongo.Collection(collName, {connection: conn}); var testSubError = function (options) { conn.subscribe("publisherErrors", collName, options, { onReady: expect(), onStop: expect( failureOnStopped(test, options.internalError ? 500 : 412, options.internalError ? "Internal server error" : "Explicit error")) }); }; testSubError({throwInHandler: true}); testSubError({throwInHandler: true, internalError: true}); testSubError({errorInHandler: true}); testSubError({errorInHandler: true, internalError: true}); testSubError({errorLater: true}); testSubError({errorLater: true, internalError: true}); }, function (test, expect) { test.equal(coll.find().count(), 0); test.equal(_.size(conn._subscriptions), 0); // white-box test conn.subscribe("publisherErrors", collName, {throwWhenUserIdSet: true}, { onReady: expect(), onStop: function (error) { errorFromRerun = error; } }); }, function (test, expect) { // Because the last subscription is ready, we should have a document. test.equal(coll.find().count(), 1); test.isFalse(errorFromRerun); test.equal(_.size(conn._subscriptions), 1); // white-box test conn.call('setUserId', 'bla', expect(function(){})); }, function (test, expect) { // Now that we've re-run, we should have stopped the subscription, // gotten a error, and lost the document. test.equal(coll.find().count(), 0); test.isTrue(errorFromRerun); test.instanceOf(errorFromRerun, Meteor.Error); test.equal(errorFromRerun.error, 412); test.equal(errorFromRerun.reason, "Explicit error"); test.equal(_.size(conn._subscriptions), 0); // white-box test conn.subscribe("publisherErrors", collName, {stopInHandler: true}, { onStop: function(error) { if (error) { gotErrorFromStopper = true; } } }); // Call a method. This method won't be processed until the publisher's // function returns, so blocking on it being done ensures that we've // gotten the removed/nosub/etc. conn.call('nothing', expect(function(){})); }, function (test, expect) { test.equal(coll.find().count(), 0); // sub.stop does NOT call onError. test.isFalse(gotErrorFromStopper); test.equal(_.size(conn._subscriptions), 0); // white-box test conn._stream.disconnect({_permanent: true}); } ];})()); testAsyncMulti("livedata - publish multiple cursors", [ function (test, expect) { Meteor.subscribe("multiPublish", {normal: 1}, { onReady: expect(function () { test.equal(One.find().count(), 2); test.equal(Two.find().count(), 3); }), onError: failure() }); }, function (test, expect) { Meteor.subscribe("multiPublish", {dup: 1}, { onReady: failure(), onError: expect(failure(test, 500, "Internal server error")) }); }, function (test, expect) { Meteor.subscribe("multiPublish", {notCursor: 1}, { onReady: failure(), onError: expect(failure(test, 500, "Internal server error")) }); } ]); } var selfUrl = Meteor.isServer ? Meteor.absoluteUrl() : Meteor._relativeToSiteRootUrl('/'); if (Meteor.isServer) { Meteor.methods({ "s2s": function (arg) { check(arg, String); return "s2s " + arg; } }); } (function () { testAsyncMulti("livedata - connect works from both client and server", [ function (test, expect) { var self = this; self.conn = DDP.connect(selfUrl); pollUntil(expect, function () { return self.conn.status().connected; }, 10000); }, function (test, expect) { var self = this; if (self.conn.status().connected) { self.conn.call('s2s', 'foo', expect(function (err, res) { if (err) throw err; test.equal(res, "s2s foo"); })); } } ]); })(); if (Meteor.isServer) { (function () { testAsyncMulti("livedata - method call on server blocks in a fiber way", [ function (test, expect) { var self = this; self.conn = DDP.connect(selfUrl); pollUntil(expect, function () { return self.conn.status().connected; }, 10000); }, function (test, expect) { var self = this; if (self.conn.status().connected) { test.equal(self.conn.call('s2s', 'foo'), "s2s foo"); } } ]); })(); } (function () { testAsyncMulti("livedata - connect fails to unknown place", [ function (test, expect) { var self = this; self.conn = DDP.connect("example.com", {_dontPrintErrors: true}); Meteor.setTimeout(expect(function () { test.isFalse(self.conn.status().connected, "Not connected"); self.conn.close(); }), 500); } ]); })(); if (Meteor.isServer) { Meteor.publish("publisherCloning", function () { var self = this; var fields = {x: {y: 42}}; self.added("publisherCloning", "a", fields); fields.x.y = 43; self.changed("publisherCloning", "a", fields); self.ready(); }); } else { var PublisherCloningCollection = new Mongo.Collection("publisherCloning"); testAsyncMulti("livedata - publish callbacks clone", [ function (test, expect) { Meteor.subscribe("publisherCloning", {normal: 1}, { onReady: expect(function () { test.equal(PublisherCloningCollection.findOne(), { _id: "a", x: {y: 43}}); }), onError: failure() }); } ]); } testAsyncMulti("livedata - result by value", [ function (test, expect) { var self = this; self.testId = Random.id(); Meteor.call('getArray', self.testId, expect(function (error, firstResult) { test.isFalse(error); test.isTrue(firstResult); self.firstResult = firstResult; })); }, function (test, expect) { var self = this; Meteor.call('pushToArray', self.testId, 'xxx', expect(function (error) { test.isFalse(error); })); }, function (test, expect) { var self = this; Meteor.call('getArray', self.testId, expect(function (error, secondResult) { test.isFalse(error); test.equal(self.firstResult.length + 1, secondResult.length); })); } ]); // XXX some things to test in greater detail: // staying in simulation mode // time warp // serialization / beginAsync(true) / beginAsync(false) // malformed messages (need raw wire access) // method completion/satisfaction // subscriptions (multiple APIs, including autorun?) // subscription completion // subscription attribute shadowing // server method calling methods on other server (eg, should simulate) // subscriptions and methods being idempotent // reconnection // reconnection not resulting in method re-execution // reconnection tolerating all kinds of lost messages (including data) // [probably lots more]
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { BadgeModule } from '../badge/badge.module'; import { IconModule } from '../icon/icon.module'; import { Tab } from './tab'; import { TabButton } from './tab-button'; import { TabHighlight } from './tab-highlight'; import { Tabs } from './tabs'; /** * @hidden */ export class TabsModule { /** * @return {?} */ static forRoot() { return { ngModule: TabsModule, providers: [] }; } } TabsModule.decorators = [ { type: NgModule, args: [{ imports: [ BadgeModule, CommonModule, IconModule ], declarations: [ Tab, TabButton, TabHighlight, Tabs ], exports: [ Tab, TabButton, TabHighlight, Tabs ] },] }, ]; /** * @nocollapse */ TabsModule.ctorParameters = () => []; function TabsModule_tsickle_Closure_declarations() { /** @type {?} */ TabsModule.decorators; /** * @nocollapse * @type {?} */ TabsModule.ctorParameters; } //# sourceMappingURL=tabs.module.js.map