code stringlengths 2 1.05M |
|---|
const chalk = require('chalk')
/**
* Adds mark check symbol
*/
function addCheckMark(callback) {
process.stdout.write(chalk.green(' ✓'))
if (callback) callback()
}
module.exports = addCheckMark
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _deleteProperty = require('babel-runtime/core-js/reflect/delete-property');
var _deleteProperty2 = _interopRequireDefault(_deleteProperty);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _httpCore = require('@ciscospark/http-core');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pattern = /(?:^\/)|(?:\/$)/;
/**
* @class
*/
/**!
*
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
var UrlInterceptor = function (_Interceptor) {
(0, _inherits3.default)(UrlInterceptor, _Interceptor);
function UrlInterceptor() {
(0, _classCallCheck3.default)(this, UrlInterceptor);
return (0, _possibleConstructorReturn3.default)(this, (UrlInterceptor.__proto__ || (0, _getPrototypeOf2.default)(UrlInterceptor)).apply(this, arguments));
}
(0, _createClass3.default)(UrlInterceptor, [{
key: 'onRequest',
/**
* @see Interceptor#onRequest
* @param {Object} options
* @returns {Object}
*/
value: function onRequest(options) {
if (!options.uri) {
this.checkOptions(options);
this.normalizeOptions(options);
return this.spark.device.getServiceUrl(options.service).then(function (uri) {
if (!uri) {
return _promise2.default.reject(new Error('`' + options.service + '` is not a known service'));
}
// strip leading and trailing slashes before assembling the full uri
if (options.resource) {
uri = uri.replace(pattern, '') + '/' + options.resource.replace(pattern, '');
}
options.uri = uri;
return options;
});
}
return options;
}
/**
* Verify that all required parameters have been specified.
* @param {Object} options
* @returns {Object}
*/
}, {
key: 'checkOptions',
value: function checkOptions(options) {
if (!options.api && !options.service) {
throw new Error('A `service` or `uri` parameter is required');
}
if (!options.resource) {
throw new Error('A `resource` parameter is required');
}
}
/**
* accept api or service and rename to service
* @param {Object} options
* @private
* @returns {Object}
*/
}, {
key: 'normalizeOptions',
value: function normalizeOptions(options) {
if (options.service) {
return;
}
(0, _assign2.default)(options, {
service: options.service || options.api
});
(0, _deleteProperty2.default)(options, 'api');
}
}], [{
key: 'create',
/**
* @returns {UrlInterceptor}
*/
value: function create() {
/* eslint no-invalid-this: [0] */
return new UrlInterceptor({ spark: this });
}
}]);
return UrlInterceptor;
}(_httpCore.Interceptor);
exports.default = UrlInterceptor;
//# sourceMappingURL=url.js.map
|
var fs = require('fs');
var mongoose = require('mongoose');
var database = require('./database');
var debug = require('debug')('api');
var clicolour = require('cli-color');
var Apps = database.Apps;
// Done
function done(err, callback) {
}
// Main api
var api = {};
function removeFirst(string) {
if (typeof string !== undefined) {
return string.substring(1)
}
}
function initR(express, app) {
var appj = require(`${app.path}/jakhu.json`)
var appr = require(`${app.path}/${appj.main}`)
}
function init(app, func) {
// Search modules in
debug("Initializing api...");
debug("Creating custom express app object...")
var mapp = app
// Add func
for (var i in func) {
api[i] = func[i];
}
mapp.listen = undefined;
debug("Searching for modules in /app/usr/modules...")
debug("Reading module list in db...")
Apps.find(function (err, apps) {
// Check exist
debug("Checking if all apps exists...")
for (var i = 0; i < apps.length; i++) {
var appsp = apps[i]
appsp.path = removeFirst(appsp.path)
appsp.iconPath = removeFirst(appsp.iconPath)
var appj;
var appr;
try {
fs.statSync(`${appsp.path}`)
appj = require(`../${appsp.path}/jakhu.json`)
appr = require(`../${appsp.path}/${appj.main}`)
} catch(e) {
if(e.code === "ENOENT") {
debug(`Could not find app ${appsp.name}`);
if (!~process.env.DEBUG.indexOf('api')) {
console.log(clicolour.cyanBright("jakhu ") + clicolour.redBright("api:warn ") + `Could not find app ${appsp.name}`);
}
} else {
throw e
}
}
// EXEC init fun
debug("Initing modules")
appr.init(mapp, api, done)
};
})
}
module.exports = {init: init};
|
import { pushQuery, pushAdditional } from './helpers';
import { assign, isUndefined } from 'lodash'
// The "SchemaCompiler" takes all of the query statements which have been
// gathered in the "SchemaBuilder" and turns them into an array of
// properly formatted / bound query strings.
function SchemaCompiler(client, builder) {
this.builder = builder
this.client = client
this.schema = builder._schema;
this.formatter = client.formatter(builder)
this.sequence = []
}
assign(SchemaCompiler.prototype, {
pushQuery: pushQuery,
pushAdditional: pushAdditional,
createTable: buildTable('create'),
createTableIfNotExists: buildTable('createIfNot'),
alterTable: buildTable('alter'),
dropTablePrefix: 'drop table ',
dropTable(tableName) {
this.pushQuery(
this.dropTablePrefix + this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
},
dropTableIfExists(tableName) {
this.pushQuery(
this.dropTablePrefix + 'if exists ' +
this.formatter.wrap(prefixedTableName(this.schema, tableName))
);
},
raw(sql, bindings) {
this.sequence.push(this.client.raw(sql, bindings).toSQL());
},
toSQL() {
const sequence = this.builder._sequence;
for (let i = 0, l = sequence.length; i < l; i++) {
const query = sequence[i];
this[query.method].apply(this, query.args);
}
return this.sequence;
}
})
function buildTable(type) {
return function(tableName, fn) {
const builder = this.client.tableBuilder(type, tableName, fn);
// pass queryContext down to tableBuilder but do not overwrite it if already set
const queryContext = this.builder.queryContext();
if (!isUndefined(queryContext) && isUndefined(builder.queryContext())) {
builder.queryContext(queryContext);
}
builder.setSchema(this.schema);
const sql = builder.toSQL();
for (let i = 0, l = sql.length; i < l; i++) {
this.sequence.push(sql[i]);
}
};
}
function prefixedTableName(prefix, table) {
return prefix ? `${prefix}.${table}` : table;
}
export default SchemaCompiler;
|
import flatten from './flatten'
export default function flattenOften(arr, max) {
if (!(max > 0)) throw new Error("'max' must be a positive number")
let l = arr.length
arr = flatten(arr)
let round = 1
while (round < max && l < arr.length) {
l = arr.length
arr = flatten(arr)
round++
}
return arr
} |
Template.postSubscribe.helpers({
canSubscribe: function() {
// you cannot subscribe to your own posts
return Meteor.userId() && this.userId !== Meteor.userId();
},
subscribed: function() {
var user = Meteor.user();
if (!user) return false;
return _.include(this.subscribers, user._id);
}
});
Template.postSubscribe.events({
'click .subscribe-link': function(e, instance) {
e.preventDefault();
if (this.userId === Meteor.userId())
return;
var post = this;
if (!Meteor.user()) {
Router.go('atSignIn');
Messages.flash(i18n.t("please_log_in_first"), "info");
}
Meteor.call('subscribePost', post._id, function(error, result) {
if (result)
trackEvent("post subscribed", {'_id': post._id});
});
},
'click .unsubscribe-link': function(e, instance) {
e.preventDefault();
var post = this;
if (!Meteor.user()) {
Router.go('atSignIn');
Messages.flash(i18n.t("please_log_in_first"), "info");
}
Meteor.call('unsubscribePost', post._id, function(error, result) {
if (result)
trackEvent("post unsubscribed", {'_id': post._id});
});
}
});
|
'use strict';
/* jasmine specs for controllers go here */
describe('controllers', function(){
beforeEach(module('spApp'));
it('should ....', inject(function() {
//spec body
}));
it('should ....', inject(function() {
//spec body
}));
});
|
const should = require('should');
const supertest = require('supertest');
const testUtils = require('../../utils');
const config = require('../../../core/shared/config');
const localUtils = require('./utils');
describe('Email API', function () {
let request;
before(async function () {
await localUtils.startGhost();
request = supertest.agent(config.get('url'));
await localUtils.doAuth(request, 'posts', 'emails');
});
it('Can read an email', async function () {
const res = await request
.get(localUtils.API.getApiQuery(`emails/${testUtils.DataGenerator.Content.emails[0].id}/`))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200);
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.emails);
jsonResponse.emails.should.have.length(1);
localUtils.API.checkResponse(jsonResponse.emails[0], 'email');
});
});
|
import React from 'react'
import { shallow } from 'enzyme'
import sinon from 'sinon'
import MinimizeButton from '../EventsList/MinimizeButton'
import { Button } from 'reactstrap'
describe('<MinimizeButton />', () => {
const shallowRender = (props) => {
return shallow(
<MinimizeButton
{...props}
/>
)
}
const component = shallowRender({ toggleFilters: () => {} })
it('should render a button with id "minimize"', () => {
expect(component.find(Button)).toHaveLength(1)
expect(component.props().id).toEqual('minimize')
})
//// Not sure why this test is not working
// it('should get an onMinimize prop to be called upon click event', () => {
// const spy = sinon.spy()
// const component_ = shallowRender({ onMinimize: spy })
// component_.simulate('Click')
// expect(spy.calledOnce).toBe(true)
// })
})
|
describe('purlView', function() {
beforeEach(function() {
var that = this, done = false;
require(['purl', 'views/libs/purlView'], function(purl, purlView) {
that.purl = purl;
that.purlView = purlView;
done = true;
});
//等待初始化完成
waitsFor(function() {
return done;
}, "Create util");
});
afterEach(function() {
});
describe('链接参数测试', function() {
it('获取单个参数', function() {
var href = 'http://www.quyou.com/play/play.aspx?id=2818';
var attrs = this.purl(href).param();
expect(attrs['id']).toEqual('2818');
});
it('拼接链接', function() {
var href = 'http://www.quyou.com/play/play?id=2818&time=2';
var url = this.purl(href);
var attrs = url.param();
var host = url.attr('host');
var path = url.attr('path');
var query = [];
for(var key in attrs) {
query.push(key + '=' + attrs[key]);
}
expect('http://' + host + path + "?" + query.join('&')).toEqual(href);
});
it('没有P标签', function() {
var href = 'http://www.quyou.com/play/play.aspx';
var url = _getPageUrl(this, href);
expect(url).toEqual(href + '?p=1');
});
it('有P标签', function() {
var href = 'http://www.quyou.com/play/play.aspx?p=3';
var url = _getPageUrl(this, href);
expect(url).toEqual('http://www.quyou.com/play/play.aspx?p=2');
});
it('有P标签和其他标签', function() {
var href = escape('http://www.quyou.com/play/play.aspx?p=3&z=23&xx=pwewe&n=平稳');
var url = _getPageUrl(this, href);
expect(url).toEqual('http://www.quyou.com/play/play.aspx?p=2&z=23&xx=pwewe&n=%u5E73%u7A33');
});
function _getPageUrl(that, href) {
var url = that.purl(unescape(href));
var attrs = url.param();
var host = url.attr('host');
var path = url.attr('path');
var query = [];
var keys = _.keys(attrs);
if(!_.contains(keys, 'p')) {
query.push('p=1');
}else {
attrs['p'] = '2';
for(var key in attrs) {
query.push(key + '=' + escape(attrs[key]));
}
}
return 'http://' + host + path + "?" + query.join('&');
}
});
describe('getParamsValue', function() {
it('数字', function() {
var href = encodeURIComponent('http://www.quyou.com/play/play.aspx?p=3&z=23&xx=pwewe&n=平稳');
var p = this.purlView.getParamsValue('p', href);
expect(p).toEqual('3');
expect(p).toNotEqual(3);
});
it('中文', function() {
var href = encodeURIComponent('http://www.quyou.com/play/play.aspx?p=3&z=23&xx=pwewe&n=平稳');
var n = this.purlView.getParamsValue('n', href);
expect(n).toEqual('平稳');
});
it('不存在', function() {
var href = encodeURIComponent('http://www.quyou.com/play/play.aspx?p=3&z=23&xx=pwewe&n=平稳');
var y = this.purlView.getParamsValue('y', href);
expect(y).toEqual(undefined);
});
});
}); |
import * as t from 'constants/ActionTypes';
const initialState = {
/*
* comics = {
* "manhua-yiquanchaoren": [
* {
* title: "rtyukjkl"
* link: "sfdafg"
* cid: "asdfasdf",
* },
* {
* title: "rtyukjkl"
* link: "sfdafg"
* cid: "12333"
* }
* ]
* }
*/
comics: {},
chapters: [],
/*
*
readingChapters = [
{
cid: "",
images: [
]
}
]
*/
readingChapters: [],
readingChapterID: null,
/*
* readingImages is an array of array
[
// chapter 1
[
"image1",
"image2",
"image3",
],
// chapter 2
[
"image1",
"image2",
"image3",
],
]
*/
readingImages: [],
flattenReadingImages: [],
readingIndex: null,
appBarTitle: 'Loading...',
comicName: null,
comicManager: null
};
export default function comics(state = initialState, action) {
switch(action.type) {
case t.LOAD_NEXT_CHAPTER:
return state;
case t.LOAD_PREVIOUS_CHAPTER:
return state;
case t.SWITCH_CHAPTER:
// var flatten = action.readingImages.reduce((prev, cur) => {
// return prev.concat(cur);
// }, []);
return {
...state,
readingChapters: action.readingChapters,
readingImages: action.readingImages,
appBarTitle: action.appBarTitle,
readingChapterID: action.readingChapterID
// flattenReadingImages: flatten
};
case t.CLEAR_COMIC_IMAGES:
return {
...state,
readingImages: [],
readingChapterID: null,
appBarTitle: 'Loading...'
};
case t.INIT_COMIC_MANAGER:
return {
...state,
chapters: action.chapters,
comicManager: action.comicManager,
comicID: action.comicID,
comics: {
...comics,
[action.comicID]: action.chapters
}
};
case t.SET_COMIC_NAME:
return {
...state,
comicName: action.comicName
};
default:
return state;
}
}
|
function FizzBuzz() {
this.respond = function(i) {
return i % 3 === 0;
};
};
var fizzbuzz = new FizzBuzz;
var a = prompt("Please enter a number");
a = parseInt(a);
var output = fizzbuzz.respond(a).toString();
alert("Divisible by 3? " + output); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M18 11c.34 0 .67.03 1 .08V4c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h7.26c-.79-1.13-1.26-2.51-1.26-4 0-3.87 3.13-7 7-7zm-10.24-.45c-.34.2-.76-.04-.76-.43V4h5v6.12c0 .39-.42.63-.76.43L9.5 9.5l-1.74 1.05z"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M18 13c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm-1.25 6.6v-3.2c0-.39.43-.63.76-.42l2.56 1.6c.31.2.31.65 0 .85l-2.56 1.6c-.33.2-.76-.04-.76-.43z"
}, "1")], 'PlayLessonRounded');
exports.default = _default; |
PieceFunctions.newPiece = function ($el){
this.functions = PieceFunctions;
if (!!$el){
this.$el = $el;
this.side = $el.data('side');
this.type = $el.data('type');
}
this.getImage = function(){
}
this.img = this.getImage(this.type, this.side);
this.$el;
this.assign$El = function($el){
this.$el = $el;
}
return this;
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7 16V8l-4 4zm4-9h10v2H11zm0 4h10v2H11zm0 4h10v2H11zm-8 4h18v2H3zM3 3h18v2H3z" />
, 'FormatIndentDecreaseTwoTone');
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global','./library','sap/ui/core/LayoutData'],function(q,l,L){"use strict";var T=L.extend("sap.m.ToolbarLayoutData",{metadata:{library:"sap.m",properties:{shrinkable:{type:"boolean",group:"Behavior",defaultValue:false},minWidth:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:null},maxWidth:{type:"sap.ui.core.CSSSize",group:"Dimension",defaultValue:null}}}});T.prototype.getParentStyle=function(){var p=this.getParent();if(!p||!p.getDomRef){return{};}var d=p.getDomRef();return d?d.style:{};};T.prototype.applyProperties=function(){var s=this.getParentStyle();s.minWidth=this.getMinWidth();s.maxWidth=this.getMaxWidth();return this;};return T;},true);
|
import cx from 'classnames'
import _ from 'lodash'
import React, { Component, PropTypes } from 'react'
import {
customPropTypes,
createShorthandFactory,
getElementType,
getUnhandledProps,
makeDebugger,
META,
SUI,
useKeyOnly,
useKeyOrValueAndKey,
useValueAndKey,
} from '../../lib'
import Icon from '../Icon/Icon'
import Label from '../Label/Label'
import ButtonContent from './ButtonContent'
import ButtonGroup from './ButtonGroup'
import ButtonOr from './ButtonOr'
const debug = makeDebugger('button')
/**
* A Button indicates a possible user action.
* @see Form
* @see Icon
* @see Label
*/
class Button extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A button can show it is currently the active user selection. */
active: PropTypes.bool,
/** A button can animate to show hidden content. */
animated: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.oneOf(['fade', 'vertical']),
]),
/** A button can be attached to the top or bottom of other content. */
attached: PropTypes.oneOf(['left', 'right', 'top', 'bottom']),
/** A basic button is less pronounced. */
basic: PropTypes.bool,
/** Primary content. */
children: customPropTypes.every([
PropTypes.node,
customPropTypes.disallow(['label']),
customPropTypes.givenProps(
{
icon: PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.object.isRequired,
PropTypes.element.isRequired,
]),
},
customPropTypes.disallow(['icon']),
),
]),
/** Additional classes. */
className: PropTypes.string,
/** A button can be circular. */
circular: PropTypes.bool,
/** A button can have different colors */
color: PropTypes.oneOf([
...SUI.COLORS,
'facebook', 'google plus', 'instagram', 'linkedin', 'twitter', 'vk', 'youtube',
]),
/** A button can reduce its padding to fit into tighter spaces. */
compact: PropTypes.bool,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/** A button can show it is currently unable to be interacted with. */
disabled: PropTypes.bool,
/** A button can be aligned to the left or right of its container. */
floated: PropTypes.oneOf(SUI.FLOATS),
/** A button can take the width of its container. */
fluid: PropTypes.bool,
/** Add an Icon by name, props object, or pass an <Icon />. */
icon: customPropTypes.some([
PropTypes.bool,
PropTypes.string,
PropTypes.object,
PropTypes.element,
]),
/** A button can be formatted to appear on dark backgrounds. */
inverted: PropTypes.bool,
/** Add a Label by text, props object, or pass a <Label />. */
label: customPropTypes.some([
PropTypes.string,
PropTypes.object,
PropTypes.element,
]),
/** A labeled button can format a Label or Icon to appear on the left or right. */
labelPosition: PropTypes.oneOf(['right', 'left']),
/** A button can show a loading indicator. */
loading: PropTypes.bool,
/** A button can hint towards a negative consequence. */
negative: PropTypes.bool,
/**
* Called after user's click.
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: PropTypes.func,
/** A button can hint towards a positive consequence. */
positive: PropTypes.bool,
/** A button can be formatted to show different levels of emphasis. */
primary: PropTypes.bool,
/** A button can be formatted to show different levels of emphasis. */
secondary: PropTypes.bool,
/** A button can have different sizes. */
size: PropTypes.oneOf(SUI.SIZES),
/** A button can receive focus. */
tabIndex: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
/** A button can be formatted to toggle on and off. */
toggle: PropTypes.bool,
}
static defaultProps = {
as: 'button',
}
static _meta = {
name: 'Button',
type: META.TYPES.ELEMENT,
}
static Content = ButtonContent
static Group = ButtonGroup
static Or = ButtonOr
handleClick = (e) => {
const { disabled, onClick } = this.props
if (disabled) {
e.preventDefault()
return
}
if (onClick) onClick(e, this.props)
}
computeTabIndex = ElementType => {
const { disabled, tabIndex } = this.props
if (!_.isNil(tabIndex)) return tabIndex
if (disabled) return -1
if (ElementType === 'div') return 0
}
render() {
const {
active,
animated,
attached,
basic,
children,
circular,
className,
color,
compact,
content,
disabled,
floated,
fluid,
icon,
inverted,
label,
labelPosition,
loading,
negative,
positive,
primary,
secondary,
size,
toggle,
} = this.props
const labeledClasses = cx(
useKeyOrValueAndKey(labelPosition || !!label, 'labeled'),
)
const baseClasses = cx(
color,
size,
useKeyOnly(active, 'active'),
useKeyOnly(basic, 'basic'),
useKeyOnly(circular, 'circular'),
useKeyOnly(compact, 'compact'),
useKeyOnly(disabled, 'disabled'),
useKeyOnly(fluid, 'fluid'),
useKeyOnly(icon === true || icon && (labelPosition || !children && !content), 'icon'),
useKeyOnly(inverted, 'inverted'),
useKeyOnly(loading, 'loading'),
useKeyOnly(negative, 'negative'),
useKeyOnly(positive, 'positive'),
useKeyOnly(primary, 'primary'),
useKeyOnly(secondary, 'secondary'),
useKeyOnly(toggle, 'toggle'),
useKeyOrValueAndKey(animated, 'animated'),
useKeyOrValueAndKey(attached, 'attached'),
useValueAndKey(floated, 'floated'),
)
const rest = getUnhandledProps(Button, this.props)
const ElementType = getElementType(Button, this.props, () => {
if (!_.isNil(label) || !_.isNil(attached)) return 'div'
})
const tabIndex = this.computeTabIndex(ElementType)
if (!_.isNil(children)) {
const classes = cx('ui', baseClasses, labeledClasses, 'button', className)
debug('render children:', { classes })
return (
<ElementType {...rest} className={classes} tabIndex={tabIndex} onClick={this.handleClick}>
{children}
</ElementType>
)
}
const labelElement = Label.create(label, {
basic: true,
pointing: labelPosition === 'left' ? 'right' : 'left',
})
if (labelElement) {
const classes = cx('ui', baseClasses, 'button', className)
const containerClasses = cx('ui', labeledClasses, 'button', className)
debug('render label:', { classes, containerClasses }, this.props)
return (
<ElementType {...rest} className={containerClasses} onClick={this.handleClick}>
{labelPosition === 'left' && labelElement}
<button className={classes}>
{Icon.create(icon)} {content}
</button>
{(labelPosition === 'right' || !labelPosition) && labelElement}
</ElementType>
)
}
if (!_.isNil(icon) && _.isNil(label)) {
const classes = cx('ui', labeledClasses, baseClasses, 'button', className)
debug('render icon && !label:', { classes })
return (
<ElementType {...rest} className={classes} tabIndex={tabIndex} onClick={this.handleClick}>
{Icon.create(icon)} {content}
</ElementType>
)
}
const classes = cx('ui', labeledClasses, baseClasses, 'button', className)
debug('render default:', { classes })
return (
<ElementType {...rest} className={classes} tabIndex={tabIndex} onClick={this.handleClick}>
{content}
</ElementType>
)
}
}
Button.create = createShorthandFactory(Button, value => ({ content: value }))
export default Button
|
/*
*
* LearningToCode constants
*
*/
export const DEFAULT_ACTION = 'app/LearningToCode/DEFAULT_ACTION';
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 9.58c-2.95 0-5.47 1.83-6.5 4.41h13c-1.03-2.58-3.55-4.41-6.5-4.41z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M2 17h20v2H2zm11.84-9.21c.1-.24.16-.51.16-.79 0-1.1-.9-2-2-2s-2 .9-2 2c0 .28.06.55.16.79C6.25 8.6 3.27 11.93 3 16h18c-.27-4.07-3.25-7.4-7.16-8.21zM12 9.58c2.95 0 5.47 1.83 6.5 4.41h-13c1.03-2.58 3.55-4.41 6.5-4.41z"
}, "1")], 'RoomServiceTwoTone');
exports.default = _default; |
module.exports={A:{A:{"2":"K D G E A B hB"},B:{"2":"2 C d J M H I"},C:{"1":"3 4 CB FB","2":"0 1 2 6 7 8 9 eB DB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB BB YB XB"},D:{"1":"RB MB LB kB JB NB OB PB","2":"0 1 2 3 4 6 7 8 9 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z HB GB BB CB FB"},E:{"1":"5 C p ZB","2":"F N K D G E A QB IB SB TB UB VB WB","132":"B"},F:{"1":"0 1 z","2":"5 6 E B C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y aB bB cB dB p AB fB"},G:{"1":"rB sB tB","2":"G IB gB EB iB jB KB lB mB nB oB pB","132":"qB"},H:{"2":"uB"},I:{"1":"4","2":"DB F vB wB xB yB EB zB 0B"},J:{"2":"D A"},K:{"2":"5 A B C L p AB"},L:{"1":"JB"},M:{"1":"3"},N:{"2":"A B"},O:{"2":"1B"},P:{"2":"F 2B 3B 4B 5B 6B"},Q:{"2":"7B"},R:{"2":"8B"},S:{"2":"9B"}},B:7,C:"CSS Environment Variables env()"};
|
// Generated by CoffeeScript 1.6.2
var error;
try {
allHellBreaksLoose();
catsAndDogsLivingTogether();
} catch (_error) {
error = _error;
print(error);
} finally {
cleanUp();
}
|
/**
* Disable all fitting logic.
*
* @type {number}
*/
export const FITTING_NONE = 0;
/**
* Stretch child elements to fit the parent container.
*
* @type {number}
*/
export const FITTING_STRETCH = 1;
/**
* Shrink child elements to fit the parent container.
*
* @type {number}
*/
export const FITTING_SHRINK = 2;
/**
* Apply both STRETCH and SHRINK fitting logic where applicable.
*
* @type {number}
*/
export const FITTING_BOTH = 3;
|
describe('loginCtrl', function () {
var $rootScope, $q, deferred, $scope, store, $state, spy, socket, createController, auth, Auth,$ionicHistory, $http, $httpBackend, $controller;
beforeEach(module('app'));
beforeEach(inject(function ($injector) {
$q = $injector.get('$q');
deferred = $q.defer();
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
store = $injector.get('store');
auth = $injector.get('auth');
$ionicHistory = $injector.get('$ionicHistory');
$http = $injector.get('$http');
$controller = $injector.get('$controller');
$state = $injector.get('$state');
Auth = $injector.get('Auth');
socket = $injector.get('socket');
spy = spyOn($state, 'go');
createController = function () {
return $controller('loginCtrl', {
$rootScope: $rootScope,
$scope: $scope,
store: store,
auth: auth,
$ionicHistory: $ionicHistory,
$http: $http,
$state: $state,
Auth: Auth,
socket: socket
});
};
}));
beforeEach(function () {
createController();
});
describe('#login', function() {
it('should have a login method on the $scope', function () {
expect($scope.login).toEqual(jasmine.any(Function));
});
it('if successful, should change to state to main', function(done) {
deferred.resolve($state.go('main'));
$scope.login();
expect(spy).toHaveBeenCalledWith('main');
done();
});
it('if failure, should change state to login', function(done) {
deferred.reject($state.go('login'));
expect(spy).toHaveBeenCalledWith('login');
done();
});
});
describe('#logout', function () {
it('should have a logout method on the $scope', function () {
expect($scope.logout).toEqual(jasmine.any(Function));
});
it('should call logout when account is logged out', function () {
$scope.logout();
expect(spy).toHaveBeenCalledWith('login');
});
});
});
|
// For the examples, make sure that the output is stable
var consoleLog = console.log
var stringify = require('json-stable-stringify')
console.log = function () {
consoleLog.apply(this, Array.prototype.map.call(
arguments, (arg) => stringify(arg, { space: 2 })
))
}
|
import { approxDeepEqual } from '../../assert'
import transform from '../../../src/path/transform'
import encoder from '../../../src/path/encoder'
import lineToCurve from '../../../src/path/transformers/line-to-curve'
describe('lineToCurve()', function()
{
})
|
(function() {
'use strict';
angular
.module('app.user')
.controller('ChangePasswordController', ChangePasswordController);
ChangePasswordController.$inject = ['$location', '$rootScope', 'dataService'];
function ChangePasswordController($location, $rootScope, dataService) {
var vm = this;
vm.generalError = false;
vm.requestReset = requestReset;
vm.resetError = false;
vm.resetPassword = resetPassword;
vm.resetSuccess = false;
vm.submitChangePassword = submitChangePassword;
vm.users = {
username: $rootScope.username
};
activate();
////////////////////////////////////////////////////////////////////////////
// FUNCTIONS //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/**
* Prepare the page.
*/
function activate() {
// Start focus on appropriate field
$("input[name='username']").focus();
if ($location.path() === '/change-password') {
$("input[name='oldPassword']").focus();
}
// Hide mismatch error when user acknowledges
$("#pw-mismatch-btn").on("click", function() {
$(".wrapper").removeClass("openerror");
$("#pw-mismatch-modal").addClass("inactive");
});
// Hide incorrect password modal after user acknowledges
$("#incorrect-pw-btn").on("click", function() {
$(".wrapper").removeClass("openerror");
$("#incorrect-pw-modal").addClass("inactive");
});
// Hide password change success modal when user acknowledges
$("#pw-success-btn").on("click", function() {
$(".wrapper").removeClass("openerror");
$("#pw-success-modal").addClass("inactive");
});
}
/**
* Submit the entered username for password reset.
*/
function requestReset() {
// Reset the flags
vm.resetError = false;
vm.resetSuccess = false;
vm.generalError = false;
dataService.post('/api/get-reset/', vm.users)
.then(successCallbackRequestReset, errorCallbackRequestReset);
function errorCallbackRequestReset() {
// TODO: Convert to modal?
vm.generalError = true;
}
function successCallbackRequestReset(response) {
if (response.data) {
vm.resetError = true;
return;
}
vm.resetSuccess = true;
}
}
/**
* If the passwords match, attempt to update password.
*
* @param {boolean} mismatch Were the two passwords entered different?
*/
function resetPassword(mismatch) {
if (mismatch) {
// Show password mismatch modal
$(".wrapper").addClass("openerror");
$("#pw-mismatch-modal").removeClass("inactive");
return;
}
dataService.post('/api/reset-pw/', vm.users)
.then(successCallbackResetPassword, errorCallbackResetPassword);
function errorCallbackResetPassword(response) {
// TODO: What is this error handling mechanism, and why is it used
// here and not other places?
$rootScope.errorMessage = response.data;
}
function successCallbackResetPassword(response) {
dataService.setCredentials(response.data.token);
// Reset the users property and navigate to the root of the app
vm.users = {};
$location.path('/');
}
}
/**
* If the passwords match, attempt to update password.
*
* @param {boolean} mismatch Do the two entered new passwords differ?
*/
function submitChangePassword(mismatch) {
if (mismatch) {
// Show password mismatch modal
$(".wrapper").addClass("openerror");
$("#pw-mismatch-modal").removeClass("inactive");
return;
}
vm.users.username = $rootScope.username;
dataService.post('/api/change-pw/', vm.users)
.then(successCallbackChangePassword, errorCallbackChangePassword);
function errorCallbackChangePassword() {
// Show error changing password modal
$(".wrapper").addClass("openerror");
$("#incorrect-pw-modal").removeClass("inactive");
// Reset users data
vm.users = {};
}
function successCallbackChangePassword() {
// Show password change success modal
$(".wrapper").addClass("openerror");
$("#pw-success-modal").removeClass("inactive");
// Navigate to the root of the app
$location.path('/');
}
}
}
})();
|
import { nodeList } from "../dom/node_list";
var splitNode = function(pivot) {
if (pivot.nextSibling) {
var parent = pivot.parentNode;
var fork = document.createElement(parent.nodeName);
var childNodes = nodeList.toArray(parent.childNodes);
childNodes = childNodes.slice(childNodes.indexOf(pivot) + 1);
childNodes.forEach(function(node) {
fork.appendChild(node);
});
parent.parentNode.insertBefore(fork, parent.nextSibling);
return fork;
}
return null;
};
export { splitNode };
|
(function() {
'use strict';
describe('Routing', function() {
var state;
beforeEach(module('myApp'));
beforeEach(inject(function ($state) {
state = $state;
}));
it('State 1 url should be /state1', function () {
var config = state.get('state1');
expect(config.url).toBe('/state1');
});
});
})(); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m12 6-2-2H2v16h20V6H12zm7 11h-6V9h3.5l2.5 2.5V17zm-3.12-6.5 1.62 1.62v3.38h-3v-5h1.38z"
}), 'SnippetFolderSharp');
exports.default = _default; |
require('./lib/newrelic');
require('./lib/underscore');
var express = require('express'),
fs = require('fs'),
path = require('path')
;
global.Project = {};
global.app = express();
Project.root_path = __dirname;
require('./config/application.js').configure({
express: express,
paths: {
controllers: path.join(Project.root_path, 'app', 'controllers'),
models: path.join(Project.root_path, 'app', 'models'),
views: path.join(Project.root_path, 'app', 'views'),
assets: path.join(Project.root_path, 'app', 'assets'),
public: path.join(Project.root_path, 'public'),
config: path.join(Project.root_path, 'config'),
lib: path.join(Project.root_path, 'lib')
}
}).listen(app.get('port'), function(){
console.log('running on %s', app.get('port'))
});
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('route:curriculum-inventory-sequence-block', 'Unit | Route | curriculum inventory sequence block', {
needs: ['service:currentUser', 'service:iliosMetrics', 'service:headData', 'service:session'],
});
test('it exists', function(assert) {
let route = this.subject();
assert.ok(route);
});
|
//# Bootstrap row with auto clearfix control
var React = require('react');///addons
module.exports = function (props) {
var items = [];
var xs_row = 0;
var sm_row = 0;
var md_row = 0;
var lg_row = 0;
React.Children.forEach(props.children, function (child, index){
var xs = 12;
var sm = 12;
var md = 12;
var lg = 12;
//# calculate columns of the element in each range
if(child.props.xs){
xs = child.props.xs;
sm = child.props.xs;
md = child.props.xs;
lg = child.props.xs;
}
if(child.props.sm){
sm = child.props.sm;
md = child.props.sm;
lg = child.props.sm;
}
if(child.props.md){
md = child.props.md;
lg = child.props.md;
}
if(child.props.lg){
lg = child.props.lg;
}
//# add child
items.push(child);
//# add clearfixes if needed
if(!props.noClearfix){
xs_row = xs_row + parseInt(xs);
sm_row = sm_row + parseInt(sm);
md_row = md_row + parseInt(md);
lg_row = lg_row + parseInt(lg);
if(xs_row >= 12){
xs_row = 0;
items.push(<div key={index+'xs'} className="clearfix visible-xs-block"/>);
}
if(sm_row >= 12){
sm_row = 0;
items.push(<div key={index+'sm'} className="clearfix visible-sm-block"/>);
}
if(md_row >= 12){
md_row = 0;
items.push(<div key={index+'md'} className="clearfix visible-md-block"/>);
}
if(lg_row >= 12){
lg_row = 0;
items.push(<div key={index+'lg'} className="clearfix visible-lg-block"/>);
}
}
})
var className = props.className ? props.className : '';
return (
<div className={className + ' row'}>
{items}
</div>
)
} |
'use strict'
var inherits = require('inherits')
var AbstractIterator = require('abstract-leveldown').AbstractIterator
var createKeyRange = require('./util/key-range')
var deserialize = require('./util/deserialize')
var noop = function () {}
module.exports = Iterator
function Iterator (db, location, options) {
AbstractIterator.call(this, db)
this._limit = options.limit
this._count = 0
this._callback = null
this._cache = []
this._completed = false
this._aborted = false
this._error = null
this._transaction = null
this._keys = options.keys
this._values = options.values
this._keyAsBuffer = options.keyAsBuffer
this._valueAsBuffer = options.valueAsBuffer
if (this._limit === 0) {
this._completed = true
return
}
try {
var keyRange = createKeyRange(options)
} catch (e) {
// The lower key is greater than the upper key.
// IndexedDB throws an error, but we'll just return 0 results.
this._completed = true
return
}
this.createIterator(location, keyRange, options.reverse)
}
inherits(Iterator, AbstractIterator)
Iterator.prototype.createIterator = function (location, keyRange, reverse) {
var self = this
var transaction = this.db.db.transaction([location], 'readonly')
var store = transaction.objectStore(location)
var req = store.openCursor(keyRange, reverse ? 'prev' : 'next')
req.onsuccess = function (ev) {
var cursor = ev.target.result
if (cursor) self.onItem(cursor)
}
this._transaction = transaction
// If an error occurs (on the request), the transaction will abort.
transaction.onabort = function () {
self.onAbort(self._transaction.error || new Error('aborted by user'))
}
transaction.oncomplete = function () {
self.onComplete()
}
}
Iterator.prototype.onItem = function (cursor) {
this._cache.push(cursor.key, cursor.value)
if (this._limit <= 0 || ++this._count < this._limit) {
cursor.continue()
}
this.maybeNext()
}
Iterator.prototype.onAbort = function (err) {
this._aborted = true
this._error = err
this.maybeNext()
}
Iterator.prototype.onComplete = function () {
this._completed = true
this.maybeNext()
}
Iterator.prototype.maybeNext = function () {
if (this._callback) {
this._next(this._callback)
this._callback = null
}
}
Iterator.prototype._next = function (callback) {
if (this._aborted) {
// The error should be picked up by either next() or end().
var err = this._error
this._error = null
this._nextTick(callback, err)
} else if (this._cache.length > 0) {
var key = this._cache.shift()
var value = this._cache.shift()
if (this._keys && key !== undefined) {
key = this._deserializeKey(key, this._keyAsBuffer)
} else {
key = undefined
}
if (this._values && value !== undefined) {
value = this._deserializeValue(value, this._valueAsBuffer)
} else {
value = undefined
}
this._nextTick(callback, null, key, value)
} else if (this._completed) {
this._nextTick(callback)
} else {
this._callback = callback
}
}
// Exposed for the v4 to v5 upgrade utility
Iterator.prototype._deserializeKey = deserialize
Iterator.prototype._deserializeValue = deserialize
Iterator.prototype._end = function (callback) {
if (this._aborted || this._completed) {
return this._nextTick(callback, this._error)
}
// Don't advance the cursor anymore, and the transaction will complete
// on its own in the next tick. This approach is much cleaner than calling
// transaction.abort() with its unpredictable event order.
this.onItem = noop
this.onAbort = callback
this.onComplete = callback
}
|
"use strict";
const should = require("should");
const Parser = require("../lib/Parser");
const BasicEvaluatedExpression = require("../lib/BasicEvaluatedExpression");
describe("Parser", () => {
const testCases = {
"call ident": [
function() {
abc("test");
}, {
abc: ["test"]
}
],
"call member": [
function() {
cde.abc("membertest");
}, {
cdeabc: ["membertest"]
}
],
"call member using bracket notation": [
function() {
cde["abc"]("membertest");
}, {
cdeabc: ["membertest"]
}
],
"call inner member": [
function() {
cde.ddd.abc("inner");
}, {
cdedddabc: ["inner"]
}
],
"call inner member using bracket notation": [
function() {
cde.ddd["abc"]("inner");
}, {
cdedddabc: ["inner"]
}
],
"expression": [
function() {
fgh;
}, {
fgh: [""]
}
],
"expression sub": [
function() {
fgh.sub;
}, {
fghsub: ["notry"]
}
],
"member expression": [
function() {
test[memberExpr]
test[+memberExpr]
}, {
expressions: ["memberExpr", "memberExpr"]
}
],
"in function definition": [
function() {
(function(abc, cde, fgh) {
abc("test");
cde.abc("test");
cde.ddd.abc("test");
fgh;
fgh.sub;
})();
}, {}
],
"const definition": [
function() {
let abc, cde, fgh;
abc("test");
cde.abc("test");
cde.ddd.abc("test");
fgh;
fgh.sub;
}, {}
],
"var definition": [
function() {
var abc, cde, fgh;
abc("test");
cde.abc("test");
cde.ddd.abc("test");
fgh;
fgh.sub;
}, {}
],
"function definition": [
function() {
function abc() {}
function cde() {}
function fgh() {}
abc("test");
cde.abc("test");
cde.ddd.abc("test");
fgh;
fgh.sub;
}, {}
],
"in try": [
function() {
try {
fgh.sub;
fgh;
function test(ttt) {
fgh.sub;
fgh;
}
} catch(e) {
fgh.sub;
fgh;
}
}, {
fghsub: ["try", "notry", "notry"],
fgh: ["test", "test ttt", "test e"]
}
],
"renaming with const": [
function() {
const xyz = abc;
xyz("test");
}, {
abc: ["test"]
}
],
"renaming with var": [
function() {
var xyz = abc;
xyz("test");
}, {
abc: ["test"]
}
],
"renaming with assignment": [
function() {
const xyz = abc;
xyz("test");
}, {
abc: ["test"]
}
],
"renaming with IIFE": [
function() {
! function(xyz) {
xyz("test");
}(abc);
}, {
abc: ["test"]
}
],
"renaming with IIFE (called)": [
function() {
! function(xyz) {
xyz("test");
}.call(fgh, abc);
}, {
abc: ["test"],
fgh: [""]
}
],
};
Object.keys(testCases).forEach((name) => {
it("should parse " + name, () => {
let source = testCases[name][0].toString();
source = source.substr(13, source.length - 14).trim();
const state = testCases[name][1];
const testParser = new Parser({});
testParser.plugin("can-rename abc", (expr) => true);
testParser.plugin("call abc", (expr) => {
if(!testParser.state.abc) testParser.state.abc = [];
testParser.state.abc.push(testParser.parseString(expr.arguments[0]));
return true;
});
testParser.plugin("call cde.abc", (expr) => {
if(!testParser.state.cdeabc) testParser.state.cdeabc = [];
testParser.state.cdeabc.push(testParser.parseString(expr.arguments[0]));
return true;
});
testParser.plugin("call cde.ddd.abc", (expr) => {
if(!testParser.state.cdedddabc) testParser.state.cdedddabc = [];
testParser.state.cdedddabc.push(testParser.parseString(expr.arguments[0]));
return true;
});
testParser.plugin("expression fgh", (expr) => {
if(!testParser.state.fgh) testParser.state.fgh = [];
testParser.state.fgh.push(testParser.scope.definitions.join(" "));
return true;
});
testParser.plugin("expression fgh.sub", (expr) => {
if(!testParser.state.fghsub) testParser.state.fghsub = [];
testParser.state.fghsub.push(testParser.scope.inTry ? "try" : "notry");
return true;
});
testParser.plugin("expression memberExpr", (expr) => {
if(!testParser.state.expressions) testParser.state.expressions = [];
testParser.state.expressions.push(expr.name);
return true;
});
const actual = testParser.parse(source);
should.strictEqual(typeof actual, "object");
actual.should.be.eql(state);
});
});
it("should parse comments", () => {
const source = "//comment1\n/*comment2*/";
const state = [{
type: "Line",
value: "comment1"
}, {
type: "Block",
value: "comment2"
}];
const testParser = new Parser({});
testParser.plugin("program", (ast, comments) => {
if(!testParser.state.comments) testParser.state.comments = comments;
return true;
});
const actual = testParser.parse(source);
should.strictEqual(typeof actual, "object");
should.strictEqual(typeof actual.comments, "object");
actual.comments.forEach((element, index) => {
should.strictEqual(typeof element.type, "string");
should.strictEqual(typeof element.value, "string");
element.type.should.be.eql(state[index].type);
element.value.should.be.eql(state[index].value);
});
});
describe("expression evaluation", () => {
function evaluateInParser(source) {
const parser = new Parser();
parser.plugin("call test", (expr) => {
parser.state.result = parser.evaluateExpression(expr.arguments[0]);
});
parser.plugin("evaluate Identifier aString", (expr) =>
new BasicEvaluatedExpression().setString("aString").setRange(expr.range));
parser.plugin("evaluate Identifier b.Number", (expr) =>
new BasicEvaluatedExpression().setNumber(123).setRange(expr.range));
return parser.parse("test(" + source + ");").result;
}
const testCases = {
"\"strrring\"": "string=strrring",
"\"strr\" + \"ring\"": "string=strrring",
"\"s\" + (\"trr\" + \"rin\") + \"g\"": "string=strrring",
"'S' + (\"strr\" + \"ring\") + 'y'": "string=Sstrrringy",
"/abc/": "regExp=/abc/",
"1": "number=1",
"1 + 3": "number=4",
"3 - 1": "number=2",
"1 == 1": "bool=true",
"1 === 1": "bool=true",
"3 != 1": "bool=true",
"3 !== 1": "bool=true",
"3 == 1": "bool=false",
"3 === 1": "bool=false",
"1 != 1": "bool=false",
"1 !== 1": "bool=false",
"true === false": "bool=false",
"false !== false": "bool=false",
"true == true": "bool=true",
"false != true": "bool=true",
"!'a'": "bool=false",
"!''": "bool=true",
"'pre' + a": "wrapped=['pre' string=pre]+[null]",
"a + 'post'": "wrapped=[null]+['post' string=post]",
"'pre' + a + 'post'": "wrapped=['pre' string=pre]+['post' string=post]",
"1 + a + 2": "",
"1 + a + 'post'": "wrapped=[null]+['post' string=post]",
"'' + 1 + a + 2": "wrapped=['' + 1 string=1]+[2 string=2]",
"'' + 1 + a + 2 + 3": "wrapped=['' + 1 string=1]+[2 + 3 string=23]",
"'' + 1 + a + (2 + 3)": "wrapped=['' + 1 string=1]+[2 + 3 string=5]",
"'pre' + (1 + a) + (2 + 3)": "wrapped=['pre' string=pre]+[2 + 3 string=5]",
"a ? 'o1' : 'o2'": "options=['o1' string=o1],['o2' string=o2]",
"a ? 'o1' : b ? 'o2' : 'o3'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3]",
"a ? (b ? 'o1' : 'o2') : 'o3'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3]",
"a ? (b ? 'o1' : 'o2') : c ? 'o3' : 'o4'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3],['o4' string=o4]",
"a ? 'o1' : b ? 'o2' : c ? 'o3' : 'o4'": "options=['o1' string=o1],['o2' string=o2],['o3' string=o3],['o4' string=o4]",
"a ? 'o1' : b ? b : c ? 'o3' : c": "options=['o1' string=o1],[b],['o3' string=o3],[c]",
"['i1', 'i2', 3, a, b ? 4 : 5]": "items=['i1' string=i1],['i2' string=i2],[3 number=3],[a],[b ? 4 : 5 options=[4 number=4],[5 number=5]]",
"typeof 'str'": "string=string",
"typeof aString": "string=string",
"typeof b.Number": "string=number",
"typeof b['Number']": "string=number",
"typeof b[Number]": "",
"b.Number": "number=123",
"b['Number']": "number=123",
"b[Number]": "",
"'abc'.substr(1)": "string=bc",
"'abcdef'.substr(2, 3)": "string=cde",
"'abcdef'.substring(2, 3)": "string=c",
"'abcdef'.substring(2, 3, 4)": "",
"'abc'[\"substr\"](1)": "string=bc",
"'abc'[substr](1)": "",
"'1,2+3'.split(/[,+]/)": "array=[1],[2],[3]",
"'1,2+3'.split(expr)": "",
"'a' + (expr + 'c')": "wrapped=['a' string=a]+['c' string=c]",
"1 + 'a'": "string=1a",
"'a' + 1": "string=a1",
"'a' + expr + 1": "wrapped=['a' string=a]+[1 string=1]",
};
Object.keys(testCases).forEach((key) => {
function evalExprToString(evalExpr) {
if(!evalExpr) {
return "null";
} else {
const result = [];
if(evalExpr.isString()) result.push("string=" + evalExpr.string);
if(evalExpr.isNumber()) result.push("number=" + evalExpr.number);
if(evalExpr.isBoolean()) result.push("bool=" + evalExpr.bool);
if(evalExpr.isRegExp()) result.push("regExp=" + evalExpr.regExp);
if(evalExpr.isConditional()) result.push("options=[" + evalExpr.options.map(evalExprToString).join("],[") + "]");
if(evalExpr.isArray()) result.push("items=[" + evalExpr.items.map(evalExprToString).join("],[") + "]");
if(evalExpr.isConstArray()) result.push("array=[" + evalExpr.array.join("],[") + "]");
if(evalExpr.isWrapped()) result.push("wrapped=[" + evalExprToString(evalExpr.prefix) + "]+[" + evalExprToString(evalExpr.postfix) + "]");
if(evalExpr.range) {
const start = evalExpr.range[0] - 5;
const end = evalExpr.range[1] - 5;
return key.substr(start, end - start) + (result.length > 0 ? " " + result.join(" ") : "");
}
return result.join(" ");
}
}
it("should eval " + key, () => {
const evalExpr = evaluateInParser(key);
evalExprToString(evalExpr).should.be.eql(testCases[key] ? key + " " + testCases[key] : key);
});
});
});
describe("async/await support", () => {
describe("should accept", () => {
const cases = {
"async function": "async function x() {}",
"async arrow function": "async () => {}",
"await expression": "async function x(y) { await y }"
};
const parser = new Parser();
Object.keys(cases).forEach((name) => {
const expr = cases[name];
it(name, () => {
const actual = parser.parse(expr);
should.strictEqual(typeof actual, "object");
});
});
});
describe("should parse await", () => {
const cases = {
"require": [
"async function x() { await require('y'); }", {
param: "y"
}
],
"System.import": [
"async function x() { const y = await System.import('z'); }", {
param: "z"
}
]
};
const parser = new Parser();
parser.plugin("call require", (expr) => {
const param = parser.evaluateExpression(expr.arguments[0]);
parser.state.param = param.string;
});
parser.plugin("call System.import", (expr) => {
const param = parser.evaluateExpression(expr.arguments[0]);
parser.state.param = param.string;
});
Object.keys(cases).forEach((name) => {
it(name, () => {
const actual = parser.parse(cases[name][0]);
actual.should.be.eql(cases[name][1]);
});
});
});
});
});
|
class CheckboxToggler {
constructor(options, container){
this.options = options;
this.container = container;
this._init();
this._bind();
}
option(_key, _value) {
}
_init() {
if (!this.container) {
throw new Error('Container element not found');
} else {
this.$container = $(this.container);
}
if (!this.$container.find('.toggle_all').length) {
throw new Error('"toggle all" checkbox not found');
} else {
this.toggle_all_checkbox = this.$container.find('.toggle_all');
}
this.checkboxes = this.$container.find(':checkbox').not(this.toggle_all_checkbox);
}
_bind() {
this.checkboxes.change(event => this._didChangeCheckbox(event.target));
this.toggle_all_checkbox.change(() => this._didChangeToggleAllCheckbox());
}
_didChangeCheckbox(_checkbox){
const numChecked = this.checkboxes.filter(':checked').length;
const allChecked = numChecked === this.checkboxes.length;
const someChecked = (numChecked > 0) && (numChecked < this.checkboxes.length);
this.toggle_all_checkbox.prop({ checked: allChecked, indeterminate: someChecked });
}
_didChangeToggleAllCheckbox() {
const setting = this.toggle_all_checkbox.prop('checked');
this.checkboxes.prop({ checked: setting });
return setting;
}
}
export default CheckboxToggler;
|
Request = Meteor.wrapAsync(Npm.require('request'));
|
angular.module('collabjs.controllers')
.controller('AdminAccountsCtrl', ['$scope', '$q', 'adminService', 'uiService',
function ($scope, $q, adminService, uiService) {
'use strict';
$scope.accounts = [];
$scope.init = function () {
adminService.getAccounts().then(function (accounts) {
$scope.accounts = accounts;
});
};
$scope.deleteAccount = function (account) {
if (account) {
uiService.confirmDialog(
'Are you sure you want to remove account "' + account.account + '"?',
function () {
var d = $q.defer();
adminService
.deleteAccount(account.account)
.then(function () {
var i = $scope.accounts.indexOf(account);
if (i > -1) {
$scope.accounts.splice(i, 1);
}
d.resolve();
});
return d.promise;
}
);
}
};
}]); |
;(function( should, sum, undefined ) {
'use strict';
describe( 'Get email', function() {
beforeEach(function() {
window.BT_SharedWorkerName = 'shared_sync_worker#randalmaia@gmail.com';
});
it("get user email", function () {
var inbox = new Inbox();
var email = inbox.getEmail();
email.should.equal('randalmaia@gmail.com');
});
});
describe( 'Get Username', function() {
var nameContainer;
beforeEach(function() {
nameContainer= document.createElement('div');
nameContainer.setAttribute('class','gb_Xa');
nameContainer.innerHTML = "Randal Maia";
document.body.appendChild(nameContainer);
});
it("get user name", function () {
var inbox = new Inbox();
var username = inbox.getUsername();
console.log( document.querySelector('.gb_Xa').innerHTML);
username.should.equal('Randal Maia');
});
});
})( chai.should(), window.sum ); |
/* @flow */
import React from 'react-native';
import AppText from '../AppText';
import Icon from '../Icon';
import Colors from '../../../Colors.json';
const {
View,
StyleSheet
} = React;
const styles = StyleSheet.create({
label: {
color: Colors.white,
fontWeight: 'bold',
margin: 16
},
icon: {
color: Colors.fadedBlack
}
});
export default class NextButtonLabel extends React.Component {
static propTypes = {
label: React.PropTypes.string,
style: View.propTypes.style
};
setNativeProps(nativeProps) {
this._root.setNativeProps(nativeProps);
}
render() {
return (
<View {...this.props} ref={c => this._root = c}>
<AppText style={styles.label}>{this.props.label.toUpperCase()}</AppText>
<Icon
style={styles.icon}
name="arrow-forward"
size={16}
/>
</View>
);
}
}
export default NextButtonLabel;
|
var SizeMonitor = /** @class */ (function () {
function SizeMonitor() {
}
SizeMonitor.init = function () {
var _this = this;
var NativeResizeObserver = window.ResizeObserver;
if (NativeResizeObserver) {
this.resizeObserver = new NativeResizeObserver(function (entries) {
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var entry = entries_1[_i];
var _a = entry.contentRect, width = _a.width, height = _a.height;
_this.checkSize(_this.elements.get(entry.target), entry.target, width, height);
}
});
}
else { // polyfill (more reliable even in browsers that support ResizeObserver)
var step = function () {
_this.elements.forEach(function (entry, element) {
var width = element.clientWidth ? element.clientWidth : 0;
var height = element.clientHeight ? element.clientHeight : 0;
_this.checkSize(entry, element, width, height);
});
};
window.setInterval(step, 100);
}
this.ready = true;
};
SizeMonitor.checkSize = function (entry, element, width, height) {
if (entry) {
if (!entry.size || width !== entry.size.width || height !== entry.size.height) {
entry.size = { width: width, height: height };
entry.cb(entry.size, element);
}
}
};
// Only a single callback is supported.
SizeMonitor.observe = function (element, cb) {
if (!this.ready) {
this.init();
}
this.unobserve(element);
if (this.resizeObserver) {
this.resizeObserver.observe(element);
}
this.elements.set(element, { cb: cb });
};
SizeMonitor.unobserve = function (element) {
if (this.resizeObserver) {
this.resizeObserver.unobserve(element);
}
this.elements.delete(element);
};
SizeMonitor.elements = new Map();
SizeMonitor.requestAnimationFrameId = 0;
SizeMonitor.ready = false;
return SizeMonitor;
}());
export { SizeMonitor };
|
/* eslint no-param-reassign: ["error", { "props": false }] */
import * as types from './mutation-types';
export default {
[types.LOGIN_SUCCESS](state, { token }) {
state.isAuthenticated = true;
state.token = token;
localStorage.token = token;
},
[types.LOGOUT](state) {
state.isAuthenticated = false;
state.token = null;
state.user = {};
localStorage.removeItem('token');
},
[types.FETCH_PROFILE](state, { user }) {
state.user = user;
},
};
|
(function (angular) {
"use strict";
angular.module(
"healthBam.program",
[
"ngResource"
]
);
}(window.angular));
|
"use strict";
var assert = require("assert");
var fs = require("fs");
var glob = require("glob");
var vows = require("vows-si");
var jsv = require("JSV").JSV.createEnvironment();
var gitUrlParse = require("git-url-parse");
var isThere = require("is-there");
var libsToRun = require("./support/libsToRun")
function parse(jsonFile, ignoreMissing) {
var content;
try {
content = fs.readFileSync(jsonFile, 'utf8');
} catch (err1) {
if (!ignoreMissing) {
assert.ok(0, jsonFile + " doesn't exist!");
}
return null;
}
try {
return JSON.parse(content);
} catch (err2) {
assert.ok(0, jsonFile + " failed to parse, you can validate your json here: http://jsonlint.com/");
return null;
}
}
function pkgName(jsonFile) {
return jsonFile.split("/")[3];
}
function prettyError(err) {
return err.message + " (" + err.details + "): " +
err.schemaUri.split("#")[1];
}
// load up those files
var packages = glob.sync(`./ajax/libs/${libsToRun()}/`).map(function(pkg) {
if (!fs.lstatSync(pkg.substring(0, pkg.length - 1)).isSymbolicLink()) {
return pkg + "package.json";
}
return null;
}).filter(function(n) {
return (typeof n === 'string');
});
var schemata = glob.sync("./test/schemata/*.json").map(function(schema) {
return jsv.createSchema(parse(schema));
});
var suite = vows.describe('Package structure');
packages.map(function(pkg) {
var packageVows = {topic: pkg};
var pname = pkgName(pkg);
var context = {};
packageVows[pname + " has package.json"] = function(pkg) {
assert.ok(isThere(pkg), pkgName(pkg) + " missing!");
};
packageVows[pname + " package.json is well-formed"] = function(pkg) {
assert.ok(parse(pkg, true),
pkgName(pkg) + " malformed!");
};
packageVows[pname + " package.json is valid"] = function(pkg) {
var pkgObj = parse(pkg, true);
var valid = true;
var errors;
if (pkgObj === null) {
// we already know about the problem
return;
}
errors = schemata.map(function(schema) {
var schemaErrors = schema.validate(pkgObj).errors;
if (schemaErrors.length) {
return {
name: schema._attributes.name,
errors: schemaErrors
};
}
return null;
}).filter(Boolean);
if (errors.length) {
valid = false;
}
if (!valid) {
assert.ok(valid,
[pkgName(pkg) + " is not a valid cdnjs package.json format:"].concat(
errors
.filter(function(schema) {
return schema !== null;
})
.map(function(schema) {
return "\t » " + schema.name +
"\n\t\t" +
schema.errors.map(prettyError).join("\n\t\t");
})
)
.join("\n"));
}
};
packageVows[pname + ": filename from package.json exists"] = function(pkg) {
var json = parse(pkg, true);
if (json.version === undefined) {
return;
}
var filePath = "./ajax/libs/" + json.name + "/" + json.version +
"/" + json.filename;
assert.ok(isThere(filePath),
filePath + " does not exist but is referenced in package.json!");
};
packageVows[pname + ": name in package.json should be parent folder name"] = function(pkg) {
var json = parse(pkg, true);
var dirs = pkg.split("/");
var trueName = dirs[dirs.length - 2];
assert.ok(trueName === json.name,
pkgName(pkg) + ": Name property should be '" + trueName + "', not '" + json.name + "'");
};
packageVows[pname + ": make sure repository field follow npm package.json format"] = function(pkg) {
var json = parse(pkg, true);
if (json.repository) {
assert.ok(
((json.repository.type !== undefined) && (json.repository.url !== undefined)),
"There repository field in " + json.name + "'s package.json should follow npm's format, must have type and url field."
);
}
};
packageVows[pname + ": must have auto-update config if it has no version specified"] = function(pkg) {
var json = parse(pkg, true);
if (json.version !== undefined) {
return;
}
assert.ok((json.npmName !== undefined && json.npmFileMap !== undefined && Array.isArray(json.npmFileMap)) || (json.autoupdate !== undefined),
pkgName(pkg) + ": must have a valid auto-update config");
};
packageVows[pname + ": npmName and npmFileMap should be a pair"] = function(pkg) {
var json = parse(pkg, true);
if (!json.npmName && !json.npmFileMap) {
return;
}
assert.ok(json.npmName !== undefined && json.npmFileMap !== undefined,
pkgName(pkg) + ": npmName and npmFileMap should be a pair");
};
var targetPrefixes = new RegExp("^git://.+.git$");
packageVows[pname + ": autoupdate block is valid (if present)"] = function(pkg) {
var json = parse(pkg, true);
var fileMapPostfixes = new RegExp("\\*\\*$");
if (json.autoupdate) {
assert.ok(json.autoupdate.source === "git",
pkgName(pkg) + ": Autoupdate source should be 'git', not " + json.autoupdate.source);
assert.ok(targetPrefixes.test(json.autoupdate.target),
pkgName(pkg) + ": Autoupdate target should match '" + targetPrefixes +
"', but is " + json.autoupdate.target);
for (var i in json.autoupdate.files) {
assert.ok(!fileMapPostfixes.test(json.autoupdate.files[i]),
pkgName(pkg) + ": fileMap should not end with ***");
}
} else if (json.npmFileMap) {
assert.ok(Array.isArray(json.npmFileMap),
pkgName(pkg) + ": npmFileMap should be an array and include one or multiply objects to describe corresponding bash path and files");
for (var i in json.npmFileMap) {
for (var j in json.npmFileMap[i].files) {
assert.ok(!fileMapPostfixes.test(json.npmFileMap[i].files[j]),
pkgName(pkg) + ": fileMap should not end with ***");
}
}
}
};
packageVows[pname + ": should not have multiple auto-update configs"] = function(pkg) {
var json = parse(pkg, true);
assert.ok(json.autoupdate === undefined || json.npmFileMap === undefined,
pkgName(pkg) + ": has both git and npm auto-update config, should remove one of it");
};
packageVows[pname + ": should point filename field to minified file"] = function(pkg) {
var json = parse(pkg, true);
if (json.filename) {
var path = "./ajax/libs/" + json.name + "/" + json.version + "/";
var orig = json.filename.split(".");
var min = '';
if (orig[orig.length - 2] !== 'min') {
var temp = orig;
var ext = temp.pop();
temp.push("min");
temp.push(ext);
min = temp.join(".");
}
assert.ok(min === '' || !isThere(path + min),
pkgName(pkg) + ": filename field in package.json should point filename field to minified file.");
}
};
packageVows[pname + ": format check"] = function(pkg) {
var orig = fs.readFileSync(pkg, 'utf8');
var correct = JSON.stringify(JSON.parse(orig), null, 2) + '\n';
var content = JSON.parse(correct);
if (content.version === undefined) {
return;
}
assert.ok(orig === correct,
pkgName(pkg) + ": package.json wrong indent, please use 2-spaces as indent, remove trailing spaces, you can use our tool: tools/fixFormat.js to fix it for you, here is an example: (Please ignore the first 2 spaces and the wildcard symbol in autoupadte config due to a bug)\n" + correct + "\n");
if (content.author !== undefined) {
assert.ok(!Array.isArray(content.author),
pkgName(pkg) + ": author field in package.json should be a object or string to show its author info, if there is multiple authors info, you should use 'authors' instead, you can use our tool: tools/fixFormat.js to fix it for you.");
}
if (content.authors !== undefined) {
assert.ok(Array.isArray(content.authors) && content.authors.length > 1,
pkgName(pkg) + ": authors field in package.json should be an array to include multiple authors info, if there is only one author, you should use 'author' instead, you can use our tool: tools/fixFormat.js to fix it for you.");
}
if (content.licenses !== undefined) {
assert.ok(Array.isArray(content.licenses),
pkgName(pkg) + ": licenses field in package.json should be an array to include multiple licenses info, if there is only one license, you should use 'license' instead, you can use our tool: tools/fixFormat.js to fix it for you.");
}
};
packageVows[pname + ": useless fields check"] = function(pkg) {
var json = parse(pkg, true);
var jsonFix = JSON.parse(JSON.stringify(json));
delete jsonFix.bin;
delete jsonFix.jshintConfig;
delete jsonFix.eslintConfig;
delete jsonFix.requiredFiles;
delete jsonFix.styles;
delete jsonFix.install;
delete jsonFix.typescript;
delete jsonFix.browserify;
delete jsonFix.browser;
delete jsonFix.jam;
delete jsonFix.jest;
delete jsonFix.scripts;
delete jsonFix.devDependencies;
delete jsonFix.main;
delete jsonFix.peerDependencies;
delete jsonFix.contributors;
delete jsonFix.maintainers;
delete jsonFix.bugs;
delete jsonFix.gitHEAD;
delete jsonFix.gitHead;
delete jsonFix.spm;
delete jsonFix.dist;
delete jsonFix.issues;
delete jsonFix.files;
delete jsonFix.ignore;
delete jsonFix.engines;
delete jsonFix.engine;
delete jsonFix.directories;
delete jsonFix.repositories;
assert.ok(JSON.stringify(json) === JSON.stringify(jsonFix),
pkgName(pkg) + ": we don't need bin, jshintConfig, eslintConfig, styles, install, typescript, browserify, browser, jam, jest, scripts, devDependencies, main, peerDependencies, contributors, bugs, gitHEAD, issues, files, ignore, engines, engine, directories, repositories and maintainers fields in package.json");
};
packageVows[pname + ": There must be repository information when using auto-update config"] = function(pkg) {
var json = parse(pkg, true);
assert.ok(
(
(json.repository !== undefined) ||
(json.autoupdate === undefined && json.npmFileMap === undefined)
),
pkgName(pkg) + ": Need to add repository information in package.json");
};
packageVows[pname + ": Homepage doesn't need to be set if it's the same as repository"] = function(pkg) {
var json = parse(pkg, true);
if ((json.repository !== undefined) && (json.repository.type === 'git') && (json.homepage !== undefined)) {
var repoUrlHttps = gitUrlParse(json.repository.url).toString("https");
assert.ok(
(
(json.homepage !== repoUrlHttps) &&
(json.homepage !== repoUrlHttps + '#readme') &&
(json.homepage !== repoUrlHttps + '.git')
),
pkgName(pkg) + ": Maybe you'll like to use its GitHub page or GitLab page as its homepage?");
}
};
packageVows[pname + ": There must be \"String\" type basePath in auto-update config"] = function(pkg) {
var json = parse(pkg, true);
if (json.npmFileMap) {
for (var i in json.npmFileMap) {
assert.ok(json.npmFileMap[i].basePath != undefined && ((typeof json.npmFileMap[i].basePath) == "string"),
pkgName(pkg) + ": Need to add \"String\" type basePath in auto-update config");
}
} else if (json.autoupdate) {
var autoupdate = json.autoupdate;
if (autoupdate.fileMap) {
assert.ok(autoupdate.basePath === undefined, "The autoupadte.basePath should appear inside of fileMap only.");
assert.ok(Array.isArray(autoupdate.fileMap) === true, "The fileMap should be an array.");
autoupdate.fileMap.forEach(function (c) {
assert.ok(c && typeof c.basePath === "string", "The basePath should be a string.");
assert.ok(Array.isArray(c.files), "The files field should be an array.");
c.files.forEach(function (cFile) {
assert.ok(cFile && typeof cFile === "string", "The file items should be a non-empty strings.");
});
});
} else {
assert.ok(json.autoupdate.basePath != undefined && ((typeof json.autoupdate.basePath) == "string"),
pkgName(pkg) + ": Need to add \"String\" type basePath in auto-update config or a fileMap \"Array\"");
}
}
}
packageVows[pname + ": There should not be leading slash (\"/\") in filename "] = function(pkg) {
var json = parse(pkg, true);
assert.ok(json.filename[0] != '/',
pkgName(pkg) + ": Need to remove leading/trailing slash (\"/\") in filename in package.json");
}
packageVows[pname + ": There should not be leading or trailing slash (\"/\") in basePath "] = function(pkg) {
var json = parse(pkg, true);
if (json.npmFileMap) {
for (var i in json.npmFileMap) {
if (json.npmFileMap[i].basePath) {
var basePath = json.npmFileMap[i].basePath;
assert.ok(
(
(basePath.length == 0) ||
(basePath[0] != '/' && basePath[basePath.length-1] != '/')
),
pkgName(pkg) + ": Need to remove leading/trailing slash (\"/\") in basePath in package.json");
}
}
} else if (json.autoupdate) {
if (json.autoupdate.basePath) {
var basePath = json.autoupdate.basePath;
assert.ok(
(
(basePath.length == 0) ||
(basePath[0] != '/' && basePath[basePath.length-1] != '/')
),
pkgName(pkg) + ": Need to remove \"/\" at the front or the last of basePath in package.json");
}
}
};
packageVows[pname + ": There must be array datatype files in auto-update config"] = function(pkg) {
var json = parse(pkg, true);
if (json.npmFileMap) {
for (var i in json.npmFileMap) {
assert.ok(Array.isArray(json.npmFileMap[i].files),
pkgName(pkg) + ": files in auto-update config file map need to be an array");
}
} else if (json.autoupdate) {
assert.ok(json.autoupdate.files === undefined,
pkgName(pkg) + ": files in auto-update config file is deprecated.");
}
};
packageVows[pname + ": keys with leading underscore should be removed"] = function(pkg) {
var json = parse(pkg, true);
for (var key in json) {
assert.ok(key[0] !== '_',
pkgName(pkg) + ": keys with leading underscore in package.json need to be removed");
}
};
context[pname] = packageVows;
suite.addBatch(context);
return null;
});
suite.export(module);
|
import { Form } from '../../../../src';
const fields = {
state: {
label: 'State',
value: 'USA',
fields: {
city: {
label: 'City',
value: 'New York',
fields: {
places: {
label: 'NY Places',
fields: {
centralPark: {
label: 'Central Park',
value: true,
},
statueOfLiberty: {
label: 'Statue of Liberty',
value: false,
},
empireStateBuilding: {
label: 'Empire State Building',
value: true,
},
brooklynBridge: {
label: 'Brooklyn Bridge',
value: true,
},
},
},
},
},
},
},
};
class NewForm extends Form {
hooks() {
return {
onInit(form) {
form.$('state.city.places').set('label', 'NY Cool Places');
form.$('state.city.places').update({
empireStateBuilding: false,
centralPark: false,
});
},
};
}
}
export default new NewForm({ fields }, { name: 'Nested-C' });
|
'use strict';
module.exports = function mochaIstanbul(grunt) {
// Load task
grunt.loadNpmTasks('grunt-mocha-istanbul');
return {
coverage: {
src: 'test/spec/server', /* the folder name for the tests */
options: {
recursive: true,
coverage: true, /* emit the coverage event */
/* quiet: true, */
excludes: [],
mochaOptions: [
'--reporter', 'spec-xunit-file'
]
}
}
};
};
|
var crypto = require('crypto')
, http = require('http')
, Cleverbot = function () {
this.params = Cleverbot.default_params;
};
Cleverbot.default_params = {
'stimulus': '', 'start': 'y', 'sessionid': '',
'vText8': '', 'vText7': '', 'vText6': '',
'vText5': '', 'vText4': '', 'vText3': '',
'vText2': '', 'icognoid': 'wsf', 'icognocheck': '',
'fno': '0', 'prevref': '', 'emotionaloutput': '',
'emotionalhistory': '', 'asbotname': '', 'ttsvoice': '',
'typing': '', 'lineref': '', 'sub': 'Say',
'islearning': '1', 'cleanslate': 'false',
};
Cleverbot.parserKeys = [
'message', 'sessionid', 'logurl', 'vText8',
'vText7', 'vText6', 'vText5', 'vText4',
'vText3', 'vText2', 'prevref', '',
'emotionalhistory', 'ttsLocMP3', 'ttsLocTXT', 'ttsLocTXT3',
'ttsText', 'lineref', 'lineURL', 'linePOST',
'lineChoices', 'lineChoicesAbbrev', 'typingData', 'divert'
];
Cleverbot.digest = function (body) {
var m = crypto.createHash('md5');
m.update(body)
return m.digest('hex');
};
Cleverbot.encodeParams = function (a1) {
var u = [];
for (x in a1) {
if (a1[x] instanceof Array)
u.push(x + "=" + encodeURIComponent(a1[x].join(",")));
else if (a1[x] instanceof Object)
u.push(params(a1[x]));
else
u.push(x + "=" + encodeURIComponent(a1[x]));
}
return u.join("&");
};
Cleverbot.cookies = {};
Cleverbot.prepare = function (callback) {
var options = {
host: 'www.cleverbot.com',
port: 80,
path: '/',
method: 'GET'
};
var req = http.request(options, function (res) {
res.on('data', function (chunk) {});
if (res.headers && res.headers["set-cookie"]) {
var list = res.headers["set-cookie"];
for (var i = 0; i < list.length; i++) {
var single_cookie = list[i].split(";");
var current_cookie = single_cookie[0].split("=");
Cleverbot.cookies[current_cookie[0]] = current_cookie[1];
}
callback()
}
});
req.end();
};
Cleverbot.prototype = {
write: function (message, callback) {
var clever = this;
body = this.params;
body.stimulus = message;
body.icognocheck = Cleverbot.digest(Cleverbot.encodeParams(body).substring(9, 35));
var cookie_string = '';
var cookie_tmp = [];
for (var key in Cleverbot.cookies) {
if (Cleverbot.cookies.hasOwnProperty(key)) {
var val = Cleverbot.cookies[key];
cookie_tmp.push(key + "=" + val);
}
}
cookie_string += cookie_tmp.join(';');
var options = {
host: 'www.cleverbot.com',
port: 80,
path: '/webservicemin?uc=165&',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Cleverbot.encodeParams(body).length,
'Cache-Control': 'no-cache',
'Cookie': cookie_string
}
};
var req = http.request(options, function (res) {
var cb = callback || function () {
};
res.on('data', function (chunk) {
var chunk_data = chunk.toString().split("\r")
, responseHash = {};
for (var i = 0, iLen = chunk_data.length; i < iLen; i++) {
clever.params[Cleverbot.parserKeys[i]] = responseHash[Cleverbot.parserKeys[i]] = chunk_data[i];
}
cb(responseHash);
});
});
req.write(Cleverbot.encodeParams(body));
req.end();
}
};
module.exports = Cleverbot;
|
var glob = require('glob');
var async = require('async');
var parseBlueprint = require('../parse/blueprint');
var endpointSorter = require('./endpoint-sorter');
module.exports = function(options, cb) {
var sourceFiles = options.sourceFiles;
var autoOptions = options.autoOptions;
var routeMap = {};
glob(sourceFiles, {} , function (err, files) {
if (err) {
console.error('Failed to parse contracts path.', err);
return cb(err);
}
var asyncFunctions = [];
files.forEach(function(filePath) {
asyncFunctions.push(parseBlueprint(filePath, autoOptions, routeMap));
});
async.series(asyncFunctions, function(err) {
cb(err, endpointSorter.sort(routeMap));
});
});
};
|
$(document).ready(function(){$("ul#filters a").click(function(){$(this).css("outline","none");$("ul#filters .current").removeClass("current");$(this).parent().addClass("current");var e=$(this).text().toLowerCase().replace(" ","-");e==="all"?$("ul#project-list li.hidden").fadeIn("slow").removeClass("hidden"):$("ul#project-list li").each(function(){$(this).hasClass(e)?$(this).fadeIn("slow").removeClass("hidden"):$(this).fadeOut("normal").addClass("hidden")});return!1})}); |
import { setupServer } from 'msw/node';
import { rest } from 'msw';
const server = setupServer(
rest.get('*/i18n/iso-locales', (req, res, ctx) => {
const defaultLocales = [
{
code: 'af',
name: 'Afrikaans (af)',
},
{
code: 'en',
name: 'English (en)',
},
{
code: 'fr',
name: 'French (fr)',
},
];
return res(ctx.json(defaultLocales));
}),
rest.get('*/i18n/locales', (req, res, ctx) => {
const defaultLocales = [
{
code: 'en',
name: 'English (en)',
id: 2,
isDefault: true,
},
];
return res(ctx.json(defaultLocales));
})
);
export default server;
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Richard Backhouse
*
* 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.
*/
define([
'../mpd/MPDClient'
],
function(MPDClient) {
var available = false;
var previousStatus;
function statusHasChanged(status) {
if (previousStatus) {
if (status.state !== previousStatus.state) {
return true;
}
if (status.volume !== previousStatus.volume) {
return true;
}
if (status.currentsong) {
if (status.currentsong.title !== previousStatus.currentsong.title) {
return true;
}
if (status.currentsong.artist !== previousStatus.currentsong.artist) {
return true;
}
if (status.currentsong.album !== previousStatus.currentsong.album) {
return true;
}
}
return false;
} else {
return true;
}
}
var statusListener = function(status) {
var sendStatus = true;
//if (statusHasChanged(status)) {
var currentSong = {artist: "", album: "", title: ""};
var strTime = "";
var volume = -1;
if (status.currentsong && status.currentsong.artist && status.state != "stop") {
currentSong = status.currentsong;
var time = Math.floor(parseInt(status.time));
var minutes = Math.floor(time / 60);
var seconds = time - minutes * 60;
seconds = (seconds < 10 ? '0' : '') + seconds;
strTime = minutes+":"+seconds;
volume = parseInt(status.volume)
}
var message = {state: status.state, volume: volume, currentSong: currentSong, time: strTime};
MMWormhole.sendMessage(message, "mpdjsStatus",
function() {
},
function(err) {
console.log("Apple Watch sending message failed "+err);
}
);
//}
previousStatus = status;
}.bind(this);
if (window.cordova) {
require(['deviceReady!'], function() {
MMWormhole.init("group.org.potpie.mpdjs2", function () {
console.log("Apple Watch initialized");
available = true;
MPDClient.addStatusListener(statusListener);
MMWormhole.listen("mpdjsCommand", function (command) {
previousStatus = undefined;
console.log("Apple Watch Command : "+JSON.stringify(command));
if (command.command === "changeVolume") {
MPDClient.changeVolume(command.value, function() {});
} else {
MPDClient.sendControlCmd(command.command, function() {});
}
});
}, function (err) {
console.log("Apple Watch error :"+err);
});
});
}
return {}
}); |
module.exports={A:{A:{"2":"YB","8":"K C G E","260":"A B"},B:{"260":"D w Z I M H"},C:{"8":"WB AB UB OB","516":"0 1 3 5 6 7 8 F J K C G E A B D w Z I M H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v z x"},D:{"1":"IB DB FB ZB GB","8":"F J K C G E A B D w Z I M H N O","132":"0 1 3 5 6 7 8 P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v z x BB"},E:{"8":"F J K C G E A B HB CB JB KB LB MB NB g PB"},F:{"1":"4 9 E B D QB RB SB TB g VB","132":"I M H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v"},G:{"8":"2 G CB XB EB aB bB cB dB eB fB gB hB iB"},H:{"2":"jB"},I:{"1":"pB","8":"2 AB F kB lB mB nB oB","132":"BB"},J:{"1":"A","8":"C"},K:{"1":"4 9 A B D g","8":"L"},L:{"1":"DB"},M:{"516":"x"},N:{"8":"A B"},O:{"8":"qB"},P:{"1":"F J rB"},Q:{"1":"sB"},R:{"1":"tB"}},B:1,C:"Datalist element"};
|
'use strict';
const AbstractConnectionManager = require('../abstract/connection-manager');
const Utils = require('../../utils');
const debug = Utils.getLogger().debugContext('connection:mysql');
const Promise = require('../../promise');
const sequelizeErrors = require('../../errors');
const dataTypes = require('../../data-types').mysql;
const parserMap = new Map();
class ConnectionManager extends AbstractConnectionManager {
constructor(dialect, sequelize) {
super(dialect, sequelize);
this.sequelize = sequelize;
this.sequelize.config.port = this.sequelize.config.port || 3306;
try {
if (sequelize.config.dialectModulePath) {
this.lib = require(sequelize.config.dialectModulePath);
} else {
this.lib = require('mysql');
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error('Please install mysql package manually');
}
throw err;
}
this.refreshTypeParser(dataTypes);
}
// Expose this as a method so that the parsing may be updated when the user has added additional, custom types
$refreshTypeParser(dataType) {
for (const type of dataType.types.mysql) {
parserMap.set(type, dataType.parse);
}
}
$clearTypeParser() {
parserMap.clear();
}
static $typecast(field, next) {
if (parserMap.has(field.type)) {
return parserMap.get(field.type)(field, this.sequelize.options);
}
return next();
}
connect(config) {
return new Promise((resolve, reject) => {
const connectionConfig = {
host: config.host,
port: config.port,
user: config.username,
password: config.password,
database: config.database,
timezone: this.sequelize.options.timezone,
typeCast: ConnectionManager.$typecast.bind(this),
bigNumberStrings: false,
supportBigNumbers: true
};
if (config.dialectOptions) {
for (const key of Object.keys(config.dialectOptions)) {
connectionConfig[key] = config.dialectOptions[key];
}
}
const connection = this.lib.createConnection(connectionConfig);
connection.connect(err => {
if (err) {
if (err.code) {
switch (err.code) {
case 'ECONNREFUSED':
reject(new sequelizeErrors.ConnectionRefusedError(err));
break;
case 'ER_ACCESS_DENIED_ERROR':
reject(new sequelizeErrors.AccessDeniedError(err));
break;
case 'ENOTFOUND':
reject(new sequelizeErrors.HostNotFoundError(err));
break;
case 'EHOSTUNREACH':
reject(new sequelizeErrors.HostNotReachableError(err));
break;
case 'EINVAL':
reject(new sequelizeErrors.InvalidConnectionError(err));
break;
default:
reject(new sequelizeErrors.ConnectionError(err));
break;
}
} else {
reject(new sequelizeErrors.ConnectionError(err));
}
return;
}
if (config.pool.handleDisconnects) {
// Connection to the MySQL server is usually
// lost due to either server restart, or a
// connnection idle timeout (the wait_timeout
// server variable configures this)
//
// See [stackoverflow answer](http://stackoverflow.com/questions/20210522/nodejs-mysql-error-connection-lost-the-server-closed-the-connection)
connection.on('error', err => {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
// Remove it from read/write pool
this.pool.destroy(connection);
}
debug(`connection error ${err.code}`);
});
}
debug(`connection acquired`);
resolve(connection);
});
}).tap(connection => {
connection.query("SET time_zone = '" + this.sequelize.options.timezone + "'"); /* jshint ignore: line */
});
}
disconnect(connection) {
// Dont disconnect connections with an ended protocol
// That wil trigger a connection error
if (connection._protocol._ended) {
debug(`connection tried to disconnect but was already at ENDED state`);
return Promise.resolve();
}
return new Promise((resolve, reject) => {
connection.end(err => {
if (err) return reject(new sequelizeErrors.ConnectionError(err));
debug(`connection disconnected`);
resolve();
});
});
}
validate(connection) {
return connection && ['disconnected', 'protocol_error'].indexOf(connection.state) === -1;
}
}
Utils._.extend(ConnectionManager.prototype, AbstractConnectionManager.prototype);
module.exports = ConnectionManager;
module.exports.ConnectionManager = ConnectionManager;
module.exports.default = ConnectionManager;
|
'use strict'
const fs = require('fs')
const log = require('bestikk-log')
log.task('Check unsupported features')
const data = fs.readFileSync('build/asciidoctor-browser.js', 'utf8')
const mutableStringPattern = /\['\$(g)?sub!'\]/
if (mutableStringPattern.test(data)) {
log.error('Mutable String methods are not supported in Opal, please replace sub! and gsub! methods')
process.exit(1)
}
|
var os = require('os')
, isWin = /^win32/.test(os.platform());
// A reference configuration file.
exports.config = {
// ----- How to setup Selenium -----
//
// There are three ways to specify how to use Selenium. Specify one of the
// following:
//
// 1. seleniumServerJar - to start Selenium Standalone locally.
// 2. seleniumAddress - to connect to a Selenium server which is already
// running.
// 3. sauceUser/sauceKey - to use remote Selenium servers via SauceLabs.
// The location of the selenium standalone server .jar file.
// http://docs.seleniumhq.org/download/
seleniumServerJar: './scripts/selenium-server-standalone-2.42.0.jar',
// The port to start the selenium server on, or null if the server should
// find its own unused port.
seleniumPort: 4444,
// https://npmjs.org/package/protractor
// seleniumAddress: 'http://localhost:4444/wd/hub',
// Chromedriver location is used to help the selenium standalone server
// find chromedriver. This will be passed to the selenium jar as
// the system property webdriver.chrome.driver. If null, selenium will
// attempt to find chromedriver using PATH.
chromeDriver: isWin ? './scripts/Chromedriver.exe' : './scripts/Chromedriver',
// Additional command line options to pass to selenium. For example,
// if you need to change the browser timeout, use
// seleniumArgs: ['-browserTimeout=60'],
seleniumArgs: [],
// If sauceUser and sauceKey are specified, seleniumServerJar will be ignored.
// The tests will be run remotely using SauceLabs.
sauceUser: null,
sauceKey: null,
// ----- What tests to run -----
//
// Spec patterns are relative to the location of this config.
specs: [
'./test*/e2e/**/*.js',
'./app/test*/e2e/**/*.js',
'./app/modules/auth/tests/e2e/signIn.test.js',
'./app/modules/roles/tests/e2e/permissions.test.js',
'./app/modules/roles/tests/e2e/roles.test.js',
'./app/modules/cs_accounts/tests/e2e/accounts.test.js',
'./app/modules/auth/tests/e2e/users.test.js',
'./app/modules/auth/tests/e2e/signOut.test.js',
'./app/modules/auth/tests/e2e/passwordReset.test.js',
'./app/modules/auth/tests/e2e/signUp.test.js',
'./app/modules/**/test*/e2e/*.js'
],
// ----- Capabilities to be passed to the webdriver instance ----
//
// For a full list of available capabilities, see
// https://code.google.com/p/selenium/wiki/DesiredCapabilities
// and
// https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js
capabilities: {
'browserName': 'chrome'
},
/*
Example config for PhantomJS
1. You need to download manually PhantomJS just put in test dir.
http://phantomjs.org/download.html
2. You also need to apply this patch to fix a known bug.
https://github.com/vrtdev/protractor/commit/2f18b01378e4f054331df23ce536e4081ee1ccf0
*/
// capabilities: {
// 'browserName': 'phantomjs',
// 'phantomjs.binary.path': './node_modules/phantom/bin/phantomjs'
// },
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
// If you change your dev server port this will need to match. - default 'http://127.0.0.1:9000'
baseUrl: 'http://127.0.0.1:9000',
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'body',
// ----- Options to be passed to minijasminenode -----
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: true,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 20000
}
};
|
define(function(require, exports, module) {
"use strict";
var app = require("app");
var Collection = Backbone.Collection.extend({
url: function() {
return app.api + "repos/" + this.user + "/" + this.repo +
"/commits?callback=?";
}
});
module.exports = Collection;
});
|
'use strict';
import type MediaStreamError from './MediaStreamError';
export default class MediaStreamErrorEvent {
type: string;
error: ?MediaStreamError;
constructor(type, eventInitDict) {
this.type = type.toString();
Object.assign(this, eventInitDict);
}
}
|
import Controller from './CustomController.js';
const VisibleTodos = function() {
return {
value: [],
deps: {
todos: ['todos']
},
get: function(refs, deps) {
return refs.map((ref) => deps.todos[ref]);
}
};
};
const state = {
nextRef: 0,
url: '/',
todos: {},
visibleTodos: VisibleTodos,
newTodoTitle: '',
isSaving: false,
isAllChecked: false,
editedTodo: null,
showCompleted: true,
showNotCompleted: true,
remainingCount: 0,
completedCount: 0,
filter: 'all'
};
export default Controller(state);
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.14_A4;
* @section: 12.14;
* @assertion: Sanity test for "catch(Indetifier) statement";
* @description: Checking if deleting an exception fails;
*/
// CHECK#1
try {
throw "catchme";
$ERROR('#1.1: throw "catchme" lead to throwing exception');
}
catch (e) {
if (delete e){
$ERROR('#1.2: Exception has DontDelete property');
}
if (e!=="catchme") {
$ERROR('#1.3: Exception === "catchme". Actual: Exception ==='+ e );
}
}
// CHECK#2
try {
throw "catchme";
$ERROR('#2.1: throw "catchme" lead to throwing exception');
}
catch(e){}
try{
e;
$ERROR('#2.2: Deleting catching exception after ending "catch" block');
}
catch(err){}
|
export const hello = (event, context, cb) => {
const p = new Promise((resolve, reject) => {
resolve('success');
});
p.then(r =>
cb(null, {
message: 'Go Serverless Webpack (Babel) v1.0! Second module!',
event
})
).catch(e => cb(e));
};
|
import Ember from 'ember';
export default Ember.Route.extend({
status: 'friends',
titleToken: function() {
return this.get('status');
}
});
|
import {
blockString,
hasBlock,
optionsHaveIgnoredAtRule,
rawNodeString,
report,
ruleMessages,
validateOptions,
whitespaceChecker,
} from "../../utils"
import { isString } from "lodash"
export const ruleName = "block-closing-brace-newline-after"
export const messages = ruleMessages(ruleName, {
expectedAfter: () => "Expected newline after \"}\"",
expectedAfterSingleLine: () => "Expected newline after \"}\" of a single-line block",
rejectedAfterSingleLine: () => "Unexpected whitespace after \"}\" of a single-line block",
expectedAfterMultiLine: () => "Expected newline after \"}\" of a multi-line block",
rejectedAfterMultiLine: () => "Unexpected whitespace after \"}\" of a multi-line block",
})
export default function (expectation, options) {
const checker = whitespaceChecker("newline", expectation, messages)
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: expectation,
possible: [
"always",
"always-single-line",
"never-single-line",
"always-multi-line",
"never-multi-line",
],
}, {
actual: options,
possible: {
ignoreAtRules: [isString],
},
optional: true,
})
if (!validOptions) { return }
// Check both kinds of statements: rules and at-rules
root.walkRules(check)
root.walkAtRules(check)
function check(statement) {
if (!hasBlock(statement)) { return }
if (optionsHaveIgnoredAtRule(options, statement)) { return }
const nextNode = statement.next()
if (!nextNode) { return }
// Allow an end-of-line comment x spaces after the brace
const nextNodeIsSingleLineComment = (
nextNode.type === "comment"
&& !/[^ ]/.test(nextNode.raw("before"))
&& nextNode.toString().indexOf("\n") === -1
)
const nodeToCheck = (nextNodeIsSingleLineComment) ? nextNode.next() : nextNode
if (!nodeToCheck) { return }
// Only check one after, because there might be other
// spaces handled by the indentation rule
checker.afterOneOnly({
source: rawNodeString(nodeToCheck),
index: -1,
lineCheckStr: blockString(statement),
err: msg => {
report({
message: msg,
node: statement,
index: statement.toString().length,
result,
ruleName,
})
},
})
}
}
}
|
var a = [1, 2, 3];
var b = [7, 5, 1];
var i = 0;
while (i < 3) console.log(a[i] - b[i++]);
//https://pt.stackoverflow.com/q/345392/101
|
var searchData=
[
['hash',['hash',['../struct__dictionary__.html#a94cbe0bcb2d50b793bf7898ff983cf6f',1,'_dictionary_']]],
['have',['have',['../structgz_file__s.html#a23e1c8c5dbaaba5b7f2abc17cebd9dcc',1,'gzFile_s']]],
['hcrc',['hcrc',['../structgz__header__s.html#ab54066d1aca7e674fbc6d5579cc48894',1,'gz_header_s']]],
['height',['height',['../struct___s_s_l___tile___layer__.html#ab2e78c61905b4419fcc7b4cfc500fe85',1,'_SSL_Tile_Layer_']]],
['hovered',['hovered',['../struct___s_s_l___button___status__.html#a04d9c4c9b283d16ce102b1482fdff900',1,'_SSL_Button_Status_']]],
['hovered_5fframe',['hovered_frame',['../struct___element___image___info.html#af8a5ba21b924c957da4106fe3fcab385',1,'_Element_Image_Info']]]
];
|
import testRule from "../../../testUtils/testRule"
import rule, { ruleName, messages } from ".."
testRule(rule, {
ruleName,
config: [1],
accept: [ {
code: "a { b { top: 0; }}",
}, {
code: "@media print { a { b { top: 0; }}}",
}, {
code: "a { top: 0; b { top: 0; }}",
}, {
code: "a { @nest b { top: 0; }}",
}, {
code: "a { b { @include foo; } }",
description: "at-rule without block",
} ],
reject: [ {
code: "a { b { c { top: 0; }}}",
message: messages.rejected(1),
}, {
code: "@media print { a { b { c { top: 0; }}}}",
message: messages.rejected(1),
}, {
code: "a { top: 0; b { top: 0; c { top: 0; }}}",
message: messages.rejected(1),
}, {
code: "a { b { top: 0; c { top: 0; }} top: 0; }",
message: messages.rejected(1),
}, {
code: "a { @nest b { c { top: 0; }}}",
message: messages.rejected(1),
} ],
})
testRule(rule, {
ruleName,
config: [3],
accept: [ {
code: "a { b { c { d { top: 0; }}}}",
}, {
code: "@media print { a { b { c { d { top: 0; }}}}}",
}, {
code: "a { & > b { @media print { color: pink; }}}",
}, {
code: "a { & > b { & > c { @media print { color: pink; }}}}",
description: messages.rejected(3),
} ],
reject: [{
code: "a { b { c { d { e { top: 0; }}}}}",
message: messages.rejected(3),
}],
})
testRule(rule, {
ruleName,
config: [ 1, { ignore: ["at-rules-without-declaration-blocks"] } ],
accept: [ {
code: "a { b { top: 0; }}",
}, {
code: "a { @media print { b { top: 0; }}}",
}, {
code: "a { @nest b { c { top: 0; }}}",
} ],
reject: [ {
code: "a { b { c { top: 0; }}}",
message: messages.rejected(1),
}, {
code: "a { @media print { b { c { top: 0; }}}}",
message: messages.rejected(1),
}, {
code: "a { @nest b { @nest c { top: 0; @nest d { bottom: 0; }}}}",
message: messages.rejected(1),
} ],
})
|
'use strict';
module.exports = function (t, a) {
a(t('user'), false);
a(t('officialization'), false);
a(t('official'), false);
a(t('officialHippo'), true);
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M21 3H3v18h18V3zm-2 12h-4c0 1.66-1.35 3-3 3s-3-1.34-3-3H4.99V5H19v10zm-3-5h-2V7h-4v3H8l4 4 4-4z" /></React.Fragment>
, 'MoveToInboxSharp');
|
import React from 'react';
import HashTagPic from './HashTagPicComponent';
const HashTagPicsContainer = (props) => {
return (
<div>
<p>
<i className="icon small instagram"></i>Tag your grams for this Spread with {props.hashtag} <i className="icon small arrow circle down"></i>
</p>
{props.hashTagPics.map((pic, index) =>
<HashTagPic
key={index}
id={index}
pic = {pic}
/>
)}
</div>
);
};
export default HashTagPicsContainer;
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M1 5h2v14H1V5zm4 0h2v14H5V5zm18 0H9v14h14V5zM11 17l2.5-3.15L15.29 16l2.5-3.22L21 17H11z" />
, 'BurstModeSharp');
|
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: loopback-sdk-angular
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
// Karma configuration
// Generated on Fri Jan 17 2014 19:17:51 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['mocha', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'test.e2e/test-main.js',
{ pattern: 'node_modules/chai/**/*.js', included: false },
{ pattern: 'node_modules/angular*/**/*.js', included: false },
{ pattern: 'test.e2e/**/*.js', included: false },
// Include lib/ files to let Karma watch for changes there
{ pattern: 'lib/**/*.js', included: false },
],
// list of files to exclude
exclude: [
// 'test/**/*.js'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['mocha', 'junit'],
// CI friendly test output
junitReporter: {
outputFile: 'karma-xunit.xml',
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 5000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
});
};
|
import './lib/actionButton';
import './lib/tabBar';
import './views/autoTranslateFlexTab.html';
import './views/autoTranslateFlexTab';
export { AutoTranslate } from './lib/autotranslate';
|
/**
* 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.
*
* @generated SignedSource<<e96120e3bc16826b5420f0b47a9ca39b>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { ReaderFragment } from 'relay-runtime';
import type { FragmentReference } from "relay-runtime";
declare export opaque type RelayModernStoreTest5Fragment$ref: FragmentReference;
declare export opaque type RelayModernStoreTest5Fragment$fragmentType: RelayModernStoreTest5Fragment$ref;
export type RelayModernStoreTest5Fragment = {|
+name: ?string,
+profilePicture: ?{|
+uri: ?string,
|},
+emailAddresses: ?$ReadOnlyArray<?string>,
+$refType: RelayModernStoreTest5Fragment$ref,
|};
export type RelayModernStoreTest5Fragment$data = RelayModernStoreTest5Fragment;
export type RelayModernStoreTest5Fragment$key = {
+$data?: RelayModernStoreTest5Fragment$data,
+$fragmentRefs: RelayModernStoreTest5Fragment$ref,
...
};
*/
var node/*: ReaderFragment*/ = {
"argumentDefinitions": [
{
"kind": "RootArgument",
"name": "size"
}
],
"kind": "Fragment",
"metadata": null,
"name": "RelayModernStoreTest5Fragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Variable",
"name": "size",
"variableName": "size"
}
],
"concreteType": "Image",
"kind": "LinkedField",
"name": "profilePicture",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "uri",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "emailAddresses",
"storageKey": null
}
],
"type": "User",
"abstractKey": null
};
if (__DEV__) {
(node/*: any*/).hash = "bafa0effa0e5f104fada10c8e21b490a";
}
module.exports = node;
|
BASE.require([
"BASE.query.ExpressionVisitor",
"Array.prototype.indexOfByFunction",
"BASE.collections.Hashmap",
"BASE.query.Queryable"
], function () {
BASE.namespace("BASE.query");
var Future = BASE.async.Future;
var ExpressionVisitor = BASE.query.ExpressionVisitor;
var Queryable = BASE.query.Queryable;
var Hashmap = BASE.collections.Hashmap;
var emptyFuture = Future.fromResult();
var getNavigationProperties = function (edm, model) {
var propertyModels = {};
var tempEntity = new model.type();
var oneToOneRelationships = edm.getOneToOneRelationships(tempEntity);
var oneToOneAsTargetRelationships = edm.getOneToOneAsTargetRelationships(tempEntity);
var oneToManyRelationships = edm.getOneToManyRelationships(tempEntity);
var oneToManyAsTargetRelationships = edm.getOneToManyAsTargetRelationships(tempEntity);
oneToOneRelationships.reduce(function (propertyModels, relationship) {
propertyModels[relationship.hasOne] = {
model: edm.getModelByType(relationship.ofType),
setupEntities: function (service, entities, queryable) {
if (entities.length === 0) {
return emptyFuture;
}
queryable = queryable || new Queryable();
var Target = relationship.ofType;
var keys = entities.map(function (entity) {
return entity[relationship.hasKey];
});
return service.asQueryable(Target).where(function (expBuilder) {
return expBuilder.property(relationship.withForeignKey).isIn(keys);
}).merge(queryable).toArray(function (targets) {
var entitiesById = entities.reduce(function (entitiesById, entity) {
entitiesById.add(entity[relationship.hasKey], entity);
return entitiesById;
}, new Hashmap());
targets.forEach(function (target) {
var sourceId = target[relationship.withForeignKey];
var source = entitiesById.get(sourceId);
source[relationship.hasOne] = target;
});
});
}
};
return propertyModels;
}, propertyModels);
oneToOneAsTargetRelationships.reduce(function (propertyModels, relationship) {
propertyModels[relationship.withOne] = {
model: edm.getModelByType(relationship.type),
setupEntities: function (service, entities, queryable) {
if (entities.length === 0) {
return emptyFuture;
}
queryable = queryable || new Queryable();
var Source = relationship.type;
var keys = entities.map(function (entity) {
return entity[relationship.withKey];
});
return service.asQueryable(Source).where(function (expBuilder) {
return expBuilder.property(relationship.hasKey).isIn(keys);
}).merge(queryable).toArray(function (sources) {
var entitiesById = sources.reduce(function (entitiesById, entity) {
entitiesById.add(entity[relationship.hasKey], entity);
return entitiesById;
}, new Hashmap());
entities.forEach(function (target) {
var sourceId = target[relationship.withForeignKey];
var source = entitiesById.get(sourceId);
target[relationship.withOne] = source;
});
});
}
};
return propertyModels;
}, propertyModels);
oneToManyRelationships.reduce(function (propertyModels, relationship) {
propertyModels[relationship.hasMany] = {
model: edm.getModelByType(relationship.ofType),
setupEntities: function (service, entities, queryable) {
if (entities.length === 0) {
return emptyFuture;
}
queryable = queryable || new Queryable();
var Target = relationship.ofType;
var keys = entities.map(function (entity) {
return entity[relationship.hasKey];
});
return service.asQueryable(Target).where(function (expBuilder) {
return expBuilder.property(relationship.withForeignKey).isIn(keys);
}).merge(queryable).toArray(function (targets) {
var entitiesById = entities.reduce(function (entitiesById, entity) {
entitiesById.add(entity[relationship.hasKey], entity);
return entitiesById;
}, new Hashmap());
targets.forEach(function (target) {
var sourceId = target[relationship.withForeignKey];
var source = entitiesById.get(sourceId);
source[relationship.hasMany].push(target);
});
});
}
};
return propertyModels;
}, propertyModels);
oneToManyAsTargetRelationships.reduce(function (propertyModels, relationship) {
propertyModels[relationship.withOne] = {
model: edm.getModelByType(relationship.type),
setupEntities: function (service, entities, queryable) {
if (entities.length === 0) {
return emptyFuture;
}
queryable = queryable || new Queryable();
var Source = relationship.type;
var keys = entities.map(function (entity) {
return entity[relationship.withForeignKey];
});
return service.asQueryable(Source).where(function (expBuilder) {
return expBuilder.property(relationship.hasKey).isIn(keys);
}).merge(queryable).toArray(function (sources) {
var entitiesById = sources.reduce(function (entitiesById, entity) {
entitiesById.add(entity[relationship.hasKey], entity);
return entitiesById;
}, new Hashmap());
entities.forEach(function (target) {
var sourceId = target[relationship.withForeignKey];
var source = entitiesById.get(sourceId);
target[relationship.withOne] = source;
});
});
}
};
return propertyModels;
}, propertyModels);
return propertyModels;
};
var IncludeVisitor = function (Type, entities, service, parameters) {
var self = this;
ExpressionVisitor.call(this);
this._entities = entities;
this._service = service;
this._edm = service.getEdm();
this._model = this._edm.getModelByType(Type);
this._cache = {};
this._parameters = parameters;
};
IncludeVisitor.prototype = Object.create(ExpressionVisitor.prototype);
IncludeVisitor.prototype.constructor = IncludeVisitor;
IncludeVisitor.prototype["include"] = function () {
var allQueryables = Array.prototype.slice.call(arguments, 0);
var entities = this._entities;
return Future.all(allQueryables).chain(function () { return entities; });
};
IncludeVisitor.prototype["queryable"] = function (properties, expression) {
var entities = this._entities;
var service = this._service;
var cache = this._cache;
var currentNamespace = "entity";
// Take the first one off because we start with the entities supplied from the constructor.
properties.shift();
return properties.reduce(function (future, propertyData, index) {
return future.chain(function (entities) {
var setupEntitiesArgs = [];
setupEntitiesArgs.push(service, entities);
if (index === properties.length - 1) {
setupEntitiesArgs.push(new Queryable(Object, { where: expression }));
}
var property = propertyData.property;
var namespace = currentNamespace = currentNamespace + "." + property;
var futureArray;
if (typeof cache[namespace] === "undefined") {
futureArray = propertyData.propertyAccess.setupEntities.apply(propertyData.propertyAccess, setupEntitiesArgs);
cache[namespace] = futureArray;
} else {
futureArray = cache[namespace];
}
return futureArray;
});
}, Future.fromResult(entities));
};
IncludeVisitor.prototype["expression"] = function (expression) {
return expression.value;
};
IncludeVisitor.prototype["propertyAccess"] = function (properties, property) {
var lastPropertyAccess = properties[properties.length - 1];
var propertyAccess = lastPropertyAccess.navigationProperties[property];
var propertyModel = propertyAccess.model;
if (typeof propertyModel === "undefined") {
throw new Error("Cannot find navigation property with name: " + property);
}
var navigationProperties = getNavigationProperties(this._edm, propertyModel);
properties.push({
propertyAccess: propertyAccess,
propertyModel: propertyModel,
property: property,
navigationProperties: navigationProperties
});
return properties;
};
IncludeVisitor.prototype["property"] = function (valueExpression) {
return valueExpression.value;
};
IncludeVisitor.prototype["type"] = function () {
var navigationProperties = getNavigationProperties(this._edm, this._model);
return [{
propertyAccess: null,
property: "",
propertyModel: null,
navigationProperties: navigationProperties
}];
};
BASE.query.IncludeVisitor = IncludeVisitor;
});
|
var loc = document.getElementById("c_location");
var map;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
loc.value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
//alert(position.coords.latitude);
// loc.value = "works";
document.getElementById("c_location").setAttribute('value', position.coords.latitude +
"," + position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
loc.value = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
loc.value = "Location information is unavailable."
break;
case error.TIMEOUT:
loc.value = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
loc.value = "An unknown error occurred."
break;
}
}
function initialize() {
var mapProp = {
center:new google.maps.LatLng(29.7604,-95.3698),
zoom:12,
mapTypeControl: false,
scaleControl: true,
streetViewControl: false,
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
|
/*
* grunt-bower-vinstall
* https://github.com/slhenty/grunt-bower-vinstall
*
* Copyright (c) 2014 cognivator
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('bower_vinstall', 'Install bower packages into folders that include package version information.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
|
jQuery(document).ready(function($) {
$('html').removeClass('no-js');
});
|
/*!
* chadQuery JavaScript Library v1.9.1
* http://chadquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 chadQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://chadquery.org/license
*
* Date: 2013-2-4
*/
(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 chadQuery(document)
rootchadQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over chadQuery in case of overwrite
_chadQuery = window.chadQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1",
// 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 chadQuery
chadQuery = function( selector, context ) {
// The chadQuery object is actually just the init constructor 'enhanced'
return new chadQuery.fn.init( selector, context, rootchadQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by chadQuery.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();
chadQuery.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 );
}
};
chadQuery.fn = chadQuery.prototype = {
// The current version of chadQuery being used
chadquery: core_version,
constructor: chadQuery,
init: function( selector, context, rootchadQuery ) {
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 chadQuery ? context[0] : context;
// scripts is true for back-compat
chadQuery.merge( this, chadQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && chadQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( chadQuery.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 rootchadQuery.find( selector );
}
// Otherwise, we inject the element directly into the chadQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.chadquery ) {
return ( context || rootchadQuery ).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 ( chadQuery.isFunction( selector ) ) {
return rootchadQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return chadQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a chadQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new chadQuery matched element set
var ret = chadQuery.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 chadQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
chadQuery.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( chadQuery.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 chadQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the chadQuery prototype for later instantiation
chadQuery.fn.init.prototype = chadQuery.fn;
chadQuery.extend = chadQuery.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" && !chadQuery.isFunction(target) ) {
target = {};
}
// extend chadQuery 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 && ( chadQuery.isPlainObject(copy) || (copyIsArray = chadQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && chadQuery.isArray(src) ? src : [];
} else {
clone = src && chadQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = chadQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
chadQuery.extend({
noConflict: function( deep ) {
if ( window.$ === chadQuery ) {
window.$ = _$;
}
if ( deep && window.chadQuery === chadQuery ) {
window.chadQuery = _chadQuery;
}
return chadQuery;
},
// 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 ) {
chadQuery.readyWait++;
} else {
chadQuery.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 ? --chadQuery.readyWait : chadQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( chadQuery.ready );
}
// Remember that the DOM is ready
chadQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --chadQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ chadQuery ] );
// Trigger any bound ready events
if ( chadQuery.fn.trigger ) {
chadQuery( 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 chadQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return chadQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || chadQuery.type(obj) !== "object" || obj.nodeType || chadQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = chadQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
chadQuery( scripts ).remove();
}
return chadQuery.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 = chadQuery.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 ) )();
}
}
}
chadQuery.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 ) {
chadQuery.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 && chadQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than chadQuery 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) ) ) {
chadQuery.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 ( !chadQuery.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 || chadQuery.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 ( chadQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
chadQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !chadQuery.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( chadQuery( 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();
}
});
chadQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = chadQuery.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.chadquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( chadQuery.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 ( !chadQuery.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
chadQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
chadQuery.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 = chadQuery.type( obj );
if ( chadQuery.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 chadQuery objects should point back to these
rootchadQuery = chadQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
chadQuery.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
*
*/
chadQuery.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 ) ) :
chadQuery.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 ) {
chadQuery.each( args, function( _, arg ) {
var type = chadQuery.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 ) {
chadQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = chadQuery.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 ? chadQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
chadQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", chadQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", chadQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", chadQuery.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 chadQuery.Deferred(function( newDefer ) {
chadQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = chadQuery.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 && chadQuery.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 ? chadQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
chadQuery.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 && chadQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : chadQuery.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 ] && chadQuery.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();
}
});
chadQuery.support = (function() {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// chadQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
chadQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !chadQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = chadQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global chadQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? chadQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = core_deletedIds.pop() || chadQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing chadQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = chadQuery.noop;
}
}
// An object can be passed to chadQuery.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 ] = chadQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = chadQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// chadQuery 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[ chadQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ chadQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !chadQuery.acceptData( elem ) ) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See chadQuery.data for more information
cache = isNode ? chadQuery.cache : elem,
id = isNode ? elem[ chadQuery.expando ] : chadQuery.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 ( !chadQuery.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 = chadQuery.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( chadQuery.map( name, chadQuery.camelCase ) );
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : chadQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See chadQuery.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 ) {
chadQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( chadQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
chadQuery.extend({
cache: {},
// Unique for each copy of chadQuery on the page
// Non-digits removed to match rinlinechadQuery
expando: "chadQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? chadQuery.cache[ elem[chadQuery.expando] ] : elem[ chadQuery.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 && chadQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
chadQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = chadQuery.data( elem );
if ( elem.nodeType === 1 && !chadQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( !name.indexOf( "data-" ) ) {
name = chadQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
chadQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
chadQuery.data( this, key );
});
}
return chadQuery.access( this, function( value ) {
if ( value === undefined ) {
// Try to fetch any internally stored data first
return elem ? dataAttr( elem, key, chadQuery.data( elem, key ) ) : null;
}
this.each(function() {
chadQuery.data( this, key, value );
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
chadQuery.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 ) ? chadQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
chadQuery.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" && chadQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
chadQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = chadQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || chadQuery.isArray(data) ) {
queue = chadQuery._data( elem, type, chadQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = chadQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = chadQuery._queueHooks( elem, type ),
next = function() {
chadQuery.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 chadQuery._data( elem, key ) || chadQuery._data( elem, key, {
empty: chadQuery.Callbacks("once memory").add(function() {
chadQuery._removeData( elem, type + "queue" );
chadQuery._removeData( elem, key );
})
});
}
});
chadQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return chadQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = chadQuery.queue( this, type, data );
// ensure a hooks for this queue
chadQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
chadQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
chadQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/chadquery-delay/
delay: function( time, type ) {
time = chadQuery.fx ? chadQuery.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 = chadQuery.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 = chadQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = chadQuery.support.getSetAttribute,
getSetInput = chadQuery.support.input;
chadQuery.fn.extend({
attr: function( name, value ) {
return chadQuery.access( this, chadQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
chadQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return chadQuery.access( this, chadQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = chadQuery.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 ( chadQuery.isFunction( value ) ) {
return this.each(function( j ) {
chadQuery( 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 = chadQuery.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 ( chadQuery.isFunction( value ) ) {
return this.each(function( j ) {
chadQuery( 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 ? chadQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( chadQuery.isFunction( value ) ) {
return this.each(function( i ) {
chadQuery( 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 = chadQuery( 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
chadQuery._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 ? "" : chadQuery._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 = chadQuery.valHooks[ elem.type ] || chadQuery.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 = chadQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = chadQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( chadQuery.isArray( val ) ) {
val = chadQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = chadQuery.valHooks[ this.type ] || chadQuery.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;
}
});
}
});
chadQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( chadQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !chadQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = chadQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = chadQuery.makeArray( value );
chadQuery(elem).find("option").each(function() {
this.selected = chadQuery.inArray( chadQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return chadQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !chadQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = chadQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
chadQuery.removeAttr( elem, name );
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== core_strundefined ) {
ret = elem.getAttribute( name );
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = chadQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( rboolean.test( name ) ) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if ( !getSetAttribute && ruseDefault.test( name ) ) {
elem[ chadQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
chadQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !chadQuery.support.radioValue && value === "radio" && chadQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !chadQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = chadQuery.propFix[ name ] || name;
hooks = chadQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = chadQuery.prop( elem, name ),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ chadQuery.camelCase( "default-" + name ) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name );
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
chadQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && chadQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ chadQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
chadQuery.attrHooks.value = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return chadQuery.nodeName( elem, "input" ) ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function( elem, value, name ) {
if ( chadQuery.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 = chadQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
chadQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
chadQuery.each([ "width", "height" ], function( i, name ) {
chadQuery.attrHooks[ name ] = chadQuery.extend( chadQuery.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 ( !chadQuery.support.hrefNormalized ) {
chadQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
chadQuery.attrHooks[ name ] = chadQuery.extend( chadQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret == null ? undefined : ret;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
chadQuery.each([ "href", "src" ], function( i, name ) {
chadQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !chadQuery.support.style ) {
chadQuery.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 ( !chadQuery.support.optSelected ) {
chadQuery.propHooks.selected = chadQuery.extend( chadQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !chadQuery.support.enctype ) {
chadQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !chadQuery.support.checkOn ) {
chadQuery.each([ "radio", "checkbox" ], function() {
chadQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
chadQuery.each([ "radio", "checkbox" ], function() {
chadQuery.valHooks[ this ] = chadQuery.extend( chadQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( chadQuery.isArray( value ) ) {
return ( elem.checked = chadQuery.inArray( chadQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
chadQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = chadQuery._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 = chadQuery.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 chadQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof chadQuery !== core_strundefined && (!e || chadQuery.event.triggered !== e.type) ?
chadQuery.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
// chadQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = chadQuery.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 = chadQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = chadQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && chadQuery.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
chadQuery.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 = chadQuery.hasData( elem ) && chadQuery._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 ) {
chadQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = chadQuery.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 ) {
chadQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( chadQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
chadQuery._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 + chadQuery.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 chadQuery.Event object, Object, or just an event type string
event = event[ chadQuery.expando ] ?
event :
new chadQuery.Event( type, typeof event === "object" && event );
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
chadQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = chadQuery.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 && !chadQuery.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;
// chadQuery handler
handle = ( chadQuery._data( cur, "events" ) || {} )[ event.type ] && chadQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && chadQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && chadQuery.nodeName( elem, "a" )) && chadQuery.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 ] && !chadQuery.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
chadQuery.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
}
chadQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable chadQuery.Event from the native event object
event = chadQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( chadQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = chadQuery.event.special[ event.type ] || {};
// Use the fix-ed chadQuery.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 = chadQuery.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 = ( (chadQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
chadQuery( sel, this ).index( cur ) >= 0 :
chadQuery.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[ chadQuery.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 chadQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( chadQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = chadQuery.extend(
new chadQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
chadQuery.event.trigger( e, null, elem );
} else {
chadQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
chadQuery.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 );
}
};
chadQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof chadQuery.Event) ) {
return new chadQuery.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 ) {
chadQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || chadQuery.now();
// Mark it as fixed
this[ chadQuery.expando ] = true;
};
// chadQuery.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
chadQuery.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
chadQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
chadQuery.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 && !chadQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !chadQuery.support.submitBubbles ) {
chadQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( chadQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
chadQuery.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 = chadQuery.nodeName( elem, "input" ) || chadQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !chadQuery._data( form, "submitBubbles" ) ) {
chadQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
chadQuery._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 ) {
chadQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( chadQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
chadQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !chadQuery.support.changeBubbles ) {
chadQuery.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" ) {
chadQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
chadQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
chadQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
chadQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !chadQuery._data( elem, "changeBubbles" ) ) {
chadQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
chadQuery.event.simulate( "change", this.parentNode, event, true );
}
});
chadQuery._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() {
chadQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !chadQuery.support.focusinBubbles ) {
chadQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
chadQuery.event.simulate( fix, event.target, chadQuery.event.fix( event ), true );
};
chadQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
chadQuery.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
chadQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = chadQuery.guid++ );
}
return this.each( function() {
chadQuery.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 chadQuery.Event
handleObj = types.handleObj;
chadQuery( 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() {
chadQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
chadQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return chadQuery.event.trigger( type, data, elem, true );
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 chadQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
while ( (elem = this[i++]) ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.chadquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = chadQuery.attr;
chadQuery.find = Sizzle;
chadQuery.expr = Sizzle.selectors;
chadQuery.expr[":"] = chadQuery.expr.pseudos;
chadQuery.unique = Sizzle.uniqueSort;
chadQuery.text = Sizzle.getText;
chadQuery.isXMLDoc = Sizzle.isXML;
chadQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = chadQuery.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
};
chadQuery.fn.extend({
find: function( selector ) {
var i, ret, self,
len = this.length;
if ( typeof selector !== "string" ) {
self = this;
return this.pushStack( chadQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( chadQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
ret = [];
for ( i = 0; i < len; i++ ) {
chadQuery.find( selector, this[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? chadQuery.unique( ret ) : ret );
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function( target ) {
var i,
targets = chadQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( chadQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true) );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
chadQuery( selector, this.context ).index( this[0] ) >= 0 :
chadQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
chadQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : chadQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
return this.pushStack( ret.length > 1 ? chadQuery.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 chadQuery.inArray( this[0], chadQuery( elem ) );
}
// Locate the position of the desired element
return chadQuery.inArray(
// If it receives a chadQuery object, the first element is used
elem.chadquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
chadQuery( selector, context ) :
chadQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = chadQuery.merge( this.get(), set );
return this.pushStack( chadQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
chadQuery.fn.andSelf = chadQuery.fn.addBack;
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
chadQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return chadQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return chadQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return chadQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return chadQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return chadQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return chadQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return chadQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return chadQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return chadQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
chadQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
chadQuery.fn[ name ] = function( until, selector ) {
var ret = chadQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = chadQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? chadQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret );
};
});
chadQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
chadQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
chadQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !chadQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( chadQuery.isFunction( qualifier ) ) {
return chadQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return chadQuery.grep(elements, function( elem ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = chadQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return chadQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = chadQuery.filter( qualifier, filtered );
}
}
return chadQuery.grep(elements, function( elem ) {
return ( chadQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinechadQuery = / chadQuery\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: chadQuery.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;
chadQuery.fn.extend({
text: function( value ) {
return chadQuery.access( this, function( value ) {
return value === undefined ?
chadQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( chadQuery.isFunction( html ) ) {
return this.each(function(i) {
chadQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = chadQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( chadQuery.isFunction( html ) ) {
return this.each(function(i) {
chadQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = chadQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = chadQuery.isFunction( html );
return this.each(function(i) {
chadQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !chadQuery.nodeName( this, "body" ) ) {
chadQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || chadQuery.filter( selector, [ elem ] ).length > 0 ) {
if ( !keepData && elem.nodeType === 1 ) {
chadQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && chadQuery.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 ) {
chadQuery.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 && chadQuery.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 chadQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return chadQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinechadQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( chadQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( chadQuery.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 ) {
chadQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
var isFunc = chadQuery.isFunction( value );
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !isFunc && typeof value !== "string" ) {
value = chadQuery( value ).not( this ).detach();
}
return this.domManip( [ value ], true, function( elem ) {
var next = this.nextSibling,
parent = this.parentNode;
if ( parent ) {
chadQuery( this ).remove();
parent.insertBefore( elem, next );
}
});
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = chadQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || chadQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, table ? self.html() : undefined );
}
self.domManip( args, table, callback );
});
}
if ( l ) {
fragment = chadQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && chadQuery.nodeName( first, "tr" );
scripts = chadQuery.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 = chadQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
chadQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call(
table && chadQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
node,
i
);
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
chadQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!chadQuery._data( node, "globalEval" ) && chadQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
chadQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
chadQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
chadQuery._data( elem, "globalEval", !refElements || chadQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !chadQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = chadQuery._data( src ),
curData = chadQuery._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++ ) {
chadQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = chadQuery.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 ( !chadQuery.support.noCloneEvent && dest[ chadQuery.expando ] ) {
data = chadQuery._data( dest );
for ( e in data.events ) {
chadQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( chadQuery.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 ( chadQuery.support.html5Clone && ( src.innerHTML && !chadQuery.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;
}
}
chadQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
chadQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = chadQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
chadQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply chadQuery 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 || chadQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
chadQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && chadQuery.nodeName( context, tag ) ?
chadQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
chadQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = chadQuery.contains( elem.ownerDocument, elem );
if ( chadQuery.support.html5Clone || chadQuery.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 ( (!chadQuery.support.noCloneEvent || !chadQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !chadQuery.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 ( chadQuery.type( elem ) === "object" ) {
chadQuery.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 ( !chadQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !chadQuery.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 ( chadQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
chadQuery.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 ( !chadQuery.support.appendChecked ) {
chadQuery.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 && chadQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = chadQuery.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 = chadQuery.expando,
cache = chadQuery.cache,
deleteExpando = chadQuery.support.deleteExpando,
special = chadQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || chadQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
chadQuery.event.remove( elem, type );
// This is a shortcut to avoid chadQuery.event.remove's overhead
} else {
chadQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by chadQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from chadQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return chadQuery.css( elem, "display" ) === "none" || !chadQuery.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 ] = chadQuery._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 ] = chadQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
chadQuery._data( elem, "olddisplay", hidden ? display : chadQuery.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;
}
chadQuery.fn.extend({
css: function( name, value ) {
return chadQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( chadQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = chadQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
chadQuery.style( elem, name, value ) :
chadQuery.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 ) ) {
chadQuery( this ).show();
} else {
chadQuery( this ).hide();
}
});
}
});
chadQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": chadQuery.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 = chadQuery.camelCase( name ),
style = elem.style;
name = chadQuery.cssProps[ origName ] || ( chadQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = chadQuery.cssHooks[ name ] || chadQuery.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( chadQuery.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" && !chadQuery.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 ( !chadQuery.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 = chadQuery.camelCase( name );
// Make sure that we're working with the right name
name = chadQuery.cssProps[ origName ] || ( chadQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = chadQuery.cssHooks[ name ] || chadQuery.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 || chadQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !chadQuery.contains( elem.ownerDocument, elem ) ) {
ret = chadQuery.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 += chadQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= chadQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= chadQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += chadQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += chadQuery.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 = chadQuery.support.boxSizing && chadQuery.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 && ( chadQuery.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 ||
chadQuery("<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 = chadQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = chadQuery.css( elem[0], "display" );
elem.remove();
return display;
}
chadQuery.each([ "height", "width" ], function( i, name ) {
chadQuery.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( chadQuery.css( elem, "display" ) ) ?
chadQuery.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,
chadQuery.support.boxSizing && chadQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !chadQuery.support.opacity ) {
chadQuery.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 = chadQuery.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 === "" ) &&
chadQuery.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
chadQuery(function() {
if ( !chadQuery.support.reliableMarginRight ) {
chadQuery.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 chadQuery.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 ( !chadQuery.support.pixelPosition && chadQuery.fn.position ) {
chadQuery.each( [ "top", "left" ], function( i, prop ) {
chadQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
chadQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( chadQuery.expr && chadQuery.expr.filters ) {
chadQuery.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 ||
(!chadQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || chadQuery.css( elem, "display" )) === "none");
};
chadQuery.expr.filters.visible = function( elem ) {
return !chadQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
chadQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
chadQuery.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 ) ) {
chadQuery.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;
chadQuery.fn.extend({
serialize: function() {
return chadQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = chadQuery.prop( this, "elements" );
return elements ? chadQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !chadQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = chadQuery( this ).val();
return val == null ?
null :
chadQuery.isArray( val ) ?
chadQuery.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
chadQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = chadQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for chadQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = chadQuery.ajaxSettings && chadQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( chadQuery.isArray( a ) || ( a.chadquery && !chadQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
chadQuery.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 ( chadQuery.isArray( obj ) ) {
// Serialize array item.
chadQuery.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 && chadQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
chadQuery.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
chadQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
chadQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = chadQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = chadQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for chadQuery.ajaxPrefilter and chadQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( chadQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
chadQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = chadQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
chadQuery.extend( true, target, deep );
}
return target;
}
chadQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( chadQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
chadQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
chadQuery("<div>").append( chadQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
chadQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
chadQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
chadQuery.each( [ "get", "post" ], function( i, method ) {
chadQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( chadQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return chadQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
chadQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": chadQuery.parseJSON,
// Parse text as xml
"text xml": chadQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, chadQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( chadQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = chadQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or chadQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.chadquery ) ?
chadQuery( callbackContext ) :
chadQuery.event,
// Deferreds
deferred = chadQuery.Deferred(),
completeDeferred = chadQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = chadQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = chadQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && chadQuery.active++ === 0 ) {
chadQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( chadQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", chadQuery.lastModified[ cacheURL ] );
}
if ( chadQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", chadQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
chadQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
chadQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 ) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --chadQuery.active ) ) {
chadQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getScript: function( url, callback ) {
return chadQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return chadQuery.get( url, data, callback, "json" );
}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv2, current, conv, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ];
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
// Install script dataType
chadQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
chadQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
chadQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
chadQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || chadQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
chadQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( chadQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
chadQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = chadQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
chadQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && chadQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
chadQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = chadQuery.ajaxSettings.xhr();
chadQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = chadQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
chadQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || chadQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in chadQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = chadQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
chadQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( chadQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = chadQuery.css( tween.elem, prop, true ) || end || 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;
chadQuery.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 );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = chadQuery.now() );
}
function createTweens( animation, props ) {
chadQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = chadQuery.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: chadQuery.extend( {}, properties ),
opts: chadQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = chadQuery.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;
}
}
createTweens( animation, props );
if ( chadQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
chadQuery.fx.timer(
chadQuery.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 value, name, index, easing, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = chadQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( chadQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = chadQuery.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;
}
}
}
chadQuery.Animation = chadQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( chadQuery.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, index, length,
value, dataShow, toggle,
tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = chadQuery._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 ( !chadQuery.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 ( chadQuery.css( elem, "display" ) === "inline" &&
chadQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !chadQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !chadQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = chadQuery._data( elem, "fxshow" ) || chadQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
chadQuery( elem ).show();
} else {
anim.done(function() {
chadQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
chadQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
chadQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || chadQuery.style( elem, prop );
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 );
}
chadQuery.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 || ( chadQuery.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 = chadQuery.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 = chadQuery.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 ( chadQuery.fx.step[ tween.prop ] ) {
chadQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ chadQuery.cssProps[ tween.prop ] ] != null || chadQuery.cssHooks[ tween.prop ] ) ) {
chadQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's 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;
}
}
};
chadQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = chadQuery.fn[ name ];
chadQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
chadQuery.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 = chadQuery.isEmptyObject( prop ),
optall = chadQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, chadQuery.extend( {}, prop ), optall );
doAnimation.finish = function() {
anim.stop( true );
};
// Empty animations, or finishing resolves immediately
if ( empty || chadQuery._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 = chadQuery.timers,
data = chadQuery._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 ) {
chadQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = chadQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = chadQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
chadQuery.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
chadQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
chadQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
chadQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? chadQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
chadQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !chadQuery.isFunction( easing ) && easing
};
opt.duration = chadQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in chadQuery.fx.speeds ? chadQuery.fx.speeds[ opt.duration ] : chadQuery.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 ( chadQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
chadQuery.dequeue( this, opt.queue );
}
};
return opt;
};
chadQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
chadQuery.timers = [];
chadQuery.fx = Tween.prototype.init;
chadQuery.fx.tick = function() {
var timer,
timers = chadQuery.timers,
i = 0;
fxNow = chadQuery.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 ) {
chadQuery.fx.stop();
}
fxNow = undefined;
};
chadQuery.fx.timer = function( timer ) {
if ( timer() && chadQuery.timers.push( timer ) ) {
chadQuery.fx.start();
}
};
chadQuery.fx.interval = 13;
chadQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( chadQuery.fx.tick, chadQuery.fx.interval );
}
};
chadQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
chadQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
chadQuery.fx.step = {};
if ( chadQuery.expr && chadQuery.expr.filters ) {
chadQuery.expr.filters.animated = function( elem ) {
return chadQuery.grep(chadQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
chadQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
chadQuery.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 ( !chadQuery.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 )
};
};
chadQuery.offset = {
setOffset: function( elem, options, i ) {
var position = chadQuery.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 = chadQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = chadQuery.css( elem, "top" ),
curCSSLeft = chadQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && chadQuery.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 ( chadQuery.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 );
}
}
};
chadQuery.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 ( chadQuery.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 ( !chadQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += chadQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += chadQuery.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 - chadQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - chadQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.documentElement;
while ( offsetParent && ( !chadQuery.nodeName( offsetParent, "html" ) && chadQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
chadQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
chadQuery.fn[ method ] = function( val ) {
return chadQuery.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 : chadQuery( win ).scrollLeft(),
top ? val : chadQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return chadQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
chadQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
chadQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
chadQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return chadQuery.access( this, function( elem, type, value ) {
var doc;
if ( chadQuery.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/chadquery/chadquery/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
chadQuery.css( elem, type, extra ) :
// Set width or height on the element
chadQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// })();
// Expose chadQuery to the global object
window.chadQuery = window.$ = chadQuery;
// Expose chadQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of chadQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple chadQuery versions by
// specifying define.amd.chadQuery = true. Register as a named module,
// since chadQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase chadquery is used because AMD module names are derived from
// file names, and chadQuery 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 chadQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.chadQuery ) {
define( "chadquery", [], function () { return chadQuery; } );
}
})( window );
|
import { module, test } from 'qunit';
import Server from 'ember-cli-mirage/server';
import { Model, belongsTo, hasMany } from 'ember-cli-mirage';
import PostShorthandRouteHandler from 'ember-cli-mirage/route-handlers/shorthands/post';
import JSONAPISerializer from 'ember-cli-mirage/serializers/json-api-serializer';
import promiseAjax from '../../../helpers/promise-ajax';
module('Integration | Server | Shorthands | Patch with relationships', function(hooks) {
hooks.beforeEach(function() {
this.newServerWithSchema = function(schema) {
this.server = new Server({
environment: 'development',
models: schema
});
this.server.timing = 0;
this.server.logging = false;
this.schema = this.server.schema;
this.serializer = new JSONAPISerializer();
return this.server;
};
this.handleRequest = function({ url, body }) {
let request = { requestBody: JSON.stringify(body), url };
let handler = new PostShorthandRouteHandler(this.schema, this.serializer);
return handler.handle(request);
};
});
hooks.afterEach(function() {
this.server.shutdown();
});
test('it can null out belongs to relationships', async function(assert) {
let server = this.newServerWithSchema({
author: Model.extend({
posts: hasMany()
}),
post: Model.extend({
author: belongsTo()
})
});
server.loadConfig(function() {
this.patch('/posts/:id');
});
let author = server.create('author');
let post = server.create('post', { author });
await promiseAjax({
method: 'PATCH',
url: `/posts/${post.id}`,
data: JSON.stringify({
data: {
attributes: {
title: 'Post 1'
},
relationships: {
author: {
data: null
}
}
}
})
});
post.reload();
assert.equal(post.author, null);
});
test('it can null out belongs to polymorphic relationships', async function(assert) {
let server = this.newServerWithSchema({
video: Model.extend(),
post: Model.extend(),
comment: Model.extend({
commentable: belongsTo({ polymorphic: true })
})
});
server.loadConfig(function() {
this.patch('/comments/:id');
});
let video = server.create('video');
let comment = server.create('comment', {
commentable: video
});
await promiseAjax({
method: 'PATCH',
url: `/comments/${comment.id}`,
data: JSON.stringify({
data: {
attributes: {
title: 'Post 1'
},
relationships: {
commentable: {
data: null
}
}
}
})
});
comment.reload();
assert.equal(comment.commentable, null);
});
test('it can null out has many polymorphic relationships', async function(assert) {
let server = this.newServerWithSchema({
car: Model.extend(),
watch: Model.extend(),
user: Model.extend({
collectibles: hasMany({ polymorphic: true })
})
});
server.loadConfig(function() {
this.patch('/users/:id');
});
let car = server.create('car');
let watch = server.create('watch');
let user = server.create('user', {
collectibles: [ car, watch ]
});
await promiseAjax({
method: 'PATCH',
url: `/users/${user.id}`,
data: JSON.stringify({
data: {
attributes: {
},
relationships: {
collectibles: {
data: null
}
}
}
})
});
user.reload();
assert.equal(user.collectibles.length, 0);
});
test('it camelizes relationship names', async function(assert) {
let server = this.newServerWithSchema({
postAuthor: Model.extend({
posts: hasMany()
}),
post: Model.extend({
postAuthor: belongsTo()
})
});
server.loadConfig(function() {
this.patch('/posts/:id');
});
let postAuthor = server.create('post-author');
let post = server.create('post');
await promiseAjax({
method: 'PATCH',
url: `/posts/${post.id}`,
data: JSON.stringify({
data: {
attributes: {
},
relationships: {
'post-author': {
data: {
id: postAuthor.id,
type: 'post-authors'
}
}
}
}
})
});
post.reload();
assert.equal(post.postAuthorId, postAuthor.id, 'relationship gets updated successfully');
});
});
|
"use strict"
function foo() {
if (true) return
var x = 1
return
"foo"
}
function bar() {
for (var i = 0; i < 10; i++) {
if (i === 0) continue
var y = 2
if (i === 1) break
var z = 3
switch (z) {
case 3:
var m = ""
return
case 2:
break
default:
break
}
}
}
foo()
(function () {})()
[ "one", "two" ].forEach(function (i) {
console.log(i)
})
var a = 1
var b = '1'
var c = "1"
function foobar() {}
(function () {})()
a = 2
+b
*c
|
async function* fn() {
for await (const result of [Promise.resolve("ok")]) {
return { result };
}
}
return fn().next().then(result => {
expect(result).toEqual({
done: true,
value: { result: "ok" }
});
});
|
lychee.define('game.Main').requires([
'game.state.Game'
]).includes([
'lychee.app.Main'
]).exports((lychee, global, attachments) => {
const _game = lychee.import('game');
const _Main = lychee.import('lychee.app.Main');
/*
* IMPLEMENTATION
*/
const Composite = function(data) {
let states = Object.assign({
client: null,
input: null,
server: null,
stash: null,
storage: null,
jukebox: {
music: false,
sound: true
},
renderer: {
width: null,
height: null
},
viewport: {
fullscreen: false
}
}, data);
_Main.call(this, states);
states = null;
/*
* INITIALIZATION
*/
this.bind('load', oncomplete => {
oncomplete(true);
}, this);
this.bind('init', function() {
let viewport = this.viewport || null;
if (viewport !== null) {
// viewport.unbind('hide');
// viewport.unbind('show');
}
this.setState('game', new _game.state.Game(this));
this.changeState('game');
}, this, true);
};
Composite.prototype = {
/*
* ENTITY API
*/
// deserialize: function(blob) {},
serialize: function() {
let data = _Main.prototype.serialize.call(this);
data['constructor'] = 'game.Main';
let states = data['arguments'][0] || {};
let blob = data['blob'] || {};
data['arguments'][0] = states;
data['blob'] = Object.keys(blob).length > 0 ? blob : null;
return data;
}
};
return Composite;
});
|
function gen_harvest_request(resourcetype, source) {
var xml = '<Harvest service="CSW" version="2.0.2" xmlns="http://www.opengis.net/cat/csw/2.0.2">';
xml += '<Source>' + source + '</Source>';
xml += '<ResourceType>' + resourcetype + '</ResourceType>';
xml += '</Harvest>';
return xml;
}
function gen_transaction_insert_request(csw_xml) {
var xml = '<Transaction service="CSW" version="2.0.2" xmlns="http://www.opengis.net/cat/csw/2.0.2">';
xml += '<Insert>';
xml += csw_xml;
xml += '</Insert>';
xml += '</Transaction>';
return xml;
}
function focus_page() {
// autofocus on page inits
var focus_fields = [
'input#id_old_password',
'input#id_username',
'input[name=q]'
];
for (var i = 0; i < focus_fields.length; i++) {
if ($(focus_fields[i]).length) {
$(focus_fields[i]).focus();
}
}
}
$('#publish-resource').click(function(event) {
var data = null;
var $publish_button = $(this);
$publish_button.button('loading');
var publishtype = $('#csw-publishtype').val();
var resourcetype = $('#csw-resourcetype').val();
var source = $('#csw-source').val();
var csw_url = $('#csw-url').val();
var csw_xml = $('#csw-xml').val();
if (publishtype === 'Layer') {
data = gen_transaction_insert_request(csw_xml);
} else {
data = gen_harvest_request(resourcetype, source);
}
console.log(data);
$.ajax({
type: 'post',
crossDomain: true,
url: csw_url,
data: data,
dataType: 'text',
success: function(xml) {
var result_text = null;
$("#csw-publish-result").removeClass('alert-success');
$("#csw-publish-result").removeClass('alert-danger');
$xml = $($.parseXML(xml));
var exception = $xml.find('ows\\:ExceptionText').text();
if (exception) {
$("#csw-publish-result").addClass('alert-danger');
result_text = 'CSW-T Error: ' + exception;
} else {
$("#csw-publish-result").addClass('alert-success');
var inserted = $xml.find('csw\\:totalInserted').text();
var updated = $xml.find('csw\\:totalUpdated').text();
var deleted = $xml.find('csw\\:totalDeleted').text();
result_text = 'inserted: ' + inserted + " " + 'updated: ' + updated + " " + 'deleted: ' + deleted;
}
$("#csw-publish-result").removeClass('hidden');
$("#csw-publish-result-text").html(result_text);
$publish_button.button('reset');
console.log(xml);
}
});
});
// page init
$(function() {
focus_page();
});
|
/*
* File: jquery.flexisel.js
* Version: 1.0.0
* Description: Responsive carousel jQuery plugin
* Author: 9bit Studios
* Copyright 2012, 9bit Studios
* http://www.9bitstudios.com
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
$.fn.flexisel = function (options) {
var defaults = $.extend({
visibleItems: 4,
animationSpeed: 200,
autoPlay: false,
autoPlaySpeed: 3000,
pauseOnHover: true,
setMaxWidthAndHeight: false,
enableResponsiveBreakpoints: false,
responsiveBreakpoints: {
portrait: {
changePoint: 480,
visibleItems: 1
},
landscape: {
changePoint: 640,
visibleItems: 2
},
tablet: {
changePoint: 768,
visibleItems: 3
}
}
}, options);
/******************************
Private Variables
*******************************/
var object = $(this);
var settings = $.extend(defaults, options);
var itemsWidth; // Declare the global width of each item in carousel
var canNavigate = true;
var itemsVisible = settings.visibleItems;
/******************************
Public Methods
*******************************/
var methods = {
init: function () {
return this.each(function () {
methods.appendHTML();
methods.setEventHandlers();
methods.initializeItems();
});
},
/******************************
Initialize Items
*******************************/
initializeItems: function () {
var listParent = object.parent();
var innerHeight = listParent.height();
var childSet = object.children();
var innerWidth = listParent.width(); // Set widths
itemsWidth = (innerWidth) / itemsVisible;
childSet.width(itemsWidth);
childSet.last().insertBefore(childSet.first());
childSet.last().insertBefore(childSet.first());
object.css({'left': -itemsWidth});
object.fadeIn();
$(window).trigger("resize"); // needed to position arrows correctly
},
/******************************
Append HTML
*******************************/
appendHTML: function () {
object.addClass("nbs-flexisel-ul");
object.wrap("<div class='nbs-flexisel-container'><div class='nbs-flexisel-inner'></div></div>");
object.find("li").addClass("nbs-flexisel-item");
if (settings.setMaxWidthAndHeight) {
var baseWidth = $(".nbs-flexisel-item > img").width();
var baseHeight = $(".nbs-flexisel-item > img").height();
$(".nbs-flexisel-item > img").css("max-width", baseWidth);
$(".nbs-flexisel-item > img").css("max-height", baseHeight);
}
$("<div class='nbs-flexisel-nav-left'></div><div class='nbs-flexisel-nav-right'></div>").insertAfter(object);
var cloneContent = object.children().clone();
object.append(cloneContent);
},
/******************************
Set Event Handlers
*******************************/
setEventHandlers: function () {
var listParent = object.parent();
var childSet = object.children();
var leftArrow = listParent.find($(".nbs-flexisel-nav-left"));
var rightArrow = listParent.find($(".nbs-flexisel-nav-right"));
$(window).on("resize", function (event) {
methods.setResponsiveEvents();
var innerWidth = $(listParent).width();
var innerHeight = $(listParent).height();
itemsWidth = (innerWidth) / itemsVisible;
childSet.width(itemsWidth);
object.css({'left': -itemsWidth});
var halfArrowHeight = (leftArrow.height()) / 2;
var arrowMargin = (innerHeight / 2) - halfArrowHeight;
leftArrow.css("top", arrowMargin + "px");
rightArrow.css("top", arrowMargin + "px");
});
$(leftArrow).on("click", function (event) {
methods.scrollLeft();
});
$(rightArrow).on("click", function (event) {
methods.scrollRight();
});
if (settings.pauseOnHover == true) {
$(".nbs-flexisel-item").on({
mouseenter: function () {
canNavigate = false;
},
mouseleave: function () {
canNavigate = true;
}
});
}
if (settings.autoPlay == true) {
setInterval(function () {
if (canNavigate == true)
methods.scrollRight();
}, settings.autoPlaySpeed);
}
},
/******************************
Set Responsive Events
*******************************/
setResponsiveEvents: function () {
var contentWidth = $('html').width();
if (settings.enableResponsiveBreakpoints == true) {
if (contentWidth < settings.responsiveBreakpoints.portrait.changePoint) {
itemsVisible = settings.responsiveBreakpoints.portrait.visibleItems;
}
else if (contentWidth > settings.responsiveBreakpoints.portrait.changePoint && contentWidth < settings.responsiveBreakpoints.landscape.changePoint) {
itemsVisible = settings.responsiveBreakpoints.landscape.visibleItems;
}
else if (contentWidth > settings.responsiveBreakpoints.landscape.changePoint && contentWidth < settings.responsiveBreakpoints.tablet.changePoint) {
itemsVisible = settings.responsiveBreakpoints.tablet.visibleItems;
}
else {
itemsVisible = settings.visibleItems;
}
}
},
/******************************
Scroll Left
*******************************/
scrollLeft: function () {
if (canNavigate == true) {
canNavigate = false;
var listParent = object.parent();
var innerWidth = listParent.width();
itemsWidth = (innerWidth) / itemsVisible;
var childSet = object.children();
object.animate({
'left': "+=" + itemsWidth
},
{
queue: false,
duration: settings.animationSpeed,
easing: "linear",
complete: function () {
childSet.last().insertBefore(childSet.first()); // Get the first list item and put it after the last list item (that's how the infinite effects is made)
methods.adjustScroll();
canNavigate = true;
}
}
);
}
},
/******************************
Scroll Right
*******************************/
scrollRight: function () {
if (canNavigate == true) {
canNavigate = false;
var listParent = object.parent();
var innerWidth = listParent.width();
itemsWidth = (innerWidth) / itemsVisible;
var childSet = object.children();
object.animate({
'left': "-=" + itemsWidth
},
{
queue: false,
duration: settings.animationSpeed,
easing: "linear",
complete: function () {
childSet.first().insertAfter(childSet.last()); // Get the first list item and put it after the last list item (that's how the infinite effects is made)
methods.adjustScroll();
canNavigate = true;
}
}
);
}
},
/******************************
Adjust Scroll
*******************************/
adjustScroll: function () {
var listParent = object.parent();
var childSet = object.children();
var innerWidth = listParent.width();
itemsWidth = (innerWidth) / itemsVisible;
childSet.width(itemsWidth);
object.css({'left': -itemsWidth});
}
};
if (methods[options]) { // $("#element").pluginName('methodName', 'arg1', 'arg2');
return methods[options].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof options === 'object' || !options) { // $("#element").pluginName({ option: 1, option:2 });
return methods.init.apply(this);
} else {
$.error('Method "' + method + '" does not exist in flexisel plugin!');
}
};
})(jQuery);
|
import closeLastOpenedWindow from 'src/support/action/closeLastOpenedWindow';
describe(
'closeLastOpenedWindow', () => {
let done;
beforeEach(() => {
global.browser = {
windowHandles: jest.fn(() => ({
value: [
'one',
'two',
'three',
],
})),
window: jest.fn(),
close: jest.fn(),
};
done = jest.fn();
});
it('should call closeLastOpenedWindow on the browser', () => {
closeLastOpenedWindow('', done);
expect(global.browser.windowHandles).toHaveBeenCalledTimes(1);
expect(global.browser.window).toHaveBeenCalledTimes(1);
expect(global.browser.window).toHaveBeenCalledWith('three');
expect(global.browser.close).toHaveBeenCalledTimes(1);
expect(done).toHaveBeenCalledTimes(1);
});
}
);
|
'use strict';
var Q = require('q'),
U = require('../util'),
PATH = require('../path'),
FS = require('fs'),
BlockNode = require('./block').BlockNodeName,
fileNodes = require('./file'),
BemCreateNode = require('./create'),
BemBuildNode = require('./build'),
BemDeclNode = require('./decl'),
BorschikNode = require('./borschik'),
MagicNode = require('./magic'),
registry = require('../nodesregistry'),
LOGGER = require('../logger'),
BundleNodeName = exports.BundleNodeName = 'BundleNode';
/* jshint -W106 */
exports.__defineGetter__(BundleNodeName, function() {
return registry.getNodeClass(BundleNodeName);
});
/* jshint +W106 */
registry.decl(BundleNodeName, BlockNode, /** @lends BundleNode.prototype */ {
nodeType: 6,
make: function() {
return this.ctx.arch.withLock(this.alterArch(), this);
},
alterArch: function() {
var ctx = this.ctx;
return function() {
// create real node for page
var arch = ctx.arch,
bundleNode;
if (arch.hasNode(this.path)) {
bundleNode = arch.getNode(this.path);
} else {
bundleNode = new fileNodes.FileNode({
root: this.root,
path: this.path
});
arch.setNode(bundleNode, arch.getParents(this).filter(function(p) {
return !(arch.getNode(p) instanceof MagicNode.MagicNode);
}), this);
}
// generate targets for page files
var optTechs = this.getOptimizerTechs(),
usedSuffixes = {};
this.getTechs().forEach(function(tech) {
this.level.getTech(tech).getBuildSuffixes().forEach(function(suffix) {
(usedSuffixes[suffix] || (usedSuffixes[suffix] = [])).push(tech);
});
var techNode = this.createTechNode(tech, bundleNode, this);
if (techNode && ~optTechs.indexOf(tech)) {
this.createOptimizerNode(tech, techNode, bundleNode);
}
}, this);
Object.keys(usedSuffixes).forEach(function(suffix) {
if (usedSuffixes[suffix].length > 1) LOGGER.fwarn('Bundle %s is configured to build techs %s ' +
'which have common build suffix %s. Consider using only one of these techs.',
this.path,
usedSuffixes[suffix].join(', '),
suffix);
}, this);
return Q.when(this.takeSnapshot('after alterArch BundleNode ' + this.getId()));
};
},
lastModified: function() {
return Q.resolve(0);
},
createTechNode: function(tech, bundleNode, magicNode) {
var f = 'create-' + tech + '-node';
f = typeof this[f] === 'function'? f : 'createDefaultTechNode';
LOGGER.fdebug('Using %s() to create node for tech %s', f, tech);
return this[f].apply(this, arguments);
},
createOptimizerNode: function(tech, sourceNode, bundleNode) {
var f = 'create-' + tech + '-optimizer-node';
f = typeof this[f] === 'function'? f : 'createDefaultOptimizerNode';
LOGGER.fdebug('Using %s() to create optimizer node for tech %s', f, tech);
return this[f].apply(this, arguments);
},
getBundlePath: function(tech) {
return this.level.getPath(this.getNodePrefix(), tech);
},
getTechs: function() {
return [
'bemjson.js',
'bemdecl.js',
'deps.js',
'bemhtml',
'css',
'ie.css',
'js',
'html'
];
},
/**
* Returns an array of the techs to build in a forked process. The techs not in the list will be built inprocess.
* @return {Array}
*/
getForkedTechs: function() {
return [
'bemhtml'
];
},
getOptimizerTechs: function() {
return this.getTechs();
},
cleanup: function() {
var arch = this.ctx.arch;
if (!arch.hasNode(this.path)) return;
arch.removeTree(this.path);
},
/**
* Constructs array of levels to build tech from.
*
* @param {String} tech Tech name.
* @return {Array} Array of levels.
*/
getLevels: function(tech) {
return (this.level.getConfig().bundleBuildLevels || [])
.concat([PATH.resolve(this.root, PATH.dirname(this.getNodePrefix()), 'blocks')]);
},
/**
* Checks that dependencies for specified node are met (appropriate nodes exist in the arch) or that node's file is
* already exists on the file system.
* @param node
* @return {Node} Specified node if dependencies are met, FileNode if not but file does exist, null otherwise.
*/
useFileOrBuild: function(node) {
var deps = node.getDependencies();
for(var i = 0, l = deps.length; i < l; i++) {
var d = deps[i];
if (!this.ctx.arch.hasNode(d)) {
LOGGER.fverbose('Dependency %s is required to build %s but does not exist, checking if target already built', d, node.getId());
if (!PATH.existsSync(node.getPath())) {
LOGGER.fwarn('%s will not be built because dependency file %s does not exist', node.path, d);
return null;
}
return new fileNodes.FileNode({
root: this.root,
path: node.getId()
});
}
}
return node;
},
/**
* Create a bem build node, add it to the arch, add
* dependencies to it. Then create a meta node and link
* it to the build node.
*
* @param {String} techName
* @param {String} techPath
* @param {String} declPath
* @param {String} bundleNode
* @param {String} magicNode
* @param {Boolean} [forked]
* @return {Node}
*/
setBemBuildNode: function(techName, techPath, declPath, bundleNode, magicNode, forked) {
var arch = this.ctx.arch,
buildNode = new BemBuildNode.BemBuildNode({
root: this.root,
bundlesLevel: this.level,
levels: this.getLevels(techName),
declPath: declPath,
techPath: techPath,
techName: techName,
output: this.getNodePrefix(),
forked: forked === undefined? ~this.getForkedTechs().indexOf(techName): forked
});
var tech = this.level.getTech(techName, techPath),
metaNode;
/* techs-v2: don't create meta node */
if (tech.API_VER !== 2) metaNode = buildNode.getMetaNode();
// Set bem build node to arch and add dependencies to it
arch.setNode(buildNode)
.addChildren(buildNode, buildNode.getDependencies());
// Add file aliases to arch and link with buildNode as parents
buildNode.getFiles().forEach(function(f) {
if (buildNode.getId() === f) return;
var alias = new fileNodes.FileNode({ path: f, root: this.root });
arch.setNode(alias).addParents(buildNode, alias);
}, this);
bundleNode && arch.addParents(buildNode, bundleNode);
magicNode && arch.addChildren(buildNode, magicNode);
/* techs-v2: don't add dependency on meta node */
if (metaNode) {
// Set bem build meta node to arch
arch.setNode(metaNode)
.addParents(metaNode, buildNode)
.addChildren(metaNode, metaNode.getDependencies());
}
return buildNode;
},
/**
* Create a bem create node, add it to the arch,
* add dependencies to it.
*
* @param {String} techName
* @param {String} techPath
* @param {String} bundleNode
* @param {String} magicNode
* @param {Boolean} [force]
* @param {Boolean} [forked]
* @return {Node | undefined}
*/
setBemCreateNode: function(techName, techPath, bundleNode, magicNode, force, forked) {
var arch = this.ctx.arch,
node = this.useFileOrBuild(new BemCreateNode.BemCreateNode({
root: this.root,
level: this.level,
item: this.item,
techPath: techPath,
techName: techName,
force: force,
forked: forked === undefined? ~this.getForkedTechs().indexOf(techName): forked
}));
if (!node) return;
// Set bem create node to arch and add dependencies to it
arch.setNode(node)
.addChildren(node, node.getDependencies());
// Add file aliases to arch and link with node as parents
node.getFiles && node.getFiles().forEach(function(f) {
if (node.getId() === f) return;
var alias = new fileNodes.FileNode({ path: f, root: this.root });
arch.setNode(alias).addParents(node, alias);
}, this);
bundleNode && arch.addParents(node, bundleNode);
magicNode && arch.addChildren(node, magicNode);
return node;
},
/**
* Create file node, add it to the arch, add dependencies to it.
*
* @param {String} tech
* @param {String} bundleNode
* @param {String} magicNode
* @return {Node | undefined}
*/
setFileNode: function(tech, bundleNode, magicNode) {
var arch = this.ctx.arch,
filePath = this.getBundlePath(tech);
if (!PATH.existsSync(PATH.resolve(this.root, filePath))) return;
var node = new fileNodes.FileNode({
root: this.root,
path: filePath
});
arch.setNode(node);
bundleNode && arch.addParents(node, bundleNode);
magicNode && arch.addChildren(node, magicNode);
return node;
},
createDefaultTechNode: function(tech, bundleNode, magicNode) {
return this.setBemBuildNode(
tech,
this.level.resolveTech(tech),
this.getBundlePath('deps.js'),
bundleNode,
magicNode);
},
createDefaultOptimizerNode: function(tech, sourceNode, bundleNode) {},
createBorschikOptimizerNode: function(tech, sourceNode, bundleNode) {
var files = sourceNode.getFiles? sourceNode.getFiles() : [sourceNode.path];
LOGGER.fdebug('Creating borschik nodes for %s', files);
return files.map(function(file) {
var node = new (registry.getNodeClass('BorschikNode'))({
root: this.root,
input: file,
tech: tech,
forked: true
});
this.ctx.arch
.setNode(node)
.addParents(node, bundleNode)
.addChildren(node, sourceNode);
return node;
}, this);
},
'create-bemjson.js-node': function(tech, bundleNode, magicNode) {
return this.setFileNode.apply(this, arguments);
},
'create-bemdecl.js-node': function(tech, bundleNode, magicNode) {
return this.setBemCreateNode(
tech,
this.level.resolveTech(tech),
bundleNode,
magicNode);
},
'create-deps.js-node': function(tech, bundleNode, magicNode) {
return this.setBemBuildNode(
tech,
this.level.resolveTech(tech),
this.getBundlePath('bemdecl.js'),
bundleNode,
magicNode);
},
'create-html-node': function(tech, bundleNode, magicNode) {
return this.setBemCreateNode(
tech,
this.level.resolveTech(tech),
bundleNode,
magicNode);
},
'create-js-optimizer-node': function(tech, sourceNode, bundleNode) {
return this.createBorschikOptimizerNode('js', sourceNode, bundleNode);
},
'create-browser.js+bemhtml-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-js-optimizer-node'].apply(this, arguments);
},
'create-priv.js-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-js-optimizer-node'].apply(this, arguments);
},
'create-bemhtml-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-js-optimizer-node'].apply(this, arguments);
},
'create-bemhtml.js-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-bemhtml-optimizer-node'].apply(this, arguments);
},
'create-css-optimizer-node': function(tech, sourceNode, bundleNode) {
return this.createBorschikOptimizerNode('cleancss', sourceNode, bundleNode);
},
'create-ie.css-optimizer-node': function(tech, sourceNode, bundleNode) {
var nodes = this['create-css-optimizer-node'].apply(this, arguments);
this.ctx.arch.link(this.getBundlePath('css'), nodes);
return nodes;
},
'create-ie6.css-optimizer-node': function(tech, sourceNode, bundleNode) {
var nodes = this['create-ie.css-optimizer-node'].apply(this, arguments);
this.ctx.arch.link(this.getBundlePath('ie.css'), nodes);
return nodes;
},
'create-ie7.css-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-ie6.css-optimizer-node'].apply(this, arguments);
},
'create-ie8.css-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-ie6.css-optimizer-node'].apply(this, arguments);
},
'create-ie9.css-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-ie.css-optimizer-node'].apply(this, arguments);
},
'create-less-optimizer-node': function(tech, sourceNode, bundleNode) {
return this['create-css-optimizer-node'].apply(this, arguments);
}
});
var MergedBundleNodeName = exports.MergedBundleNodeName = 'MergedBundleNode';
/* jshint -W106 */
exports.__defineGetter__(MergedBundleNodeName, function() {
return registry.getNodeClass(MergedBundleNodeName);
});
/* jshint +W106 */
registry.decl(MergedBundleNodeName, BundleNodeName, /** @lends MergedBundleNode.prototype */ {
make: function() {
var path = PATH.resolve(this.root, this.path);
if (!PATH.existsSync(path)) FS.mkdirSync(path);
return this.__base();
},
/**
* Overriden. Creates BemDecl node linked to the deps.js nodes of the bundles within containing level.
* @param tech
* @param bundleNode
* @param magicNode
* @return {*}
*/
'create-deps.js-node': function(tech, bundleNode, magicNode) {
var ctx = this.ctx,
arch = ctx.arch,
levelNode = arch.getNode(PATH.relative(this.root, this.level.dir)),
depsTech = this.level.getTech('deps.js').getTechName(),
bundles = arch.getChildren(levelNode)
.filter(function(b) {
var n = arch.getNode(b);
return n instanceof exports.BundleNode && n !== this;
}, this)
.map(function(b) {
return U.getNodeTechPath(this.level, arch.getNode(b).item, depsTech);
}, this);
return this.setBemDeclNode(
tech,
this.level.resolveTech(tech),
bundleNode,
magicNode,
'merge',
bundles);
},
/**
* Creates BemDecl node which maps to 'bem decl [cmd] [decls]'.
* @param techName
* @param techPath
* @param bundleNode
* @param magicNode
* @param cmd Command to execute (merge or substract).
* @param decls Declaration paths to execute command on.
* @param [force]
* @return {Node | undefined}
*/
setBemDeclNode: function(techName, techPath, bundleNode, magicNode, cmd, decls, force) {
var arch = this.ctx.arch,
node = this.useFileOrBuild(new BemDeclNode.BemDeclNode({
root: this.root,
level: this.level,
item: this.item,
techPath: techPath,
techName: techName,
cmd: cmd,
decls: decls,
force: force
}));
if (!node) return;
// Set bem create node to arch and add dependencies to it
arch.setNode(node)
.addChildren(node, node.getDependencies());
bundleNode && arch.addParents(node, bundleNode);
magicNode && arch.addChildren(node, magicNode);
return node;
}
});
|
angular.module('contact', []); |
$(document).ready(function(){
/////////////////
// Global variables
/////////////////
var newEmailId = 0;
////////////////
// Functions dealing with submit buttons
////////////////
$('body').on('click', '#btn-all-ok', function(){
$(this).attr('id', 'btn-all-not-ok');
$(this).text('Wait a second...');
$(this).removeClass('btn-info');
$(this).addClass('btn-success');
$('<button id="btn-send-email" class="btn btn-warning col-sm-6" type="submit">Send Email</button>').insertAfter(this);
});
$('body').on('click', '#btn-all-not-ok', function(){
$(this).attr('id', 'btn-all-ok');
$(this).text('Everything looks good');
$(this).removeClass('btn-success');
$(this).addClass('btn-info');
$('#btn-send-email').remove();
});
$('body').on('click', '#btn-send-email', function(){
var emptyFields = $('input[required]').filter(function(){
return $(this).val().trim() == '';
}).length;
if (emptyFields == 0) {
$('#doNotCloseModal').modal('show');
};
});
///////////////////
// Functions dealing with removing email from list
///////////////////
$('body').on('click', '.delete-step-1', function(){
var rowId = $(this).attr('related-email');
$(this).removeClass('delete-step-1 btn-default');
$(this).addClass('delete-step-2 btn-warning');
$(this).text('Remove');
$('<button class="btn btn-success btn-restore" type="button" related-email="' + rowId + '">Oops..</button>').insertAfter(this);
});
$('body').on('click', '.btn-restore', function(){
var rowId = $(this).attr('related-email');
var removeBtn = $('#remove-email-btn-' + rowId);
removeBtn.removeClass('delete-step-2 btn-warning');
removeBtn.addClass('delete-step-1 btn-default');
removeBtn.html('<span class="glyphicon glyphicon-remove"></span>');
$(this).remove();
});
$('body').on('click', '.delete-step-2', function(){
var rowId = $(this).attr('related-email');
$('#row' + rowId).remove();
});
///////////////////
// Functions dealing with adding a new email recipient
///////////////////
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
};
$('body').on('click', '.add-email-btn', function(){
var rowId = $(this).attr('related-email');
var newEmailAddress = $('#' + rowId).val()
if (isEmail(newEmailAddress)){
$(this).removeClass('add-email-btn');
$(this).addClass('delete-step-1');
$(this).html('<span class="glyphicon glyphicon-remove"></span>');
newEmailId += 1;
var rowId = newEmailId.toString();
$('<tr id="rowN' + rowId + '">' +
'<td><button class="btn btn-default ' +
'add-email-btn" type="button" related-email="N' + rowId +
'" id="remove-email-btn-N' + rowId + '">' +
'<span class="glyphicon glyphicon-plus"></span></button></td>' +
'<td><input type="email" name="address_N"' + rowId +
' class="form-control" id="N' + rowId + '" /></td>' +
'<td><input name="salutation_N' + rowId + '" class="form-control" ' +
'id="salutation_N' + rowId + '" /></td>' +
'<td>New Recipient</td></tr>').insertAfter(
'#rowN' + (newEmailId - 1).toString()
)
}
});
});
|
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
import { openBlock, createElementBlock, normalizeClass, renderSlot, computed, resolveComponent, unref, createBlock, withCtx, createElementVNode, withModifiers, createVNode, createCommentVNode, withDirectives, normalizeStyle, withKeys, vModelText, toDisplayString, createTextVNode } from "vue";
function isExist(obj) {
return typeof obj !== "undefined" && obj !== null;
}
var defaultLang = {
uiv: {
datePicker: {
clear: "Clear",
today: "Today",
month: "Month",
month1: "January",
month2: "February",
month3: "March",
month4: "April",
month5: "May",
month6: "June",
month7: "July",
month8: "August",
month9: "September",
month10: "October",
month11: "November",
month12: "December",
year: "Year",
week1: "Mon",
week2: "Tue",
week3: "Wed",
week4: "Thu",
week5: "Fri",
week6: "Sat",
week7: "Sun"
},
timePicker: {
am: "AM",
pm: "PM"
},
modal: {
cancel: "Cancel",
ok: "OK"
},
multiSelect: {
placeholder: "Select...",
filterPlaceholder: "Search..."
}
}
};
let lang = defaultLang;
let i18nHandler = function() {
if ("$t" in this) {
return this.$t.apply(this, arguments);
}
return null;
};
const t = function(path, options) {
options = options || {};
let value;
try {
value = i18nHandler.apply(this, arguments);
if (isExist(value) && !options.$$locale) {
return value;
}
} catch (e) {
}
const array = path.split(".");
let current = options.$$locale || lang;
for (let i = 0, j = array.length; i < j; i++) {
const property = array[i];
value = current[property];
if (i === j - 1)
return value;
if (!value)
return "";
current = value;
}
return "";
};
const _sfc_main$2 = {
props: {
size: { type: String, default: void 0 },
vertical: { type: Boolean, default: false },
justified: { type: Boolean, default: false }
},
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
class: normalizeClass({
"btn-group": !__props.vertical,
"btn-group-vertical": __props.vertical,
"btn-group-justified": __props.justified,
[`btn-group-${__props.size}`]: __props.size
}),
role: "group",
"data-toggle": "buttons"
}, [
renderSlot(_ctx.$slots, "default")
], 2);
};
}
};
const linkProps = {
href: { type: String, default: void 0 },
target: { type: String, default: void 0 },
to: { type: null, default: void 0 },
replace: { type: Boolean, default: false },
append: { type: Boolean, default: false },
exact: { type: Boolean, default: false }
};
const _hoisted_1$1 = ["href", "target"];
const _hoisted_2$1 = ["type", "checked", "disabled"];
const _hoisted_3$1 = ["type", "disabled"];
const _hoisted_4$1 = ["type", "disabled"];
const _sfc_main$1 = {
props: __spreadProps(__spreadValues({}, linkProps), {
justified: { type: Boolean, default: false },
type: { type: String, default: "default" },
nativeType: { type: String, default: "button" },
size: { type: String, default: void 0 },
block: { type: Boolean, default: false },
active: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
modelValue: { type: null, default: null },
inputValue: { type: null, default: null },
inputType: {
type: String,
validator(value) {
return value === "checkbox" || value === "radio";
},
default: void 0
}
}),
emits: ["update:modelValue"],
setup(__props, { emit }) {
const props = __props;
const isInputActive = computed(() => props.inputType === "checkbox" ? props.modelValue.indexOf(props.inputValue) >= 0 : props.modelValue === props.inputValue);
const classes = computed(() => ({
btn: true,
active: props.inputType ? isInputActive.value : props.active,
disabled: props.disabled,
"btn-block": props.block,
[`btn-${props.type}`]: !!props.type,
[`btn-${props.size}`]: !!props.size
}));
function onClick(e) {
if (props.disabled && e instanceof Event) {
e.preventDefault();
e.stopPropagation();
}
}
function onInputChange() {
if (props.inputType === "checkbox") {
const valueCopied = props.modelValue.slice();
if (isInputActive.value) {
valueCopied.splice(valueCopied.indexOf(props.inputValue), 1);
} else {
valueCopied.push(props.inputValue);
}
emit("update:modelValue", valueCopied);
} else {
emit("update:modelValue", props.inputValue);
}
}
return (_ctx, _cache) => {
const _component_RouterLink = resolveComponent("RouterLink");
return _ctx.href ? (openBlock(), createElementBlock("a", {
key: 0,
href: _ctx.href,
target: _ctx.target,
role: "button",
class: normalizeClass(unref(classes)),
onClick
}, [
renderSlot(_ctx.$slots, "default")
], 10, _hoisted_1$1)) : _ctx.to ? (openBlock(), createBlock(_component_RouterLink, {
key: 1,
to: _ctx.to,
class: normalizeClass(unref(classes)),
event: __props.disabled ? "" : "click",
replace: _ctx.replace,
append: _ctx.append,
exact: _ctx.exact,
role: "button",
onClick
}, {
default: withCtx(() => [
renderSlot(_ctx.$slots, "default")
]),
_: 3
}, 8, ["to", "class", "event", "replace", "append", "exact"])) : __props.inputType ? (openBlock(), createElementBlock("label", {
key: 2,
class: normalizeClass(unref(classes)),
onClick
}, [
createElementVNode("input", {
autocomplete: "off",
type: __props.inputType,
checked: unref(isInputActive),
disabled: __props.disabled,
onInput: _cache[0] || (_cache[0] = withModifiers(() => {
}, ["stop"])),
onChange: onInputChange
}, null, 40, _hoisted_2$1),
renderSlot(_ctx.$slots, "default")
], 2)) : __props.justified ? (openBlock(), createBlock(_sfc_main$2, { key: 3 }, {
default: withCtx(() => [
createElementVNode("button", {
class: normalizeClass(unref(classes)),
type: __props.nativeType,
disabled: __props.disabled,
onClick
}, [
renderSlot(_ctx.$slots, "default")
], 10, _hoisted_3$1)
]),
_: 3
})) : (openBlock(), createElementBlock("button", {
key: 4,
class: normalizeClass(unref(classes)),
type: __props.nativeType,
disabled: __props.disabled,
onClick
}, [
renderSlot(_ctx.$slots, "default")
], 10, _hoisted_4$1));
};
}
};
function pad(value, num) {
let res = value.toString();
for (let i = num - res.length; i > 0; i--) {
res = "0" + res;
}
return res;
}
var _export_sfc = (sfc, props) => {
const target = sfc.__vccOpts || sfc;
for (const [key, val] of props) {
target[key] = val;
}
return target;
};
const maxHours = 23;
const zero = 0;
const maxMinutes = 59;
const cutUpAmAndPm = 12;
const _sfc_main = {
components: { Btn: _sfc_main$1 },
props: {
modelValue: { type: Date, required: true },
showMeridian: { type: Boolean, default: true },
min: { type: null, default: void 0 },
max: { type: null, default: void 0 },
hourStep: { type: Number, default: 1 },
minStep: { type: Number, default: 1 },
readonly: { type: Boolean, default: false },
controls: { type: Boolean, default: true },
iconControlUp: { type: String, default: "glyphicon glyphicon-chevron-up" },
iconControlDown: {
type: String,
default: "glyphicon glyphicon-chevron-down"
},
inputWidth: { type: Number, default: 50 }
},
emits: ["update:modelValue"],
data() {
return {
hours: 0,
minutes: 0,
meridian: true,
hoursText: "",
minutesText: ""
};
},
computed: {
inputStyles() {
return {
width: `${this.inputWidth}px`
};
}
},
watch: {
modelValue(value) {
this.updateByValue(value);
},
showMeridian(value) {
this.setTime();
},
hoursText(value) {
if (this.hours === 0 && value === "") {
return;
}
const hour = parseInt(value);
if (this.showMeridian) {
if (hour >= 1 && hour <= cutUpAmAndPm) {
if (this.meridian) {
this.hours = hour === cutUpAmAndPm ? 0 : hour;
} else {
this.hours = hour === cutUpAmAndPm ? cutUpAmAndPm : hour + cutUpAmAndPm;
}
}
} else if (hour >= zero && hour <= maxHours) {
this.hours = hour;
}
this.setTime();
},
minutesText(value) {
if (this.minutes === 0 && value === "") {
return;
}
const minutesStr = parseInt(value);
if (minutesStr >= zero && minutesStr <= maxMinutes) {
this.minutes = minutesStr;
}
this.setTime();
}
},
mounted() {
this.updateByValue(this.modelValue);
},
methods: {
t,
updateByValue(value) {
if (isNaN(value.getTime())) {
this.hours = 0;
this.minutes = 0;
this.hoursText = "";
this.minutesText = "";
this.meridian = true;
return;
}
this.hours = value.getHours();
this.minutes = value.getMinutes();
if (!this.showMeridian) {
this.hoursText = pad(this.hours, 2);
} else {
if (this.hours >= cutUpAmAndPm) {
if (this.hours === cutUpAmAndPm) {
this.hoursText = this.hours + "";
} else {
this.hoursText = pad(this.hours - cutUpAmAndPm, 2);
}
this.meridian = false;
} else {
if (this.hours === zero) {
this.hoursText = cutUpAmAndPm.toString();
} else {
this.hoursText = pad(this.hours, 2);
}
this.meridian = true;
}
}
this.minutesText = pad(this.minutes, 2);
this.$refs.hoursInput.value = this.hoursText;
this.$refs.minutesInput.value = this.minutesText;
},
addHour(step) {
step = step || this.hourStep;
this.hours = this.hours >= maxHours ? zero : this.hours + step;
},
reduceHour(step) {
step = step || this.hourStep;
this.hours = this.hours <= zero ? maxHours : this.hours - step;
},
addMinute() {
if (this.minutes >= maxMinutes) {
this.minutes = zero;
this.addHour(1);
} else {
this.minutes += this.minStep;
}
},
reduceMinute() {
if (this.minutes <= zero) {
this.minutes = maxMinutes + 1 - this.minStep;
this.reduceHour(1);
} else {
this.minutes -= this.minStep;
}
},
changeTime(isHour, isPlus) {
if (!this.readonly) {
if (isHour && isPlus) {
this.addHour();
} else if (isHour && !isPlus) {
this.reduceHour();
} else if (!isHour && isPlus) {
this.addMinute();
} else {
this.reduceMinute();
}
this.setTime();
}
},
toggleMeridian() {
this.meridian = !this.meridian;
if (this.meridian) {
this.hours -= cutUpAmAndPm;
} else {
this.hours += cutUpAmAndPm;
}
this.setTime();
},
onWheel(e, isHour) {
if (!this.readonly) {
e.preventDefault();
this.changeTime(isHour, e.deltaY < 0);
}
},
setTime() {
let time = this.modelValue;
if (isNaN(time.getTime())) {
time = new Date();
time.setHours(0);
time.setMinutes(0);
}
time.setHours(this.hours);
time.setMinutes(this.minutes);
if (this.max instanceof Date) {
const max = new Date(time);
max.setHours(this.max.getHours());
max.setMinutes(this.max.getMinutes());
time = time > max ? max : time;
}
if (this.min instanceof Date) {
const min = new Date(time);
min.setHours(this.min.getHours());
min.setMinutes(this.min.getMinutes());
time = time < min ? min : time;
}
this.$emit("update:modelValue", new Date(time));
},
selectInputValue(e) {
e.target.setSelectionRange(0, 2);
}
}
};
const _hoisted_1 = {
key: 0,
class: "text-center"
};
const _hoisted_2 = /* @__PURE__ */ createElementVNode("td", null, "\xA0", -1);
const _hoisted_3 = { key: 0 };
const _hoisted_4 = { class: "form-group" };
const _hoisted_5 = ["readonly"];
const _hoisted_6 = /* @__PURE__ */ createElementVNode("td", null, [
/* @__PURE__ */ createTextVNode("\xA0"),
/* @__PURE__ */ createElementVNode("b", null, ":"),
/* @__PURE__ */ createTextVNode("\xA0")
], -1);
const _hoisted_7 = { class: "form-group" };
const _hoisted_8 = ["readonly"];
const _hoisted_9 = { key: 0 };
const _hoisted_10 = /* @__PURE__ */ createTextVNode(" \xA0 ");
const _hoisted_11 = {
key: 1,
class: "text-center"
};
const _hoisted_12 = /* @__PURE__ */ createElementVNode("td", null, "\xA0", -1);
const _hoisted_13 = { key: 0 };
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
const _component_btn = resolveComponent("btn");
return openBlock(), createElementBlock("section", {
onClick: _cache[14] || (_cache[14] = withModifiers(() => {
}, ["stop"]))
}, [
createElementVNode("table", null, [
createElementVNode("tbody", null, [
$props.controls ? (openBlock(), createElementBlock("tr", _hoisted_1, [
createElementVNode("td", null, [
createVNode(_component_btn, {
type: "link",
size: "sm",
disabled: $props.readonly,
onClick: _cache[0] || (_cache[0] = ($event) => $options.changeTime(1, 1))
}, {
default: withCtx(() => [
createElementVNode("i", {
class: normalizeClass($props.iconControlUp)
}, null, 2)
]),
_: 1
}, 8, ["disabled"])
]),
_hoisted_2,
createElementVNode("td", null, [
createVNode(_component_btn, {
type: "link",
size: "sm",
disabled: $props.readonly,
onClick: _cache[1] || (_cache[1] = ($event) => $options.changeTime(0, 1))
}, {
default: withCtx(() => [
createElementVNode("i", {
class: normalizeClass($props.iconControlUp)
}, null, 2)
]),
_: 1
}, 8, ["disabled"])
]),
$props.showMeridian ? (openBlock(), createElementBlock("td", _hoisted_3)) : createCommentVNode("", true)
])) : createCommentVNode("", true),
createElementVNode("tr", null, [
createElementVNode("td", _hoisted_4, [
withDirectives(createElementVNode("input", {
ref: "hoursInput",
"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => $data.hoursText = $event),
type: "tel",
pattern: "\\d*",
class: "form-control text-center",
style: normalizeStyle($options.inputStyles),
placeholder: "HH",
readonly: $props.readonly,
maxlength: "2",
size: "2",
onMouseup: _cache[3] || (_cache[3] = (...args) => $options.selectInputValue && $options.selectInputValue(...args)),
onKeydown: [
_cache[4] || (_cache[4] = withKeys(withModifiers(($event) => $options.changeTime(1, 1), ["prevent"]), ["up"])),
_cache[5] || (_cache[5] = withKeys(withModifiers(($event) => $options.changeTime(1, 0), ["prevent"]), ["down"]))
],
onWheel: _cache[6] || (_cache[6] = ($event) => $options.onWheel($event, true))
}, null, 44, _hoisted_5), [
[
vModelText,
$data.hoursText,
void 0,
{ lazy: true }
]
])
]),
_hoisted_6,
createElementVNode("td", _hoisted_7, [
withDirectives(createElementVNode("input", {
ref: "minutesInput",
"onUpdate:modelValue": _cache[7] || (_cache[7] = ($event) => $data.minutesText = $event),
type: "tel",
pattern: "\\d*",
class: "form-control text-center",
style: normalizeStyle($options.inputStyles),
placeholder: "MM",
readonly: $props.readonly,
maxlength: "2",
size: "2",
onMouseup: _cache[8] || (_cache[8] = (...args) => $options.selectInputValue && $options.selectInputValue(...args)),
onKeydown: [
_cache[9] || (_cache[9] = withKeys(withModifiers(($event) => $options.changeTime(0, 1), ["prevent"]), ["up"])),
_cache[10] || (_cache[10] = withKeys(withModifiers(($event) => $options.changeTime(0, 0), ["prevent"]), ["down"]))
],
onWheel: _cache[11] || (_cache[11] = ($event) => $options.onWheel($event, false))
}, null, 44, _hoisted_8), [
[
vModelText,
$data.minutesText,
void 0,
{ lazy: true }
]
])
]),
$props.showMeridian ? (openBlock(), createElementBlock("td", _hoisted_9, [
_hoisted_10,
createVNode(_component_btn, {
"data-action": "toggleMeridian",
disabled: $props.readonly,
onClick: $options.toggleMeridian,
textContent: toDisplayString($data.meridian ? $options.t("uiv.timePicker.am") : $options.t("uiv.timePicker.pm"))
}, null, 8, ["disabled", "onClick", "textContent"])
])) : createCommentVNode("", true)
]),
$props.controls ? (openBlock(), createElementBlock("tr", _hoisted_11, [
createElementVNode("td", null, [
createVNode(_component_btn, {
type: "link",
size: "sm",
disabled: $props.readonly,
onClick: _cache[12] || (_cache[12] = ($event) => $options.changeTime(1, 0))
}, {
default: withCtx(() => [
createElementVNode("i", {
class: normalizeClass($props.iconControlDown)
}, null, 2)
]),
_: 1
}, 8, ["disabled"])
]),
_hoisted_12,
createElementVNode("td", null, [
createVNode(_component_btn, {
type: "link",
size: "sm",
disabled: $props.readonly,
onClick: _cache[13] || (_cache[13] = ($event) => $options.changeTime(0, 0))
}, {
default: withCtx(() => [
createElementVNode("i", {
class: normalizeClass($props.iconControlDown)
}, null, 2)
]),
_: 1
}, 8, ["disabled"])
]),
$props.showMeridian ? (openBlock(), createElementBlock("td", _hoisted_13)) : createCommentVNode("", true)
])) : createCommentVNode("", true)
])
])
]);
}
var TimePicker = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render]]);
export { TimePicker as default };
|
/**
* Safe chained function
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*
* @param {function} functions to chain
* @returns {function|null}
*/
export default function createChainedFunction() {
for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.reduce(function (acc, func) {
if (func == null) {
return acc;
}
if (process.env.NODE_ENV !== 'production') {
if (typeof func !== 'function') {
console.error('Material-UI: Invalid Argument Type, must only provide functions, undefined, or null.');
}
}
return function chainedFunction() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
acc.apply(this, args);
func.apply(this, args);
};
}, function () {});
} |
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.reset = reset;
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 _utils = require("@material-ui/utils");
var _styles = require("@material-ui/styles");
var _Drawer = _interopRequireWildcard(require("../Drawer/Drawer"));
var _ownerDocument = _interopRequireDefault(require("../utils/ownerDocument"));
var _ownerWindow = _interopRequireDefault(require("../utils/ownerWindow"));
var _useEventCallback = _interopRequireDefault(require("../utils/useEventCallback"));
var _useEnhancedEffect = _interopRequireDefault(require("../utils/useEnhancedEffect"));
var _transitions = require("../styles/transitions");
var _useTheme = _interopRequireDefault(require("../styles/useTheme"));
var _utils2 = require("../transitions/utils");
var _NoSsr = _interopRequireDefault(require("../NoSsr"));
var _SwipeArea = _interopRequireDefault(require("./SwipeArea"));
// This value is closed to what browsers are using internally to
// trigger a native scroll.
const UNCERTAINTY_THRESHOLD = 3; // px
// This is the part of the drawer displayed on touch start.
const DRAG_STARTED_SIGNAL = 20; // px
// We can only have one instance at the time claiming ownership for handling the swipe.
// Otherwise, the UX would be confusing.
// That's why we use a singleton here.
let claimedSwipeInstance = null; // Exported for test purposes.
function reset() {
claimedSwipeInstance = null;
}
function calculateCurrentX(anchor, touches, doc) {
return anchor === 'right' ? doc.body.offsetWidth - touches[0].pageX : touches[0].pageX;
}
function calculateCurrentY(anchor, touches, containerWindow) {
return anchor === 'bottom' ? containerWindow.innerHeight - touches[0].clientY : touches[0].clientY;
}
function getMaxTranslate(horizontalSwipe, paperInstance) {
return horizontalSwipe ? paperInstance.clientWidth : paperInstance.clientHeight;
}
function getTranslate(currentTranslate, startLocation, open, maxTranslate) {
return Math.min(Math.max(open ? startLocation - currentTranslate : maxTranslate + startLocation - currentTranslate, 0), maxTranslate);
}
/**
* @param {Element | null} element
* @param {Element} rootNode
*/
function getDomTreeShapes(element, rootNode) {
// Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L129
const domTreeShapes = [];
while (element && element !== rootNode.parentElement) {
const style = (0, _ownerWindow.default)(rootNode).getComputedStyle(element);
if ( // Ignore the scroll children if the element is absolute positioned.
style.getPropertyValue('position') === 'absolute' || // Ignore the scroll children if the element has an overflowX hidden
style.getPropertyValue('overflow-x') === 'hidden') {// noop
} else if (element.clientWidth > 0 && element.scrollWidth > element.clientWidth || element.clientHeight > 0 && element.scrollHeight > element.clientHeight) {
// Ignore the nodes that have no width.
// Keep elements with a scroll
domTreeShapes.push(element);
}
element = element.parentElement;
}
return domTreeShapes;
}
/**
* @param {object} param0
* @param {ReturnType<getDomTreeShapes>} param0.domTreeShapes
*/
function computeHasNativeHandler({
domTreeShapes,
start,
current,
anchor
}) {
// Adapted from https://github.com/oliviertassinari/react-swipeable-views/blob/7666de1dba253b896911adf2790ce51467670856/packages/react-swipeable-views/src/SwipeableViews.js#L175
const axisProperties = {
scrollPosition: {
x: 'scrollLeft',
y: 'scrollTop'
},
scrollLength: {
x: 'scrollWidth',
y: 'scrollHeight'
},
clientLength: {
x: 'clientWidth',
y: 'clientHeight'
}
};
return domTreeShapes.some(shape => {
// Determine if we are going backward or forward.
let goingForward = current >= start;
if (anchor === 'top' || anchor === 'left') {
goingForward = !goingForward;
}
const axis = anchor === 'left' || anchor === 'right' ? 'x' : 'y';
const scrollPosition = Math.round(shape[axisProperties.scrollPosition[axis]]);
const areNotAtStart = scrollPosition > 0;
const areNotAtEnd = scrollPosition + shape[axisProperties.clientLength[axis]] < shape[axisProperties.scrollLength[axis]];
if (goingForward && areNotAtEnd || !goingForward && areNotAtStart) {
return true;
}
return false;
});
}
const iOS = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent);
const transitionDurationDefault = {
enter: _transitions.duration.enteringScreen,
exit: _transitions.duration.leavingScreen
};
const SwipeableDrawer = /*#__PURE__*/React.forwardRef(function SwipeableDrawer(inProps, ref) {
const theme = (0, _useTheme.default)();
const props = (0, _styles.getThemeProps)({
name: 'MuiSwipeableDrawer',
props: inProps,
theme
});
const {
anchor = 'left',
disableBackdropTransition = false,
disableDiscovery = false,
disableSwipeToOpen = iOS,
hideBackdrop,
hysteresis = 0.52,
minFlingVelocity = 450,
ModalProps: {
BackdropProps
} = {},
onClose,
onOpen,
open,
PaperProps = {},
SwipeAreaProps,
swipeAreaWidth = 20,
transitionDuration = transitionDurationDefault,
variant = 'temporary'
} = props,
ModalPropsProp = (0, _objectWithoutPropertiesLoose2.default)(props.ModalProps, ["BackdropProps"]),
other = (0, _objectWithoutPropertiesLoose2.default)(props, ["anchor", "disableBackdropTransition", "disableDiscovery", "disableSwipeToOpen", "hideBackdrop", "hysteresis", "minFlingVelocity", "ModalProps", "onClose", "onOpen", "open", "PaperProps", "SwipeAreaProps", "swipeAreaWidth", "transitionDuration", "variant"]);
const [maybeSwiping, setMaybeSwiping] = React.useState(false);
const swipeInstance = React.useRef({
isSwiping: null
});
const swipeAreaRef = React.useRef();
const backdropRef = React.useRef();
const paperRef = React.useRef();
const touchDetected = React.useRef(false); // Ref for transition duration based on / to match swipe speed
const calculatedDurationRef = React.useRef(); // Use a ref so the open value used is always up to date inside useCallback.
(0, _useEnhancedEffect.default)(() => {
calculatedDurationRef.current = null;
}, [open]);
const setPosition = React.useCallback((translate, options = {}) => {
const {
mode = null,
changeTransition = true
} = options;
const anchorRtl = (0, _Drawer.getAnchor)(theme, anchor);
const rtlTranslateMultiplier = ['right', 'bottom'].indexOf(anchorRtl) !== -1 ? 1 : -1;
const horizontalSwipe = (0, _Drawer.isHorizontal)(anchor);
const transform = horizontalSwipe ? `translate(${rtlTranslateMultiplier * translate}px, 0)` : `translate(0, ${rtlTranslateMultiplier * translate}px)`;
const drawerStyle = paperRef.current.style;
drawerStyle.webkitTransform = transform;
drawerStyle.transform = transform;
let transition = '';
if (mode) {
transition = theme.transitions.create('all', (0, _utils2.getTransitionProps)({
timeout: transitionDuration
}, {
mode
}));
}
if (changeTransition) {
drawerStyle.webkitTransition = transition;
drawerStyle.transition = transition;
}
if (!disableBackdropTransition && !hideBackdrop) {
const backdropStyle = backdropRef.current.style;
backdropStyle.opacity = 1 - translate / getMaxTranslate(horizontalSwipe, paperRef.current);
if (changeTransition) {
backdropStyle.webkitTransition = transition;
backdropStyle.transition = transition;
}
}
}, [anchor, disableBackdropTransition, hideBackdrop, theme, transitionDuration]);
const handleBodyTouchEnd = (0, _useEventCallback.default)(nativeEvent => {
if (!touchDetected.current) {
return;
}
claimedSwipeInstance = null;
touchDetected.current = false;
setMaybeSwiping(false); // The swipe wasn't started.
if (!swipeInstance.current.isSwiping) {
swipeInstance.current.isSwiping = null;
return;
}
swipeInstance.current.isSwiping = null;
const anchorRtl = (0, _Drawer.getAnchor)(theme, anchor);
const horizontal = (0, _Drawer.isHorizontal)(anchor);
let current;
if (horizontal) {
current = calculateCurrentX(anchorRtl, nativeEvent.changedTouches, (0, _ownerDocument.default)(nativeEvent.currentTarget));
} else {
current = calculateCurrentY(anchorRtl, nativeEvent.changedTouches, (0, _ownerWindow.default)(nativeEvent.currentTarget));
}
const startLocation = horizontal ? swipeInstance.current.startX : swipeInstance.current.startY;
const maxTranslate = getMaxTranslate(horizontal, paperRef.current);
const currentTranslate = getTranslate(current, startLocation, open, maxTranslate);
const translateRatio = currentTranslate / maxTranslate;
if (Math.abs(swipeInstance.current.velocity) > minFlingVelocity) {
// Calculate transition duration to match swipe speed
calculatedDurationRef.current = Math.abs((maxTranslate - currentTranslate) / swipeInstance.current.velocity) * 1000;
}
if (open) {
if (swipeInstance.current.velocity > minFlingVelocity || translateRatio > hysteresis) {
onClose();
} else {
// Reset the position, the swipe was aborted.
setPosition(0, {
mode: 'exit'
});
}
return;
}
if (swipeInstance.current.velocity < -minFlingVelocity || 1 - translateRatio > hysteresis) {
onOpen();
} else {
// Reset the position, the swipe was aborted.
setPosition(getMaxTranslate(horizontal, paperRef.current), {
mode: 'enter'
});
}
});
const handleBodyTouchMove = (0, _useEventCallback.default)(nativeEvent => {
// the ref may be null when a parent component updates while swiping
if (!paperRef.current || !touchDetected.current) {
return;
} // We are not supposed to handle this touch move because the swipe was started in a scrollable container in the drawer
if (claimedSwipeInstance !== null && claimedSwipeInstance !== swipeInstance.current) {
return;
}
const anchorRtl = (0, _Drawer.getAnchor)(theme, anchor);
const horizontalSwipe = (0, _Drawer.isHorizontal)(anchor);
const currentX = calculateCurrentX(anchorRtl, nativeEvent.touches, (0, _ownerDocument.default)(nativeEvent.currentTarget));
const currentY = calculateCurrentY(anchorRtl, nativeEvent.touches, (0, _ownerWindow.default)(nativeEvent.currentTarget));
if (open && paperRef.current.contains(nativeEvent.target) && claimedSwipeInstance === null) {
const domTreeShapes = getDomTreeShapes(nativeEvent.target, paperRef.current);
const hasNativeHandler = computeHasNativeHandler({
domTreeShapes,
start: horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY,
current: horizontalSwipe ? currentX : currentY,
anchor
});
if (hasNativeHandler) {
claimedSwipeInstance = true;
return;
}
claimedSwipeInstance = swipeInstance.current;
} // We don't know yet.
if (swipeInstance.current.isSwiping == null) {
const dx = Math.abs(currentX - swipeInstance.current.startX);
const dy = Math.abs(currentY - swipeInstance.current.startY);
const definitelySwiping = horizontalSwipe ? dx > dy && dx > UNCERTAINTY_THRESHOLD : dy > dx && dy > UNCERTAINTY_THRESHOLD;
if (definitelySwiping && nativeEvent.cancelable) {
nativeEvent.preventDefault();
}
if (definitelySwiping === true || (horizontalSwipe ? dy > UNCERTAINTY_THRESHOLD : dx > UNCERTAINTY_THRESHOLD)) {
swipeInstance.current.isSwiping = definitelySwiping;
if (!definitelySwiping) {
handleBodyTouchEnd(nativeEvent);
return;
} // Shift the starting point.
swipeInstance.current.startX = currentX;
swipeInstance.current.startY = currentY; // Compensate for the part of the drawer displayed on touch start.
if (!disableDiscovery && !open) {
if (horizontalSwipe) {
swipeInstance.current.startX -= DRAG_STARTED_SIGNAL;
} else {
swipeInstance.current.startY -= DRAG_STARTED_SIGNAL;
}
}
}
}
if (!swipeInstance.current.isSwiping) {
return;
}
const maxTranslate = getMaxTranslate(horizontalSwipe, paperRef.current);
let startLocation = horizontalSwipe ? swipeInstance.current.startX : swipeInstance.current.startY;
if (open && !swipeInstance.current.paperHit) {
startLocation = Math.min(startLocation, maxTranslate);
}
const translate = getTranslate(horizontalSwipe ? currentX : currentY, startLocation, open, maxTranslate);
if (open) {
if (!swipeInstance.current.paperHit) {
const paperHit = horizontalSwipe ? currentX < maxTranslate : currentY < maxTranslate;
if (paperHit) {
swipeInstance.current.paperHit = true;
swipeInstance.current.startX = currentX;
swipeInstance.current.startY = currentY;
} else {
return;
}
} else if (translate === 0) {
swipeInstance.current.startX = currentX;
swipeInstance.current.startY = currentY;
}
}
if (swipeInstance.current.lastTranslate === null) {
swipeInstance.current.lastTranslate = translate;
swipeInstance.current.lastTime = performance.now() + 1;
}
const velocity = (translate - swipeInstance.current.lastTranslate) / (performance.now() - swipeInstance.current.lastTime) * 1e3; // Low Pass filter.
swipeInstance.current.velocity = swipeInstance.current.velocity * 0.4 + velocity * 0.6;
swipeInstance.current.lastTranslate = translate;
swipeInstance.current.lastTime = performance.now(); // We are swiping, let's prevent the scroll event on iOS.
if (nativeEvent.cancelable) {
nativeEvent.preventDefault();
}
setPosition(translate);
});
const handleBodyTouchStart = (0, _useEventCallback.default)(nativeEvent => {
// We are not supposed to handle this touch move.
// Example of use case: ignore the event if there is a Slider.
if (nativeEvent.defaultPrevented) {
return;
} // We can only have one node at the time claiming ownership for handling the swipe.
if (nativeEvent.defaultMuiPrevented) {
return;
} // At least one element clogs the drawer interaction zone.
if (open && !backdropRef.current.contains(nativeEvent.target) && !paperRef.current.contains(nativeEvent.target)) {
return;
}
const anchorRtl = (0, _Drawer.getAnchor)(theme, anchor);
const horizontalSwipe = (0, _Drawer.isHorizontal)(anchor);
const currentX = calculateCurrentX(anchorRtl, nativeEvent.touches, (0, _ownerDocument.default)(nativeEvent.currentTarget));
const currentY = calculateCurrentY(anchorRtl, nativeEvent.touches, (0, _ownerWindow.default)(nativeEvent.currentTarget));
if (!open) {
if (disableSwipeToOpen || nativeEvent.target !== swipeAreaRef.current) {
return;
}
if (horizontalSwipe) {
if (currentX > swipeAreaWidth) {
return;
}
} else if (currentY > swipeAreaWidth) {
return;
}
}
nativeEvent.defaultMuiPrevented = true;
claimedSwipeInstance = null;
swipeInstance.current.startX = currentX;
swipeInstance.current.startY = currentY;
setMaybeSwiping(true);
if (!open && paperRef.current) {
// The ref may be null when a parent component updates while swiping.
setPosition(getMaxTranslate(horizontalSwipe, paperRef.current) + (disableDiscovery ? 15 : -DRAG_STARTED_SIGNAL), {
changeTransition: false
});
}
swipeInstance.current.velocity = 0;
swipeInstance.current.lastTime = null;
swipeInstance.current.lastTranslate = null;
swipeInstance.current.paperHit = false;
touchDetected.current = true;
});
React.useEffect(() => {
if (variant === 'temporary') {
const doc = (0, _ownerDocument.default)(paperRef.current);
doc.addEventListener('touchstart', handleBodyTouchStart); // A blocking listener prevents Firefox's navbar to auto-hide on scroll.
// It only needs to prevent scrolling on the drawer's content when open.
// When closed, the overlay prevents scrolling.
doc.addEventListener('touchmove', handleBodyTouchMove, {
passive: !open
});
doc.addEventListener('touchend', handleBodyTouchEnd);
return () => {
doc.removeEventListener('touchstart', handleBodyTouchStart);
doc.removeEventListener('touchmove', handleBodyTouchMove, {
passive: !open
});
doc.removeEventListener('touchend', handleBodyTouchEnd);
};
}
return undefined;
}, [variant, open, handleBodyTouchStart, handleBodyTouchMove, handleBodyTouchEnd]);
React.useEffect(() => () => {
// We need to release the lock.
if (claimedSwipeInstance === swipeInstance.current) {
claimedSwipeInstance = null;
}
}, []);
React.useEffect(() => {
if (!open) {
setMaybeSwiping(false);
}
}, [open]);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_Drawer.default, (0, _extends2.default)({
open: variant === 'temporary' && maybeSwiping ? true : open,
variant: variant,
ModalProps: (0, _extends2.default)({
BackdropProps: (0, _extends2.default)({}, BackdropProps, {
ref: backdropRef
})
}, ModalPropsProp),
PaperProps: (0, _extends2.default)({}, PaperProps, {
style: (0, _extends2.default)({
pointerEvents: variant === 'temporary' && !open ? 'none' : ''
}, PaperProps.style),
ref: paperRef
}),
anchor: anchor,
transitionDuration: calculatedDurationRef.current || transitionDuration,
onClose: onClose,
ref: ref
}, other)), !disableSwipeToOpen && variant === 'temporary' && /*#__PURE__*/React.createElement(_NoSsr.default, null, /*#__PURE__*/React.createElement(_SwipeArea.default, (0, _extends2.default)({
anchor: anchor,
ref: swipeAreaRef,
width: swipeAreaWidth
}, SwipeAreaProps))));
});
process.env.NODE_ENV !== "production" ? SwipeableDrawer.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
anchor: _propTypes.default.oneOf(['bottom', 'left', 'right', 'top']),
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Disable the backdrop transition.
* This can improve the FPS on low-end devices.
* @default false
*/
disableBackdropTransition: _propTypes.default.bool,
/**
* If `true`, touching the screen near the edge of the drawer will not slide in the drawer a bit
* to promote accidental discovery of the swipe gesture.
* @default false
*/
disableDiscovery: _propTypes.default.bool,
/**
* If `true`, swipe to open is disabled. This is useful in browsers where swiping triggers
* navigation actions. Swipe to open is disabled on iOS browsers by default.
* @default typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)
*/
disableSwipeToOpen: _propTypes.default.bool,
/**
* @ignore
*/
hideBackdrop: _propTypes.default.bool,
/**
* Affects how far the drawer must be opened/closed to change his state.
* Specified as percent (0-1) of the width of the drawer
* @default 0.52
*/
hysteresis: _propTypes.default.number,
/**
* Defines, from which (average) velocity on, the swipe is
* defined as complete although hysteresis isn't reached.
* Good threshold is between 250 - 1000 px/s
* @default 450
*/
minFlingVelocity: _propTypes.default.number,
/**
* @ignore
*/
ModalProps: _propTypes.default
/* @typescript-to-proptypes-ignore */
.shape({
BackdropProps: _propTypes.default.shape({
component: _utils.elementTypeAcceptingRef
})
}),
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
*/
onClose: _propTypes.default.func.isRequired,
/**
* Callback fired when the component requests to be opened.
*
* @param {object} event The event source of the callback.
*/
onOpen: _propTypes.default.func.isRequired,
/**
* If `true`, the component is shown.
*/
open: _propTypes.default.bool.isRequired,
/**
* @ignore
*/
PaperProps: _propTypes.default
/* @typescript-to-proptypes-ignore */
.shape({
component: _utils.elementTypeAcceptingRef,
style: _propTypes.default.object
}),
/**
* The element is used to intercept the touch events on the edge.
*/
SwipeAreaProps: _propTypes.default.object,
/**
* The width of the left most (or right most) area in `px` that
* the drawer can be swiped open from.
* @default 20
*/
swipeAreaWidth: _propTypes.default.number,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
* @default { enter: duration.enteringScreen, exit: duration.leavingScreen }
*/
transitionDuration: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.shape({
appear: _propTypes.default.number,
enter: _propTypes.default.number,
exit: _propTypes.default.number
})]),
/**
* @ignore
*/
variant: _propTypes.default.oneOf(['permanent', 'persistent', 'temporary'])
} : void 0;
var _default = SwipeableDrawer;
exports.default = _default; |
/*!
* froala_editor v1.2.3 (http://editor.froala.com)
* Copyright 2014-2014 Froala
*/
/**
* German
*/
$.Editable.LANGS['de'] = {
translation: {
"Bold": "Fett",
"Italic": "Kursiv",
"Underline": "Unterstrichen",
"Strikethrough": "Durchgestrichen",
"Font Size": "Schriftgr\u00f6\u00dfe",
"Color": "Farbe",
"Background": "Hintergrund",
"Text": "Text",
"Format Block": "Formate",
"Normal": "Normal",
"Paragraph": "Absatz",
"Code": "Quelltext",
"Quote": "Zitat",
"Heading 1": "\u00dcberschrift 1",
"Heading 2": "\u00dcberschrift 2",
"Heading 3": "\u00dcberschrift 3",
"Heading 4": "\u00dcberschrift 4",
"Heading 5": "\u00dcberschrift 5",
"Heading 6": "\u00dcberschrift 6",
"Block Style": "Block-Stil",
"Alignment": "Ausrichtung",
"Align Left": "Linksb\u00fcndig ausrichten",
"Align Center": "Zentriert ausrichten",
"Align Right": "Rechtsb\u00fcndig ausrichten",
"Justify": "Blocksatz",
"Numbered List": "Nummerierte Liste",
"Bulleted List": "Aufz\u00e4hlung",
"Indent Less": "Einzug verkleinern",
"Indent More": "Einzug vergr\u00f6\u00dfern",
"Select All": "Alles ausw\u00e4hlen",
"Insert Link": "Link einf\u00fcgen",
"Insert Image": "Bild einf\u00fcgen",
"Insert Video": "Video einf\u00fcgen",
"Undo": "R\u00fcckg\u00e4ngig",
"Redo": "Wiederholen",
"Show HTML": "HTML anzeigen",
"Float Left": "Linksb\u00fcndig",
"Float None": "Keine",
"Float Right": "Rechtsb\u00fcndig",
"Replace Image": "Bild ersetzen",
"Remove Image": "Bild entfernen",
"Title": "Titel",
"Drop image": "Ziehen Sie ein Bild hierhin",
"or click": "oder klicken Sie auf",
"or": "oder",
"Enter URL": "URL eingeben",
"Please wait!": "Bitte warten Sie!",
"Are you sure? Image will be deleted.": "Sind Sie sicher? Das Bild wird gel\u00f6scht.",
"UNLINK": "Link entfernen",
"Open in new tab": "In neuer Registerkarte \u00f6ffnen",
"Type something": "Schreiben Sie etwas",
"Cancel": "Abbrechen",
"OK": "Ok",
"Manage images": "Bilder verwalten",
"Delete": "L\u00f6schen",
"Font Family": "Schriftart",
"Insert Horizontal Line": "Horizontale Linie Einf\u00fcgen",
"Table": "Tabelle",
"Insert table": "Tabelle einf\u00fcgen",
"Cell": "Zelle",
"Row": "Zeile",
"Column": "Spalte",
"Delete table": "Tabelle l\u00f6schen",
"Insert cell before": "Neue zelle davor einf\u00fcgen",
"Insert cell after": "Neue zelle danach einf\u00fcgen",
"Delete cell": "Zelle l\u00f6schen",
"Merge cells": "Zelle verschmelzen",
"Horizontal split": "Horizontal aufteilung",
"Vertical split": "Vertikal aufteilung",
"Insert row above": "Neue Zeile davor einf\u00fcgen",
"Insert row below": "Neue Zeile danach einf\u00fcgen",
"Delete row": "Zeile l\u00f6schen",
"Insert column before": "Neue Spalte davor einf\u00fcgen",
"Insert column after": "Neue Spalte danach einf\u00fcgen",
"Delete column": "Spalte l\u00f6schen"
},
direction: "ltr"
}; |
'use strict'
var should = require('should')
var config = require('../lib/config')
, reserved = require('../config/reserved')
, Grant = require('../').express()
describe('config', function () {
describe('initProvider', function () {
it('shortcuts', function () {
var provider = {}, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
grant:true, name:'grant'
})
})
it('consumer_key and consumer_secret', function () {
var provider = {consumer_key:'key', consumer_secret:'secret', oauth:1}
, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
consumer_key: 'key', consumer_secret: 'secret', oauth: 1,
grant: true, name: 'grant', key: 'key', secret: 'secret'
})
})
it('client_id and client_secret', function () {
var provider = {client_id:'key', client_secret:'secret', oauth:2}
, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
client_id: 'key', client_secret: 'secret', oauth: 2,
grant: true, name: 'grant', key: 'key', secret: 'secret'
})
})
describe('scope', function () {
it('array with comma', function () {
var provider = {scope:['scope1','scope2']}
, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
scope:'scope1,scope2', grant:true, name:'grant'
})
})
it('array with delimiter', function () {
var provider = {scope:['scope1','scope2'], scope_delimiter:' '}
, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
scope:'scope1 scope2', scope_delimiter:' ', grant:true, name:'grant'
})
})
it('stringify scope object', function () {
var provider = {scope:{profile:{read:true}}}
, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
scope:'{"profile":{"read":true}}', grant:true, name:'grant'
})
})
it('string', function () {
var provider = {scope:'scope1,scope2'}
, options = {}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
scope:'scope1,scope2', grant:true, name:'grant'
})
})
})
describe('custom_params', function () {
it('empty keys in options.custom_params are excluded', function () {
var provider = {custom_params:{name:'grant'}}
, options = {custom_params:{name:''}}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_params:{name:'grant'}, grant:true, name:'grant'
})
})
it('options.custom_params override provider.custom_params', function () {
var provider = {custom_params:{name:'grant'}}
, options = {custom_params:{name:'purest'}}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_params:{name:'purest'}, grant:true, name:'grant'
})
})
})
describe('custom_parameters', function () {
it('skip params not defined in custom_parameters', function () {
var provider = {custom_parameters:['access_type']}
, options = {something:'interesting'}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_parameters:['access_type'], grant:true, name:'grant'
})
})
it('skip params that are reserved keys', function () {
var provider = {custom_parameters:['name']}
, options = {name:'purest'}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_parameters:['name'], grant:true, name:'grant'
})
})
it('set custom_parameters value', function () {
var provider = {custom_parameters:['expiration']}
, options = {expiration:'never'}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_parameters:['expiration'], custom_params:{expiration:'never'},
grant:true, name:'grant'
})
})
it('set object as custom_parameters value', function () {
var provider = {custom_parameters:['meta']}
, options = {meta:{a:'b'}}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_parameters:['meta'], custom_params:{meta:{a:'b'}},
grant:true, name:'grant'
})
})
it('custom_parameters extends provider.custom_params', function () {
var provider = {custom_parameters:['expiration'], custom_params:{name:'grant'}}
, options = {expiration:'never'}, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
custom_parameters:['expiration'],
custom_params:{name:'grant', expiration:'never'},
grant:true, name:'grant'
})
})
})
describe('overrides', function () {
it('set overrides', function () {
var provider = {scope:['scope'], callback:'/callback'}
, options = {sub1:{scope:['scope1']}, sub2:{scope:['scope2']}}
, server = {}, name = 'grant'
var result = config.initProvider(provider, options, server, name)
should.deepEqual(result, {
scope:'scope', callback:'/callback', grant:true, name:'grant',
overrides:{sub1:{
scope:'scope1', callback:'/callback', grant:true, name:'grant'
}, sub2:{
scope:'scope2', callback:'/callback', grant:true, name:'grant'
}}
})
})
})
})
describe('init', function () {
it('initialize only the specified providers', function () {
var options = {
server:{protocol:'http', host:'localhost:3000'},
facebook:{},
custom:{}
}
var result = config.init(options)
should.deepEqual(result, {
server:{protocol:'http', host:'localhost:3000'},
facebook:{
authorize_url:'https://www.facebook.com/dialog/oauth',
access_url:'https://graph.facebook.com/oauth/access_token',
oauth:2, facebook:true, name:'facebook',
protocol:'http', host:'localhost:3000'
},
custom:{
custom:true, name:'custom',
protocol:'http', host:'localhost:3000'
}
})
})
it('initialize without server key', function () {
var options = {
facebook:{protocol:'http', host:'localhost:3000'},
custom:{protocol:'http', host:'localhost:3000'}
}
var result = config.init(options)
should.deepEqual(result, {
server:{},
facebook:{
authorize_url:'https://www.facebook.com/dialog/oauth',
access_url:'https://graph.facebook.com/oauth/access_token',
oauth:2, facebook:true, name:'facebook',
protocol:'http', host:'localhost:3000'
},
custom:{
custom:true, name:'custom',
protocol:'http', host:'localhost:3000'
}
})
})
})
describe('state', function () {
it('string', function () {
var provider = {state:'123'}
, result = config.state(provider)
result.should.equal('123')
})
it('number', function () {
var provider = {state:123}
, result = config.state(provider)
result.should.equal('123')
})
it('boolean true', function () {
var provider = {state:true}
, result = config.state(provider)
result.should.be.type('string')
result.should.match(/^\w+$/)
})
it('boolean false', function () {
var provider = {state:false}
, result = config.state(provider)
should.equal(result, undefined)
})
})
describe('provider', function () {
it('pre configured', function () {
var options = {grant:{name:'grant'}}
, session = {provider:'grant'}
var result = config.provider(options, session)
should.deepEqual(result, {name:'grant'})
should.deepEqual(options, {grant:{name:'grant'}})
})
it('non configured, existing oauth provider', function () {
var options = {}
, session = {provider:'facebook'}
var result = config.provider(options, session)
should.deepEqual(result, {
authorize_url:'https://www.facebook.com/dialog/oauth',
access_url:'https://graph.facebook.com/oauth/access_token',
oauth:2, facebook:true, name:'facebook'
})
should.deepEqual(options, {facebook:{
authorize_url:'https://www.facebook.com/dialog/oauth',
access_url:'https://graph.facebook.com/oauth/access_token',
oauth:2, facebook:true, name:'facebook'
}})
})
it('non configured, non existing oauth provider', function () {
var options = {}
, session = {provider:'grant'}
var result = config.provider(options, session)
should.deepEqual(result, {})
should.deepEqual(options, {})
})
describe('overrides', function () {
it('no existing overrides - defaults to provider', function () {
var options = {grant:{callback:'/'}}
, session = {provider:'grant', override:'purest'}
var result = config.provider(options, session)
should.deepEqual(result, {callback:'/'})
})
it('non existing override - defaults to provider', function () {
var options = {grant:{
callback:'/', overrides:{oauth:{callback:'/callback'}}
}}
var session = {provider:'grant', override:'purest'}
var result = config.provider(options, session)
should.deepEqual(result, {
callback:'/', overrides:{oauth:{callback:'/callback'}}
})
})
it('pick override', function () {
var options = {grant:{
callback:'/', overrides:{purest:{callback:'/callback'}}
}}
var session = {provider:'grant', override:'purest'}
var result = config.provider(options, session)
should.deepEqual(result, {callback:'/callback'})
})
})
describe('dynamic', function () {
it('override provider key', function () {
var options = {grant:{callback:'/'}}
, session = {provider:'grant', dynamic:{callback:'/callback'}}
var result = config.provider(options, session)
should.deepEqual(result, {callback:'/callback'})
})
it('override custom_parameters string value', function () {
var options = {grant:{custom_parameters:['expiration']}}
var session = {
provider:'grant',
dynamic:{expiration:'never', custom_params:{name:'grant'}}
}
var result = config.provider(options, session)
should.deepEqual(result, {
custom_parameters:['expiration'],
custom_params:{name:'grant', expiration:'never'}
})
})
it('override custom_parameters object value', function () {
var options = {grant:{custom_parameters:['meta']}}
var session = {
provider:'grant', dynamic:{meta:{a:'b'}}
}
var result = config.provider(options, session)
should.deepEqual(result, {
custom_parameters:['meta'], custom_params:{meta:{a:'b'}}
})
})
})
describe('state', function () {
it('state dcopy', function () {
var options = {grant:{state:true}}
, session = {provider:'grant'}
var result = config.provider(options, session)
result.state.should.be.type('string')
result.state.should.match(/\d+/)
should.deepEqual(options, {grant:{state:true}})
})
})
})
describe('expose', function () {
it('config and _config', function () {
var grant = new Grant()
grant.config.should.be.type('object')
grant._config.oauth.should.be.type('object')
})
})
})
|
/**
* Created by yunshengli on 2014/10/22.
*/
(function(window) {
var LOG_LEVELS = ["DEBUG", "LOG", "INFO", "WARN", "ERROR"], //日志级别
//TODO 是否可以做成队列阈值和倒计时时间由UI配置?
THRESHOLD = 200, // 触发日志上传的阈值,设置大一点,避免高频的请求导致并发问题
TIMER = 1000, // 倒计时,间隔发送时间
URL = location.protocol + "//__rosin__.qq.com",
KEY = +new Date() + '_' + parseInt(Math.random() * 1e8); // 每个页面生成一个唯一key
// https的请求,使用另外的通信协议
if(location.protocol === "https:") {
URL = "https://" + location.host + '/?__rosin__';
}
/**
* 上传任务队列
* 队列长度达到阈值触发POST日志
* @type {{_queueArr: Array, add: add, _post: _post}}
*/
var queue = {
_queueArr: [], //数组模拟队列
add: function() {
Array.prototype.push.apply(this._queueArr, arguments);
clock.start();
//队列达到阈值就触发上传
if (this._queueArr.length >= THRESHOLD) {
this._post(this._queueArr.splice(0, this._queueArr.length));
return;
}
},
_post: function(logArr) {
var headers = {};
var setHeader = function(name, value) {
headers[name.toLowerCase()] = [name, value]
};
var xhr = new XMLHttpRequest();
var nativeSetHeader = xhr.setRequestHeader;
setHeader('Accept', '*/*');
setHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader = setHeader;
xhr.onreadystatechange = function(){}; // do nothing
xhr.open('POST', URL, true);
// chrome 控制台会看到一个报错
// A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
// xhr.withCredentials = true;
for (name in headers) nativeSetHeader.apply(xhr, headers[name]);
xhr.send(JSON.stringify(logArr));
}
},
/**
* 自定义日志对象
* @type {{DELIMITER: string, _record: _record, debug: debug, log: log, info: info, warn: warn, error: error}}
*/
FConsole = {
DELIMITER: " ", //分隔符
JSON_TAG_LEFT: '\uFFFE', // 用于标识json对象字符串的等宽字符
JSON_TAG_RIGHT: '\uFEFF',
_record: function(logLevel) {
var log = {
"key": KEY,
"level": logLevel, //日志级别
"time": new Date().getTime() //日志时间,时间戳
// "url" : window.location.href //记录日志的URL
},
content = ""; //日志内容
for (var i = 1; i < arguments.length; i++) {
if (Array.isArray(arguments[i])) {
content += (i === 1 ? "" : FConsole.DELIMITER) + FConsole.JSON_TAG_LEFT + "[" + arguments[i] + "]" + FConsole.JSON_TAG_RIGHT;
} else if (typeof arguments[i] === "object") {
content += (i === 1 ? "" : FConsole.DELIMITER) + FConsole.JSON_TAG_LEFT + JSON.stringify(arguments[i]) + FConsole.JSON_TAG_RIGHT;
} else {
content += (i === 1 ? "" : FConsole.DELIMITER) + arguments[i];
}
}
log["content"] = content;
//日志记录加入队列
queue.add(log)
},
debug: function() {
Array.prototype.unshift.call(arguments, LOG_LEVELS[0]);
FConsole._record.apply(FConsole, arguments);
},
log: function() {
Array.prototype.unshift.call(arguments, LOG_LEVELS[1]);
FConsole._record.apply(FConsole, arguments);
},
info: function() {
Array.prototype.unshift.call(arguments, LOG_LEVELS[2]);
FConsole._record.apply(FConsole, arguments);
},
warn: function() {
Array.prototype.unshift.call(arguments, LOG_LEVELS[3]);
FConsole._record.apply(FConsole, arguments);
},
error: function() {
Array.prototype.unshift.call(arguments, LOG_LEVELS[4]);
FConsole._record.apply(FConsole, arguments);
}
},
/**
* 全局定时器,监听队列
* @type {{timeout: null, start: Function, clear: Function}}
*/
clock = {
timeout: null,
start: function() {
var self = this;
if (!this.timeout) this.timeout = setInterval(function() {
if (queue._queueArr.length > 0) {
queue._post(queue._queueArr.splice(0, queue._queueArr.length));
}
}, TIMER);
},
clear: function() {
clearTimeout(this.timeout);
this.timeout = null;
}
};
function _extendObj(obj) {
if (typeof obj !== 'object') return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (Object.prototype.hasOwnProperty.call(source, prop)) {
// 不覆盖原方法执行,只是加个壳
(function(obj, prop) {
if (typeof obj[prop] === "function") {
var oldFun = obj[prop].bind(obj);
obj[prop] = function() {
source[prop].apply(source, arguments);
// oldFun.apply(obj, arguments);
oldFun(arguments[0]);
};
} else {
obj[prop] = source[prop];
}
})(obj, prop);
}
}
}
return obj;
};
//将自定义的日志API覆盖到原生console中
_extendObj(window.console, FConsole);
// script error监听解析
(function(win) {
var scriptErrorHander = function(errorMsg, url, lineNumber) {
var errorObj = {};
errorObj.errorMsg = errorMsg;
errorObj.url = url || '';
errorObj.lineNumber = lineNumber || 0;
FConsole.error('script error,', errorObj);
};
if (win.addEventListener) {
win.addEventListener('error', function(e){
scriptErrorHander(e.message, e.filename, e.lineno);
}, false);
} else if (win.attachEvent) {
win.attachEvent('error', function(e){
scriptErrorHander(e.message, e.filename, e.lineno);
});
} else {
win.onerror = scriptErrorHander;
}
})(window);
})(window) |
import {
Color,
LinearFilter,
MathUtils,
Matrix4,
Mesh,
PerspectiveCamera,
Plane,
Quaternion,
RGBFormat,
ShaderMaterial,
UniformsUtils,
Vector3,
Vector4,
WebGLRenderTarget
} from '../../../build/three.module.js';
class Refractor extends Mesh {
constructor( geometry, options = {} ) {
super( geometry );
this.type = 'Refractor';
const scope = this;
const color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
const textureWidth = options.textureWidth || 512;
const textureHeight = options.textureHeight || 512;
const clipBias = options.clipBias || 0;
const shader = options.shader || Refractor.RefractorShader;
//
const virtualCamera = new PerspectiveCamera();
virtualCamera.matrixAutoUpdate = false;
virtualCamera.userData.refractor = true;
//
const refractorPlane = new Plane();
const textureMatrix = new Matrix4();
// render target
const parameters = {
minFilter: LinearFilter,
magFilter: LinearFilter,
format: RGBFormat
};
const renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
renderTarget.texture.generateMipmaps = false;
}
// material
this.material = new ShaderMaterial( {
uniforms: UniformsUtils.clone( shader.uniforms ),
vertexShader: shader.vertexShader,
fragmentShader: shader.fragmentShader,
transparent: true // ensures, refractors are drawn from farthest to closest
} );
this.material.uniforms[ 'color' ].value = color;
this.material.uniforms[ 'tDiffuse' ].value = renderTarget.texture;
this.material.uniforms[ 'textureMatrix' ].value = textureMatrix;
// functions
const visible = ( function () {
const refractorWorldPosition = new Vector3();
const cameraWorldPosition = new Vector3();
const rotationMatrix = new Matrix4();
const view = new Vector3();
const normal = new Vector3();
return function visible( camera ) {
refractorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
view.subVectors( refractorWorldPosition, cameraWorldPosition );
rotationMatrix.extractRotation( scope.matrixWorld );
normal.set( 0, 0, 1 );
normal.applyMatrix4( rotationMatrix );
return view.dot( normal ) < 0;
};
} )();
const updateRefractorPlane = ( function () {
const normal = new Vector3();
const position = new Vector3();
const quaternion = new Quaternion();
const scale = new Vector3();
return function updateRefractorPlane() {
scope.matrixWorld.decompose( position, quaternion, scale );
normal.set( 0, 0, 1 ).applyQuaternion( quaternion ).normalize();
// flip the normal because we want to cull everything above the plane
normal.negate();
refractorPlane.setFromNormalAndCoplanarPoint( normal, position );
};
} )();
const updateVirtualCamera = ( function () {
const clipPlane = new Plane();
const clipVector = new Vector4();
const q = new Vector4();
return function updateVirtualCamera( camera ) {
virtualCamera.matrixWorld.copy( camera.matrixWorld );
virtualCamera.matrixWorldInverse.copy( virtualCamera.matrixWorld ).invert();
virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
virtualCamera.far = camera.far; // used in WebGLBackground
// The following code creates an oblique view frustum for clipping.
// see: Lengyel, Eric. “Oblique View Frustum Depth Projection and Clipping”.
// Journal of Game Development, Vol. 1, No. 2 (2005), Charles River Media, pp. 5–16
clipPlane.copy( refractorPlane );
clipPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
clipVector.set( clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant );
// calculate the clip-space corner point opposite the clipping plane and
// transform it into camera space by multiplying it by the inverse of the projection matrix
const projectionMatrix = virtualCamera.projectionMatrix;
q.x = ( Math.sign( clipVector.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
q.y = ( Math.sign( clipVector.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
q.z = - 1.0;
q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
// calculate the scaled plane vector
clipVector.multiplyScalar( 2.0 / clipVector.dot( q ) );
// replacing the third row of the projection matrix
projectionMatrix.elements[ 2 ] = clipVector.x;
projectionMatrix.elements[ 6 ] = clipVector.y;
projectionMatrix.elements[ 10 ] = clipVector.z + 1.0 - clipBias;
projectionMatrix.elements[ 14 ] = clipVector.w;
};
} )();
// This will update the texture matrix that is used for projective texture mapping in the shader.
// see: http://developer.download.nvidia.com/assets/gamedev/docs/projective_texture_mapping.pdf
function updateTextureMatrix( camera ) {
// this matrix does range mapping to [ 0, 1 ]
textureMatrix.set(
0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0
);
// we use "Object Linear Texgen", so we need to multiply the texture matrix T
// (matrix above) with the projection and view matrix of the virtual camera
// and the model matrix of the refractor
textureMatrix.multiply( camera.projectionMatrix );
textureMatrix.multiply( camera.matrixWorldInverse );
textureMatrix.multiply( scope.matrixWorld );
}
//
function render( renderer, scene, camera ) {
scope.visible = false;
const currentRenderTarget = renderer.getRenderTarget();
const currentXrEnabled = renderer.xr.enabled;
const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
renderer.xr.enabled = false; // avoid camera modification
renderer.shadowMap.autoUpdate = false; // avoid re-computing shadows
renderer.setRenderTarget( renderTarget );
if ( renderer.autoClear === false ) renderer.clear();
renderer.render( scene, virtualCamera );
renderer.xr.enabled = currentXrEnabled;
renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
renderer.setRenderTarget( currentRenderTarget );
// restore viewport
const viewport = camera.viewport;
if ( viewport !== undefined ) {
renderer.state.viewport( viewport );
}
scope.visible = true;
}
//
this.onBeforeRender = function ( renderer, scene, camera ) {
// Render
renderTarget.texture.encoding = renderer.outputEncoding;
// ensure refractors are rendered only once per frame
if ( camera.userData.refractor === true ) return;
// avoid rendering when the refractor is viewed from behind
if ( ! visible( camera ) === true ) return;
// update
updateRefractorPlane();
updateTextureMatrix( camera );
updateVirtualCamera( camera );
render( renderer, scene, camera );
};
this.getRenderTarget = function () {
return renderTarget;
};
}
}
Refractor.prototype.isRefractor = true;
Refractor.RefractorShader = {
uniforms: {
'color': {
value: null
},
'tDiffuse': {
value: null
},
'textureMatrix': {
value: null
}
},
vertexShader: /* glsl */`
uniform mat4 textureMatrix;
varying vec4 vUv;
void main() {
vUv = textureMatrix * vec4( position, 1.0 );
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,
fragmentShader: /* glsl */`
uniform vec3 color;
uniform sampler2D tDiffuse;
varying vec4 vUv;
float blendOverlay( float base, float blend ) {
return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );
}
vec3 blendOverlay( vec3 base, vec3 blend ) {
return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );
}
void main() {
vec4 base = texture2DProj( tDiffuse, vUv );
gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );
}`
};
export { Refractor };
|
'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
build.initialize(gulp);
|
import { useState, useEffect } from 'react'
export default function RegeneratorTest() {
const [message, setMessage] = useState('')
useEffect(() => {
;(async () => {
await new Promise((resolve) => setTimeout(resolve, 50))
setMessage('Hello World')
})()
}, [])
return <h1>{message}</h1>
}
|
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: @VERSION
* Revision: @REVISION
*
* Copyright (c) 2009-2016 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
// Class: $.jqplot.DivTitleRenderer
// The default title renderer for jqPlot. This class has no options beyond the <Title> class.
$.jqplot.DivTitleRenderer = function() {
};
$.jqplot.DivTitleRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.DivTitleRenderer.prototype.draw = function() {
// Memory Leaks patch
if (this._elem) {
this._elem.emptyForce();
this._elem = null;
}
var r = this.renderer;
var elem = document.createElement('div');
this._elem = $(elem);
this._elem.addClass('jqplot-title');
if (!this.text) {
this.show = false;
this._elem.height(0);
this._elem.width(0);
}
else if (this.text) {
var color;
if (this.color) {
color = this.color;
}
else if (this.textColor) {
color = this.textColor;
}
// don't trust that a stylesheet is present, set the position.
var styles = {position:'absolute', top:'0px', left:'0px'};
if (this._plotWidth) {
styles['width'] = this._plotWidth+'px';
}
if (this.fontSize) {
styles['fontSize'] = this.fontSize;
}
if (typeof this.textAlign === 'string') {
styles['textAlign'] = this.textAlign;
}
else {
styles['textAlign'] = 'center';
}
if (color) {
styles['color'] = color;
}
if (this.paddingBottom) {
styles['paddingBottom'] = this.paddingBottom;
}
if (this.fontFamily) {
styles['fontFamily'] = this.fontFamily;
}
this._elem.css(styles);
if (this.escapeHtml) {
this._elem.text(this.text);
}
else {
this._elem.html(this.text);
}
// styletext += (this._plotWidth) ? 'width:'+this._plotWidth+'px;' : '';
// styletext += (this.fontSize) ? 'font-size:'+this.fontSize+';' : '';
// styletext += (this.textAlign) ? 'text-align:'+this.textAlign+';' : 'text-align:center;';
// styletext += (color) ? 'color:'+color+';' : '';
// styletext += (this.paddingBottom) ? 'padding-bottom:'+this.paddingBottom+';' : '';
// this._elem = $('<div class="jqplot-title" style="'+styletext+'">'+this.text+'</div>');
// if (this.fontFamily) {
// this._elem.css('font-family', this.fontFamily);
// }
}
elem = null;
return this._elem;
};
$.jqplot.DivTitleRenderer.prototype.pack = function() {
// nothing to do here
};
})(jQuery); |
import LooseTransformer from "./loose";
import VanillaTransformer from "./vanilla";
import annotateAsPure from "@babel/helper-annotate-as-pure";
import nameFunction from "@babel/helper-function-name";
import splitExportDeclaration from "@babel/helper-split-export-declaration";
import { types as t } from "@babel/core";
import globals from "globals";
const getBuiltinClasses = category =>
Object.keys(globals[category]).filter(name => /^[A-Z]/.test(name));
const builtinClasses = new Set([
...getBuiltinClasses("builtin"),
...getBuiltinClasses("browser"),
]);
export default function(api, options) {
const { loose } = options;
const Constructor = loose ? LooseTransformer : VanillaTransformer;
// todo: investigate traversal requeueing
const VISITED = Symbol();
return {
visitor: {
ExportDefaultDeclaration(path) {
if (!path.get("declaration").isClassDeclaration()) return;
splitExportDeclaration(path);
},
ClassDeclaration(path) {
const { node } = path;
const ref = node.id || path.scope.generateUidIdentifier("class");
path.replaceWith(
t.variableDeclaration("let", [
t.variableDeclarator(ref, t.toExpression(node)),
]),
);
},
ClassExpression(path, state) {
const { node } = path;
if (node[VISITED]) return;
const inferred = nameFunction(path);
if (inferred && inferred !== node) {
path.replaceWith(inferred);
return;
}
node[VISITED] = true;
path.replaceWith(
new Constructor(path, state.file, builtinClasses).run(),
);
if (path.isCallExpression()) {
annotateAsPure(path);
if (path.get("callee").isArrowFunctionExpression()) {
path.get("callee").arrowFunctionToExpression();
}
}
},
},
};
}
|
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.layer.Image');
goog.require('ol.layer.Tile');
goog.require('ol.source.ImageWMS');
goog.require('ol.source.OSM');
var layers = [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Image({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ol.source.ImageWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states'},
serverType: 'geoserver'
})
})
];
var map = new ol.Map({
layers: layers,
target: 'map',
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
|
import handlePageDidActivate from '../handlePageDidActivate';
import {PREBUFFER, PLAY, actionCreators} from '../../actions';
import {pageDidActivate, pageWillDeactivate} from 'pages/actions';
import {delay} from 'redux-saga';
import {expect} from 'support/chai';
import {runSagaInPageScope} from 'support/sagas';
import sinon from 'sinon';
const {prebuffered} = actionCreators();
describe('handlePageDidActivate', () => {
it('prebuffers when page did activate', () => {
const run = runSagaInPageScope(handlePageDidActivate)
.dispatch(pageDidActivate());
expect(run.put).to.have.been.calledWith(sinon.match({type: PREBUFFER}));
});
it('plays video once it is prebuffered', () => {
const run = runSagaInPageScope(handlePageDidActivate)
.stubCall(delay)
.dispatch(pageDidActivate())
.dispatch(prebuffered());
expect(run.put).to.have.been.calledWith(sinon.match({type: PLAY}));
});
it('does not play video once prebuffered if autoplay is false', () => {
const run = runSagaInPageScope(handlePageDidActivate,
{page: {attributes: {autoplay: false}}})
.stubCall(delay)
.dispatch(pageDidActivate())
.dispatch(prebuffered());
expect(run.put).not.to.have.been.calledWith(sinon.match({type: PLAY}));
});
it('does not play video if page is deactivated while prebuffering', () => {
const run = runSagaInPageScope(handlePageDidActivate)
.stubCall(delay)
.dispatch(pageDidActivate())
.dispatch(pageWillDeactivate())
.dispatch(prebuffered());
expect(run.put).not.to.have.been.calledWith(sinon.match({type: PLAY}));
});
});
|
define([
'lib/glMatrix',
'misc/Utils',
'misc/Tablet',
'editor/tools/SculptBase',
'editor/tools/Paint',
'editor/tools/Smooth',
'mesh/Mesh'
], function (glm, Utils, Tablet, SculptBase, Paint, Smooth, Mesh) {
'use strict';
var vec3 = glm.vec3;
var mat3 = glm.mat3;
var Masking = function (main) {
SculptBase.call(this, main);
this._radius = 50;
this._hardness = 0.25;
this._intensity = 1.0;
this._negative = true;
this._culling = false;
this._idAlpha = 0;
this._lockPosition = false;
this._thickness = 1.0;
};
Masking.prototype = {
pushState: function () {
// too lazy to add a pushStateMaterial
this._states.pushStateColorAndMaterial(this.getMesh());
},
updateMeshBuffers: function () {
var mesh = this.getMesh();
if (mesh.getDynamicTopology)
mesh.updateBuffers();
else
mesh.updateMaterialBuffer();
},
stroke: function (picking) {
Paint.prototype.stroke.call(this, picking);
},
/** Paint color vertices */
paint: function (iVerts, center, radiusSquared, intensity, hardness, picking) {
var mesh = this.getMesh();
var vAr = mesh.getVertices();
var mAr = mesh.getMaterials();
var radius = Math.sqrt(radiusSquared);
var cx = center[0];
var cy = center[1];
var cz = center[2];
var softness = 2 * (1 - hardness);
var maskIntensity = this._negative ? -intensity : intensity;
for (var i = 0, l = iVerts.length; i < l; ++i) {
var ind = iVerts[i] * 3;
var vx = vAr[ind];
var vy = vAr[ind + 1];
var vz = vAr[ind + 2];
var dx = vx - cx;
var dy = vy - cy;
var dz = vz - cz;
var dist = Math.sqrt(dx * dx + dy * dy + dz * dz) / radius;
var fallOff = Math.pow(1 - dist, softness);
fallOff *= maskIntensity * picking.getAlpha(vx, vy, vz);
mAr[ind + 2] = Math.min(Math.max(mAr[ind + 2] + fallOff, 0.0), 1.0);
}
},
updateAndRenderMask: function () {
var mesh = this.getMesh();
mesh.updateDuplicateColorsAndMaterials();
mesh.updateFlatShading();
this.updateRender();
},
blur: function () {
var mesh = this.getMesh();
var iVerts = this.getMaskedVertices();
if (iVerts.length === 0)
return;
iVerts = mesh.expandsVertices(iVerts, 1);
this.pushState();
this._states.pushVertices(iVerts);
var mAr = mesh.getMaterials();
var nbVerts = iVerts.length;
var smoothVerts = new Float32Array(nbVerts * 3);
this.laplacianSmooth(iVerts, smoothVerts, mAr);
for (var i = 0; i < nbVerts; ++i)
mAr[iVerts[i] * 3 + 2] = smoothVerts[i * 3 + 2];
this.updateAndRenderMask();
},
sharpen: function () {
var mesh = this.getMesh();
var iVerts = this.getMaskedVertices();
if (iVerts.length === 0)
return;
this.pushState();
this._states.pushVertices(iVerts);
var mAr = mesh.getMaterials();
var nbVerts = iVerts.length;
for (var i = 0; i < nbVerts; ++i) {
var idm = iVerts[i] * 3 + 2;
var val = mAr[idm];
mAr[idm] = val > 0.5 ? Math.min(val + 0.1, 1.0) : Math.max(val - 1.0, 0.0);
}
this.updateAndRenderMask();
},
clear: function () {
var mesh = this.getMesh();
var iVerts = this.getMaskedVertices();
if (iVerts.length === 0)
return;
this.pushState();
this._states.pushVertices(iVerts);
var mAr = mesh.getMaterials();
for (var i = 0, nb = iVerts.length; i < nb; ++i)
mAr[iVerts[i] * 3 + 2] = 1.0;
this.updateAndRenderMask();
},
invert: function (isState, meshState) {
var mesh = meshState;
if (!mesh) mesh = this.getMesh();
if (!isState)
this._states.pushStateCustom(this.invert.bind(this, true, mesh));
var mAr = mesh.getMaterials();
for (var i = 0, nb = mesh.getNbVertices(); i < nb; ++i)
mAr[i * 3 + 2] = 1.0 - mAr[i * 3 + 2];
this.updateAndRenderMask();
},
remapAndMirrorIndices: function (fAr, nbFaces, iVerts) {
var nbVertices = this.getMesh().getNbVertices();
var iTag = new Uint32Array(Utils.getMemory(nbVertices * 4), 0, nbVertices);
var i = 0;
var j = 0;
var nbVerts = iVerts.length;
for (i = 0; i < nbVerts; ++i)
iTag[iVerts[i]] = i;
var endFaces = nbFaces * 2;
for (i = 0; i < endFaces; ++i) {
j = i * 4;
var offset = i < nbFaces ? 0 : nbVerts;
fAr[j] = iTag[fAr[j]] + offset;
fAr[j + 1] = iTag[fAr[j + 1]] + offset;
fAr[j + 2] = iTag[fAr[j + 2]] + offset;
var id4 = fAr[j + 3];
if (id4 >= 0) fAr[j + 3] = iTag[id4] + offset;
}
var end = fAr.length / 4;
for (i = endFaces; i < end; ++i) {
j = i * 4;
fAr[j] = iTag[fAr[j]];
fAr[j + 1] = iTag[fAr[j + 1]];
fAr[j + 2] = iTag[fAr[j + 2]] + nbVerts;
fAr[j + 3] = iTag[fAr[j + 3]] + nbVerts;
}
},
invertFaces: function (fAr) {
for (var i = 0, nb = fAr.length; i < nb; ++i) {
var id = i * 4;
var temp = fAr[id];
fAr[id] = fAr[id + 2];
fAr[id + 2] = temp;
}
},
extractFaces: function (iFaces, iVerts, maskClamp) {
var mesh = this.getMesh();
var fAr = mesh.getFaces();
var mAr = mesh.getMaterials();
var eAr = mesh.getVerticesOnEdge();
var noThick = this._thickness === 0;
var nbFaces = iFaces.length;
var nbNewFaces = new Int32Array(Utils.getMemory(nbFaces * 4 * 4 * 3), 0, nbFaces * 4 * 3);
var offsetFLink = noThick ? nbFaces : nbFaces * 2;
for (var i = 0; i < nbFaces; ++i) {
var idf = i * 4;
var idOld = iFaces[i] * 4;
var iv1 = nbNewFaces[idf] = fAr[idOld];
var iv2 = nbNewFaces[idf + 1] = fAr[idOld + 1];
var iv3 = nbNewFaces[idf + 2] = fAr[idOld + 2];
var iv4 = nbNewFaces[idf + 3] = fAr[idOld + 3];
if (noThick)
continue;
var isQuad = iv4 >= 0;
var b1 = mAr[iv1 * 3 + 2] >= maskClamp || eAr[iv1] >= 1;
var b2 = mAr[iv2 * 3 + 2] >= maskClamp || eAr[iv2] >= 1;
var b3 = mAr[iv3 * 3 + 2] >= maskClamp || eAr[iv3] >= 1;
var b4 = isQuad ? mAr[iv4 * 3 + 2] >= maskClamp || eAr[iv4] >= 1 : false;
// create opposite face (layer), invert clockwise
// quad =>
// 1 2 3 2
// 4 3 4 1
// tri =>
// 1 2 3 2
// 3 1
idf += nbFaces * 4;
nbNewFaces[idf] = iv3;
nbNewFaces[idf + 1] = iv2;
nbNewFaces[idf + 2] = iv1;
nbNewFaces[idf + 3] = iv4;
// create bridges faces
if (b2) {
if (b1) {
idf = 4 * (offsetFLink++);
nbNewFaces[idf] = nbNewFaces[idf + 3] = iv2;
nbNewFaces[idf + 1] = nbNewFaces[idf + 2] = iv1;
}
if (b3) {
idf = 4 * (offsetFLink++);
nbNewFaces[idf] = nbNewFaces[idf + 3] = iv3;
nbNewFaces[idf + 1] = nbNewFaces[idf + 2] = iv2;
}
}
if (isQuad) {
if (b4) {
if (b1) {
idf = 4 * (offsetFLink++);
nbNewFaces[idf] = nbNewFaces[idf + 3] = iv1;
nbNewFaces[idf + 1] = nbNewFaces[idf + 2] = iv4;
}
if (b3) {
idf = 4 * (offsetFLink++);
nbNewFaces[idf] = nbNewFaces[idf + 3] = iv4;
nbNewFaces[idf + 1] = nbNewFaces[idf + 2] = iv3;
}
}
} else {
if (b1 && b3) {
idf = 4 * (offsetFLink++);
nbNewFaces[idf] = nbNewFaces[idf + 3] = iv1;
nbNewFaces[idf + 1] = nbNewFaces[idf + 2] = iv3;
}
}
}
var fArNew = new Int32Array(nbNewFaces.subarray(0, offsetFLink * 4));
this.remapAndMirrorIndices(fArNew, nbFaces, iVerts);
if (this._thickness > 0)
this.invertFaces(fArNew);
return fArNew;
},
extractVertices: function (iVerts) {
var mesh = this.getMesh();
var vAr = mesh.getVertices();
var nAr = mesh.getNormals();
var mat = mesh.getMatrix();
var nMat = mat3.normalFromMat4(mat3.create(), mat);
var nbVerts = iVerts.length;
var vArNew = new Float32Array(nbVerts * 2 * 3);
var vTemp = [0.0, 0.0, 0.0];
var nTemp = [0.0, 0.0, 0.0];
var vOffset = nbVerts * 3;
var thick = this._thickness;
var eps = 0.01;
if (thick < 0) eps = -eps;
for (var i = 0; i < nbVerts; ++i) {
var idv = i * 3;
var idvOld = iVerts[i] * 3;
vTemp[0] = vAr[idvOld];
vTemp[1] = vAr[idvOld + 1];
vTemp[2] = vAr[idvOld + 2];
nTemp[0] = nAr[idvOld];
nTemp[1] = nAr[idvOld + 1];
nTemp[2] = nAr[idvOld + 2];
vec3.transformMat3(nTemp, nTemp, nMat);
vec3.normalize(nTemp, nTemp);
vec3.transformMat4(vTemp, vTemp, mat);
vec3.scaleAndAdd(vTemp, vTemp, nTemp, eps);
vArNew[idv] = vTemp[0];
vArNew[idv + 1] = vTemp[1];
vArNew[idv + 2] = vTemp[2];
vec3.scaleAndAdd(vTemp, vTemp, nTemp, thick);
idv += vOffset;
vArNew[idv] = vTemp[0];
vArNew[idv + 1] = vTemp[1];
vArNew[idv + 2] = vTemp[2];
}
return vArNew;
},
smoothBorder: function (mesh, iFaces) {
var startBridge = iFaces.length * 2;
var fBridge = new Uint32Array(mesh.getNbFaces() - startBridge);
for (var i = 0, nbBridge = fBridge.length; i < nbBridge; ++i)
fBridge[i] = startBridge + i;
var vBridge = mesh.expandsVertices(mesh.getVerticesFromFaces(fBridge), 1);
var smo = new Smooth();
smo.setToolMesh(mesh);
smo.smooth(vBridge, 1.0);
smo.smooth(vBridge, 1.0);
smo.smooth(vBridge, 1.0);
},
extract: function () {
var mesh = this.getMesh();
var maskClamp = 0.5;
var iVerts = this.filterMaskedVertices(-Infinity, maskClamp);
if (iVerts.length === 0)
return;
var iFaces = mesh.getFacesFromVertices(iVerts);
iVerts = mesh.getVerticesFromFaces(iFaces);
var fArNew = this.extractFaces(iFaces, iVerts, maskClamp);
var vArNew = this.extractVertices(iVerts);
var newMesh = new Mesh(mesh.getGL());
newMesh.setVertices(vArNew);
newMesh.setFaces(fArNew);
// we don't use newMesh.init because we want to smooth
// the border (we want to avoid an update octree/normal/etc...)
newMesh.initColorsAndMaterials();
newMesh.allocateArrays();
newMesh.initTopology();
if (this._thickness !== 0.0)
this.smoothBorder(newMesh, iFaces);
newMesh.updateGeometry();
newMesh.updateDuplicateColorsAndMaterials();
newMesh.copyRenderConfig(mesh);
newMesh.initRender();
var main = this._main;
main.addNewMesh(newMesh);
main.setMesh(mesh);
}
};
Utils.makeProxy(SculptBase, Masking);
return Masking;
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.