code
stringlengths 2
1.05M
|
|---|
var gulp = require('gulp'),
$ = require("gulp-load-plugins")(),
express = require('express'),
path = require('path'),
tinylr = require('tiny-lr'),
app = express(),
server = tinylr(),
deploy = require('gulp-gh-pages'),
psi = require('psi'),
fs = require('fs'),
moment = require('moment'),
mkdirp = require('mkdirp'),
cssshrink = require('gulp-cssshrink'),
minifyCSS = require('gulp-minify-css'),
psisite = 'http://irondom.github.io/ironDOM-class-module/';
var year = moment().get('year'),
month = moment().get('month'),
day = moment().get('date'),
hour = moment().get('hour'),
minute = moment().get('minute'),
second = moment().get('second'),
fullDate = year + '-' + month + '-' + day + '-T' + hour + '-' + minute + '-' + second;
gulp.task('speed-mobile', function (cb) {
var options = {
// key: key,
nokey: 'true',
url: psisite,
strategy: 'mobile'
};
psi(options, function (err, data) {
var perfContent =
'# Peformance results of '+ fullDate +': \n' +
' \n' +
'- Url: ' + data.id + '\n' +
'- Score: ' + data.score + '\n' +
'\n' +
'## Page stats: \n' +
'- Number Resources: ' + data.pageStats.numberResources + '\n' +
'- Total Request Bytes: ' + data.pageStats.totalRequestBytes + '\n' +
'- Number Static Resources: ' + data.pageStats.numberStaticResources + '\n' +
'- HTML Response Bytes: ' + data.pageStats.htmlResponseBytes + ' bytes \n' +
'- CSS Response Bytes: ' + data.pageStats.cssResponseBytes + ' bytes \n' +
'- JavaScript Response Bytes: ' + data.pageStats.javascriptResponseBytes + ' bytes \n' +
'- Number JavaScript Resources: ' + data.pageStats.numberJsResources + '\n' +
'- Number CSS Resources: ' + data.pageStats.numberCssResources + '\n'+
'- Avoid Landing Page Redirects: ' + JSON.stringify(data.formattedResults.ruleResults.AvoidLandingPageRedirects.ruleImpact) + '\n' +
'- Enable Gzip Compression: ' + JSON.stringify(data.formattedResults.ruleResults.EnableGzipCompression.ruleImpact) + '\n' +
'- Leverage Browser Caching: ' + JSON.stringify(data.formattedResults.ruleResults.LeverageBrowserCaching.ruleImpact) + '\n' +
'- Main Resource Server Response Time: ' + JSON.stringify(data.formattedResults.ruleResults.MainResourceServerResponseTime.ruleImpact) + '\n' +
'- Minify CSS: ' + JSON.stringify(data.formattedResults.ruleResults.MinifyCss.ruleImpact) + '\n' +
'- Minify HTML: ' + JSON.stringify(data.formattedResults.ruleResults.MinifyHTML.ruleImpact) + '\n' +
'- Minify JavaScript: ' + JSON.stringify(data.formattedResults.ruleResults.MinifyJavaScript.ruleImpact) + '\n' +
'- MinimizeRenderBlockingResources: ' + JSON.stringify(data.formattedResults.ruleResults.MinimizeRenderBlockingResources.ruleImpact) + '\n' +
'- Optimize Images: ' + JSON.stringify(data.formattedResults.ruleResults.OptimizeImages.ruleImpact) + '\n' +
'- Prioritize Visible Content: ' + JSON.stringify(data.formattedResults.ruleResults.PrioritizeVisibleContent.ruleImpact) + '\n';
//console.log(data.formattedResults.ruleResults.PrioritizeVisibleContent);
mkdirp('performance-reports/mobile/', function (err) {
if (err) {
console.error(err)
} else {
fs.writeFile('performance-reports/mobile/test-mobile-' + fullDate + '.md', perfContent);
console.log('You can find the report: performance-reports/mobile/test-mobile-' + fullDate + '.md');
}
});
//console.log(data);
});
});
gulp.task('speed-desktop', function (cb) {
var options = {
// key: key,
nokey: 'true',
url: psisite,
strategy: 'desktop'
};
psi(options, function (err, data) {
var perfContent =
'# Peformance results of '+ fullDate +': \n' +
' \n' +
'- Url: ' + data.id + '\n' +
'- Score: ' + data.score + '\n' +
'\n' +
'## Page stats: \n' +
'- Number Resources: ' + data.pageStats.numberResources + '\n' +
'- Total Request Bytes: ' + data.pageStats.totalRequestBytes + '\n' +
'- Number Static Resources: ' + data.pageStats.numberStaticResources + '\n' +
'- HTML Response Bytes: ' + data.pageStats.htmlResponseBytes + ' bytes \n' +
'- CSS Response Bytes: ' + data.pageStats.cssResponseBytes + ' bytes \n' +
'- JavaScript Response Bytes: ' + data.pageStats.javascriptResponseBytes + ' bytes \n' +
'- Number JavaScript Resources: ' + data.pageStats.numberJsResources + '\n' +
'- Number CSS Resources: ' + data.pageStats.numberCssResources + '\n'+
'- Avoid Landing Page Redirects: ' + JSON.stringify(data.formattedResults.ruleResults.AvoidLandingPageRedirects.ruleImpact) + '\n' +
'- Enable Gzip Compression: ' + JSON.stringify(data.formattedResults.ruleResults.EnableGzipCompression.ruleImpact) + '\n' +
'- Leverage Browser Caching: ' + JSON.stringify(data.formattedResults.ruleResults.LeverageBrowserCaching.ruleImpact) + '\n' +
'- Main Resource Server Response Time: ' + JSON.stringify(data.formattedResults.ruleResults.MainResourceServerResponseTime.ruleImpact) + '\n' +
'- Minify CSS: ' + JSON.stringify(data.formattedResults.ruleResults.MinifyCss.ruleImpact) + '\n' +
'- Minify HTML: ' + JSON.stringify(data.formattedResults.ruleResults.MinifyHTML.ruleImpact) + '\n' +
'- Minify JavaScript: ' + JSON.stringify(data.formattedResults.ruleResults.MinifyJavaScript.ruleImpact) + '\n' +
'- MinimizeRenderBlockingResources: ' + JSON.stringify(data.formattedResults.ruleResults.MinimizeRenderBlockingResources.ruleImpact) + '\n' +
'- Optimize Images: ' + JSON.stringify(data.formattedResults.ruleResults.OptimizeImages.ruleImpact) + '\n' +
'- Prioritize Visible Content: ' + JSON.stringify(data.formattedResults.ruleResults.PrioritizeVisibleContent.ruleImpact) + '\n';
mkdirp('performance-reports/desktop/', function (err) {
if (err) {
console.error(err)
} else {
fs.writeFile('performance-reports/desktop/test-desktop-' + fullDate + '.md', perfContent);
console.log('You can find the report: performance-reports/desktop/test-desktop-' + fullDate + '.md');
}
});
//console.log(data);
});
});
gulp.task('compass', function() {
gulp.src('./src/stylesheets/**/*.scss')
.pipe($.plumber())
.pipe($.compass({
css: 'dist/stylesheets',
sass: 'src/stylesheets'
}))
.pipe(cssshrink())
.pipe(gulp.dest('dist/stylesheets'))
.pipe( $.livereload( server ));
});
gulp.task('jslib', function() {
return gulp.src('src/scripts/*.js')
.pipe($.concat("irondom.js"))
.pipe(gulp.dest('dist/scripts'))
.pipe( $.livereload( server ) );
});
gulp.task('js', function() {
return gulp.src('src/test/*.js')
.pipe($.concat("test.js"))
.pipe(gulp.dest('dist/scripts'))
.pipe( $.livereload( server ) );
});
gulp.task('images', function() {
return gulp.src('./src/images/*')
.pipe(gulp.dest('./dist/images'))
.pipe( $.livereload( server ));
})
gulp.task('templates', function() {
return gulp.src('src/*.jade')
.pipe($.plumber())
.pipe($.jade({
pretty: true
}))
.pipe( gulp.dest('dist/') )
.pipe( $.livereload( server ));
});
gulp.task('express', function() {
app.use(express.static(path.resolve('./dist')));
app.listen(1337);
$.util.log('Listening on port: 1337');
});
gulp.task('watch', function () {
server.listen(35729, function (err) {
if (err) {
return console.log(err);
}
gulp.watch('src/stylesheets/**/*.scss',['compass']);
gulp.watch('src/scripts/**/*.js',['jslib']);
gulp.watch('src/test/**/*.js',['js']);
gulp.watch('src/*.jade',['templates']);
});
});
// Default Task
gulp.task('default', ['jslib', 'js','compass','templates', 'images', 'express','watch']);
gulp.task('perf', ['speed-desktop', 'speed-mobile']);
|
/* globals jasmine */
'use strict';
/**
* @returns {PlaybackSlotMock}
*/
function playbackSlotMock(props) {
props = props || {
entry: {},
video: {provider: 'mock', id: 'mock'}
};
/**
* @typedef PlaybackSlotMock
* @name PlaybackSlotMock
*/
var PlaybackSlotMock = {
/**
* @return {Entry}
*/
get entry() {
return props.entry;
},
/**
* @returns {Video}
*/
get video() {
return props.video;
},
load: jasmine.createSpy('loadSpy'),
start: jasmine.createSpy('startSpy'),
end: jasmine.createSpy('endSpy'),
suspend: jasmine.createSpy('suspendSpy'),
proceed: jasmine.createSpy('proceedSpy')
};
return Object.freeze(PlaybackSlotMock);
}
module.exports = playbackSlotMock;
|
var productControl = function() {}
productControl.prototype.proList = function( req,res,next ) {
var ep = new EventProxy();
dataSource.getConn(ep);
adminModule.proList(ep);
ep.on("success",function( data ) {
res.json(data).end();
});
ep.fail(function( err ){
next(err);
});
}
productControl.prototype.proAdd = function( req,res,next ) {
var ep = new EventProxy();
ep.all('fileup','conn',function( filename,conn ) {
var url = "/upfile/" + filename;
adminModule.proAdd(ep,conn,[req.body.pname,req.body.price,req.body.strock,url,req.body.type]);
});
util.upfile(ep,req.file); //上传文件
dataSource.getConn(ep); //获取连接
ep.on("success",function( data ) {
if( data.insertId ) {
res.json(config.info.suc).end();
} else {
res.json(config.error.proAddErr).end();
}
});
ep.fail(function( err ){
next(err);
});
}
productControl.prototype.proDel = function( req,res,next ) {
var ep = new EventProxy();
dataSource.getConn(ep);
adminModule.proDel(ep,[ req.params.pid ]);
ep.on("success",function( data ) {
res.json(config.info.suc).end();
});
ep.fail(function( err ){
next(err);
});
}
module.exports = function() {
return new productControl();
}
|
var searchData=
[
['newframe',['newFrame',['../classProcessingThread.html#a61e298bf34c03a0a1bb7b6c2785c0e27',1,'ProcessingThread']]],
['newimageprocessingflags',['newImageProcessingFlags',['../classMainWindow.html#a7b63ea5756cb708a00304c582f3d6105',1,'MainWindow']]],
['newimageprocessingsettings',['newImageProcessingSettings',['../classImageProcessingSettingsDialog.html#ac767f423a21ebe35553fb0b1ef699b6d',1,'ImageProcessingSettingsDialog']]],
['nextframe',['nextFrame',['../classPlaybackThread.html#af645aac63299d55fa4822f974f268f24',1,'PlaybackThread']]]
];
|
declare module 'vscode' {
/**
* The version of the editor.
*/
declare export var version: string;
/**
* Represents a reference to a command. Provides a title which
* will be used to represent a command in the UI and, optionally,
* an array of arguments which will be passed to the command handler
* function when invoked.
*/
declare export interface Command {
/**
* Title of the command, like `save`.
*/
title: string;
/**
* The identifier of the actual command handler.
* @see [commands.registerCommand](#commands.registerCommand).
*/
command: string;
/**
* Arguments that the command handler should be
* invoked with.
*/
arguments?: any[];
}
/**
* Represents a line of text, such as a line of source code.
*
* TextLine objects are __immutable__. When a [document](#TextDocument) changes,
* previously retrieved lines will not represent the latest state.
*/
declare export interface TextLine {
/**
* The zero-based line number.
*
* @readonly
*/
lineNumber: number;
/**
* The text of this line without the line separator characters.
*
* @readonly
*/
text: string;
/**
* The range this line covers without the line separator characters.
*
* @readonly
*/
range: Range;
/**
* The range this line covers with the line separator characters.
*
* @readonly
*/
rangeIncludingLineBreak: Range;
/**
* The offset of the first character which is not a whitespace character as defined
* by `/\s/`.
*
* @readonly
*/
firstNonWhitespaceCharacterIndex: number;
/**
* Whether this line is whitespace only, shorthand
* for [TextLine.firstNonWhitespaceCharacterIndex](#TextLine.firstNonWhitespaceCharacterIndex]) === [TextLine.text.length](#TextLine.text.length).
*
* @readonly
*/
isEmptyOrWhitespace: boolean;
}
/**
* Represents a text document, such as a source file. Text documents have
* [lines](#TextLine) and knowledge about an underlying resource like a file.
*/
declare export interface TextDocument {
/**
* The associated URI for this document. Most documents have the __file__-scheme, indicating that they
* represent files on disk. However, some documents may have other schemes indicating that they are not
* available on disk.
*
* @readonly
*/
uri: Uri;
/**
* The file system path of the associated resource. Shorthand
* notation for [TextDocument.uri.fsPath](#TextDocument.uri.fsPath). Independent of the uri scheme.
*
* @readonly
*/
fileName: string;
/**
* Is this document representing an untitled file.
*
* @readonly
*/
isUntitled: boolean;
/**
* The identifier of the language associated with this document.
*
* @readonly
*/
languageId: string;
/**
* The version number of this document (it will strictly increase after each
* change, including undo/redo).
*
* @readonly
*/
version: number;
/**
* true if there are unpersisted changes.
*
* @readonly
*/
isDirty: boolean;
/**
* Save the underlying file.
*
* @return A promise that will resolve to true when the file
* has been saved.
*/
save(): Thenable<boolean>;
/**
* The number of lines in this document.
*
* @readonly
*/
lineCount: number;
/**
* Returns a text line denoted by the line number. Note
* that the returned object is *not* live and changes to the
* document are not reflected.
*
* @param line A line number in [0, lineCount).
* @return A [line](#TextLine).
*/
lineAt(line: number): TextLine;
/**
* Returns a text line denoted by the position. Note
* that the returned object is *not* live and changes to the
* document are not reflected.
*
* The position will be [adjusted](#TextDocument.validatePosition).
*
* @see [TextDocument.lineAt](#TextDocument.lineAt)
* @param position A position.
* @return A [line](#TextLine).
*/
lineAt(position: Position): TextLine;
/**
* Converts the position to a zero-based offset.
*
* The position will be [adjusted](#TextDocument.validatePosition).
*
* @param position A position.
* @return A valid zero-based offset.
*/
offsetAt(position: Position): number;
/**
* Converts a zero-based offset to a position.
*
* @param offset A zero-based offset.
* @return A valid [position](#Position).
*/
positionAt(offset: number): Position;
/**
* Get the text of this document. A substring can be retrieved by providing
* a range. The range will be [adjusted](#TextDocument.validateRange).
*
* @param range Include only the text included by the range.
* @return The text inside the provided range or the entire text.
*/
getText(range?: Range): string;
/**
* Get a word-range at the given position. By default words are defined by
* common separators, like space, -, _, etc. In addition, per languge custom
* [word definitions](#LanguageConfiguration.wordPattern) can be defined.
*
* The position will be [adjusted](#TextDocument.validatePosition).
*
* @param position A position.
* @return A range spanning a word, or `undefined`.
*/
getWordRangeAtPosition(position: Position): Range;
/**
* Ensure a range is completely contained in this document.
*
* @param range A range.
* @return The given range or a new, adjusted range.
*/
validateRange(range: Range): Range;
/**
* Ensure a position is contained in the range of this document.
*
* @param position A position.
* @return The given position or a new, adjusted position.
*/
validatePosition(position: Position): Position;
}
/**
* Represents a line and character position, such as
* the position of the cursor.
*
* Position objects are __immutable__. Use the [with](#Position.with) or
* [translate](#Position.translate) methods to derive new positions
* from an existing position.
*/
declare export class Position {
/**
* The zero-based line value.
* @readonly
*/
line: number;
/**
* The zero-based character value.
* @readonly
*/
character: number;
/**
* @param line A zero-based line value.
* @param character A zero-based character value.
*/
constructor(line: number, character: number): void;
/**
* Check if `other` is before this position.
*
* @param other A position.
* @return `true` if position is on a smaller line
* or on the same line on a smaller character.
*/
isBefore(other: Position): boolean;
/**
* Check if `other` is before or equal to this position.
*
* @param other A position.
* @return `true` if position is on a smaller line
* or on the same line on a smaller or equal character.
*/
isBeforeOrEqual(other: Position): boolean;
/**
* Check if `other` is after this position.
*
* @param other A position.
* @return `true` if position is on a greater line
* or on the same line on a greater character.
*/
isAfter(other: Position): boolean;
/**
* Check if `other` is after or equal to this position.
*
* @param other A position.
* @return `true` if position is on a greater line
* or on the same line on a greater or equal character.
*/
isAfterOrEqual(other: Position): boolean;
/**
* Check if `other` equals this position.
*
* @param other A position.
* @return `true` if the line and character of the given position are equal to
* the line and character of this position.
*/
isEqual(other: Position): boolean;
/**
* Compare this to `other`.
*
* @param other A position.
* @return A number smaller than zero if this position is before the given position,
* a number greater than zero if this position is after the given position, or zero when
* this and the given position are equal.
*/
compareTo(other: Position): number;
/**
* Create a new position relative to this position.
*
* @param lineDelta Delta value for the line value, default is `0`.
* @param characterDelta Delta value for the character value, default is `0`.
* @return A position which line and character is the sum of the current line and
* character and the corresponding deltas.
*/
translate(lineDelta?: number, characterDelta?: number): Position;
/**
* Create a new position derived from this position.
*
* @param line Value that should be used as line value, default is the [existing value](#Position.line)
* @param character Value that should be used as character value, default is the [existing value](#Position.character)
* @return A position where line and character are replaced by the given values.
*/
with(line?: number, character?: number): Position;
}
/**
* A range represents an ordered pair of two positions.
* It is guaranteed that [start](#Range.start).isBeforeOrEqual([end](#Range.end))
*
* Range objects are __immutable__. Use the [with](#Range.with),
* [intersection](#Range.intersection), or [union](#Range.union) methods
* to derive new ranges from an existing range.
*/
declare export class Range {
/**
* The start position. It is before or equal to [end](#Range.end).
* @readonly
*/
start: Position;
/**
* The end position. It is after or equal to [start](#Range.start).
* @readonly
*/
end: Position;
/**
* Create a new range from two positions. If `start` is not
* before or equal to `end`, the values will be swapped.
*
* @param start A position.
* @param end A position.
*/
constructor(start: Position, end: Position): void;
/**
* Create a new range from number coordinates. It is a shorter equivalent of
* using `new Range(new Position(startLine, startCharacter), new Position(endLine, endCharacter))`
*
* @param startLine A zero-based line value.
* @param startCharacter A zero-based character value.
* @param endLine A zero-based line value.
* @param endCharacter A zero-based character value.
*/
constructor(startLine: number, startCharacter: number, endLine: number, endCharacter: number): void;
/**
* `true` iff `start` and `end` are equal.
*/
isEmpty: boolean;
/**
* `true` iff `start.line` and `end.line` are equal.
*/
isSingleLine: boolean;
/**
* Check if a position or a range is contained in this range.
*
* @param positionOrRange A position or a range.
* @return `true` iff the position or range is inside or equal
* to this range.
*/
contains(positionOrRange: Position | Range): boolean;
/**
* Check if `other` equals this range.
*
* @param other A range.
* @return `true` when start and end are [equal](#Position.isEqual) to
* start and end of this range.
*/
isEqual(other: Range): boolean;
/**
* Intersect `range` with this range and returns a new range or `undefined`
* if the ranges have no overlap.
*
* @param range A range.
* @return A range of the greater start and smaller end positions. Will
* return undefined when there is no overlap.
*/
intersection(range: Range): Range;
/**
* Compute the union of `other` with this range.
*
* @param other A range.
* @return A range of smaller start position and the greater end position.
*/
union(other: Range): Range;
/**
* Create a new range derived from this range.
*
* @param start A position that should be used as start. The default value is the [current start](#Range.start).
* @param end A position that should be used as end. The default value is the [current end](#Range.end).
* @return A range derived from this range with the given start and end position.
* If start and end are not different this range will be returned.
*/
with(start?: Position, end?: Position): Range;
}
/**
* Represents a text selection in an editor.
*/
declare export class Selection extends Range {
/**
* The position at which the selection starts.
* This position might be before or after [active](#Selection.active).
*/
anchor: Position;
/**
* The position of the cursor.
* This position might be before or after [anchor](#Selection.anchor).
*/
active: Position;
/**
* Create a selection from two postions.
*
* @param anchor A position.
* @param active A position.
*/
constructor(anchor: Position, active: Position): void;
/**
* Create a selection from four coordinates.
*
* @param anchorLine A zero-based line value.
* @param anchorCharacter A zero-based character value.
* @param activeLine A zero-based line value.
* @param activeCharacter A zero-based character value.
*/
constructor(anchorLine: number, anchorCharacter: number, activeLine: number, activeCharacter: number): void;
/**
* A selection is reversed if [active](#Selection.active).isBefore([anchor](#Selection.anchor)).
*/
isReversed: boolean;
}
/**
* Represents an event describing the change in a [text editor's selections](#TextEditor.selections).
*/
declare export interface TextEditorSelectionChangeEvent {
/**
* The [text editor](#TextEditor) for which the selections have changed.
*/
textEditor: TextEditor;
/**
* The new value for the [text editor's selections](#TextEditor.selections).
*/
selections: Selection[];
}
/**
* Represents an event describing the change in a [text editor's options](#TextEditor.options).
*/
declare export interface TextEditorOptionsChangeEvent {
/**
* The [text editor](#TextEditor) for which the options have changed.
*/
textEditor: TextEditor;
/**
* The new value for the [text editor's options](#TextEditor.options).
*/
options: TextEditorOptions;
}
/**
* Represents a [text editor](#TextEditor)'s [options](#TextEditor.options).
*/
declare export interface TextEditorOptions {
/**
* The size in spaces a tab takes. This is used for two purposes:
* - the rendering width of a tab character;
* - the number of spaces to insert when [insertSpaces](#TextEditorOptions.insertSpaces) is true.
*/
tabSize: number;
/**
* When pressing Tab insert [n](#TextEditorOptions.tabSize) spaces.
*/
insertSpaces: boolean;
}
/**
* Represents a handle to a set of decorations
* sharing the same [styling options](#DecorationRenderOptions) in a [text editor](#TextEditor).
*
* To get an instance of a `TextEditorDecorationType` use
* [createTextEditorDecorationType](#window.createTextEditorDecorationType).
*/
declare export interface TextEditorDecorationType {
/**
* Internal representation of the handle.
* @readonly
*/
key: string;
/**
* Remove this decoration type and all decorations on all text editors using it.
*/
dispose(): void;
}
/**
* Represents different [reveal](#TextEditor.revealRange) strategies in a text editor.
*/
declare export type TextEditorRevealTypeType = 0 | 1 | 2;
declare export var TextEditorRevealType: {
/**
* The range will be revealed with as little scrolling as possible.
*/
Default: 0,
/**
* The range will always be revealed in the center of the viewport.
*/
InCenter: 1,
/**
* If the range is outside the viewport, it will be revealed in the center of the viewport.
* Otherwise, it will be revealed with as little scrolling as possible.
*/
InCenterIfOutsideViewport: 2,
...
}
/**
* Represents different positions for rendering a decoration in an [overview ruler](#DecorationRenderOptions.overviewRulerLane).
* The overview ruler supports three lanes.
*/
declare export type OverviewRulerLaneType = 1 | 2 | 4 | 6;
declare export var OverviewRulerLane: {
Left: 1,
Center: 2,
Right: 4,
Full: 7,
...
}
/**
* Represents theme specific rendering styles for a [text editor decoration](#TextEditorDecorationType).
*/
declare export interface ThemableDecorationRenderOptions {
/**
* Background color of the decoration. Use rgba() and define transparent background colors to play well with other decorations.
*/
backgroundColor?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
outlineColor?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
outlineStyle?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
outlineWidth?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
borderColor?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
borderRadius?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
borderSpacing?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
borderStyle?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
borderWidth?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
textDecoration?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
cursor?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
color?: string;
/**
* An **absolute path** to an image to be rendered in the gutterIconPath.
*/
gutterIconPath?: string;
/**
* The color of the decoration in the overview ruler. Use rgba() and define transparent colors to play well with other decorations.
*/
overviewRulerColor?: string;
}
/**
* Represents rendering styles for a [text editor decoration](#TextEditorDecorationType).
*/
declare export interface DecorationRenderOptions extends ThemableDecorationRenderOptions {
/**
* Should the decoration be rendered also on the whitespace after the line text.
* Defaults to `false`.
*/
isWholeLine?: boolean;
/**
* The position in the overview ruler where the decoration should be rendered.
*/
overviewRulerLane?: OverviewRulerLaneType;
/**
* Overwrite options for light themes.
*/
light?: ThemableDecorationRenderOptions;
/**
* Overwrite options for dark themes.
*/
dark?: ThemableDecorationRenderOptions;
}
/**
* Represents options for a specific decoration in a [decoration set](#TextEditorDecorationType).
*/
declare export interface DecorationOptions {
/**
* Range to which this decoration is applied.
*/
range: Range;
/**
* A message that should be rendered when hovering over the decoration.
*/
hoverMessage: MarkedString | MarkedString[];
}
/**
* Represents an editor that is attached to a [document](#TextDocument).
*/
declare export interface TextEditor {
/**
* The document associated with this text editor. The document will be the same for the entire lifetime of this text editor.
*/
document: TextDocument;
/**
* The primary selection on this text editor. Shorthand for `TextEditor.selections[0]`.
*/
selection: Selection;
/**
* The selections in this text editor. The primary selection is always at index 0.
*/
selections: Selection[];
/**
* Text editor options.
*/
options: TextEditorOptions;
/**
* Perform an edit on the document associated with this text editor.
*
* The given callback-function is invoked with an [edit-builder](#TextEditorEdit) which must
* be used to make edits. Note that the edit-builder is only valid while the
* callback executes.
*
* @param callback A function which can make edits using an [edit-builder](#TextEditorEdit).
* @return A promise that resolves with a value indicating if the edits could be applied.
*/
edit(callback: (editBuilder: TextEditorEdit) => void): Thenable<boolean>;
/**
* Adds a set of decorations to the text editor. If a set of decorations already exists with
* the given [decoration type](#TextEditorDecorationType), they will be replaced.
*
* @see [createTextEditorDecorationType](#window.createTextEditorDecorationType).
*
* @param decorationType A decoration type.
* @param rangesOrOptions Either [ranges](#Range) or more detailed [options](#DecorationOptions).
*/
setDecorations(decorationType: TextEditorDecorationType, rangesOrOptions: Range[] | DecorationOptions[]): void;
/**
* Scroll as indicated by `revealType` in order to reveal the given range.
*
* @param range A range.
* @param revealType The scrolling strategy for revealing `range`.
*/
revealRange(range: Range, revealType?: TextEditorRevealTypeType): void;
/**
* Show the text editor.
*
* @deprecated **This method is deprecated.** Use [window.showTextDocument](#window.showTextDocument)
* instead. This method shows unexpected behavior and will be removed in the next major update.
*
* @param column The [column](#ViewColumn) in which to show this editor.
*/
show(column?: ViewColumnType): void;
/**
* Hide the text editor.
*
* @deprecated **This method is deprecated.** Use the command 'workbench.action.closeActiveEditor' instead.
* This method shows unexpected behavior and will be removed in the next major update.
*/
hide(): void;
}
/**
* A complex edit that will be applied in one transaction on a TextEditor.
* This holds a description of the edits and if the edits are valid (i.e. no overlapping regions, document was not changed in the meantime, etc.)
* they can be applied on a [document](#Document) associated with a [text editor](#TextEditor).
*
*/
declare export interface TextEditorEdit {
/**
* Replace a certain text region with a new value.
* You can use \r\n or \n in `value` and they will be normalized to the current [document](#Document).
*
* @param location The range this operation should remove.
* @param value The new text this operation should insert after removing `location`.
*/
replace(location: Position | Range | Selection, value: string): void;
/**
* Insert text at a location.
* You can use \r\n or \n in `value` and they will be normalized to the current [document](#Document).
* Although the equivalent text edit can be made with [replace](#TextEditorEdit.replace), `insert` will produce a different resulting selection (it will get moved).
*
* @param location The position where the new text should be inserted.
* @param value The new text this operation should insert.
*/
insert(location: Position, value: string): void;
/**
* Delete a certain text region.
*
* @param location The range this operation should remove.
*/
delete(location: Range | Selection): void;
}
/**
* A universal resource identifier representing either a file on disk
* or another resource, like untitled resources.
*/
declare export class Uri {
/**
* Create an URI from a file system path. The [scheme](#Uri.scheme)
* will be `file`.
*
* @param path A file system or UNC path.
* @return A new Uri instance.
*/
static file(path: string): Uri;
/**
* Create an URI from a string. Will throw if the given value is not
* valid.
*
* @param value The string value of an Uri.
* @return A new Uri instance.
*/
static parse(value: string): Uri;
/**
* Scheme is the `http` part of `http://www.msft.com/some/path?query#fragment`.
* The part before the first colon.
*/
scheme: string;
/**
* Authority is the `www.msft.com` part of `http://www.msft.com/some/path?query#fragment`.
* The part between the first double slashes and the next slash.
*/
authority: string;
/**
* Path is the `/some/path` part of `http://www.msft.com/some/path?query#fragment`.
*/
path: string;
/**
* Query is the `query` part of `http://www.msft.com/some/path?query#fragment`.
*/
query: string;
/**
* Fragment is the `fragment` part of `http://www.msft.com/some/path?query#fragment`.
*/
fragment: string;
/**
* The string representing the corresponding file system path of this URI.
*
* Will handle UNC paths and normalize windows drive letters to lower-case. Also
* uses the platform specific path separator. Will *not* validate the path for
* invalid characters and semantics. Will *not* look at the scheme of this URI.
*/
fsPath: string;
/**
* Returns a canonical representation of this URI. The representation and normalization
* of a URI depends on the scheme.
*
* @returns A string that is the encoded version of this Uri.
*/
toString(): string;
/**
* Returns a JSON representation of this Uri.
*
* @return An object.
*/
toJSON(): any;
}
/**
* A cancellation token is passed to an asynchronous or long running
* operation to request cancellation, like cancelling a request
* for completion items because the user continued to type.
*/
declare export interface CancellationToken {
/**
* Is `true` when the token has been cancelled, `false` otherwise.
*/
isCancellationRequested: boolean;
/**
* An [event](#Event) which fires upon cancellation.
*/
onCancellationRequested: Event<any>;
}
/**
* A cancellation source creates and controls a [cancellation token](#CancellationToken).
*/
declare export class CancellationTokenSource {
/**
* The cancellation token of this source.
*/
token: CancellationToken;
/**
* Signal cancellation on the token.
*/
cancel(): void;
/**
* Dispose object and free resources. Will call [cancel](#CancellationTokenSource.cancel).
*/
dispose(): void;
}
/**
* Represents a type which can release resources, such
* as event listening or a timer.
*/
declare export class Disposable {
/**
* Combine many disposable-likes into one. Use this method
* when having objects with a dispose function which are not
* instances of Disposable.
*
* @param disposableLikes Objects that have at least a `dispose`-function member.
* @return Returns a new disposable which, upon dispose, will
* dispose all provided disposables.
*/
static from(...disposableLikes: { dispose: () => any, ... }[]): Disposable;
/**
* Creates a new Disposable calling the provided function
* on dispose.
* @param callOnDispose Function that disposes something.
*/
constructor(callOnDispose: Function): void;
/**
* Dispose this object.
*/
dispose(): any;
}
/**
* Represents a typed event.
*
* A function that represents an event to which you subscribe by calling it with
* a listener function as argument.
*
* @sample `item.onDidChange(function(event) { console.log("Event happened: " + event); });`
*/
declare export interface Event<T> {
/**
* A function that represents an event to which you subscribe by calling it with
* a listener function as argument.
*
* @param listener The listener function will be called when the event happens.
* @param thisArgs The `this`-argument which will be used when calling the event listener.
* @param disposables An array to which a [disposeable](#Disposable) will be added.
* @return A disposable which unsubscribes the event listener.
*/
(listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable;
}
/**
* A file system watcher notifies about changes to files and folders
* on disk.
*
* To get an instance of a `FileSystemWatcher` use
* [createFileSystemWatcher](#workspace.createFileSystemWatcher).
*/
declare export interface FileSystemWatcher extends Disposable {
/**
* true if this file system watcher has been created such that
* it ignores creation file system events.
*/
ignoreCreateEvents: boolean;
/**
* true if this file system watcher has been created such that
* it ignores change file system events.
*/
ignoreChangeEvents: boolean;
/**
* true if this file system watcher has been created such that
* it ignores delete file system events.
*/
ignoreDeleteEvents: boolean;
/**
* An event which fires on file/folder creation.
*/
onDidCreate: Event<Uri>;
/**
* An event which fires on file/folder change.
*/
onDidChange: Event<Uri>;
/**
* An event which fires on file/folder deletion.
*/
onDidDelete: Event<Uri>;
}
/**
* Represents an item that can be selected from
* a list of items.
*/
declare export interface QuickPickItem {
/**
* A label. Will be rendered prominent.
*/
label: string;
/**
* A description. Will be rendered less prominent.
*/
description: string;
}
/**
* Options to configure the behavior of the quick pick UI.
*/
declare export interface QuickPickOptions {
/**
* An optional flag to include the description when filtering the picks.
*/
matchOnDescription?: boolean;
/**
* An optional string to show as place holder in the input box to guide the user what to pick on.
*/
placeHolder?: string;
}
/**
* Represents an action that is shown with an information, warning, or
* error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
* @see [showWarningMessage](#window.showWarningMessage)
* @see [showErrorMessage](#window.showErrorMessage)
*/
declare export interface MessageItem {
/**
* A short title like 'Retry', 'Open Log' etc.
*/
title: string;
}
/**
* Options to configure the behavior of the input box UI.
*/
declare export interface InputBoxOptions {
/**
* The value to prefill in the input box.
*/
value?: string;
/**
* The text to display underneath the input box.
*/
prompt?: string;
/**
* An optional string to show as place holder in the input box to guide the user what to type.
*/
placeHolder?: string;
/**
* Set to true to show a password prompt that will not show the typed value.
*/
password?: boolean;
}
/**
* A document filter denotes a document by different properties like
* the [language](#TextDocument.languageId), the [scheme](#Uri.scheme) of
* its resource, or a glob-pattern that is applied to the [path](#TextDocument.fileName).
*
* @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`
* @sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**∕project.json' }`
*/
declare export interface DocumentFilter {
/**
* A language id, like `typescript`.
*/
language?: string;
/**
* A Uri [scheme](#Uri.scheme), like `file` or `untitled`.
*/
scheme?: string;
/**
* A glob pattern, like `*.{ts,js}`.
*/
pattern?: string;
}
/**
* A language selector is the combination of one or many language identifiers
* and [language filters](#LanguageFilter).
*
* @sample `let sel:DocumentSelector = 'typescript'`;
* @sample `let sel:DocumentSelector = ['typescript', { language: 'json', pattern: '**∕tsconfig.json' }]`;
*/
declare export type DocumentSelector = string | DocumentFilter | (string | DocumentFilter)[];
/**
* Contains additional diagnostic information about the context in which
* a [code action](#CodeActionProvider.provideCodeActions) is run.
*/
declare export interface CodeActionContext {
/**
* An array of diagnostics.
*
* @readonly
*/
diagnostics: Diagnostic[];
}
/**
* The code action interface defines the contract between extensions and
* the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature.
*
* A code action can be any command that is [known](#commands.getCommands) to the system.
*/
declare export interface CodeActionProvider {
/**
* Provide commands for the given document and range.
*
* @param document The document in which the command was invoked.
* @param range The range for which the command was invoked.
* @param context Context carrying additional information.
* @param token A cancellation token.
* @return An array of commands or a thenable of such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideCodeActions(document: TextDocument, range: Range, context: CodeActionContext, token: CancellationToken): Command[] | Thenable<Command[]>;
}
/**
* A code lens represents a [command](#Command) that should be shown along with
* source text, like the number of references, a way to run tests, etc.
*
* A code lens is _unresolved_ when no command is associated to it. For performance
* reasons the creation of a code lens and resolving should be done to two stages.
*
* @see [CodeLensProvider.provideCodeLenses](#CodeLensProvider.provideCodeLenses)
* @see [CodeLensProvider.resolveCodeLens](#CodeLensProvider.resolveCodeLens)
*/
declare export class CodeLens {
/**
* The range in which this code lens is valid. Should only span a single line.
*/
range: Range;
/**
* The command this code lens represents.
*/
command: Command;
/**
* `true` when there is a command associated.
*/
isResolved: boolean;
/**
* Creates a new code lens object.
*
* @param range The range to which this code lens applies.
* @param command The command associated to this code lens.
*/
constructor(range: Range, command?: Command): void;
}
/**
* A code lens provider adds [commands](#Command) to source text. The commands will be shown
* as dedicated horizontal lines in between the source text.
*/
declare export interface CodeLensProvider {
/**
* Compute a list of [lenses](#CodeLens). This call should return as fast as possible and if
* computing the commands is expensive implementors should only return code lens objects with the
* range set and implement [resolve](#CodeLensProvider.resolveCodeLens).
*
* @param document The document in which the command was invoked.
* @param token A cancellation token.
* @return An array of code lenses or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideCodeLenses(document: TextDocument, token: CancellationToken): CodeLens[] | Thenable<CodeLens[]>;
/**
* This function will be called for each visible code lens, usually when scrolling and after
* calls to [compute](#CodeLensProvider.provideCodeLenses)-lenses.
*
* @param codeLens code lens that must be resolved.
* @param token A cancellation token.
* @return The given, resolved code lens or thenable that resolves to such.
*/
resolveCodeLens?: (codeLens: CodeLens, token: CancellationToken) => CodeLens | Thenable<CodeLens>;
}
/**
* The definition of a symbol represented as one or many [locations](#Location).
* For most programming languages there is only one location at which a symbol is
* defined.
*/
declare export type Definition = Location | Location[];
/**
* The definition provider interface defines the contract between extensions and
* the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition)
* and peek definition features.
*/
declare export interface DefinitionProvider {
/**
* Provide the definition of the symbol at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A definition or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Definition | Thenable<?Definition>;
}
/**
* FormattedString can be used to render text with a tiny subset of markdown. FormattedString
* is either a string that supports **bold** and __italic__ or a code-block that
* provides a language and a code Snippet.
*/
declare export type MarkedString = string | {
language: string,
value: string,
...
};
/**
* A hover represents additional information for a symbol or word. Hovers are
* rendered in a tooltip-like widget.
*/
declare export class Hover {
/**
* The contents of this hover.
*/
contents: MarkedString[];
/**
* The range to which this hover applies. When missing, the
* editor will use the range at the current position or the
* current position itself.
*/
range: Range;
/**
* Creates a new hover object.
*
* @param contents The contents of the hover.
* @param range The range to which the hover applies.
*/
constructor(contents: MarkedString | MarkedString[], range?: Range): void;
}
/**
* The hover provider interface defines the contract between extensions and
* the [hover](https://code.visualstudio.com/docs/editor/editingevolved#_hover)-feature.
*/
declare export interface HoverProvider {
/**
* Provide a hover for the given position and document. Multiple hovers at the same
* position will be merged by the editor. A hover can have a range which defaults
* to the word range at the position when omitted.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A hover or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideHover(document: TextDocument, position: Position, token: CancellationToken): Hover | Thenable<?Hover>;
}
/**
* A document highlight kind.
*/
declare export type DocumentHighlightKindType = 0 | 1 | 2;
declare export var DocumentHighlightKind: {
/**
* A textual occurrence.
*/
Text: 0,
/**
* Read-access of a symbol, like reading a variable.
*/
Read: 1,
/**
* Write-access of a symbol, like writing to a variable.
*/
Write: 2,
...
}
/**
* A document highlight is a range inside a text document which deserves
* special attention. Usually a document highlight is visualized by changing
* the background color of its range.
*/
declare export class DocumentHighlight {
/**
* The range this highlight applies to.
*/
range: Range;
/**
* The highlight kind, default is [text](#DocumentHighlightKind.Text).
*/
kind: DocumentHighlightKindType;
/**
* Creates a new document highlight object.
*
* @param range The range the highlight applies to.
* @param kind The highlight kind, default is [text](#DocumentHighlightKind.Text).
*/
constructor(range: Range, kind?: DocumentHighlightKindType): void;
}
/**
* The document highlight provider interface defines the contract between extensions and
* the word-highlight-feature.
*/
declare export interface DocumentHighlightProvider {
/**
* Provide a set of document highlights, like all occurrences of a variable or
* all exit-points of a function.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return An array of document highlights or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentHighlights(document: TextDocument, position: Position, token: CancellationToken): DocumentHighlight[] | Thenable<DocumentHighlight[]>;
}
/**
* A symbol kind.
*/
declare export type SymbolKindType = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
declare export var SymbolKind: {
File: 0,
Module: 1,
Namespace: 2,
Package: 3,
Class: 4,
Method: 5,
Property: 6,
Field: 7,
Constructor: 8,
Enum: 9,
Interface: 10,
Function: 11,
Variable: 12,
Constant: 13,
String: 14,
Number: 15,
Boolean: 16,
Array: 17,
...
}
/**
* Represents information about programming constructs like variables, classes,
* interfaces etc.
*/
declare export class SymbolInformation {
/**
* The name of this symbol.
*/
name: string;
/**
* The name of the symbol containing this symbol.
*/
containerName: string;
/**
* The kind of this symbol.
*/
kind: SymbolKindType;
/**
* The location of this symbol.
*/
location: Location;
/**
* Creates a new symbol information object.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the location of the symbol.
* @param uri The resource of the location of symbol, defaults to the current document.
* @param containerName The name of the symbol containing the symbol.
*/
constructor(name: string, kind: SymbolKindType, range: Range, uri?: Uri, containerName?: string): void;
}
/**
* The document symbol provider interface defines the contract between extensions and
* the [go to symbol](https://code.visualstudio.com/docs/editor/editingevolved#_goto-symbol)-feature.
*/
declare export interface DocumentSymbolProvider {
/**
* Provide symbol information for the given document.
*
* @param document The document in which the command was invoked.
* @param token A cancellation token.
* @return An array of document highlights or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentSymbols(document: TextDocument, token: CancellationToken): SymbolInformation[] | Thenable<SymbolInformation[]>;
}
/**
* The workspace symbol provider interface defines the contract between extensions and
* the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature.
*/
declare export interface WorkspaceSymbolProvider {
/**
* Project-wide search for a symbol matching the given query string. It is up to the provider
* how to search given the query string, like substring, indexOf etc.
*
* @param query A non-empty query string.
* @param token A cancellation token.
* @return An array of document highlights or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideWorkspaceSymbols(query: string, token: CancellationToken): SymbolInformation[] | Thenable<SymbolInformation[]>;
}
/**
* Value-object that contains additional information when
* requesting references.
*/
declare export interface ReferenceContext {
/**
* Include the declaration of the current symbol.
*/
includeDeclaration: boolean;
}
/**
* The reference provider interface defines the contract between extensions and
* the [find references](https://code.visualstudio.com/docs/editor/editingevolved#_peek)-feature.
*/
declare export interface ReferenceProvider {
/**
* Provide a set of project-wide references for the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param context
* @param token A cancellation token.
* @return An array of locations or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideReferences(document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken): Location[] | Thenable<Location[]>;
}
/**
* A text edit represents edits that should be applied
* to a document.
*/
declare export class TextEdit {
/**
* Utility to create a replace edit.
*
* @param range A range.
* @param newText A string.
* @return A new text edit object.
*/
static replace(range: Range, newText: string): TextEdit;
/**
* Utility to create an insert edit.
*
* @param position A position, will become an empty range.
* @param newText A string.
* @return A new text edit object.
*/
static insert(position: Position, newText: string): TextEdit;
/**
* Utility to create a delete edit.
*
* @param range A range.
* @return A new text edit object.
*/
static delete(range: Range): TextEdit;
/**
* The range this edit applies to.
*/
range: Range;
/**
* The string this edit will insert.
*/
newText: string;
/**
* Create a new TextEdit.
*
* @param range A range.
* @param newText A string.
*/
constructor(range: Range, newText: string): void;
}
/**
* A workspace edit represents textual changes for many documents.
*/
declare export class WorkspaceEdit {
/**
* The number of affected resources.
*
* @readonly
*/
size: number;
/**
* Replace the given range with given text for the given resource.
*
* @param uri A resource identifier.
* @param range A range.
* @param newText A string.
*/
replace(uri: Uri, range: Range, newText: string): void;
/**
* Insert the given text at the given position.
*
* @param uri A resource identifier.
* @param position A position.
* @param newText A string.
*/
insert(uri: Uri, position: Position, newText: string): void;
/**
* Delete the text at the given range.
*
* @param uri A resource identifier.
* @param range A range.
*/
delete(uri: Uri, range: Range): void;
/**
* Check if this edit affects the given resource.
* @param uri A resource identifier.
* @return `true` if the given resource will be touched by this edit.
*/
has(uri: Uri): boolean;
/**
* Set (and replace) text edits for a resource.
*
* @param uri A resource identifier.
* @param edits An array of text edits.
*/
set(uri: Uri, edits: TextEdit[]): void;
/**
* Get the text edits for a resource.
*
* @param uri A resource identifier.
* @return An array of text edits.
*/
get(uri: Uri): TextEdit[];
/**
* Get all text edits grouped by resource.
*
* @return An array of `[Uri, TextEdit[]]`-tuples.
*/
entries(): [Uri, TextEdit[]][];
}
/**
* The rename provider interface defines the contract between extensions and
* the [rename](https://code.visualstudio.com/docs/editor/editingevolved#_rename-symbol)-feature.
*/
declare export interface RenameProvider {
/**
* Provide an edit that describes changes that have to be made to one
* or many resources to rename a symbol to a different name.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param newName The new name of the symbol. If the given name is not valid, the provider must return a rejected promise.
* @param token A cancellation token.
* @return A workspace edit or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideRenameEdits(document: TextDocument, position: Position, newName: string, token: CancellationToken): WorkspaceEdit | Thenable<WorkspaceEdit>;
}
/**
* Value-object describing what options formatting should use.
*/
declare export interface FormattingOptions {
/**
* Size of a tab in spaces.
*/
tabSize: number;
/**
* Prefer spaces over tabs.
*/
insertSpaces: boolean;
/**
* Signature for further properties.
*/
[key: string]: boolean | number | string;
}
/**
* The document formatting provider interface defines the contract between extensions and
* the formatting-feature.
*/
declare export interface DocumentFormattingEditProvider {
/**
* Provide formatting edits for a whole document.
*
* @param document The document in which the command was invoked.
* @param options Options controlling formatting.
* @param token A cancellation token.
* @return A set of text edits or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): TextEdit[] | Thenable<TextEdit[]>;
}
/**
* The document formatting provider interface defines the contract between extensions and
* the formatting-feature.
*/
declare export interface DocumentRangeFormattingEditProvider {
/**
* Provide formatting edits for a range in a document.
*
* The given range is a hint and providers can decide to format a smaller
* or larger range. Often this is done by adjusting the start and end
* of the range to full syntax nodes.
*
* @param document The document in which the command was invoked.
* @param range The range which should be formatted.
* @param options Options controlling formatting.
* @param token A cancellation token.
* @return A set of text edits or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentRangeFormattingEdits(document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): TextEdit[] | Thenable<TextEdit[]>;
}
/**
* The document formatting provider interface defines the contract between extensions and
* the formatting-feature.
*/
declare export interface OnTypeFormattingEditProvider {
/**
* Provide formatting edits after a character has been typed.
*
* The given position and character should hint to the provider
* what range the position to expand to, like find the matching `{`
* when `}` has been entered.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param ch The character that has been typed.
* @param options Options controlling formatting.
* @param token A cancellation token.
* @return A set of text edits or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): TextEdit[] | Thenable<TextEdit[]>;
}
/**
* Represents a parameter of a callable-signature. A parameter can
* have a label and a doc-comment.
*/
declare export class ParameterInformation {
/**
* The label of this signature. Will be shown in
* the UI.
*/
label: string;
/**
* The human-readable doc-comment of this signature. Will be shown
* in the UI but can be omitted.
*/
documentation: string;
/**
* Creates a new parameter information object.
*
* @param label A label string.
* @param documentation A doc string.
*/
constructor(label: string, documentation?: string): void;
}
/**
* Represents the signature of something callable. A signature
* can have a label, like a function-name, a doc-comment, and
* a set of parameters.
*/
declare export class SignatureInformation {
/**
* The label of this signature. Will be shown in
* the UI.
*/
label: string;
/**
* The human-readable doc-comment of this signature. Will be shown
* in the UI but can be omitted.
*/
documentation: string;
/**
* The parameters of this signature.
*/
parameters: ParameterInformation[];
/**
* Creates a new signature information object.
*
* @param label A label string.
* @param documentation A doc string.
*/
constructor(label: string, documentation?: string): void;
}
/**
* Signature help represents the signature of something
* callable. There can be multiple signatures but only one
* active and only one active parameter.
*/
declare export class SignatureHelp {
/**
* One or more signatures.
*/
signatures: SignatureInformation[];
/**
* The active signature.
*/
activeSignature: number;
/**
* The active parameter of the active signature.
*/
activeParameter: number;
}
/**
* The signature help provider interface defines the contract between extensions and
* the [parameter hints](https://code.visualstudio.com/docs/editor/editingevolved#_parameter-hints)-feature.
*/
declare export interface SignatureHelpProvider {
/**
* Provide help for the signature at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return Signature help or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideSignatureHelp(document: TextDocument, position: Position, token: CancellationToken): SignatureHelp | Thenable<SignatureHelp>;
}
/**
* Completion item kinds.
*/
declare export type CompletionItemKindType = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
| 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17;
declare export var CompletionItemKind: {
Text: 0,
Method: 1,
Function: 2,
Constructor: 3,
Field: 4,
Variable: 5,
Class: 6,
Interface: 7,
Module: 8,
Property: 9,
Unit: 10,
Value: 11,
Enum: 12,
Keyword: 13,
Snippet: 14,
Color: 15,
File: 16,
Reference: 17,
...
}
/**
* A completion item represents a text snippet that is
* proposed to complete text that is being typed.
*
* @see [CompletionItemProvider.provideCompletionItems](#CompletionItemProvider.provideCompletionItems)
* @see [CompletionItemProvider.resolveCompletionItem](#CompletionItemProvider.resolveCompletionItem)
*/
declare export class CompletionItem {
/**
* The label of this completion item. By default
* this is also the text that is inserted when selecting
* this completion.
*/
label: string;
/**
* The kind of this completion item. Based on the kind
* an icon is chosen by the editor.
*/
kind: CompletionItemKindType;
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*/
detail: string;
/**
* A human-readable string that represents a doc-comment.
*/
documentation: string;
/**
* A string that should be used when comparing this item
* with other items. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
sortText: string;
/**
* A string that should be used when filtering a set of
* completion items. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
filterText: string;
/**
* A string that should be inserted in a document when selecting
* this completion. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
insertText: string;
/**
* An [edit](#TextEdit) which is applied to a document when selecting
* this completion. When an edit is provided the value of
* [insertText](#CompletionItem.insertText) is ignored.
*
* The [range](#Range) of the edit must be single-line and one the same
* line completions where [requested](#CompletionItemProvider.provideCompletionItems) at.
*/
textEdit: TextEdit;
/**
* Creates a new completion item.
*
* Completion items must have at least a [label](#CompletionItem.label) which then
* will be used as insert text as well as for sorting and filtering.
*
* @param label The label of the completion.
*/
constructor(label: string): void;
}
/**
* The completion item provider interface defines the contract between extensions and
* the [IntelliSense](https://code.visualstudio.com/docs/editor/editingevolved#_intellisense).
*
* When computing *complete* completion items is expensive, providers can optionally implement
* the `resolveCompletionItem`-function. In that case it is enough to return completion
* items with a [label](#CompletionItem.label) from the
* [provideCompletionItems](#CompletionItemProvider.provideCompletionItems)-function. Subsequently,
* when a completion item is shown in the UI and gains focus this provider is asked to resolve
* the item, like adding [doc-comment](#CompletionItem.documentation) or [details](#CompletionItem.detail).
*/
declare export interface CompletionItemProvider {
/**
* Provide completion items for the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return An array of completions or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, an empty array.
*/
provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): CompletionItem[] | Thenable<CompletionItem[]>;
/**
* Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation)
* or [details](#CompletionItem.detail).
*
* The editor will only resolve a completion item once.
*
* @param item A completion item currently active in the UI.
* @param token A cancellation token.
* @return The resolved completion item or a thenable that resolves to of such. It is OK to return the given
* `item`. When no result is returned, the given `item` will be used.
*/
resolveCompletionItem?: (item: CompletionItem, token: CancellationToken) => CompletionItem | Thenable<CompletionItem>;
}
/**
* A tuple of two characters, like a pair of
* opening and closing brackets.
*/
declare export type CharacterPair = [string, string];
/**
* Describes how comments for a language work.
*/
declare export interface CommentRule {
/**
* The line comment token, like `// this is a comment`
*/
lineComment?: string;
/**
* The block comment character pair, like `/* block comment */`
*/
blockComment?: CharacterPair;
}
/**
* Describes indentation rules for a language.
*/
declare export interface IndentationRule {
/**
* If a line matches this pattern, then all the lines after it should be unindendented once (until another rule matches).
*/
decreaseIndentPattern: RegExp;
/**
* If a line matches this pattern, then all the lines after it should be indented once (until another rule matches).
*/
increaseIndentPattern: RegExp;
/**
* If a line matches this pattern, then **only the next line** after it should be indented once.
*/
indentNextLinePattern?: RegExp;
/**
* If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules.
*/
unIndentedLinePattern?: RegExp;
}
/**
* Describes what to do with the indentation when pressing Enter.
*/
declare export type IndentActionType = 0 | 1 | 2 | 3;
declare export var IndentAction: {
/**
* Insert new line and copy the previous line's indentation.
*/
None: 0,
/**
* Insert new line and indent once (relative to the previous line's indentation).
*/
Indent: 1,
/**
* Insert two new lines:
* - the first one indented which will hold the cursor
* - the second one at the same indentation level
*/
IndentOutdent: 2,
/**
* Insert new line and outdent once (relative to the previous line's indentation).
*/
Outdent: 3,
...
}
/**
* Describes what to do when pressing Enter.
*/
declare export interface EnterAction {
/**
* Describe what to do with the indentation.
*/
indentAction: IndentActionType;
/**
* Describes text to be appended after the new line and after the indentation.
*/
appendText?: string;
/**
* Describes the number of characters to remove from the new line's indentation.
*/
removeText?: number;
}
/**
* Describes a rule to be evaluated when pressing Enter.
*/
declare export interface OnEnterRule {
/**
* This rule will only execute if the text before the cursor matches this regular expression.
*/
beforeText: RegExp;
/**
* This rule will only execute if the text after the cursor matches this regular expression.
*/
afterText?: RegExp;
/**
* The action to execute.
*/
action: EnterAction;
}
/**
* The language configuration interfaces defines the contract between extensions
* and various editor features, like automatic bracket insertion, automatic indentation etc.
*/
declare export interface LanguageConfiguration {
/**
* The language's comment settings.
*/
comments?: CommentRule;
/**
* The language's brackets.
* This configuration implicitly affects pressing Enter around these brackets.
*/
brackets?: CharacterPair[];
/**
* The language's word definition.
* If the language supports Unicode identifiers (e.g. JavaScript), it is preferable
* to provide a word definition that uses exclusion of known separators.
* e.g.: A regex that matches anything except known separators (and dot is allowed to occur in a floating point number):
* /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g
*/
wordPattern?: RegExp;
/**
* The language's indentation settings.
*/
indentationRules?: IndentationRule;
/**
* The language's rules to be evaluated when pressing Enter.
*/
onEnterRules?: OnEnterRule[];
/**
* **Deprecated** Do not use.
*
* @deprecated Will be replaced by a better API soon.
*/
__electricCharacterSupport?: {
brackets: {
tokenType: string,
open: string,
close: string,
isElectric: boolean,
...
}[],
docComment?: {
scope: string,
open: string,
lineStart: string,
close?: string,
...
},
...
};
/**
* **Deprecated** Do not use.
*
* @deprecated Will be replaced by a better API soon.
*/
__characterPairSupport?: { autoClosingPairs: {
open: string,
close: string,
notIn?: string[],
...
}[], ... };
}
/**
* Represents the workspace configuration. The workspace configuration
* is always a merged view of the configuration of the current [workspace](#workspace.rootPath)
* and the installation-wide configuration.
*/
declare export interface WorkspaceConfiguration {
/**
* Return a value from this configuration.
*
* @param section Configuration name, supports _dotted_ names.
* @param defaultValue A value should be returned when no value could be found, is `undefined`.
* @return The value `section` denotes or the default.
*/
get<T>(section: string, defaultValue?: T): T;
/**
* Check if this configuration has a certain value.
*
* @param section configuration name, supports _dotted_ names.
* @return `true` iff the section doesn't resolve to `undefined`.
*/
has(section: string): boolean;
/**
* Readable dictionary that backs this configuration.
* @readonly
*/
[key: string]: any;
}
/**
* Represents a location inside a resource, such as a line
* inside a text file.
*/
declare export class Location {
/**
* The resource identifier of this location.
*/
uri: Uri;
/**
* The document range of this locations.
*/
range: Range;
/**
* Creates a new location object.
*
* @param uri The resource identifier.
* @param rangeOrPosition The range or position. Positions will be converted to an empty range.
*/
constructor(uri: Uri, rangeOrPosition: Range | Position): void;
}
/**
* Represents the severity of diagnostics.
*/
declare export type DiagnosticSeverityType = 0 | 1 | 2 | 3;
declare export var DiagnosticSeverity: {
/**
* Something not allowed by the rules of a language or other means.
*/
Error: 0,
/**
* Something suspicious but allowed.
*/
Warning: 1,
/**
* Something to inform about but not a problem.
*/
Information: 2,
/**
* Something to hint to a better way of doing it, like proposing
* a refactoring.
*/
Hint: 3,
...
}
/**
* Represents a diagnostic, such as a compiler error or warning. Diagnostic objects
* are only valid in the scope of a file.
*/
declare export class Diagnostic {
/**
* The range to which this diagnostic applies.
*/
range: Range;
/**
* The human-readable message.
*/
message: string;
/**
* A human-readable string describing the source of this
* diagnostic, e.g. 'typescript' or 'super lint'.
*/
source: string;
/**
* The severity, default is [error](#DiagnosticSeverity.Error).
*/
severity: DiagnosticSeverityType;
/**
* A code or identifier for this diagnostics. Will not be surfaced
* to the user, but should be used for later processing, e.g. when
* providing [code actions](#CodeActionContext).
*/
code: string | number;
/**
* Creates a new diagnostic object.
*
* @param range The range to which this diagnostic applies.
* @param message The human-readable message.
* @param severity The severity, default is [error](#DiagnosticSeverity.Error).
*/
constructor(range: Range, message: string, severity?: DiagnosticSeverityType): void;
}
/**
* A diagnostics collection is a container that manages a set of
* [diagnostics](#Diagnostic). Diagnostics are always scopes to a
* a diagnostics collection and a resource.
*
* To get an instance of a `DiagnosticCollection` use
* [createDiagnosticCollection](#languages.createDiagnosticCollection).
*/
declare export interface DiagnosticCollection {
/**
* The name of this diagnostic collection, for instance `typescript`. Every diagnostic
* from this collection will be associated with this name. Also, the task framework uses this
* name when defining [problem matchers](https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher).
*/
name: string;
/**
* Assign diagnostics for given resource. Will replace
* existing diagnostics for that resource.
*
* @param uri A resource identifier.
* @param diagnostics Array of diagnostics or `undefined`
*/
set(uri: Uri, diagnostics: Diagnostic[]): void;
/**
* Remove all diagnostics from this collection that belong
* to the provided `uri`. The same as `#set(uri, undefined)`.
*
* @param uri A resource identifier.
*/
delete(uri: Uri): void;
/**
* Replace all entries in this collection.
*
* @param entries An array of tuples, like `[[file1, [d1, d2]], [file2, [d3, d4, d5]]]`, or `undefined`.
*/
set(entries: [Uri, Diagnostic[]][]): void;
/**
* Remove all diagnostics from this collection. The same
* as calling `#set(undefined)`;
*/
clear(): void;
/**
* Dispose and free associated resources. Calls
* [clear](#DiagnosticCollection.clear).
*/
dispose(): void;
}
/**
* Denotes a column in the VS Code window. Columns are
* used to show editors side by side.
*/
declare export type ViewColumnType = 1 | 2 | 3;
declare export var ViewColumn: {
One: 1,
Two: 2,
Three: 3,
...
}
/**
* An output channel is a container for readonly textual information.
*
* To get an instance of an `OutputChannel` use
* [createOutputChannel](#window.createOutputChannel).
*/
declare export interface OutputChannel {
/**
* The human-readable name of this output channel.
* @readonly
*/
name: string;
/**
* Append the given value to the channel.
*
* @param value A string, falsy values will not be printed.
*/
append(value: string): void;
/**
* Append the given value and a line feed character
* to the channel.
*
* @param value A string, falsy values will be printed.
*/
appendLine(value: string): void;
/**
* Removes all output from the channel.
*/
clear(): void;
/**
* Reveal this channel in the UI.
*
* @param column The column in which to show the channel, default in [one](#ViewColumn.One).
*/
show(column?: ViewColumnType): void;
/**
* Hide this channel from the UI.
*/
hide(): void;
/**
* Dispose and free associated resources.
*/
dispose(): void;
}
/**
* Represents the alignment of status bar items.
*/
declare export type StatusBarAlignmentType = 0 | 1;
declare export var StatusBarAlignment: {
/**
* Aligned to the left side.
*/
Left: 0,
/**
* Aligned to the right side.
*/
Right: 1,
...
}
/**
* A status bar item is a status bar contribution that can
* show text and icons and run a command on click.
*/
declare export interface StatusBarItem {
/**
* The alignment of this item.
*
* @readonly
*/
alignment: StatusBarAlignmentType;
/**
* The priority of this item. Higher value means the item should
* be shown more to the left.
*
* @readonly
*/
priority: number;
/**
* The text to show for the entry. You can embed icons in the text by leveraging the syntax:
*
* `My text $(icon-name) contains icons like $(icon'name) this one.`
*
* Where the icon-name is taken from the [octicon](https://octicons.github.com) icon set, e.g.
* `light-bulb`, `thumbsup`, `zap` etc.
*/
text: string;
/**
* The tooltip text when you hover over this entry.
*/
tooltip: string;
/**
* The foreground color for this entry.
*/
color: string;
/**
* The identifier of a command to run on click. The command must be
* [known](#commands.getCommands).
*/
command: string;
/**
* Shows the entry in the status bar.
*/
show(): void;
/**
* Hide the entry in the status bar.
*/
hide(): void;
/**
* Dispose and free associated resources. Call
* [hide](#StatusBarItem.hide).
*/
dispose(): void;
}
/**
* Represents an extension.
*
* To get an instance of an `Extension` use [getExtension](#extensions.getExtension).
*/
declare export interface Extension<T> {
/**
* The canonical extension identifier in the form of: `publisher.name`.
*
* @readonly
*/
id: string;
/**
* The absolute file path of the directory containing this extension.
*
* @readonly
*/
extensionPath: string;
/**
* `true` if the extension has been activated.
*
* @readonly
*/
isActive: boolean;
/**
* The parsed contents of the extension's package.json.
*
* @readonly
*/
packageJSON: any;
/**
* The public API declare exported by this extension. It is an invalid action
* to access this field before this extension has been activated.
*
* @readonly
*/
exports: T;
/**
* Activates this extension and returns its public API.
*
* @return A promise that will resolve when this extension has been activated.
*/
activate(): Thenable<T>;
}
/**
* An extension context is a collection of utilities private to an
* extension.
*
* An instance of an `ExtensionContext` is provided as the first
* parameter to the `activate`-call of an extension.
*/
declare export interface ExtensionContext {
/**
* An array to which disposables can be added. When this
* extension is deactivated the disposables will be disposed.
*/
subscriptions: { dispose(): any, ... }[];
/**
* A memento object that stores state in the context
* of the currently opened [workspace](#workspace.path).
*/
workspaceState: Memento;
/**
* A memento object that stores state independent
* of the current opened [workspace](#workspace.path).
*/
globalState: Memento;
/**
* The absolute file path of the directory containing the extension.
*/
extensionPath: string;
/**
* Get the absolute path of a resource contained in the extension.
*
* @param relativePath A relative path to a resource contained in the extension.
* @return The absolute path of the resource.
*/
asAbsolutePath(relativePath: string): string;
}
/**
* A memento represents a storage utility. It can store and retrieve
* values.
*/
declare export interface Memento {
/**
* Return a value.
*
* @param key A string.
* @param defaultValue A value that should be returned when there is no
* value (`undefined`) with the given key.
* @return The stored value, `undefined`, or the defaultValue.
*/
get<T>(key: string, defaultValue?: T): T;
/**
* Store a value. The value must be JSON-stringifyable.
*
* @param key A string.
* @param value A value. MUST not contain cyclic references.
*/
update(key: string, value: any): Thenable<void>;
}
/**
* Namespace for dealing with commands. In short, a command is a function with a
* unique identifier. The function is sometimes also called _command handler_.
*
* Commands can be added to the editor using the [registerCommand](#commands.registerCommand)
* and [registerTextEditorCommand](#commands.registerTextEditorCommand) functions. Commands
* can be executed [manually](#commands.executeCommand) or from a UI gesture. Those are:
*
* * palette - Use the `commands`-section in `package.json` to make a command show in
* the [command palette](https://code.visualstudio.com/docs/editor/codebasics#_command-palette).
* * keybinding - Use the `keybindings`-section in `package.json` to enable
* [keybindings](https://code.visualstudio.com/docs/customization/keybindings#_customizing-shortcuts)
* for your extension.
*
* Commands from other extensions and from the editor itself are accessible to an extension. However,
* when invoking an editor command not all argument types are supported.
*
* This is a sample that registers a command handler and adds an entry for that command to the palette. First
* register a command handler with the identfier `extension.sayHello`.
* ```javascript
* commands.registerCommand('extension.sayHello', () => {
* window.showInformationMessage('Hello World!');
* });
* ```
* Second, bind the command identfier to a title under which it will show in the palette (`package.json`).
* ```json
* {
* "contributes": {
* "commands": [{
* "command": "extension.sayHello",
* "title": "Hello World"
* }]
* }
* ```
*/
declare export var commands: {
/**
* Registers a command that can be invoked via a keyboard shortcut,
* a menu item, an action, or directly.
*
* Registering a command with an existing command identifier twice
* will cause an error.
*
* @param command A unique identifier for the command.
* @param callback A command handler function.
* @param thisArg The `this` context used when invoking the handler function.
* @return Disposable which unregisters this command on disposal.
*/
registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any): Disposable,
/**
* Registers a text editor command that can be invoked via a keyboard shortcut,
* a menu item, an action, or directly.
*
* Text editor commands are different from ordinary [commands](#commands.registerCommand) as
* they only execute when there is an active editor when the command is called. Also, the
* command handler of an editor command has access to the active editor and to an
* [edit](#TextEditorEdit)-builder.
*
* @param command A unique identifier for the command.
* @param callback A command handler function with access to an [editor](#TextEditor) and an [edit](#TextEditorEdit).
* @param thisArg The `this` context used when invoking the handler function.
* @return Disposable which unregisters this command on disposal.
*/
registerTextEditorCommand(command: string, callback: (textEditor: TextEditor, edit: TextEditorEdit) => void, thisArg?: any): Disposable,
/**
* Executes the command denoted by the given command identifier.
*
* When executing an editor command not all types are allowed to
* be passed as arguments. Allowed are the primitive types `string`, `boolean`,
* `number`, `undefined`, and `null`, as well as classes defined in this API.
* There are no restrictions when executing commands that have been contributed
* by extensions.
*
* @param command Identifier of the command to execute.
* @param rest Parameters passed to the command function.
* @return A thenable that resolves to the returned value of the given command. `undefined` when
* the command handler function doesn't return anything.
*/
executeCommand<T>(command: string, ...rest: any[]): Thenable<T>,
/**
* Retrieve the list of all available commands. Commands starting an underscore are
* treated as internal commands.
*
* @param filterInternal Set `true` to not see internal commands (starting with an underscore)
* @return Thenable that resolves to a list of command ids.
*/
getCommands(filterInternal?: boolean): Thenable<string[]>,
...
}
/**
* Namespace for dealing with the current window of the editor. That is visible
* and active editors, as well as, UI elements to show messages, selections, and
* asking for user input.
*/
declare export var window: {
/**
* The currently active editor or undefined. The active editor is the one
* that currently has focus or, when none has focus, the one that has changed
* input most recently.
*/
activeTextEditor: TextEditor,
/**
* The currently visible editors or an empty array.
*/
visibleTextEditors: TextEditor[],
/**
* An [event](#Event) which fires when the [active editor](#window.activeTextEditor)
* has changed.
*/
onDidChangeActiveTextEditor: Event<TextEditor>,
/**
* An [event](#Event) which fires when the selection in an editor has changed.
*/
onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>,
/**
* An [event](#Event) which fires when the options of an editor have changed.
*/
onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>,
/**
* Show the given document in a text editor. A [column](#ViewColumn) can be provided
* to control where the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param column A view column in which the editor should be shown. The default is the [one](#ViewColumn.One), other values
* are adjusted to be __Min(column, columnCount + 1)__.
* @return A promise that resolves to an [editor](#TextEditor).
*/
showTextDocument(document: TextDocument, column?: ViewColumnType): Thenable<TextEditor>,
/**
* Create a TextEditorDecorationType that can be used to add decorations to text editors.
*
* @param options Rendering options for the decoration type.
* @return A new decoration type instance.
*/
createTextEditorDecorationType(options: DecorationRenderOptions): TextEditorDecorationType,
/**
* Show an information message to users. Optionally provide an array of items which will be presented as
* clickable buttons.
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined`. The thenable will be rejected
* when the message was dismissed.
*/
showInformationMessage(message: string, ...items: string[]): Thenable<string>,
/**
* Show an information message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined`. The thenable will be rejected
* when the message was dismissed.
*/
showInformationMessage<T: MessageItem>(message: string, ...items: T[]): Thenable<T>,
/**
* Show a warning message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined`. The thenable will be rejected
* when the message was dismissed.
*/
showWarningMessage(message: string, ...items: string[]): Thenable<string>,
/**
* Show a warning message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined`. The thenable will be rejected
* when the message was dismissed.
*/
showWarningMessage<T: MessageItem>(message: string, ...items: T[]): Thenable<T>,
/**
* Show an error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined`. The thenable will be rejected
* when the message was dismissed.
*/
showErrorMessage(message: string, ...items: string[]): Thenable<string>,
/**
* Show an error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined`. The thenable will be rejected
* when the message was dismissed.
*/
showErrorMessage<T: MessageItem>(message: string, ...items: T[]): Thenable<T>,
/**
* Shows a selection list.
*
* @param items An array of strings, or a promise that resolves to an array of strings.
* @param options Configures the behavior of the selection list.
* @return A promise that resolves to the selection or undefined.
*/
showQuickPick(items: string[] | Thenable<string[]>, options?: QuickPickOptions): Thenable<string>,
/**
* Shows a selection list.
*
* @param items An array of items, or a promise that resolves to an array of items.
* @param options Configures the behavior of the selection list.
* @return A promise that resolves to the selected item or undefined.
*/
showQuickPick<T: QuickPickItem>(items: T[] | Thenable<T[]>, options?: QuickPickOptions): Thenable<T>,
/**
* Opens an input box to ask the user for input.
*
* The returned value will be undefined if the input box was canceled (e.g. pressing ESC). Otherwise the
* returned value will be the string typed by the user or an empty string if the user did not type
* anything but dismissed the input box with OK.
*
* @param options Configures the behavior of the input box.
* @return A promise that resolves to a string the user provided or to `undefined` in case of dismissal.
*/
showInputBox(options?: InputBoxOptions): Thenable<string>,
/**
* Create a new [output channel](#OutputChannel) with the given name.
*
* @param name Human-readable string which will be used to represent the channel in the UI.
*/
createOutputChannel(name: string): OutputChannel,
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, support icon subtitution as in status bar [items](#StatusBarItem.text).
* @return A disposable which hides the status bar message.
*/
setStatusBarMessage(text: string): Disposable,
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, support icon subtitution as in status bar [items](#StatusBarItem.text).
* @param hideAfterTimeout Timeout in milliseconds after which the message will be disposed.
* @return A disposable which hides the status bar message.
*/
setStatusBarMessage(text: string, hideAfterTimeout: number): Disposable,
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, support icon subtitution as in status bar [items](#StatusBarItem.text).
* @param hideWhenDone Thenable on which completion (resolve or reject) the message will be disposed.
* @return A disposable which hides the status bar message.
*/
setStatusBarMessage(text: string, hideWhenDone: Thenable<any>): Disposable,
/**
* Creates a status bar [item](#StatusBarItem).
*
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
createStatusBarItem(alignment?: StatusBarAlignmentType, priority?: number): StatusBarItem,
...
}
/**
* An event describing an individual change in the text of a [document](#TextDocument).
*/
declare export interface TextDocumentContentChangeEvent {
/**
* The range that got replaced.
*/
range: Range;
/**
* The length of the range that got replaced.
*/
rangeLength: number;
/**
* The new text for the range.
*/
text: string;
}
/**
* An event describing a transactional [document](#TextDocument) change.
*/
declare export interface TextDocumentChangeEvent {
/**
* The affected document.
*/
document: TextDocument;
/**
* An array of content changes.
*/
contentChanges: TextDocumentContentChangeEvent[];
}
/**
* Namespace for dealing with the current workspace. A workspace is the representation
* of the folder that has been opened. There is no workspace when just a file but not a
* folder has been opened.
*
* The workspace offers support for [listening](#workspace.createFileSystemWatcher) to fs
* events and for [finding](#workspace#findFiles) files. Both perform well and run _outside_
* the editor-process so that they should be always used instead of nodejs-equivalents.
*/
declare export var workspace: {
/**
* Creates a file system watcher.
*
* A glob pattern that filters the file events must be provided. Optionally, flags to ignore certain
* kinds of events can be provided. To stop listening to events the watcher must be disposed.
*
* @param globPattern A glob pattern that is applied to the names of created, changed, and deleted files.
* @param ignoreCreateEvents Ignore when files have been created.
* @param ignoreChangeEvents Ignore when files have been changed.
* @param ignoreDeleteEvents Ignore when files have been deleted.
* @return A new file system watcher instance.
*/
createFileSystemWatcher(globPattern: string, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher,
/**
* The folder that is open in VS Code. `undefined` when no folder
* has been opened.
*/
rootPath: string,
/**
* Returns a path that is relative to the workspace root.
*
* When there is no [workspace root](#workspace.rootPath) or when the path
* is not a child of that folder, the input is returned.
*
* @param pathOrUri A path or uri. When a uri is given its [fsPath](#Uri.fsPath) is used.
* @return A path relative to the root or the input.
*/
asRelativePath(pathOrUri: string | Uri): string,
/**
* Find files in the workspace.
*
* @sample `findFiles('**∕*.js', '**∕node_modules∕**', 10)`
* @param include A glob pattern that defines the files to search for.
* @param exclude A glob pattern that defines files and folders to exclude.
* @param maxResults An upper-bound for the result.
* @return A thenable that resolves to an array of resource identifiers.
*/
findFiles(include: string, exclude: string, maxResults?: number): Thenable<Uri[]>,
/**
* Save all dirty files.
*
* @param includeUntitled Also save files that have been created during this session.
* @return A thenable that resolves when the files have been saved.
*/
saveAll(includeUntitled?: boolean): Thenable<boolean>,
/**
* Make changes to one or many resources as defined by the given
* [workspace edit](#WorkspaceEdit).
*
* When applying a workspace edit, the editor implements an 'all-or-nothing'-strategy,
* that means failure to load one document or make changes to one document will cause
* the edit to be rejected.
*
* @param edit A workspace edit.
* @return A thenable that resolves when the edit could be applied.
*/
applyEdit(edit: WorkspaceEdit): Thenable<boolean>,
/**
* All text documents currently known to the system.
*
* @readonly
*/
textDocuments: TextDocument[],
/**
* Opens the denoted document from disk. Will return early if the
* document is already open, otherwise the document is loaded and the
* [open document](#workspace.onDidOpenTextDocument)-event fires.
* The document to open is denoted by the [uri](#Uri). Two schemes are supported:
*
* file: A file on disk, will be rejected if the file does not exist or cannot be loaded, e.g. 'file:///Users/frodo/r.ini'.
* untitled: A new file that should be saved on disk, e.g. 'untitled:/Users/frodo/new.js'. The language will be derived from the file name.
*
* Uris with other schemes will make this method return a rejected promise.
*
* @param uri Identifies the resource to open.
* @return A promise that resolves to a [document](#TextDocument).
*/
openTextDocument(uri: Uri): Thenable<TextDocument>,
/**
* A short-hand for `openTextDocument(Uri.file(fileName))`.
*
* @see [openTextDocument](#openTextDocument)
* @param fileName A name of a file on disk.
* @return A promise that resolves to a [document](#TextDocument).
*/
openTextDocument(fileName: string): Thenable<TextDocument>,
/**
* An event that is emitted when a [text document](#TextDocument) is opened.
*/
onDidOpenTextDocument: Event<TextDocument>,
/**
* An event that is emitted when a [text document](#TextDocument) is disposed.
*/
onDidCloseTextDocument: Event<TextDocument>,
/**
* An event that is emitted when a [text document](#TextDocument) is changed.
*/
onDidChangeTextDocument: Event<TextDocumentChangeEvent>,
/**
* An event that is emitted when a [text document](#TextDocument) is saved to disk.
*/
onDidSaveTextDocument: Event<TextDocument>,
/**
* Get a configuration object.
*
* When a section-identifier is provided only that part of the configuration
* is returned. Dots in the section-identifier are interpreted as child-access,
* like `{ myExt: { setting: { doIt: true }}}` and `getConfiguration('myExt.setting.doIt') === true`.
*
*
* @param section A dot-separated identifier.
* @return The full workspace configuration or a subset.
*/
getConfiguration(section?: string): WorkspaceConfiguration,
/**
* An event that is emitted when the [configuration](#WorkspaceConfiguration) changed.
*/
onDidChangeConfiguration: Event<void>,
...
}
/**
* Namespace for participating in language-specific editor [features](https://code.visualstudio.com/docs/editor/editingevolved),
* like IntelliSense, code actions, diagnostics etc.
*
* Many programming languages exist and there is huge variety in syntaxes, semantics, and paradigms. Despite that, features
* like automatic word-completion, code navigation, or code checking have become popular across different tools for different
* programming languages.
*
* The editor provides an API that makes it simple to provide such common features by having all UI and actions already in place and
* by allowing you to participate by providing data only. For instance, to contribute a hover all you have to do is provide a function
* that can be called with a [TextDocument](#TextDocument) and a [Position](#Position) returning hover info. The rest, like tracking the
* mouse, positioning the hover, keeping the hover stable etc. is taken care of by the editor.
*
* ```javascript
* languages.registerHoverProvider('javascript', {
* provideHover(document, position, token) {
* return new Hover('I am a hover!');
* }
* });
* ```
*
* Registration is done using a [document selector](#DocumentSelector) which is either a language id, like `javascript` or
* a more complex [filter](#DocumentFilter) like `{ language: 'typescript', scheme: 'file' }`. Matching a document against such
* a selector will result in a [score](#languages.match) that is used to determine if and how a provider shall be used. When
* scores are equal the provider that came last wins. For features that allow full arity, like [hover](#languages.registerHoverProvider),
* the score is only checked to be `>0`, for other features, like [IntelliSense](#languages.registerCompletionItemProvider) the
* score is used for determining the order in which providers are asked to participate.
*/
declare export var languages: {
/**
* Return the identifiers of all known languages.
* @return Promise resolving to an array of identifier strings.
*/
getLanguages(): Thenable<string[]>,
/**
* Compute the match between a document [selector](#DocumentSelector) and a document. Values
* greater than zero mean the selector matches the document. The more individual matches a selector
* and a document have, the higher the score is. These are the abstract rules given a `selector`:
*
* ```
* (1) When selector is an array, return the maximum individual result.
* (2) When selector is a string match that against the [languageId](#TextDocument.languageId).
* (2.1) When both are equal score is `10`,
* (2.2) When the selector is `*` score is `5`,
* (2.3) Else score is `0`.
* (3) When selector is a [filter](#DocumentFilter) every property must score higher `0`. Iff the score is the sum of the following:
* (3.1) When [language](#DocumentFilter.language) is set apply rules from #2, when `0` the total score is `0`.
* (3.2) When [scheme](#Document.scheme) is set and equals the [uri](#TextDocument.uri)-scheme add `10` to the score, else the total score is `0`.
* (3.3) When [pattern](#Document.pattern) is set
* (3.3.1) pattern eqauls the [uri](#TextDocument.uri)-fsPath add `10` to the score,
* (3.3.1) if the pattern matches as glob-pattern add `5` to the score,
* (3.3.1) the total score is `0`
* ```
*
* @param selector A document selector.
* @param document A text document.
* @return A number `>0` when the selector matches and `0` when the selector does not match.
*/
match(selector: DocumentSelector, document: TextDocument): number,
/**
* Create a diagnostics collection.
*
* @param name The [name](#DiagnosticCollection.name) of the collection.
* @return A new diagnostic collection.
*/
createDiagnosticCollection(name?: string): DiagnosticCollection,
/**
* Register a completion provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and groups of equal score are sequentially asked for
* completion items. The process stops when one or many providers of a group return a
* result. A failing provider (rejected promise or exception) will not fail the whole
* operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A completion provider.
* @param triggerCharacters Trigger completion when the user types one of the characters, like `.` or `:`.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerCompletionItemProvider(selector: DocumentSelector, provider: CompletionItemProvider, ...triggerCharacters: string[]): Disposable,
/**
* Register a code action provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A code action provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerCodeActionsProvider(selector: DocumentSelector, provider: CodeActionProvider): Disposable,
/**
* Register a code lens provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A code lens provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable,
/**
* Register a definition provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A definition provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable,
/**
* Register a hover provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A hover provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable,
/**
* Register a document highlight provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and groups sequentially asked for document highlights.
* The process stops when a provider returns a `non-falsy` or `non-failure` result.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document highlight provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerDocumentHighlightProvider(selector: DocumentSelector, provider: DocumentHighlightProvider): Disposable,
/**
* Register a document symbol provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document symbol provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerDocumentSymbolProvider(selector: DocumentSelector, provider: DocumentSymbolProvider): Disposable,
/**
* Register a workspace symbol provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param provider A workspace symbol provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerWorkspaceSymbolProvider(provider: WorkspaceSymbolProvider): Disposable,
/**
* Register a reference provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A reference provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerReferenceProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable,
/**
* Register a reference provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the result of best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A rename provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerRenameProvider(selector: DocumentSelector, provider: RenameProvider): Disposable,
/**
* Register a formatting provider for a document.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the result of best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document formatting edit provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerDocumentFormattingEditProvider(selector: DocumentSelector, provider: DocumentFormattingEditProvider): Disposable,
/**
* Register a formatting provider for a document range.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the result of best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document range formatting edit provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerDocumentRangeFormattingEditProvider(selector: DocumentSelector, provider: DocumentRangeFormattingEditProvider): Disposable,
/**
* Register a formatting provider that works on type.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the result of best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider An on type formatting edit provider.
* @param firstTriggerCharacter A character on which formatting should be triggered, like `}`.
* @param moreTriggerCharacter More trigger characters.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerOnTypeFormattingEditProvider(selector: DocumentSelector, provider: OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacter: string[]): Disposable,
/**
* Register a signature help provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the result of best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A signature help provider.
* @param triggerCharacters Trigger signature help when the user types one of the characters, like `,` or `(`.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, ...triggerCharacters: string[]): Disposable,
/**
* Set a [language configuration](#LanguageConfiguration) for a language.
*
* @param language A language identifier like `typescript`.
* @param configuration Language configuration.
* @return A [disposable](#Disposable) that unsets this configuration.
*/
setLanguageConfiguration(language: string, configuration: LanguageConfiguration): Disposable,
...
}
/**
* Namespace for dealing with installed extensions. Extensions are represented
* by an [extension](#Extension)-interface which allows to reflect on them.
*
* Extension writers can provide APIs to other extensions by returning their API public
* surface from the `activate`-call.
*
* ```javascript
* declare export function activate(context: vscode.ExtensionContext) {
*
* let api = {
* sum(a, b) {
* return a + b;
* },
* mul(a, b) {
* return a * b;
* }
* };
*
* // 'declare export' public api-surface
* return api;
* }
* ```
* When depending on the API of another extension add an `extensionDependency`-entry
* to `package.json`, and use the [getExtension](#extensions.getExtension)-function
* and the [declare exports](#Extension.declare exports)-property, like below:
*
* ```javascript
* let mathExt = extensions.getExtension('genius.math');
* let importedApi = mathExt.declare exports;
*
* console.log(importedApi.mul(42, 1));
* ```
*/
declare export var extensions: {
/**
* Get an extension by its full identifier in the form of: `publisher.name`.
*
* @param extensionId An extension identifier.
* @return An extension or `undefined`.
*/
getExtension(extensionId: string): Extension<any>,
/**
* Get an extension its full identifier in the form of: `publisher.name`.
*
* @param extensionId An extension identifier.
* @return An extension or `undefined`.
*/
getExtension<T>(extensionId: string): Extension<T>,
/**
* All extensions currently known to the system.
*/
all: Extension<any>[],
...
}
}
/**
* Thenable is a common denominator between ES6 promises, Q, jquery.Deferred, WinJS.Promise,
* and others. This API makes no assumption about what promise libary is being used which
* enables reusing existing code without migrating to a specific promise implementation. Still,
* we recommend the use of native promises which are available in VS Code.
*/
// TODO - starting with Flow v0.33.0, we can use $Thenable
// https://github.com/facebook/flow/pull/2291
declare type Thenable<R> = Promise<R>;
|
@CustomEditor(EasyRoads3DTerrainID)
class TerrainEditorScript extends Editor
{
function OnSceneGUI()
{
if(Event.current.shift && RoadObjectScript.ODQQCQCOQC != null) Selection.activeGameObject = RoadObjectScript.ODQQCQCOQC.gameObject;
else RoadObjectScript.ODQQCQCOQC = null;
}
}
|
const webService={
post:(api='',data={})=>{
let request = new Request(`https://cex.io/api/${api}`, {
method:"POST",
mode: 'cors',
redirect: 'follow',
body:JSON.stringify({data}),
headers: new Headers({
'Content-Type': 'text/plain'
})
});
return fetch(request).then(function(data) {
return data.json();
})
},
get:(api='')=>{
console.log(api);
let request = new Request(`https://cex.io/api/${api}`, {
method:"GET",
redirect: 'follow',
headers: new Headers({
'Content-Type': 'text/plain'
})
});
return fetch(request).then(function(data) {
return data.json();
})
}
}
export default webService;
|
"use strict";
exports.__esModule = true;
exports.createSheet = createSheet;
var _ExecutionEnvironment = _interopRequireDefault(require("fbjs/lib/ExecutionEnvironment"));
var _createCSSStyleSheet = _interopRequireDefault(require("./createCSSStyleSheet"));
var _createOrderedCSSStyleSheet = _interopRequireDefault(require("./createOrderedCSSStyleSheet"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
var defaultId = 'react-native-stylesheet';
var roots = new WeakMap();
var sheets = [];
var initialRules = [// minimal top-level reset
'html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:rgba(0,0,0,0);}', 'body{margin:0;}', // minimal form pseudo-element reset
'button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}', 'input::-webkit-search-cancel-button,input::-webkit-search-decoration,input::-webkit-search-results-button,input::-webkit-search-results-decoration{display:none;}'];
function createSheet(root, id) {
if (id === void 0) {
id = defaultId;
}
var sheet;
if (_ExecutionEnvironment.default.canUseDOM) {
var rootNode = root != null ? root.getRootNode() : document; // Create the initial style sheet
if (sheets.length === 0) {
sheet = (0, _createOrderedCSSStyleSheet.default)((0, _createCSSStyleSheet.default)(id));
initialRules.forEach(function (rule) {
sheet.insert(rule, 0);
});
roots.set(rootNode, sheets.length);
sheets.push(sheet);
} else {
var index = roots.get(rootNode);
if (index == null) {
var initialSheet = sheets[0]; // If we're creating a new sheet, populate it with existing styles
var textContent = initialSheet != null ? initialSheet.getTextContent() : ''; // Cast rootNode to 'any' because Flow types for getRootNode are wrong
sheet = (0, _createOrderedCSSStyleSheet.default)((0, _createCSSStyleSheet.default)(id, rootNode, textContent));
roots.set(rootNode, sheets.length);
sheets.push(sheet);
} else {
sheet = sheets[index];
}
}
} else {
// Create the initial style sheet
if (sheets.length === 0) {
sheet = (0, _createOrderedCSSStyleSheet.default)((0, _createCSSStyleSheet.default)(id));
initialRules.forEach(function (rule) {
sheet.insert(rule, 0);
});
sheets.push(sheet);
} else {
sheet = sheets[0];
}
}
return {
getTextContent: function getTextContent() {
return sheet.getTextContent();
},
id: id,
insert: function insert(cssText, groupValue) {
sheets.forEach(function (s) {
s.insert(cssText, groupValue);
});
}
};
}
|
module.exports = function (assert, testuser, bcrypt) {
describe("Bcrypt", function () {
describe("Test user's password", function () {
it("should match the encrypted password", function () {
assert(bcrypt.compareSync(testuser.password, bcrypt.hashSync(testuser.password)));
});
});
});
};
|
// Copyright 2013 Voxer IP LLC. All rights reserved.
var http = require("http"),
https = require("https"),
inherits = require("util").inherits;
function KeepAliveAgent(options) {
options = options || {};
http.Agent.call(this, options);
this.keepAlive = true;
this.max_reqs_per_socket = options.max_reqs_per_socket || 1000;
// Keys are host:port names, values are lists of sockets.
this.idle_sockets = {};
// Replace the 'free' listener set up by the default node Agent above.
this.removeAllListeners("free");
var self = this;
this.on("free", function (socket, host, port, local_address) {
self.on_free(socket, host, port, local_address);
});
}
inherits(KeepAliveAgent, http.Agent);
// http.Agent has a destroy() method in node 0.12 but not in node 0.10
if (!KeepAliveAgent.prototype.destroy) {
KeepAliveAgent.prototype.destroy = function destroy() {
var self = this;
if (this.sockets) {
Object.keys(this.sockets).forEach(function (key) {
var socks = self.sockets[key];
if (socks) {
socks.forEach(function (sock) {
sock.unref();
});
}
});
}
};
}
KeepAliveAgent.prototype.build_name_key = function (host, port, local_address) {
if (typeof host !== 'string') {
port = host.port;
local_address = host.localAddress;
host = host.host;
}
var name = host + ":" + port;
if (local_address) {
name += ":" + local_address;
}
return name;
};
// socket reuse strategy:
// after a request is finished, decide whether to preserve this socket
// if socket is "usable", meaning node didn't mark it as destroyed,
// check for max request_count, and destroy as necessary
KeepAliveAgent.prototype.on_free = function (socket, host, port, local_address) {
var name = this.build_name_key(host, port, local_address);
if (this.is_socket_usable(socket)) {
socket.request_count = socket.request_count ? socket.request_count + 1 : 1;
if (socket.request_count >= this.max_reqs_per_socket) {
socket.destroy();
} else {
if (!this.idle_sockets[name]) {
this.idle_sockets[name] = [];
}
this.idle_sockets[name].push(socket);
}
}
// If we had any pending requests for this name, send the next one off now.
if (this.requests[name] && this.requests[name].length) {
var next_request = this.requests[name].shift();
if (!this.requests[name].length) {
delete this.requests[name];
}
this.addRequest(next_request, host, port, local_address);
}
};
// addRequest is called by from node in http.js. We intercept this and re-use a socket if we've got one available.
KeepAliveAgent.prototype.addRequest = function (request, host, port, local_address) {
var name = this.build_name_key(host, port, local_address);
var socket = this.next_idle_socket(name);
if (socket) {
request.onSocket(socket);
} else {
http.Agent.prototype.addRequest.call(this, request, host, port, local_address);
}
};
KeepAliveAgent.prototype.next_idle_socket = function (name) {
if (!this.idle_sockets[name]) {
return null;
}
var socket;
while ((socket = this.idle_sockets[name].shift()) !== undefined) {
// Check that this socket is still healthy after sitting around on the shelf.
if (this.is_socket_usable(socket)) {
return socket;
}
}
return null;
};
KeepAliveAgent.prototype.is_socket_usable = function (socket) {
return !socket.destroyed;
};
// removeSocket is called from node in http.js. We intercept to update the idle_sockets map.
KeepAliveAgent.prototype.removeSocket = function (socket, name, host, port, local_address) {
if (this.idle_sockets[name]) {
var idx = this.idle_sockets[name].indexOf(socket);
if (idx !== -1) {
this.idle_sockets[name].splice(idx, 1);
if (!this.idle_sockets[name].length) {
delete this.idle_sockets[name];
}
}
}
http.Agent.prototype.removeSocket.call(this, socket, name, host, port, local_address);
};
function HTTPSKeepAliveAgent(options) {
KeepAliveAgent.call(this, options);
this.createConnection = https.globalAgent.createConnection; // node Agent API
}
inherits(HTTPSKeepAliveAgent, KeepAliveAgent);
// defaultPort is part of the node API for Agent
HTTPSKeepAliveAgent.prototype.defaultPort = 443;
HTTPSKeepAliveAgent.prototype.is_socket_usable = function (socket) {
// TLS sockets null out their secure pair's ssl field in destroy() and do not set destroyed the way non-secure sockets do.
return socket.pair && socket.pair.ssl;
};
module.exports = function init() {
return {
HTTP: KeepAliveAgent,
HTTPS: HTTPSKeepAliveAgent
};
};
|
/*
* Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* @class
* Initializes a new instance of the ApplicationHealthServiceHealthStatesItem class.
* @constructor
* @member {string} [serviceName]
*
* @member {number} [aggregatedHealthState]
*
*/
function ApplicationHealthServiceHealthStatesItem() {
}
/**
* Defines the metadata of ApplicationHealthServiceHealthStatesItem
*
* @returns {object} metadata of ApplicationHealthServiceHealthStatesItem
*
*/
ApplicationHealthServiceHealthStatesItem.prototype.mapper = function () {
return {
required: false,
serializedName: 'ApplicationHealth_ServiceHealthStatesItem',
type: {
name: 'Composite',
className: 'ApplicationHealthServiceHealthStatesItem',
modelProperties: {
serviceName: {
required: false,
serializedName: 'ServiceName',
type: {
name: 'String'
}
},
aggregatedHealthState: {
required: false,
serializedName: 'AggregatedHealthState',
type: {
name: 'Number'
}
}
}
}
};
};
module.exports = ApplicationHealthServiceHealthStatesItem;
|
module.exports={A:{A:{"2":"K D G E A B hB"},B:{"1":"J M H I","2":"2 C d"},C:{"1":"0 1 3 4 7 8 9 n o L q r s t u v w x y z HB GB BB CB FB","2":"2 6 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 YB XB"},D:{"1":"0 1 3 4 7 8 9 u v w x y z HB GB BB CB FB RB MB LB kB JB NB OB PB","2":"2 6 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","194":"s","257":"t"},E:{"2":"F N K D G E A QB IB SB TB UB VB WB","513":"5 B C p ZB"},F:{"1":"0 1 h i j k l m n o L q r s t u v w x y 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 aB bB cB dB p AB fB","194":"f g"},G:{"1":"qB rB sB tB","2":"G IB gB EB iB jB KB lB mB nB oB pB"},H:{"2":"uB"},I:{"2":"DB F vB wB xB yB EB zB 0B","257":"4"},J:{"2":"D A"},K:{"1":"L","2":"5 A B C p AB"},L:{"1":"JB"},M:{"1":"3"},N:{"2":"A B"},O:{"1":"1B"},P:{"1":"2B 3B 4B 5B 6B","2":"F"},Q:{"1":"7B"},R:{"2":"8B"},S:{"1":"9B"}},B:6,C:"Brotli Accept-Encoding/Content-Encoding"};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = CreateGroup;
var _end = require('../lib/end');
var _end2 = _interopRequireDefault(_end);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function CreateGroup(arcgis) {
return function create() {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var title = _ref.title;
var description = _ref.description;
var summary = _ref.summary;
var tags = _ref.tags;
var _ref$access = _ref.access;
var access = _ref$access === undefined ? 'private' : _ref$access;
var _ref$isViewOnly = _ref.isViewOnly;
var isViewOnly = _ref$isViewOnly === undefined ? false : _ref$isViewOnly;
var _ref$isInvitationOnly = _ref.isInvitationOnly;
var isInvitationOnly = _ref$isInvitationOnly === undefined ? false : _ref$isInvitationOnly;
var cb = arguments[1];
var options = {
title: title,
description: description,
snippet: summary,
tags: tags.join(','),
access: access,
isViewOnly: isViewOnly,
isInvitationOnly: isInvitationOnly
};
var createPromise = arcgis.request({
url: 'community/createGroup',
form: options,
post: true
}).then(function (confirmation) {
return confirmation.group;
});
return (0, _end2.default)(createPromise, cb);
};
}
|
jQuery(document).ready(function() {
// quick button
var topBtn = jQuery('#quick-link');
topBtn.hide();
jQuery('.scroll-content').scroll(function () {
if (jQuery(this).scrollTop() > 100) {
topBtn.fadeIn();
} else {
topBtn.fadeOut();
}
});
jQuery(window).scroll(function () {
if (jQuery(this).scrollTop() > 100) {
topBtn.fadeIn();
} else {
topBtn.fadeOut();
}
});
jQuery('#page-top').click(function () {
jQuery('.scroll-content,body,html').animate({
scrollTop: 0
}, 300);
return false;
});
// menu-icon button
var menuBtn = jQuery('#menu-icon');
var toggleMenu = menuBtn.next('nav').children('.trigger');
menuBtn.click(function() {
toggleMenu.toggle('fast');
return false;
});
jQuery(document).click(function() {
if(menuBtn.css('display') == "block") {
toggleMenu.hide('fast');
}
toggleMenu.click(function(e) {
e.stopPropagation();
});
});
//TOC-area
var markBtn = jQuery("#bookmark");
markBtn.click(function () {
jQuery("article").toggleClass("home post", "fast", "easeOutSine");
jQuery("#toc-area").toggle("50");
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Cache {
constructor() {
this._cache = {};
}
put(key, value) {
this._cache[key] = value;
}
get(key) {
return this._cache[key];
}
del(key) {
delete this._cache[key];
}
clear() {
this._cache = {};
}
}
exports.default = Cache;
//# sourceMappingURL=cache.js.map
|
'use strict';
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var ReactIs = require('react-is');
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[ReactIs.ForwardRef] = FORWARD_REF_STATICS;
function getStatics(component) {
if (ReactIs.isMemo(component)) {
return MEMO_STATICS;
}
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
|
var path = require('path');
var appRoot = 'src/';
var outputRoot = 'dist/';
module.exports = {
root: appRoot,
tsConfig: './tsconfig.json',
source: appRoot + '**/*.js',
html: appRoot + '**/*.html',
style: 'styles/**/*.css',
output: outputRoot,
doc:'./doc',
e2eSpecsSrc: 'test/e2e/src/*.js',
e2eSpecsDist: 'test/e2e/dist/'
};
|
var RoomCache = require("../RoomCache");
module.exports = function(name, dispatcher, db){
return new RoomCache(dispatcher, db, {
name: name
});
};
|
var anim8 = require('../build/anim8js.js');
module.exports = {
/**
* Prepare for all tests in this file
*/
setUp: function(callback)
{
callback();
},
/**
* Example test
*/
parse: function(test)
{
var path = anim8.path({type: 'point', point: 5});
test.ok( path instanceof anim8.PathPoint );
test.strictEqual( path.resolvePoint(0), 5 );
test.done();
},
live: function(test)
{
var path = anim8.path({
type: 'point',
point: function(i, dt) {
return dt;
}
});
test.strictEqual( path.compute(0, 0.25), 0.25 );
test.done();
}
};
|
import React from 'react';
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormControl from '@material-ui/core/FormControl';
import FormLabel from '@material-ui/core/FormLabel';
function FormControlLabelPosition() {
const [value, setValue] = React.useState('female');
function handleChange(event) {
setValue(event.target.value);
}
return (
<FormControl component="fieldset">
<FormLabel component="legend">labelPlacement</FormLabel>
<RadioGroup aria-label="position" name="position" value={value} onChange={handleChange} row>
<FormControlLabel
value="top"
control={<Radio color="primary" />}
label="Top"
labelPlacement="top"
/>
<FormControlLabel
value="start"
control={<Radio color="primary" />}
label="Start"
labelPlacement="start"
/>
<FormControlLabel
value="bottom"
control={<Radio color="primary" />}
label="Bottom"
labelPlacement="bottom"
/>
<FormControlLabel
value="end"
control={<Radio color="primary" />}
label="End"
labelPlacement="end"
/>
</RadioGroup>
</FormControl>
);
}
export default FormControlLabelPosition;
|
/**
* validation for my page
*/
v.me = (function (v) {
var Schema = v.Schema;
return {
update: new Schema({
_id: {
required: true
},
username: {
required: true,
minLength: 2
},
email: {
format: 'email'
}
}),
password_change: new Schema({
_id: {
required: true
},
password: {
required: true
},
password_again: {
required: true
}
})
}
})(v);
|
/*
// See the README.md for info on this blueprint
*/
module.exports.name = 'repoBlueprint';
module.exports.singleton = true;
module.exports.dependencies = ['Blueprint'];
module.exports.factory = function (Blueprint) {
'use strict';
return new Blueprint({
get: {
type: 'function',
args: ['uid', 'callback']
},
find: {
type: 'function',
args: ['options', 'callback']
},
create: {
type: 'function',
args: ['payload', 'callback']
},
update: {
type: 'function',
args: ['options', 'payload', 'callback']
},
remove: {
type: 'function',
args: ['uid', 'callback']
}
});
};
|
var restify = require("restify");
var api = require("../api");
var db = require("../../db/db");
/**
* Routes related to the RESTful manipulation of the Project database object.
*/
module.exports = function () {
"use strict";
var Project = db.getProjectModel();
return [
{
description: "Output an array of all project documents",
route: "/projects",
method: "get",
needsAuth: false,
needsSession: true,
handler: function (req,res,next) {
Project.getProjects(function (err,doc) {
api.handleDatabaseResult(req,res,next,err,doc);
});
}
},
{
description: "Create a new project document",
route: "/projects",
method: "post",
needsAuth: true,
needsSession: true,
handler: function (req,res,next) {
if ( req.body ) {
Project.createProject(req.body,function (err,doc) {
if ( !err && doc ) {
res.setHeader("Location","/projects/"+doc._id);
}
api.handleDatabaseResult(req,res,next,err,doc,201);
});
} else {
api.handleBadParamsError(req,res,next);
}
}
},
{
description: "Output a single project document by project id",
route: "/projects/:id",
method: "get",
needsAuth: false,
needsSession: true,
handler: function (req,res,next) {
Project.getProject(req.params.id,function (err,doc) {
api.handleDatabaseResult(req,res,next,err,doc);
});
}
},
{
description: "Update some or all of a project document's fields (except its tag array)",
route: "/projects/:id",
method: "put",
needsAuth: true,
needsSession: true,
handler: function (req,res,next) {
if ( req.body ) {
Project.updateProject(req.params.id,req.body,function (err,doc) {
api.handleDatabaseResult(req,res,next,err,doc);
});
} else {
api.handleBadParamsError(req,res,next);
}
}
},
{
description: "Delete a project document by project id",
route: "/projects/:id",
method: "del",
needsAuth: true,
needsSession: true,
handler: function (req,res,next) {
Project.deleteProject(req.params.id,function (err,doc) {
api.handleDatabaseResult(req,res,next,err,doc,200);
});
}
},
{
description: "Output an array of a project document's tags by project id",
route: "/projects/:id/tags",
method: "get",
needsAuth: false,
needsSession: true,
handler: function (req,res,next) {
Project.getProjectTags(req.params.id,function (err,doc) {
api.handleDatabaseResult(req,res,next,err,doc);
});
}
},
{
description: "Replace a project document's array of tag ids with a new one by project id",
route: "/projects/:id/tags",
method: "put",
needsAuth: true,
handler: function (req,res,next) {
if ( req.body ) {
Project.replaceProjectTags(req.params.id,req.body,function (err,doc) {
api.handleDatabaseResult(req,res,next,err,doc);
});
} else {
api.handleBadParamsError(req,res,next);
}
}
}
];
};
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function() {
var ns = MOA.ns('SafeFlag.Utils');
var Ci = Components.interfaces;
var Cc = Components.classes;
ns.getTabIDForHttpChannel = function (oHttpChannel) {
if (!gBrowser)
return null;
try {
if (oHttpChannel.notificationCallbacks) {
var interfaceRequestor = oHttpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
var targetDoc = interfaceRequestor.getInterface(Ci.nsIDOMWindow).document;
var tab = null;
var targetBrowserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
// handle the case where there was no tab associated with the request (rss etc.)
if (targetBrowserIndex != -1) {
tab = gBrowser.tabContainer.childNodes[targetBrowserIndex];
} else {
return null;
}
return tab.linkedPanel;
}
} catch (ex) {
return null;
}
return null;
};
ns.getRequestWebProgress = function(request) {
try {
if (request && request.notificationCallbacks)
return request.notificationCallbacks.getInterface(Ci.nsIWebProgress);
} catch (err ) {
// MOAC.log(err);
}
try {
if (request && request.loadGroup && request.loadGroup.groupObserver)
return request.loadGroup.groupObserver.QueryInterface(Ci.nsIWebProgress);
} catch (err) {
// MOAC.log(err);
}
};
ns.getWindowForRequest = function(request) {
return this.getWindowForWebProgress(this.getRequestWebProgress(request));
};
ns.getWindowForWebProgress = function(webProgress) {
try {
if (webProgress)
return webProgress.DOMWindow;
} catch (err) {
// MOAC.log(err);
}
return null;
};
ns.getRootWindow = function(win) {
for (; win; win = win.parent) {
if (!win.parent || win == win.parent || !(win.parent instanceof Window))
return win;
}
return null;
};
ns.getTabForWindow = function(win) {
aWindow = this.getRootWindow(win);
if (!aWindow || !gBrowser.getBrowserIndexForDocument)
return null;
try {
var targetDoc = aWindow.document;
var tab = null;
var targetBrowserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
if (targetBrowserIndex != -1) {
tab = gBrowser.tabContainer.childNodes[targetBrowserIndex];
return tab;
}
} catch (err) {
MOAC.log(err);
}
return null;
};
ns.getTabIdForWindow = function(win) {
var tab = this.getTabForWindow(win);
return tab ? tab.linkedPanel : null;
};
ns.getCurrentWindow = function() {
return Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getMostRecentWindow("navigator:browser");
};
ns.getCurrentURI = function() {
return this.getCurrentWindow().getBrowser().currentURI;
};
ns.get = function(id) {
return document.getElementById(id);
};
// extend object
ns.extend = function(src, target) {
for (var key in src) {
target[key] = src[key];
}
return target;
};
ns.bindFunc = function(func, context) {
var __method = func, args = Array.prototype.slice.call(arguments, 2);
return function() {
return __method.apply(context, args.concat(Array.prototype.slice.call(arguments)));
}
};
ns.getPrefs = function() {
var oldBranch = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService).getBranch('safeflag.');
var newBranch = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService).getBranch('extensions.safeflag.');
if (oldBranch.getChildList('', {}).length) {
['background.safe', 'background.unsafe'].forEach(function(key) {
if (oldBranch.prefHasUserValue(key)) {
newBranch.setBoolPref(key, oldBranch.getBoolPref(key))
}
});
oldBranch.deleteBranch('')
}
return newBranch;
};
// Returns a string version of an exception object with its stack trace
function parseException(e) {
if (!e)
return "";
else if (!e.stack)
return String(e);
else
return String(e) + " \n" + String(e.stack);
}
ns.error = function(msg, exception) {
Components.utils.reportError(msg + ' \n' + parseException(exception));
};
ns.PrefListener = function(branchName, onChanged) {
var branch = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefBranch).getBranch(branchName);
branch.QueryInterface(Ci.nsIPrefBranch2);
branch.addObserver('', this, false);
this.unregister = function() {
if (branch) {
branch.removeObserver('', this);
}
branch = null;
};
this.observe = function(subject, topic, data) {
MOA.debug('subject: ' + subject);
if (topic == 'nsPref:changed') {
onChanged(branch, data);
}
};
};
ns.getString = function(stringID) {
var stringBundle = document.getElementById("safeflag-strings");
return stringBundle.getString(stringID)
};
})();
|
(function() {
var strictMode = false;
var checkVersion = Dagaz.Model.checkVersion;
Dagaz.Model.checkVersion = function(design, name, value) {
if (name == "three-crowns-invariant") {
strictMode = (value == "strict");
} else {
checkVersion(design, name, value);
}
}
var CheckInvariants = Dagaz.Model.CheckInvariants;
Dagaz.Model.CheckInvariants = function(board) {
var design = Dagaz.Model.design;
_.each(board.moves, function(m) {
if ((m.actions.length > 0) && (m.actions[0][0] !== null) && (m.actions[0][1] !== null)) {
var dir = design.findDirection(m.actions[0][0][0], m.actions[0][1][0]);
if ((dir === null) && (m.actions.length == 1)) {
m.failed = true;
}
}
});
if (strictMode) {
if (board.parent === null) {
_.each(board.moves, function(m) {
if ((m.actions.length == 1) && (m.actions[0][0] !== null) && (m.actions[0][1] !== null)) {
var piece = board.getPiece(m.actions[0][0][0]);
if (piece !== null) {
m.actions[0][2] = [ piece.setValue(0, true) ];
}
}
});
}
var moves = [];
_.each(board.moves, function(m) {
if ((m.actions.length == 1) && (m.actions[0][0] !== null) && (m.actions[0][1] !== null)) {
var piece = board.getPiece(m.actions[0][0][0]);
if ((piece !== null) && piece.getValue(0)) {
m.actions[0][2] = [ piece.setValue(0, false) ];
moves.push(m);
}
}
});
if (moves.length > 0) {
board.moves = moves;
}
}
CheckInvariants(board);
}
})();
|
module.exports = {
style: ["src/scss/scoped.scss", "src/scss/global.scss"],
bundleDir: "dist",
bundleFileName: "yasr"
};
|
import Vue from 'vue'
import Promise from 'promise'
import eventEmitter from './event-emitter'
export default {
create(model) {
return new Promise((resolve, reject) => {
Vue.http.post('api/index.php/cards', model).then((response) => {
eventEmitter.emit('cards.created', response.json())
resolve(response.json())
}, error => {
reject(error)
})
})
},
delete(model) {
return new Promise((resolve, reject) => {
Vue.http.delete(`api/index.php/cards/${model.id}`).then(() => {
eventEmitter.emit('cards.deleted', model)
resolve()
}, error => {
reject(error)
})
})
},
get(id) {
return new Promise((resolve, reject) => {
Vue.http.get(`api/index.php/cards/${id}`).then((response) => {
resolve(response.json())
}, error => {
reject(error)
})
})
},
query() {
return new Promise((resolve, reject) => {
Vue.http.get('api/index.php/cards').then((response) => {
resolve(response.json())
}, error => {
reject(error)
})
})
},
update(model) {
return new Promise((resolve, reject) => {
Vue.http.put(`api/index.php/cards/${model.id}`, model).then(() => {
eventEmitter.emit('cards.updated', model)
resolve()
}, error => {
reject(error)
})
})
}
}
|
Clazz.declarePackage ("J.rendersurface");
Clazz.load (["J.render.MeshRenderer"], "J.rendersurface.IsosurfaceRenderer", ["java.lang.Boolean", "$.Float", "JU.V3", "JU.C", "$.Normix"], function () {
c$ = Clazz.decorateAsClass (function () {
this.iHideBackground = false;
this.isBicolorMap = false;
this.backgroundColix = 0;
this.nError = 0;
this.vertexValues = null;
this.imesh = null;
this.isosurface = null;
this.isNavigationMode = false;
this.iShowNormals = false;
this.showNumbers = false;
this.showKey = null;
this.hasColorRange = false;
this.meshScale = -1;
this.mySlabValue = 0;
this.globalSlabValue = 0;
Clazz.instantialize (this, arguments);
}, J.rendersurface, "IsosurfaceRenderer", J.render.MeshRenderer);
Clazz.overrideMethod (c$, "render",
function () {
return this.renderIso ();
});
Clazz.defineMethod (c$, "renderIso",
function () {
this.setGlobals ();
for (var i = this.isosurface.meshCount; --i >= 0; ) {
this.mesh = this.imesh = this.isosurface.meshes[i];
if (this.imesh.connections != null && !this.vwr.ms.at[this.imesh.connections[0]].checkVisible ()) continue;
this.hasColorRange = false;
if (this.renderMeshSlab ()) {
this.renderInfo ();
if (this.isExport && this.isGhostPass) {
this.exportPass = 1;
this.renderMeshSlab ();
this.exportPass = 2;
}}}
return this.needTranslucent;
});
Clazz.defineMethod (c$, "setGlobals",
function () {
this.needTranslucent = false;
this.antialias = this.g3d.isAntialiased ();
this.iShowNormals = this.vwr.getTestFlag (4);
this.showNumbers = this.vwr.getTestFlag (3);
this.isosurface = this.shape;
this.exportPass = (this.isExport ? 2 : 0);
this.isNavigationMode = this.vwr.getBoolean (603979888);
this.showKey = (this.vwr.getBoolean (603979869) ? Boolean.TRUE : null);
this.isosurface.keyXy = null;
this.meshScale = -1;
this.globalSlabValue = this.vwr.gdata.slab;
this.mySlabValue = (this.isNavigationMode ? Clazz.floatToInt (this.tm.getNavigationOffset ().z) : 2147483647);
});
Clazz.defineMethod (c$, "renderInfo",
function () {
if (this.isExport || !this.hasColorRange || this.imesh.colorEncoder == null || Boolean.TRUE !== this.showKey) return;
this.showKey = Boolean.FALSE;
var colors = null;
var colixes = null;
var vContours = null;
var n = 0;
var type = 0;
if (this.imesh.showContourLines) {
vContours = this.imesh.getContours ();
if (vContours == null) {
colixes = this.imesh.jvxlData.contourColixes;
if (colixes == null) return;
n = colixes.length;
} else {
n = vContours.length;
type = 1;
}} else {
colors = this.imesh.colorEncoder.getColorSchemeArray (this.imesh.colorEncoder.currentPalette);
n = (colors == null ? 0 : colors.length);
type = 2;
}if (n < 2) return;
var factor = (this.antialias ? 2 : 1);
var height = this.vwr.getScreenHeight () * factor;
var dy = Clazz.doubleToInt (Clazz.doubleToInt (height / 2) / (n - 1));
var y = Clazz.doubleToInt (height / 4) * 3 - dy;
var x = 10 * factor;
var dx = 20 * factor;
this.isosurface.keyXy = Clazz.newIntArray (-1, [Clazz.doubleToInt (x / factor), 0, Clazz.doubleToInt ((x + dx) / factor), Clazz.doubleToInt ((y + dy) / factor), Clazz.doubleToInt (dy / factor)]);
for (var i = 0; i < n; i++, y -= dy) {
switch (type) {
case 0:
if (!this.g3d.setC (colixes[i])) return;
break;
case 1:
if (!this.g3d.setC ((vContours[i].get (3))[0])) return;
break;
case 2:
this.vwr.gdata.setColor (colors[i]);
break;
}
this.g3d.fillRect (x, y, 5, -2147483648, dx, dy);
}
this.isosurface.keyXy[1] = Clazz.doubleToInt ((y + dy) / factor);
});
Clazz.defineMethod (c$, "renderMeshSlab",
function () {
this.volumeRender = (this.imesh.jvxlData.colorDensity && this.imesh.jvxlData.allowVolumeRender);
var thisSlabValue = this.mySlabValue;
this.frontOnly = this.mesh.frontOnly || this.shapeID == 26;
if (!this.isNavigationMode) {
this.meshSlabValue = this.imesh.jvxlData.slabValue;
if (this.meshSlabValue != -2147483648 && this.imesh.jvxlData.isSlabbable) {
var points = this.imesh.jvxlData.boundingBox;
var z0 = 3.4028235E38;
var z1 = 1.4E-45;
for (var i = points.length; --i >= 0; ) {
this.pt2f.setT (points[i]);
this.tm.transformPt3f (this.pt2f, this.pt2f);
if (this.pt2f.z < z0) z0 = this.pt2f.z;
if (this.pt2f.z > z1) z1 = this.pt2f.z;
}
thisSlabValue = Math.round (z0 + (z1 - z0) * (100 - this.meshSlabValue) / 100);
this.frontOnly = new Boolean (this.frontOnly & (this.meshSlabValue >= 100)).valueOf ();
}}var tCover = this.vwr.gdata.translucentCoverOnly;
this.vwr.gdata.translucentCoverOnly = (this.frontOnly || !this.vwr.getBoolean (603979967));
this.thePlane = this.imesh.jvxlData.jvxlPlane;
this.vertexValues = this.mesh.vvs;
var isOK;
if (thisSlabValue != 2147483647 && this.imesh.jvxlData.isSlabbable) {
this.g3d.setSlab (thisSlabValue);
isOK = this.renderMesh2 (this.mesh);
this.g3d.setSlab (this.globalSlabValue);
} else {
isOK = this.renderMesh2 (this.mesh);
}this.vwr.gdata.translucentCoverOnly = tCover;
return isOK;
});
Clazz.overrideMethod (c$, "render2",
function (isExport) {
if (this.volumeRender) {
this.renderPoints ();
return;
}switch (this.imesh.dataType) {
case 70:
this.renderLonePair (false);
return;
case 71:
this.renderLonePair (true);
return;
}
this.isBicolorMap = this.imesh.jvxlData.isBicolorMap;
this.render2b (isExport);
if (!this.g3d.setC (4)) return;
if (this.imesh.showContourLines) this.renderContourLines ();
}, "~B");
Clazz.defineMethod (c$, "renderLonePair",
function (isRadical) {
this.pt2f.setT (this.vertices[1]);
this.tm.transformPt3f (this.pt2f, this.pt2f);
var r = Clazz.floatToInt (this.vwr.tm.scaleToScreen (Clazz.floatToInt (this.pt2f.z), 100));
if (r < 1) r = 1;
if (!isRadical) {
var v1 = new JU.V3 ();
var v2 = new JU.V3 ();
this.pt1f.setT (this.vertices[0]);
this.tm.transformPt3f (this.pt1f, this.pt1f);
v1.sub2 (this.pt2f, this.pt1f);
v2.set (v1.x, v1.y, v1.z + 1);
v2.cross (v2, v1);
v2.normalize ();
var f = this.vwr.tm.scaleToScreen (Clazz.floatToInt (this.pt1f.z), 100);
v2.scale (f);
this.pt1f.add2 (this.pt2f, v2);
this.pt2f.sub (v2);
this.screens[0].set (Math.round (this.pt1f.x), Math.round (this.pt1f.y), Math.round (this.pt1f.z));
this.g3d.fillSphereI (r, this.screens[0]);
}this.screens[1].set (Math.round (this.pt2f.x), Math.round (this.pt2f.y), Math.round (this.pt2f.z));
this.g3d.fillSphereI (r, this.screens[1]);
}, "~B");
Clazz.defineMethod (c$, "renderContourLines",
function () {
var vContours = this.imesh.getContours ();
if (vContours == null) {
if (this.imesh.jvxlData.contourValues != null) this.hasColorRange = true;
return;
}this.hasColorRange = (this.mesh.meshColix == 0);
for (var i = vContours.length; --i >= 0; ) {
var v = vContours[i];
if (v.size () < 6) continue;
this.colix = (this.mesh.meshColix == 0 ? (v.get (3))[0] : this.mesh.meshColix);
if (!this.g3d.setC (this.colix)) return;
var n = v.size () - 1;
var diam = this.getDiameter ();
for (var j = 6; j < n; j++) {
var pt1 = v.get (j);
var pt2 = v.get (++j);
if (Float.isNaN (pt1.x) || Float.isNaN (pt2.x)) break;
this.tm.transformPtScrT3 (pt1, this.pt1f);
this.tm.transformPtScrT3 (pt2, this.pt2f);
this.pt1f.z -= 2;
this.pt2f.z -= 2;
if (!this.antialias && diam == 1) {
this.g3d.drawLineAB (this.pt1f, this.pt2f);
} else {
this.g3d.fillCylinderBits (1, diam, this.pt1f, this.pt2f);
}}
}
});
Clazz.overrideMethod (c$, "renderPoints",
function () {
try {
if (this.volumeRender) this.g3d.volumeRender (true);
var slabPoints = ((this.volumeRender || this.mesh.pc == 0) && this.selectedPolyOnly);
var incr = this.imesh.vertexIncrement;
var diam;
if (this.mesh.diameter <= 0) {
diam = this.vwr.getInt (553648144);
this.frontOnly = false;
} else {
diam = Clazz.doubleToInt (this.vwr.getScreenDim () / (this.volumeRender ? 50 : 100));
}var ptSize = Math.round (Float.isNaN (this.mesh.volumeRenderPointSize) ? 150 : this.mesh.volumeRenderPointSize * 1000);
if (diam < 1) diam = 1;
var cX = (this.showNumbers ? Clazz.doubleToInt (this.vwr.getScreenWidth () / 2) : 0);
var cY = (this.showNumbers ? Clazz.doubleToInt (this.vwr.getScreenHeight () / 2) : 0);
if (this.showNumbers) this.vwr.gdata.setFontFid (this.vwr.gdata.getFontFidFS ("Monospaced", 24));
for (var i = (!this.imesh.hasGridPoints || this.imesh.firstRealVertex < 0 ? 0 : this.imesh.firstRealVertex); i < this.vertexCount; i += incr) {
if (this.vertexValues != null && Float.isNaN (this.vertexValues[i]) || this.frontOnly && this.transformedVectors[this.normixes[i]].z < 0 || this.imesh.jvxlData.thisSet >= 0 && this.mesh.vertexSets[i] != this.imesh.jvxlData.thisSet || !this.mesh.isColorSolid && this.mesh.vcs != null && !this.setColix (this.mesh.vcs[i]) || this.haveBsDisplay && !this.mesh.bsDisplay.get (i) || slabPoints && !this.bsPolygons.get (i)) continue;
this.hasColorRange = true;
if (this.showNumbers && this.screens[i].z > 10 && Math.abs (this.screens[i].x - cX) < 150 && Math.abs (this.screens[i].y - cY) < 150) {
var s = i + (this.mesh.isColorSolid ? "" : " " + this.mesh.vvs[i]);
this.g3d.setC (4);
this.g3d.drawStringNoSlab (s, null, this.screens[i].x, this.screens[i].y, this.screens[i].z - 30, 0);
}if (this.volumeRender) {
diam = Clazz.floatToInt (this.vwr.tm.scaleToScreen (this.screens[i].z, ptSize));
if (diam < 1) diam = 1;
this.g3d.volumeRender4 (diam, this.screens[i].x, this.screens[i].y, this.screens[i].z);
} else {
this.g3d.fillSphereI (diam, this.screens[i]);
}}
if (incr == 3) {
this.g3d.setC (this.isTranslucent ? JU.C.getColixTranslucent3 (12, true, 0.5) : 12);
for (var i = 1; i < this.vertexCount; i += 3) this.g3d.fillCylinder (3, Clazz.doubleToInt (diam / 4), this.screens[i], this.screens[i + 1]);
this.g3d.setC (this.isTranslucent ? JU.C.getColixTranslucent3 (21, true, 0.5) : 21);
for (var i = 1; i < this.vertexCount; i += 3) this.g3d.fillSphereI (diam, this.screens[i]);
this.g3d.setC (this.isTranslucent ? JU.C.getColixTranslucent3 (7, true, 0.5) : 7);
for (var i = 2; i < this.vertexCount; i += 3) {
this.g3d.fillSphereI (diam, this.screens[i]);
}
}} catch (e) {
}
if (this.volumeRender) this.g3d.volumeRender (false);
});
Clazz.overrideMethod (c$, "renderTriangles",
function (fill, iShowTriangles, isExport) {
this.g3d.addRenderer (1073742182);
var polygonIndexes = this.mesh.pis;
this.colix = (this.isGhostPass ? this.mesh.slabColix : !fill && this.mesh.meshColix != 0 ? this.mesh.meshColix : this.mesh.colix);
var vertexColixes = (!fill && this.mesh.meshColix != 0 ? null : this.mesh.vcs);
if (this.isTranslucentInherit) this.colix = JU.C.copyColixTranslucency (this.mesh.slabColix, this.mesh.colix);
this.g3d.setC (this.colix);
var generateSet = isExport;
if (generateSet) {
if (this.frontOnly && fill) this.frontOnly = false;
this.bsPolygonsToExport.clearAll ();
}if (this.exportType == 1) {
this.frontOnly = false;
}var colorSolid = (this.isGhostPass && (!this.isBicolorMap) || vertexColixes == null || this.mesh.isColorSolid);
var noColor = (this.isGhostPass && !this.isBicolorMap || vertexColixes == null || !fill && this.mesh.meshColix != 0);
var isPlane = (this.imesh.jvxlData.jvxlPlane != null);
var colix = this.colix;
if (isPlane && !colorSolid && !fill && this.mesh.fillTriangles) {
colorSolid = true;
colix = 4;
}var colorArrayed = (colorSolid && this.mesh.pcs != null);
if (colorArrayed && !fill && this.mesh.fillTriangles) colorArrayed = false;
var contourColixes = this.imesh.jvxlData.contourColixes;
this.hasColorRange = !colorSolid && !this.isBicolorMap;
var diam = this.getDiameter ();
var i0 = 0;
for (var i = this.mesh.pc; --i >= i0; ) {
var polygon = polygonIndexes[i];
if (polygon == null || this.selectedPolyOnly && !this.bsPolygons.get (i)) continue;
var iA = polygon[0];
var iB = polygon[1];
var iC = polygon[2];
if (this.imesh.jvxlData.thisSet >= 0 && this.mesh.vertexSets != null && this.mesh.vertexSets[iA] != this.imesh.jvxlData.thisSet) continue;
if (this.haveBsDisplay && (!this.mesh.bsDisplay.get (iA) || !this.mesh.bsDisplay.get (iB) || !this.mesh.bsDisplay.get (iC))) continue;
var nA = this.normixes[iA];
var nB = this.normixes[iB];
var nC = this.normixes[iC];
var check = this.checkNormals (nA, nB, nC);
if (fill && check == 0) continue;
var colixA;
var colixB;
var colixC;
if (colorSolid) {
if (colorArrayed && i < this.mesh.pcs.length) {
var c = this.mesh.pcs[i];
if (c == 0) continue;
colix = c;
}if (iShowTriangles) colix = (Math.round (Math.random () * 10) + 5);
colixA = colixB = colixC = colix;
} else {
colixA = vertexColixes[iA];
colixB = vertexColixes[iB];
colixC = vertexColixes[iC];
if (this.isBicolorMap) {
if (colixA != colixB || colixB != colixC) continue;
if (this.isGhostPass) {
colixA = colixB = colixC = JU.C.copyColixTranslucency (this.mesh.slabColix, colixA);
}}}if (fill) {
if (generateSet) {
this.bsPolygonsToExport.set (i);
continue;
}if (iB == iC) {
this.setColix (colixA);
if (iA == iB) this.g3d.fillSphereI (diam, this.screens[iA]);
else this.g3d.fillCylinder (3, diam, this.screens[iA], this.screens[iB]);
} else if (this.mesh.colorsExplicit) {
this.vwr.gdata.setColor (polygon[4]);
colixA = JU.C.copyColixTranslucency (this.mesh.colix, 2047);
this.g3d.setC (colixA);
this.g3d.fillTriangle3CN (this.screens[iA], colixA, nA, this.screens[iB], colixA, nB, this.screens[iC], colixA, nC);
} else {
if (this.isTranslucentInherit && vertexColixes != null) {
colixA = JU.C.copyColixTranslucency (this.mesh.slabColix, vertexColixes[iA]);
colixB = JU.C.copyColixTranslucency (this.mesh.slabColix, vertexColixes[iB]);
colixC = JU.C.copyColixTranslucency (this.mesh.slabColix, vertexColixes[iC]);
}this.g3d.fillTriangle3CN (this.screens[iA], colixA, nA, this.screens[iB], colixB, nB, this.screens[iC], colixC, nC);
}if (this.iShowNormals) this.renderNormals ();
} else {
check &= polygon[3];
if (check == 0) continue;
if (iShowTriangles) check = 7;
this.pt1i.setT (this.screens[iA]);
this.pt2i.setT (this.screens[iB]);
this.pt3i.setT (this.screens[iC]);
this.pt1i.z -= 2;
this.pt2i.z -= 2;
this.pt3i.z -= 2;
if (noColor) {
} else if (colorArrayed) {
this.g3d.setC (this.mesh.fillTriangles ? 4 : contourColixes[polygon[4] % contourColixes.length]);
} else {
this.drawTriangle (this.pt1i, colixA, this.pt2i, colixB, this.pt3i, colixC, check, diam);
continue;
}this.drawTriangle (this.pt1i, colix, this.pt2i, colix, this.pt3i, colix, check, diam);
}}
if (generateSet) this.exportSurface (colorSolid ? colix : 0);
}, "~B,~B,~B");
Clazz.defineMethod (c$, "getDiameter",
function () {
var diam;
if (this.mesh.diameter <= 0) {
diam = (this.meshScale < 0 ? this.meshScale = this.vwr.getInt (553648151) : this.meshScale);
if (this.antialias) diam *= 2;
} else {
diam = Clazz.doubleToInt (this.vwr.getScreenDim () / 100);
}if (diam < 1) diam = 1;
return diam;
});
Clazz.defineMethod (c$, "renderNormals",
function () {
if (!this.g3d.setC (JU.C.copyColixTranslucency (this.mesh.colix, 8))) return;
this.vwr.gdata.setFontFid (this.vwr.gdata.getFontFidFS ("Monospaced", 24));
var vertexVectors = JU.Normix.getVertexVectors ();
for (var i = this.vertexCount; --i >= 0; ) {
if (this.vertexValues != null && Float.isNaN (this.vertexValues[i])) continue;
if (i > 100) continue;
this.pt1f.setT (this.vertices[i]);
var n = this.mesh.normixes[i];
if (n >= 0) {
this.pt1f.scaleAdd2 (3, vertexVectors[n], this.pt1f);
this.tm.transformPtScrT3 (this.pt1f, this.pt1f);
this.pt1f.set (this.screens[i].x, this.screens[i].y, this.screens[i].z);
this.g3d.drawLineAB (this.pt1f, this.pt1f);
}}
});
});
|
// flow-typed signature: d872365f23ace86d9c64d3592119507c
// flow-typed version: <<STUB>>/jwt-decode_v2.2.0/flow_v0.43.0
/**
* This is an autogenerated libdef stub for:
*
* 'jwt-decode'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'jwt-decode' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'jwt-decode/build/jwt-decode' {
declare module.exports: any;
}
declare module 'jwt-decode/build/jwt-decode.min' {
declare module.exports: any;
}
declare module 'jwt-decode/Gruntfile' {
declare module.exports: any;
}
declare module 'jwt-decode/lib/atob' {
declare module.exports: any;
}
declare module 'jwt-decode/lib/base64_url_decode' {
declare module.exports: any;
}
declare module 'jwt-decode/lib/index' {
declare module.exports: any;
}
declare module 'jwt-decode/standalone' {
declare module.exports: any;
}
declare module 'jwt-decode/test/tests' {
declare module.exports: any;
}
// Filename aliases
declare module 'jwt-decode/build/jwt-decode.js' {
declare module.exports: $Exports<'jwt-decode/build/jwt-decode'>;
}
declare module 'jwt-decode/build/jwt-decode.min.js' {
declare module.exports: $Exports<'jwt-decode/build/jwt-decode.min'>;
}
declare module 'jwt-decode/Gruntfile.js' {
declare module.exports: $Exports<'jwt-decode/Gruntfile'>;
}
declare module 'jwt-decode/lib/atob.js' {
declare module.exports: $Exports<'jwt-decode/lib/atob'>;
}
declare module 'jwt-decode/lib/base64_url_decode.js' {
declare module.exports: $Exports<'jwt-decode/lib/base64_url_decode'>;
}
declare module 'jwt-decode/lib/index.js' {
declare module.exports: $Exports<'jwt-decode/lib/index'>;
}
declare module 'jwt-decode/standalone.js' {
declare module.exports: $Exports<'jwt-decode/standalone'>;
}
declare module 'jwt-decode/test/tests.js' {
declare module.exports: $Exports<'jwt-decode/test/tests'>;
}
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import PropTypes from 'prop-types';
import NativeSelectInput from './NativeSelectInput';
import withStyles from '../styles/withStyles';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';
import Input from '../Input';
export var styles = function styles(theme) {
return {
/* Styles applied to the select component `root` class. */
root: {},
/* Styles applied to the select component `select` class. */
select: {
'-moz-appearance': 'none',
// Reset
'-webkit-appearance': 'none',
// Reset
// When interacting quickly, the text can end up selected.
// Native select can't be selected either.
userSelect: 'none',
borderRadius: 0,
// Reset
minWidth: 16,
// So it doesn't collapse.
cursor: 'pointer',
'&:focus': {
// Show that it's not an text input
backgroundColor: theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.05)' : 'rgba(255, 255, 255, 0.05)',
borderRadius: 0 // Reset Chrome style
},
// Remove IE 11 arrow
'&::-ms-expand': {
display: 'none'
},
'&$disabled': {
cursor: 'default'
},
'&[multiple]': {
height: 'auto'
},
'&:not([multiple]) option, &:not([multiple]) optgroup': {
backgroundColor: theme.palette.background.paper
},
'&&': {
paddingRight: 24
}
},
/* Styles applied to the select component if `variant="filled"`. */
filled: {
'&&': {
paddingRight: 32
}
},
/* Styles applied to the select component if `variant="outlined"`. */
outlined: {
borderRadius: theme.shape.borderRadius,
'&&': {
paddingRight: 32
}
},
/* Styles applied to the select component `selectMenu` class. */
selectMenu: {
height: 'auto',
// Resets for multpile select with chips
minHeight: '1.1876em',
// Required for select\text-field height consistency
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden'
},
/* Pseudo-class applied to the select component `disabled` class. */
disabled: {},
/* Styles applied to the icon component. */
icon: {
// We use a position absolute over a flexbox in order to forward the pointer events
// to the input and to support wrapping tags..
position: 'absolute',
right: 0,
top: 'calc(50% - 12px)',
// Center vertically
pointerEvents: 'none',
// Don't block pointer events on the select under the icon.
color: theme.palette.action.active,
'&$disabled': {
color: theme.palette.action.disabled
}
},
/* Styles applied to the icon component if the popup is open. */
iconOpen: {
transform: 'rotate(180deg)'
},
/* Styles applied to the icon component if `variant="filled"`. */
iconFilled: {
right: 7
},
/* Styles applied to the icon component if `variant="outlined"`. */
iconOutlined: {
right: 7
},
/* Styles applied to the underlying native input component. */
nativeInput: {
bottom: 0,
left: 0,
position: 'absolute',
opacity: 0,
pointerEvents: 'none',
width: '100%'
}
};
};
var defaultInput = /*#__PURE__*/React.createElement(Input, null);
/**
* An alternative to `<Select native />` with a much smaller bundle size footprint.
*/
var NativeSelect = /*#__PURE__*/React.forwardRef(function NativeSelect(props, ref) {
var children = props.children,
classes = props.classes,
_props$IconComponent = props.IconComponent,
IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent,
_props$input = props.input,
input = _props$input === void 0 ? defaultInput : _props$input,
inputProps = props.inputProps,
variant = props.variant,
other = _objectWithoutProperties(props, ["children", "classes", "IconComponent", "input", "inputProps", "variant"]);
var muiFormControl = useFormControl();
var fcs = formControlState({
props: props,
muiFormControl: muiFormControl,
states: ['variant']
});
return /*#__PURE__*/React.cloneElement(input, _extends({
// Most of the logic is implemented in `NativeSelectInput`.
// The `Select` component is a simple API wrapper to expose something better to play with.
inputComponent: NativeSelectInput,
inputProps: _extends({
children: children,
classes: classes,
IconComponent: IconComponent,
variant: fcs.variant,
type: undefined
}, inputProps, input ? input.props.inputProps : {}),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? NativeSelect.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The option elements to populate the select with.
* Can be some `<option>` elements.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* The icon that displays the arrow.
*/
IconComponent: PropTypes.elementType,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input: PropTypes.element,
/**
* Attributes applied to the `select` element.
*/
inputProps: PropTypes.object,
/**
* Callback function fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The input value. The DOM API casts this to a string.
*/
value: PropTypes.any,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
NativeSelect.muiName = 'Select';
export default withStyles(styles, {
name: 'MuiNativeSelect'
})(NativeSelect);
|
require("./_helper").assertVendor("traceur");
var fs = require("fs");
var _ = require("lodash");
require("./_transformation-helper")({
name: "traceur",
loc: __dirname + "/../vendor/traceur/test/feature",
ignoreSuites: [
// weird environmental issue make these hard to test
"Modules",
// these are the responsibility of regenerator
"AsyncFunctions",
"Yield",
// these are the responsibility of core-js
"StringExtras",
"ArrayExtras",
"Collections",
// not supported
"ProperTailCalls",
"AsyncGenerators",
// these are all internal traceur tests or non-standard features
"ObjectMixin",
"Annotations",
"TestRunner",
"Tools",
"TempVarTransformer",
"AtScript",
"FreeVariableChecker",
"TypeAssertions",
"MemberVariables",
"Types"
],
ignoreTasks: [
// broken test, see google/traceur-compiler#1797
"Classes/NestedClassSuperAnimal",
// TODO: #426
"Classes/SuperUnary",
"Classes/SuperPostfix",
// TODO: investigate
"Classes/SuperSet",
"Classes/PrototypeDescriptor",
"Classes/ExtendStrange",
"Classes/ClassNameBinding",
// these are the responsibility of core-js
"Symbol/GetOwnPropertySymbols",
"Spread/Type",
"Symbol/ObjectModel",
"Symbol/Inherited",
"Symbol/Object",
"Spread/NoIterator",
"Destructuring/Rest",
"Destructuring/Empty",
// traceur uses an old version of regexpu
"RegularExpression/Simple",
// class methods are still enumerable in traceur
"NumericLiteral/Simple",
"Classes/Method",
// Object.mixin didn't make it into ES6
"ObjectMixin",
// traceur doesn't name methods and has an incorrect test asserting that
// they have no names
"PropertyMethodAssignment/PropertyMethodAssignment",
// Babel assumes that all code transformed is a module so this isn't necessary
"Strict",
"Syntax/UseStrictEscapeSequence",
"Syntax/UseStrictLineContinuation",
// experimental es7 - the spec hasn't been finalized yet
// these both fail because of filters between blocks
"ArrayComprehension/Simple",
"GeneratorComprehension/Simple",
// yield has been added as a keyword in ES6
"Yield/YieldIdentifier",
"Syntax/StrictKeywords"
]
}, {
optional: ["es6.symbols"],
experimental: true
}, function (opts, task) {
if (!_.contains(task.exec.loc, "module.js")) {
opts.blacklist = ["strict"];
}
});
|
var kopf = angular.module('kopf', ['ngRoute', 'ntt.TreeDnD', 'ngAnimate',
'ui.bootstrap']);
// manages behavior of confirmation dialog
kopf.factory('ConfirmDialogService', function() {
this.header = 'Default Header';
this.body = 'Default Body';
this.cancel_text = 'cancel';
this.confirm_text = 'confirm';
this.confirm = function() {
// when created, does nothing
};
this.close = function() {
// when created, does nothing
};
this.open = function(header, body, action, confirmCallback, closeCallback) {
this.header = header;
this.body = body;
this.action = action;
this.confirm = confirmCallback;
this.close = closeCallback;
};
return this;
});
kopf.config(function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.
when('/cluster', {
templateUrl: 'partials/cluster_overview.html',
controller: 'ClusterOverviewController'
}).
when('/nodes', {
templateUrl: 'partials/nodes/nodes.html',
controller: 'NodesController'
}).
when('/rest', {
templateUrl: 'partials/rest_client.html',
controller: 'RestController'
}).
when('/aliases', {
templateUrl: 'partials/aliases.html',
controller: 'AliasesController'
}).
when('/analysis', {
templateUrl: 'partials/analysis.html',
controller: 'AnalysisController'
}).
when('/percolator', {
templateUrl: 'partials/percolator.html',
controller: 'PercolatorController'
}).
when('/warmers', {
templateUrl: 'partials/warmers.html',
controller: 'WarmersController'
}).
when('/snapshot', {
templateUrl: 'partials/snapshot.html',
controller: 'SnapshotController'
}).
when('/createIndex', {
templateUrl: 'partials/create_index.html',
controller: 'CreateIndexController'
}).
when('/clusterHealth', {
templateUrl: 'partials/cluster_health.html',
controller: 'ClusterHealthController'
}).
when('/clusterSettings', {
templateUrl: 'partials/cluster_settings.html',
controller: 'ClusterSettingsController'
}).
when('/indexSettings', {
templateUrl: 'partials/index_settings.html',
controller: 'IndexSettingsController'
}).
when('/indexTemplates', {
templateUrl: 'partials/index_templates.html',
controller: 'IndexTemplatesController'
}).
when('/cat', {
templateUrl: 'partials/cat.html',
controller: 'CatController'
}).
when('/hotthreads', {
templateUrl: 'partials/hotthreads.html',
controller: 'HotThreadsController'
}).
otherwise({redirectTo: '/cluster'});
});
|
var mkdirp = require('.').mkdirp;
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
var ps = [ '', 'tmp' ];
for (var i = 0; i < 25; i++) {
var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
ps.push(dir);
}
var file = ps.join('/');
// a file in the way
var itw = ps.slice(0, 3).join('/');
test('clobber-pre', function (t) {
console.error("about to write to "+itw)
fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.');
fs.stat(itw, function (er, stat) {
t.ifError(er)
t.ok(stat && stat.isFile(), 'should be file')
t.end()
})
})
test('clobber', function (t) {
t.plan(2);
mkdirp(file, 0755, function (err) {
t.ok(err);
t.equal(err.code, 'ENOTDIR');
t.end();
});
});
|
/**
* Test dependencies
*/
const exec = require("child_process").exec
const spawn = require("child_process").spawn
const fs = require("fs")
const test = require("tape")
const utils = require("./utils")
// I don't success to call the kill() process from node and both Travis CI and
// Appveyor so we avoid this test on this environnements
if (!(process.env.TRAVIS || process.env.APPVEYOR)) {
// node bin is used to help for windows
const cssnextBin = "node dist/bin"
test("cli/watcher", function(t) {
let planned = 0
const watchProcess = exec(
cssnextBin +
" --watch src/__tests__/fixtures/cli.error.css" +
" src/__tests__/fixtures/cli.output--watch.css",
function(err) {
t.ok(
err && err.signal === "SIGTERM",
"should only be killed by an interrupt when `--watch` option passed"
)
if (err && !err.killed) {
throw err
}
}
)
const msgWatch = "should output error messages when `--watch` option passed"
const watchTimeout = setTimeout(function() {
t.fail(msgWatch)
watchProcess.kill()
}, 5000)
watchProcess.stderr.on("data", function(data) {
if (utils.contains(data, "encounters an error")) {
t.pass(msgWatch)
clearTimeout(watchTimeout)
watchProcess.kill()
}
})
planned += 2
// watch/import tests
const watchOut = "src/__tests__/fixtures/cli.output--watch-import.css"
const watchImportProcess = spawn(
"node",
[
"dist/bin",
"--watch",
"src/__tests__/fixtures/cli.watch-import.css",
watchOut,
],
{stdio: "inherit"}
)
// watch an empty file doesn't seems to work great, so I am using
// /**/ to get a content
// yeah...
// trigger a change in cli.import.css to add a new watched file
// cli.import2.css
fs.writeFileSync(
"src/__tests__/fixtures/cli.watch-import.css",
"/**/ @import 'cli.watch-import-import.css';"
)
// we are using setTimeout for the watcher to do his job
setTimeout(function() {
// check the output has been updated (watcher works)
t.equal(
fs.readFileSync(
watchOut,
{encoding: "utf8"}
),
"/**/ watch{}",
"should update the file"
)
// remove this newly imported file
fs.writeFileSync("src/__tests__/fixtures/cli.watch-import.css", "/**/")
// check the output has been update
setTimeout(function() {
t.equal(
fs.readFileSync(
watchOut,
{encoding: "utf8"}
),
"/**/",
"should update the file, again"
)
setTimeout(function() {
// previously imported file should not be watched anymore
// to check that we read output mtime, modify the file that should not
// be watched and check back that the output file has the same mtime
// trigger a change in previously imported file
const now = (new Date()).getTime()
fs.utimesSync(
"src/__tests__/fixtures/cli.watch-import-import.css",
now,
now
)
// not sure why but it's better with the statSync on the watched file
// in this delayed call
setTimeout(function() {
const outStat = fs.statSync(watchOut)
setTimeout(function() {
// this time, it should not trigger anything
const outStatAfter = fs.statSync(watchOut)
t.equal(
outStat.mtime.getTime(),
outStatAfter.mtime.getTime(),
"should not modify a file if a previously imported file is " +
"modified"
)
utils.remove("cli.output--watch-import")
watchImportProcess.kill()
}, 1000)
}, 1000)
}, 1000)
}, 1000)
}, 1000)
planned += 3
t.plan(planned)
})
}
|
YUI.add('gallery-dialog', function(Y) {
var YL = Y.Lang,
LABEL_CANCEL = 'Cancel',
LABEL_OK = 'OK',
CALLBACK_CANCEL = 'cancel',
CALLBACK_OK = 'ok',
EMPTY_FN = function(){},
ATTR_CALLBACKS = 'callbacks',
ATTR_DEFAULT_BUTTON = 'defaultButton',
ATTR_DRAGGABLE = 'draggable',
ATTR_RETURN_VAL = 'returnVal',
ATTR_ICON = 'icon';
Y.Dialog = Y.Base.create('dialog', Y.Overlay, [], {
handleEnter : null,
handleEscape : null,
/**
* Plugs in Gallery_Overlay_Extras binds hide to the escape key
*
* @param config Object
*
* @see _visibleChanged
* @see hide
*/
initializer : function(config) {
Y.log('initializer','info','Y.Dialog');
this.plug(Y.Plugin.WidgetAnim);
this.plug(Y.Plugin.OverlayModal);
this.plug(Y.Plugin.OverlayKeepaligned);
},
/**
* Override of default hide(). Hides the widget then fires the
* provided callback type with the returVal as the param. If
* none is provided, the cancel callback is fired.
*
* @param callbackType String
*/
hide : function(callbackType) {
Y.log('initializer','info','Y.Dialog');
Y.one('body').set('tabIndex',-1).focus();
Y.Dialog.superclass.hide.apply(this,arguments);
var fn = (callbackType) ? this.getCallback(callbackType) : this.getCallback(CALLBACK_CANCEL);
if(YL.isFunction(fn)) {
(Y.bind(fn,this,this.get(ATTR_RETURN_VAL)))();
this.set(ATTR_RETURN_VAL,null);
}
this.anim.get('animHide').on('end',Y.bind(function(){
this.purge();
},this));
},
/**
* Override of default show(). Calls syncUI() to maintain
* centering before showing the dialog box. After showing,
* focuses on the default button.
*/
show : function() {
Y.log('initializer','info','Y.Dialog');
this.get(ATTR_DRAGGABLE);
this.handleEscape = Y.once('esc', Y.bind(function(){ this.hide(); }, this), Y.config.doc);
Y.Dialog.superclass.show.apply(this,arguments);
this.syncUI();
var dBtn = this.get(ATTR_DEFAULT_BUTTON);
if(dBtn) {
dBtn.focus();
}
this.get('boundingBox').set('tabIndex', -1);
},
/**
* Adds content to the header container based on the placement
*
* @param content HTML | Node | String
* @param placement (Optional)
*
* @see _standardizePlacement
*/
header : function(content, placement) {
Y.log('initializer','info','Y.Dialog');
this._setContent(Y.WidgetStdMod.HEADER, content, placement);
},
/**
* Adds content to the body container based on the placement
*
* @param content HTML | Node | String
* @param placement (Optional)
*
* @see _standardizePlacement
*/
body : function(content, placement) {
Y.log('initializer','info','Y.Dialog');
this._setContent(Y.WidgetStdMod.BODY, content, placement);
},
/**
* Adds content to the footer container based on the placement
*
* @param content HTML | Node | String
* @param placement (Optional)
*
* @see _standardizePlacement
*/
footer : function(content, placement) {
Y.log('initializer','info','Y.Dialog');
this._setContent(Y.WidgetStdMod.FOOTER, content, placement);
},
/**
* Builds the dialog box and populates the content areas.
*
* @param header HTML | Node | String
* @param body HTML | Node | String
* @param buttons array of Y.Button
* @return this
*/
build : function(header, body, buttons) {
Y.log('initializer','info','Y.Dialog');
var i, l, btn;
this.purge();
if(header) {
this.header(header);
}
if(body) {
this.body(body || null);
}
if(buttons) {
for(i=0, l=buttons.length; i<l; i++) {
btn = buttons[i];
btn.render();
if(btn.get('default')) {
this.set(ATTR_DEFAULT_BUTTON, btn);
}
this.footer(btn.get('boundingBox'), 'after');
}
}
return this;
},
/**
* Returns the callback function based on the type provided
*
* @param type String
* @return Function | null
*/
getCallback : function(type) {
Y.log('getCallback','info','Y.Dialog');
return (this.get(ATTR_CALLBACKS)[type] || null);
},
/**
* Sets the callback type to the callbacks array if the
* provided function is a valid function
*
* @param type String
* @param fn Function
*/
addCallback : function(type, fn) {
Y.log('addCallback','info','Y.Dialog');
if(YL.isFunction(fn)) {
this.get(ATTR_CALLBACKS)[type] = fn;
}
},
/**
* Sets the callback function type to null if found
*
* @param type String
*/
removeCallback : function(type) {
Y.log('removeCallback','info','Y.Dialog');
if(this.get(ATTR_CALLBACKS)[type]) {
this.get(ATTR_CALLBACKS)[type] = null;
}
},
/**
* Adds a close button to the header
*
* @returns this
*/
addCloseButton : function() {
Y.log('addCloseButton', 'info', 'Y.Dialog');
var btn = new Y.Button({
label: "X",
callback: Y.bind(function(e){
this.hide();
},this),
title: 'Close'
});
btn.render();
this.header(btn.get('boundingBox'),'after');
return this;
},
/**
* Removes all elements in the widget
*
* @return this
*/
purge : function() {
Y.log('purge','info','Y.Dialog');
this.header(null);
this.body(null);
this.footer(null);
},
// P R E B U I L T //
/**
* Sugar method to create an alert box
*
* @param msg String
* @param title String | null
* @param cancelCallback Function | null
*/
alert: function(msg, title, callback){
Y.log('initializer','info','Y.Dialog');
this.set(ATTR_ICON,'alert');
this.addCallback(CALLBACK_CANCEL, callback || EMPTY_FN);
var header = title || this._getDefaultTitle(),
body = msg || null,
okBtn = new Y.Button({
label: LABEL_OK,
callback: Y.bind(function(e){
this.hide();
},this),
'default': true
});
this.build(header, body, [okBtn]).addCloseButton().show();
},
/**
* Sugar method to create a confirm box
*
* @param msg String
* @param title String | null
* @param okCallback Function | null
* @param cancelCallback Function | null
*/
confirm: function(msg, title, okCallback, cancelCallback){
Y.log('initializer','info','Y.Dialog');
this.set(ATTR_ICON,'confirm');
this.addCallback(CALLBACK_OK, okCallback || EMPTY_FN);
this.addCallback(CALLBACK_CANCEL, cancelCallback || EMPTY_FN);
var header = title || this._getDefaultTitle(),
body = msg || null,
okBtn = new Y.Button({
label: LABEL_OK,
callback: Y.bind(function(e){
this.hide(CALLBACK_OK);
},this),
'default': true
}),
cancelBtn = new Y.Button({
label: LABEL_CANCEL,
callback: Y.bind(function(e){
this.hide();
},this)
});
this.build(header, body, [okBtn,cancelBtn]).addCloseButton().show();
},
/**
* Sugar method to create a prompt box. Updates returnVal to
* the value of the input box.
*
* @param msg String
* @param title String | null
* @param okCallback Function | null
* @param cancelCallback Function | null
*/
prompt: function(msg, title, okCallback, cancelCallback){
Y.log('initializer','info','Y.Dialog');
this.set(ATTR_ICON,'prompt');
this.addCallback(CALLBACK_OK, okCallback || EMPTY_FN);
this.addCallback(CALLBACK_CANCEL, cancelCallback || EMPTY_FN);
var header = title || this._getDefaultTitle(),
body = msg || null, promptInput,
okBtn = new Y.Button({
label: LABEL_OK,
callback: Y.bind(function(e){
this.hide(CALLBACK_OK);
},this),
'default': true
}),
cancelBtn = new Y.Button({
label: LABEL_CANCEL,
callback: Y.bind(function(e){
this.hide();
},this)
});
this.build(header, body, [okBtn,cancelBtn]);
// need to build the input box and bind the events to it
// then append it to the body
promptInput = Y.Node.create('<input type="text" style="display: block; margin-top: 0.5em;">');
promptInput.addClass(this.getClassName('prompt'));
promptInput.on('keyup', Y.bind(function(e){
this.set(ATTR_RETURN_VAL, promptInput.get('value'));
},this));
this.handleEnter = Y.once('enter', Y.bind(function(e){
var defBtn = this.get(ATTR_DEFAULT_BUTTON);
if(defBtn) {
defBtn.fire('press');
}
},this),promptInput);
this.body(promptInput, 'after');
this.addCloseButton().show();
},
// P R O T E C T E D //
/**
* Generates a generic title similar to system dialog boxes
*
* @return String
*/
_getDefaultTitle : function() {
Y.log('_getDefaultTitle','info','Y.Dialog');
return 'The page ' + location.protocol + '//' + location.host + '/ says:';
},
/**
* Plugs in the Drag and DDConstrained to the boundingBox and
* makes the header the handle. Fired automatically when
* draggable is updated by the setter.
*
* @param drag Boolean
*/
_updateDraggable : function(drag) {
Y.log('_updateDraggable','info','Y.Dialog');
var bb = this.get('boundingBox'),
hd = bb.all('.yui3-widget-hd');
if(drag) {
bb.plug(Y.Plugin.Drag,{
handle : hd
}).dd.plug(Y.Plugin.DDConstrained, {
constrain2view: true,
gutter: '20'
});
}else{
bb.unplug(Y.Plugin.Drag)
.unplug(Y.Plugin.DDContrained);
}
},
_setContent : function(section, content, placement) {
Y.log('_setContent','info','Y.Dialog');
this.setStdModContent(section, content, this._standardizePlacement(placement));
},
/**
* Returns the WidgetStdMod Static values for positions based
* off placement given. Accepts prepend, before, append,
* after. If not matched will return Y.WidgetStdMod.REPLACE
*
* @param placement Desired placement
* @retrun string
*/
_standardizePlacement : function(placement) {
Y.log('_standardizePlacement','info','Y.Dialog');
var p = (YL.isString(placement)) ? placement.toLowerCase() : null;
switch (p) {
case 'prepend' :
case 'before' :
return Y.WidgetStdMod.BEFORE;
case 'append' :
case 'after' :
return Y.WidgetStdMod.AFTER;
default:
return Y.WidgetStdMod.REPLACE;
}
}
},{
ATTRS : {
centered : {
value : true
},
callbacks : {
value : {}
},
constrain : {
value : true
},
defaultButton : {
validator : function(val) {
return (val instanceof Y.Button);
}
},
draggable : {
value : true,
validator : YL.isBoolean,
setter : function (val) {
this._updateDraggable(val);
return val;
}
},
render : {
value : true
},
returnVal : {
value : null
},
icon : {
validator : YL.isString,
setter : function(val) {
this.get('boundingBox').replaceClass(
this.getClassName(ATTR_ICON, this.get(ATTR_ICON) || 'default'),
this.getClassName(ATTR_ICON, val || 'default')
);
return val;
}
},
visible : {
value : false
},
zIndex : {
value : 20000
}
}
});
}, 'gallery-2011.03.11-23-49' ,{requires:['gallery-overlay-extras','gallery-button','overlay','widget-anim','node','gallery-event-nav-keys','dd-plugin']});
|
import { Component, Input, ContentChildren, Directive, TemplateRef, ContentChild, Output, EventEmitter } from '@angular/core';
import { NgbTabsetConfig } from './tabset-config';
var nextId = 0;
/**
* This directive should be used to wrap tab titles that need to contain HTML markup or other directives.
*/
export var NgbTabTitle = (function () {
function NgbTabTitle(templateRef) {
this.templateRef = templateRef;
}
NgbTabTitle.decorators = [
{ type: Directive, args: [{ selector: 'template[ngbTabTitle]' },] },
];
/** @nocollapse */
NgbTabTitle.ctorParameters = function () { return [
{ type: TemplateRef, },
]; };
return NgbTabTitle;
}());
/**
* This directive must be used to wrap content to be displayed in a tab.
*/
export var NgbTabContent = (function () {
function NgbTabContent(templateRef) {
this.templateRef = templateRef;
}
NgbTabContent.decorators = [
{ type: Directive, args: [{ selector: 'template[ngbTabContent]' },] },
];
/** @nocollapse */
NgbTabContent.ctorParameters = function () { return [
{ type: TemplateRef, },
]; };
return NgbTabContent;
}());
/**
* A directive representing an individual tab.
*/
export var NgbTab = (function () {
function NgbTab() {
/**
* Unique tab identifier. Must be unique for the entire document for proper accessibility support.
*/
this.id = "ngb-tab-" + nextId++;
/**
* Allows toggling disabled state of a given state. Disabled tabs can't be selected.
*/
this.disabled = false;
}
NgbTab.decorators = [
{ type: Directive, args: [{ selector: 'ngb-tab' },] },
];
/** @nocollapse */
NgbTab.ctorParameters = function () { return []; };
NgbTab.propDecorators = {
'id': [{ type: Input },],
'title': [{ type: Input },],
'disabled': [{ type: Input },],
'contentTpl': [{ type: ContentChild, args: [NgbTabContent,] },],
'titleTpl': [{ type: ContentChild, args: [NgbTabTitle,] },],
};
return NgbTab;
}());
/**
* A component that makes it easy to create tabbed interface.
*/
export var NgbTabset = (function () {
function NgbTabset(config) {
/**
* A tab change event fired right before the tab selection happens. See NgbTabChangeEvent for payload details
*/
this.tabChange = new EventEmitter();
this.type = config.type;
this.justify = config.justify;
}
/**
* Selects the tab with the given id and shows its associated pane.
* Any other tab that was previously selected becomes unselected and its associated pane is hidden.
*/
NgbTabset.prototype.select = function (tabId) {
var selectedTab = this._getTabById(tabId);
if (selectedTab && !selectedTab.disabled && this.activeId !== selectedTab.id) {
var defaultPrevented_1 = false;
this.tabChange.emit({ activeId: this.activeId, nextId: selectedTab.id, preventDefault: function () { defaultPrevented_1 = true; } });
if (!defaultPrevented_1) {
this.activeId = selectedTab.id;
}
}
};
NgbTabset.prototype.ngAfterContentChecked = function () {
// auto-correct activeId that might have been set incorrectly as input
var activeTab = this._getTabById(this.activeId);
this.activeId = activeTab ? activeTab.id : (this.tabs.length ? this.tabs.first.id : null);
};
NgbTabset.prototype._getTabById = function (id) {
var tabsWithId = this.tabs.filter(function (tab) { return tab.id === id; });
return tabsWithId.length ? tabsWithId[0] : null;
};
NgbTabset.decorators = [
{ type: Component, args: [{
selector: 'ngb-tabset',
exportAs: 'ngbTabset',
template: "\n <ul [class]=\"'nav nav-' + type + ' justify-content-' + justify\" role=\"tablist\">\n <li class=\"nav-item\" *ngFor=\"let tab of tabs\">\n <a [id]=\"tab.id\" class=\"nav-link\" [class.active]=\"tab.id === activeId\" [class.disabled]=\"tab.disabled\"\n href (click)=\"!!select(tab.id)\" role=\"tab\" [attr.aria-controls]=\"tab.id + '-panel'\" [attr.aria-expanded]=\"tab.id === activeId\">\n {{tab.title}}<template [ngTemplateOutlet]=\"tab.titleTpl?.templateRef\"></template>\n </a>\n </li>\n </ul>\n <div class=\"tab-content\">\n <template ngFor let-tab [ngForOf]=\"tabs\">\n <div class=\"tab-pane active\" *ngIf=\"tab.id === activeId\" role=\"tabpanel\" [attr.aria-labelledby]=\"tab.id\" id=\"{{tab.id}}-panel\">\n <template [ngTemplateOutlet]=\"tab.contentTpl.templateRef\"></template>\n </div>\n </template>\n </div>\n "
},] },
];
/** @nocollapse */
NgbTabset.ctorParameters = function () { return [
{ type: NgbTabsetConfig, },
]; };
NgbTabset.propDecorators = {
'tabs': [{ type: ContentChildren, args: [NgbTab,] },],
'activeId': [{ type: Input },],
'justify': [{ type: Input },],
'type': [{ type: Input },],
'tabChange': [{ type: Output },],
};
return NgbTabset;
}());
//# sourceMappingURL=tabset.js.map
|
import Collection from 'ember-cli-mirage/orm/collection';
import {module, test} from 'qunit';
module('Unit | Collection');
test('it can be instantiated', function(assert) {
let collection = new Collection('plant');
assert.ok(collection);
});
test('it cannot be instantiated without a modelName', function(assert) {
assert.throws(() => {
new Collection();
}, /must pass a `modelName`/);
});
test('it knows its modelname', function(assert) {
let collection = new Collection('author');
assert.equal(collection.modelName, 'author');
});
test('it can be instantiated with an array of models', function(assert) {
let models = [{ id: 1 }, { id: 2 }, { id: 3 }];
let collection = new Collection('author', models);
assert.ok(collection);
});
test('#models returns the underlying array', function(assert) {
let models = [{ id: 1 }, { id: 2 }, { id: 3 }];
let collection = new Collection('author', models);
assert.deepEqual(collection.models, models);
});
// test('collection.filter returns collection instance', function(assert) {
// let collection = new Collection('plant');
// let filteredCollection = collection.filter(Boolean);
// assert.ok(filteredCollection instanceof Collection);
// assert.equal(filteredCollection.modelName, 'plant');
// });
//
// test('collection.mergeCollection works', function(assert) {
// let collection1 = new Collection('plant', { name: 'chrerry' }, { name: 'uchreaflier' });
// let collection2 = new Collection('plant', { name: 'vlip' });
// assert.equal(collection1.length, 2);
// assert.equal(collection2.length, 1);
// collection2.mergeCollection(collection1);
// assert.equal(collection2.length, 3);
// assert.equal(collection2.modelName, 'plant');
// });
//
|
describe('typeahead tests', function () {
var $scope, $compile, $document, $timeout;
var changeInputValueTo;
beforeEach(module('ui.bootstrap.typeahead'));
beforeEach(module('template/typeahead/typeahead-popup.html'));
beforeEach(module('template/typeahead/typeahead-match.html'));
beforeEach(module(function($compileProvider) {
$compileProvider.directive('formatter', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (viewVal) {
return 'formatted' + viewVal;
});
}
};
});
}));
beforeEach(inject(function (_$rootScope_, _$compile_, _$document_, _$timeout_, $sniffer) {
$scope = _$rootScope_;
$scope.source = ['foo', 'bar', 'baz'];
$scope.states = [
{code: 'AL', name: 'Alaska'},
{code: 'CL', name: 'California'}
];
$compile = _$compile_;
$document = _$document_;
$timeout = _$timeout_;
changeInputValueTo = function (element, value) {
var inputEl = findInput(element);
inputEl.val(value);
inputEl.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
$scope.$digest();
};
}));
//utility functions
var prepareInputEl = function (inputTpl) {
var el = $compile(angular.element(inputTpl))($scope);
$scope.$digest();
return el;
};
var findInput = function (element) {
return element.find('input');
};
var findDropDown = function (element) {
return element.find('ul.dropdown-menu');
};
var findMatches = function (element) {
return findDropDown(element).find('li');
};
var triggerKeyDown = function (element, keyCode) {
var inputEl = findInput(element);
var e = $.Event('keydown');
e.which = keyCode;
inputEl.trigger(e);
};
//custom matchers
beforeEach(function () {
this.addMatchers({
toBeClosed: function () {
var typeaheadEl = findDropDown(this.actual);
this.message = function () {
return 'Expected "' + angular.mock.dump(typeaheadEl) + '" to be closed.';
};
return typeaheadEl.length === 0;
}, toBeOpenWithActive: function (noOfMatches, activeIdx) {
var typeaheadEl = findDropDown(this.actual);
var liEls = findMatches(this.actual);
this.message = function () {
return 'Expected "' + this.actual + '" to be opened.';
};
return typeaheadEl.length === 1 && liEls.length === noOfMatches && $(liEls[activeIdx]).hasClass('active');
}
});
});
afterEach(function () {
findDropDown($document.find('body')).remove();
});
//coarse grained, "integration" tests
describe('initial state and model changes', function () {
it('should be closed by default', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source"></div>');
expect(element).toBeClosed();
});
it('should correctly render initial state if the "as" keyword is used', function () {
$scope.result = $scope.states[0];
var element = prepareInputEl('<div><input ng-model="result" typeahead="state as state.name for state in states"></div>');
var inputEl = findInput(element);
expect(inputEl.val()).toEqual('Alaska');
});
it('should default to bound model for initial rendering if there is not enough info to render label', function () {
$scope.result = $scope.states[0].code;
var element = prepareInputEl('<div><input ng-model="result" typeahead="state.code as state.name + state.code for state in states"></div>');
var inputEl = findInput(element);
expect(inputEl.val()).toEqual('AL');
});
it('should not get open on model change', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source"></div>');
$scope.$apply(function () {
$scope.result = 'foo';
});
expect(element).toBeClosed();
});
});
describe('basic functionality', function () {
it('should open and close typeahead based on matches', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
var inputEl = findInput(element);
expect(inputEl.attr('aria-expanded')).toBe('false');
changeInputValueTo(element, 'ba');
expect(element).toBeOpenWithActive(2, 0);
expect(inputEl.attr('aria-expanded')).toBe('true');
changeInputValueTo(element, '');
expect(element).toBeClosed();
expect(inputEl.attr('aria-expanded')).toBe('false');
});
it('should not open typeahead if input value smaller than a defined threshold', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-min-length="2"></div>');
changeInputValueTo(element, 'b');
expect(element).toBeClosed();
});
it('should support custom model selecting function', function () {
$scope.updaterFn = function (selectedItem) {
return 'prefix' + selectedItem;
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="updaterFn(item) as item for item in source | filter:$viewValue"></div>');
changeInputValueTo(element, 'f');
triggerKeyDown(element, 13);
expect($scope.result).toEqual('prefixfoo');
});
it('should support custom label rendering function', function () {
$scope.formatterFn = function (sourceItem) {
return 'prefix' + sourceItem;
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="item as formatterFn(item) for item in source | filter:$viewValue"></div>');
changeInputValueTo(element, 'fo');
var matchHighlight = findMatches(element).find('a').html();
expect(matchHighlight).toEqual('prefix<strong>fo</strong>o');
});
it('should by default bind view value to model even if not part of matches', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
changeInputValueTo(element, 'not in matches');
expect($scope.result).toEqual('not in matches');
});
it('should support the editable property to limit model bindings to matches only', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-editable="false"></div>');
changeInputValueTo(element, 'not in matches');
expect($scope.result).toEqual(undefined);
});
it('should set validation errors for non-editable inputs', function () {
var element = prepareInputEl(
'<div><form name="form">' +
'<input name="input" ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-editable="false">' +
'</form></div>');
changeInputValueTo(element, 'not in matches');
expect($scope.result).toEqual(undefined);
expect($scope.form.input.$error.editable).toBeTruthy();
changeInputValueTo(element, 'foo');
triggerKeyDown(element, 13);
expect($scope.result).toEqual('foo');
expect($scope.form.input.$error.editable).toBeFalsy();
});
it('should not set editable validation error for empty input', function () {
var element = prepareInputEl(
'<div><form name="form">' +
'<input name="input" ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-editable="false">' +
'</form></div>');
changeInputValueTo(element, 'not in matches');
expect($scope.result).toEqual(undefined);
expect($scope.form.input.$error.editable).toBeTruthy();
changeInputValueTo(element, '');
expect($scope.result).toEqual('');
expect($scope.form.input.$error.editable).toBeFalsy();
});
it('should bind loading indicator expression', inject(function ($timeout) {
$scope.isLoading = false;
$scope.loadMatches = function (viewValue) {
return $timeout(function () {
return [];
}, 1000);
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in loadMatches()" typeahead-loading="isLoading"></div>');
changeInputValueTo(element, 'foo');
expect($scope.isLoading).toBeTruthy();
$timeout.flush();
expect($scope.isLoading).toBeFalsy();
}));
it('should support timeout before trying to match $viewValue', inject(function ($timeout) {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-wait-ms="200"></div>');
changeInputValueTo(element, 'foo');
expect(element).toBeClosed();
$timeout.flush();
expect(element).toBeOpenWithActive(1, 0);
}));
it('should cancel old timeouts when something is typed within waitTime', inject(function ($timeout) {
var values = [];
$scope.loadMatches = function(viewValue) {
values.push(viewValue);
return $scope.source;
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in loadMatches($viewValue) | filter:$viewValue" typeahead-wait-ms="200"></div>');
changeInputValueTo(element, 'first');
changeInputValueTo(element, 'second');
$timeout.flush();
expect(values).not.toContain('first');
}));
it('should allow timeouts when something is typed after waitTime has passed', inject(function ($timeout) {
var values = [];
$scope.loadMatches = function(viewValue) {
values.push(viewValue);
return $scope.source;
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in loadMatches($viewValue) | filter:$viewValue" typeahead-wait-ms="200"></div>');
changeInputValueTo(element, 'first');
$timeout.flush();
expect(values).toContain('first');
changeInputValueTo(element, 'second');
$timeout.flush();
expect(values).toContain('second');
}));
it('should support custom templates for matched items', inject(function ($templateCache) {
$templateCache.put('custom.html', '<p>{{ index }} {{ match.label }}</p>');
var element = prepareInputEl('<div><input ng-model="result" typeahead-template-url="custom.html" typeahead="state as state.name for state in states | filter:$viewValue"></div>');
changeInputValueTo(element, 'Al');
expect(findMatches(element).eq(0).find('p').text()).toEqual('0 Alaska');
}));
it('should throw error on invalid expression', function () {
var prepareInvalidDir = function () {
prepareInputEl('<div><input ng-model="result" typeahead="an invalid expression"></div>');
};
expect(prepareInvalidDir).toThrow();
});
});
describe('selecting a match', function () {
it('should select a match on enter', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
var inputEl = findInput(element);
changeInputValueTo(element, 'b');
triggerKeyDown(element, 13);
expect($scope.result).toEqual('bar');
expect(inputEl.val()).toEqual('bar');
expect(element).toBeClosed();
});
it('should select a match on tab', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
var inputEl = findInput(element);
changeInputValueTo(element, 'b');
triggerKeyDown(element, 9);
expect($scope.result).toEqual('bar');
expect(inputEl.val()).toEqual('bar');
expect(element).toBeClosed();
});
it('should select match on click', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
var inputEl = findInput(element);
changeInputValueTo(element, 'b');
var match = $(findMatches(element)[1]).find('a')[0];
$(match).click();
$scope.$digest();
expect($scope.result).toEqual('baz');
expect(inputEl.val()).toEqual('baz');
expect(element).toBeClosed();
});
it('should invoke select callback on select', function () {
$scope.onSelect = function ($item, $model, $label) {
$scope.$item = $item;
$scope.$model = $model;
$scope.$label = $label;
};
var element = prepareInputEl('<div><input ng-model="result" typeahead-on-select="onSelect($item, $model, $label)" typeahead="state.code as state.name for state in states | filter:$viewValue"></div>');
changeInputValueTo(element, 'Alas');
triggerKeyDown(element, 13);
expect($scope.result).toEqual('AL');
expect($scope.$item).toEqual($scope.states[0]);
expect($scope.$model).toEqual('AL');
expect($scope.$label).toEqual('Alaska');
});
it('should correctly update inputs value on mapping where label is not derived from the model', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="state.code as state.name for state in states | filter:$viewValue"></div>');
var inputEl = findInput(element);
changeInputValueTo(element, 'Alas');
triggerKeyDown(element, 13);
expect($scope.result).toEqual('AL');
expect(inputEl.val()).toEqual('AL');
});
});
describe('pop-up interaction', function () {
var element;
beforeEach(function () {
element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
});
it('should activate prev/next matches on up/down keys', function () {
changeInputValueTo(element, 'b');
expect(element).toBeOpenWithActive(2, 0);
// Down arrow key
triggerKeyDown(element, 40);
expect(element).toBeOpenWithActive(2, 1);
// Down arrow key goes back to first element
triggerKeyDown(element, 40);
expect(element).toBeOpenWithActive(2, 0);
// Up arrow key goes back to last element
triggerKeyDown(element, 38);
expect(element).toBeOpenWithActive(2, 1);
// Up arrow key goes back to last element
triggerKeyDown(element, 38);
expect(element).toBeOpenWithActive(2, 0);
});
it('should close popup on escape key', function () {
changeInputValueTo(element, 'b');
expect(element).toBeOpenWithActive(2, 0);
// Escape key
triggerKeyDown(element, 27);
expect(element).toBeClosed();
});
it('should highlight match on mouseenter', function () {
changeInputValueTo(element, 'b');
expect(element).toBeOpenWithActive(2, 0);
findMatches(element).eq(1).trigger('mouseenter');
expect(element).toBeOpenWithActive(2, 1);
});
});
describe('promises', function () {
var element, deferred;
beforeEach(inject(function ($q) {
deferred = $q.defer();
$scope.source = function () {
return deferred.promise;
};
element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source()"></div>');
}));
it('should display matches from promise', function () {
changeInputValueTo(element, 'c');
expect(element).toBeClosed();
deferred.resolve(['good', 'stuff']);
$scope.$digest();
expect(element).toBeOpenWithActive(2, 0);
});
it('should not display anything when promise is rejected', function () {
changeInputValueTo(element, 'c');
expect(element).toBeClosed();
deferred.reject('fail');
$scope.$digest();
expect(element).toBeClosed();
});
});
describe('non-regressions tests', function () {
it('issue 231 - closes matches popup on click outside typeahead', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
changeInputValueTo(element, 'b');
$document.find('body').click();
$scope.$digest();
expect(element).toBeClosed();
});
it('issue 591 - initial formatting for un-selected match and complex label expression', function () {
var inputEl = findInput(prepareInputEl('<div><input ng-model="result" typeahead="state as state.name + \' \' + state.code for state in states | filter:$viewValue"></div>'));
expect(inputEl.val()).toEqual('');
});
it('issue 786 - name of internal model should not conflict with scope model name', function () {
$scope.state = $scope.states[0];
var element = prepareInputEl('<div><input ng-model="state" typeahead="state as state.name for state in states | filter:$viewValue"></div>');
var inputEl = findInput(element);
expect(inputEl.val()).toEqual('Alaska');
});
it('issue 863 - it should work correctly with input type="email"', function () {
$scope.emails = ['foo@host.com', 'bar@host.com'];
var element = prepareInputEl('<div><input type="email" ng-model="email" typeahead="email for email in emails | filter:$viewValue"></div>');
var inputEl = findInput(element);
changeInputValueTo(element, 'bar');
expect(element).toBeOpenWithActive(1, 0);
triggerKeyDown(element, 13);
expect($scope.email).toEqual('bar@host.com');
expect(inputEl.val()).toEqual('bar@host.com');
});
it('issue 964 - should not show popup with matches if an element is not focused', function () {
$scope.items = function(viewValue) {
return $timeout(function(){
return [viewValue];
});
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in items($viewValue)"></div>');
var inputEl = findInput(element);
changeInputValueTo(element, 'match');
$scope.$digest();
inputEl.blur();
$timeout.flush();
expect(element).toBeClosed();
});
it('issue 1140 - should properly update loading callback when deleting characters', function () {
$scope.items = function(viewValue) {
return $timeout(function(){
return [viewValue];
});
};
var element = prepareInputEl('<div><input ng-model="result" typeahead-min-length="2" typeahead-loading="isLoading" typeahead="item for item in items($viewValue)"></div>');
changeInputValueTo(element, 'match');
$scope.$digest();
expect($scope.isLoading).toBeTruthy();
changeInputValueTo(element, 'm');
$timeout.flush();
$scope.$digest();
expect($scope.isLoading).toBeFalsy();
});
it('does not close matches popup on click in input', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue"></div>');
var inputEl = findInput(element);
// Note that this bug can only be found when element is in the document
$document.find('body').append(element);
// Extra teardown for this spec
this.after(function () { element.remove(); });
changeInputValueTo(element, 'b');
inputEl.click();
$scope.$digest();
expect(element).toBeOpenWithActive(2, 0);
});
it('issue #1238 - allow names like "query" to be used inside "in" expressions ', function () {
$scope.query = function() {
return ['foo', 'bar'];
};
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in query($viewValue)"></div>');
changeInputValueTo(element, 'bar');
expect(element).toBeOpenWithActive(2, 0);
});
});
describe('input formatting', function () {
it('should co-operate with existing formatters', function () {
$scope.result = $scope.states[0];
var element = prepareInputEl('<div><input ng-model="result.name" formatter typeahead="state.name for state in states | filter:$viewValue"></div>'),
inputEl = findInput(element);
expect(inputEl.val()).toEqual('formatted' + $scope.result.name);
});
it('should support a custom input formatting function', function () {
$scope.result = $scope.states[0];
$scope.formatInput = function($model) {
return $model.code;
};
var element = prepareInputEl('<div><input ng-model="result" typeahead-input-formatter="formatInput($model)" typeahead="state as state.name for state in states | filter:$viewValue"></div>'),
inputEl = findInput(element);
expect(inputEl.val()).toEqual('AL');
expect($scope.result).toEqual($scope.states[0]);
});
});
describe('append to body', function () {
it('append typeahead results to body', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="true"></div>');
changeInputValueTo(element, 'ba');
expect($document.find('body')).toBeOpenWithActive(2, 0);
});
it('should not append to body when value of the attribute is false', function () {
var element = prepareInputEl('<div><input ng-model="result" typeahead="item for item in source | filter:$viewValue" typeahead-append-to-body="false"></div>');
changeInputValueTo(element, 'ba');
expect(findDropDown($document.find('body')).length).toEqual(0);
});
});
});
|
/*!
* CanJS - 2.1.2
* http://canjs.us/
* Copyright (c) 2014 Bitovi
* Mon, 16 Jun 2014 20:44:18 GMT
* Licensed MIT
* Includes: CanJS default build
* Download from: http://canjs.us/
*/
// # can/util/inserted
// Used to alert interested parties of when an element is inserted into the DOM.
// Given a list of elements, check if the first is in the DOM, and if so triggers the `inserted` event on all elements and their descendants.
steal('can/util/can.js', function (can) {
can.inserted = function (elems) {
// Turn the `elems` property into an array to prevent mutations from changing the looping.
elems = can.makeArray(elems);
var inDocument = false,
// Gets the `doc` to use as a reference for finding out whether the element is in the document.
doc = can.$(document.contains ? document : document.body),
children;
// Go through `elems` and trigger the `inserted` event.
// If the first element is not in the document (a Document Fragment) it will exit the function. If it is in the document it sets the `inDocument` flag to true. This means that we only check for the first element and either exit the function or start triggering "inserted" for child elements.
for (var i = 0, elem;
(elem = elems[i]) !== undefined; i++) {
if (!inDocument) {
if (elem.getElementsByTagName) {
if (can.has(doc, elem)
.length) {
inDocument = true;
} else {
return;
}
} else {
continue;
}
}
// If we've found an element in the document then we can now trigger **"inserted"** for `elem` and all of its children. We are using `getElementsByTagName("*")` so that we grab all of the descendant nodes.
if (inDocument && elem.getElementsByTagName) {
children = can.makeArray(elem.getElementsByTagName("*"));
can.trigger(elem, "inserted", [], false);
for (var j = 0, child;
(child = children[j]) !== undefined; j++) {
can.trigger(child, "inserted", [], false);
}
}
}
};
// ## can.appendChild
// Used to append a node to an element and trigger the "inserted" event on all of the newly inserted children. Since `can.inserted` takes an array we convert the child to an array, or in the case of a DocumentFragment we first convert the childNodes to an array and call inserted on those.
can.appendChild = function (el, child) {
var children;
if (child.nodeType === 11) {
children = can.makeArray(child.childNodes);
} else {
children = [child];
}
el.appendChild(child);
can.inserted(children);
};
// ## can.insertBefore
// Like can.appendChild, used to insert a node to an element before a reference node and then trigger the "inserted" event.
can.insertBefore = function (el, child, ref) {
var children;
if (child.nodeType === 11) {
children = can.makeArray(child.childNodes);
} else {
children = [child];
}
el.insertBefore(child, ref);
can.inserted(children);
};
});
|
/*
* An if
*/
module.exports = function(obj) {
if(obj.type !== 'IF') {
throw "This is not an if!";
}
var expressionParser = require('./expression.js'),
statementParser = require('./statement.js'),
output,
i;
output = 'if (' + expressionParser(obj.condition) + ') {\n';
for(i = 0; i < obj.statements.length; i += 1) {
output += statementParser(obj.statements[i]);
}
output += '}';
return output;
};
|
/*
* Copyright (c) 2019 - present Adobe. All rights reserved.
*
* 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.
*
*/
/*global describe, runs, beforeEach, it, expect, waitsFor, waitsForDone, beforeFirst, afterLast */
define(function (require, exports, module) {
'use strict';
var SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils"),
Strings = brackets.getModule("strings"),
FileUtils = brackets.getModule("file/FileUtils"),
StringUtils = brackets.getModule("utils/StringUtils"),
StringMatch = brackets.getModule("utils/StringMatch");
var extensionRequire,
phpToolingExtension,
testWindow,
$,
PreferencesManager,
CodeInspection,
DefaultProviders,
CodeHintsProvider,
SymbolProviders,
EditorManager,
testEditor,
testFolder = FileUtils.getNativeModuleDirectoryPath(module) + "/unittest-files/",
testFile1 = "test1.php",
testFile2 = "test2.php",
testFile4 = "test4.php";
describe("PhpTooling", function () {
beforeFirst(function () {
// Create a new window that will be shared by ALL tests in this spec.
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
$ = testWindow.$;
var brackets = testWindow.brackets;
extensionRequire = brackets.test.ExtensionLoader.getRequireContextForExtension("PhpTooling");
phpToolingExtension = extensionRequire("main");
});
});
afterLast(function () {
waitsForDone(phpToolingExtension.getClient().stop(), "stoping php server");
testEditor = null;
testWindow = null;
brackets = null;
EditorManager = null;
SpecRunnerUtils.closeTestWindow();
});
beforeEach(function () {
EditorManager = testWindow.brackets.test.EditorManager;
PreferencesManager = testWindow.brackets.test.PreferencesManager;
CodeInspection = testWindow.brackets.test.CodeInspection;
CodeInspection.toggleEnabled(true);
DefaultProviders = testWindow.brackets.getModule("languageTools/DefaultProviders");
CodeHintsProvider = extensionRequire("CodeHintsProvider");
SymbolProviders = extensionRequire("PHPSymbolProviders").SymbolProviders;
});
/**
* Does a busy wait for a given number of milliseconds
* @param {Number} milliSeconds - number of milliSeconds to wait
*/
function waitForMilliSeconds(milliSeconds) {
var flag = false;
setTimeout(function () {
flag = true;
}, milliSeconds);
waitsFor(function () {
return flag;
}, "This should not fail. Please check the timeout values.",
milliSeconds + 10); // We give 10 milliSeconds as grace period
}
/**
* Check the presence of a Button in Error Prompt
* @param {String} btnId - "CANCEL" or "OPEN"
*/
function checkPopUpButton(clickbtnId) {
var doc = $(testWindow.document),
errorPopUp = doc.find(".error-dialog.instance"),
btn = errorPopUp.find('.dialog-button');
// Test if the update bar button has been displayed.
expect(btn.length).toBe(2);
if (clickbtnId) {
clickButton(clickbtnId);
}
}
/**
* Check the presence of a Button in Error Prompt
* @param {String} btnId - Button OPEN or Cancel Button
*/
function clickButton(btnId) {
var doc = $(testWindow.document),
errorPopUp = doc.find(".error-dialog.instance"),
btn = errorPopUp.find('.dialog-button'),
openBtn,
cancelBtn,
clickBtn;
if (btn[0].classList.contains("primary")) {
openBtn = btn[0];
cancelBtn = btn[1];
}
if (btn[1].classList.contains("primary")) {
openBtn = btn[1];
cancelBtn = btn[0];
}
clickBtn = cancelBtn;
if(btnId === "OPEN") {
clickBtn = openBtn;
}
if(clickBtn) {
clickBtn.click();
waitForMilliSeconds(3000);
runs(function() {
expect(doc.find(".error-dialog.instance").length).toBe(0);
});
}
}
/**
* Check the presence of Error Prompt String on Brackets Window
* @param {String} title - Title String Which will be matched with Update Bar heading.
* @param {String} description - description String Which will be matched with Update Bar description.
*/
function checkPopUpString(title, titleDescription) {
var doc = $(testWindow.document),
errorPopUp = doc.find(".error-dialog.instance"),
heading = errorPopUp.find('.dialog-title'),
description = errorPopUp.find('.dialog-message');
// Test if the update bar has been displayed.
//expect(errorPopUp.length).toBe(1);
if (title) {
expect(heading.text()).toBe(title);
}
if (titleDescription) {
expect(description.text()).toBe(titleDescription);
}
}
function toggleDiagnosisResults(visible) {
var doc = $(testWindow.document),
problemsPanel = doc.find("#problems-panel"),
statusInspection = $("#status-inspection");
statusInspection.triggerHandler("click");
expect(problemsPanel.is(":visible")).toBe(visible);
}
/**
* Wait for the editor to change positions, such as after a jump to
* definition has been triggered. Will timeout after 3 seconds
*
* @param {{line:number, ch:number}} oldLocation - the original line/col
* @param {Function} callback - the callback to apply once the editor has changed position
*/
function _waitForJump(jumpPromise, callback) {
var cursor = null,
complete = false;
jumpPromise.done(function () {
complete = true;
});
waitsFor(function () {
var activeEditor = EditorManager.getActiveEditor();
cursor = activeEditor.getCursorPos();
return complete;
}, "Expected jump did not occur", 3000);
runs(function () { callback(cursor); });
}
/*
* Expect a given list of hints to be present in a given hint
* response object
*
* @param {Object + jQuery.Deferred} hintObj - a hint response object,
* possibly deferred
* @param {Array.<string>} expectedHints - a list of hints that should be
* present in the hint response
*/
function expecthintsPresent(expectedHints) {
var hintObj = (new CodeHintsProvider.CodeHintsProvider(phpToolingExtension.getClient())).getHints(null);
_waitForHints(hintObj, function (hintList) {
expect(hintList).toBeTruthy();
expectedHints.forEach(function (expectedHint) {
expect(_indexOf(hintList, expectedHint)).not.toBe(-1);
});
});
}
/*
* Return the index at which hint occurs in hintList
*
* @param {Array.<Object>} hintList - the list of hints
* @param {string} hint - the hint to search for
* @return {number} - the index into hintList at which the hint occurs,
* or -1 if it does not
*/
function _indexOf(hintList, hint) {
var index = -1,
counter = 0;
for (counter; counter < hintList.length; counter++) {
if (hintList[counter].data("token").label === hint) {
index = counter;
break;
}
}
return index;
}
/*
* Wait for a hint response object to resolve, then apply a callback
* to the result
*
* @param {Object + jQuery.Deferred} hintObj - a hint response object,
* possibly deferred
* @param {Function} callback - the callback to apply to the resolved
* hint response object
*/
function _waitForHints(hintObj, callback) {
var complete = false,
hintList = null;
if (hintObj.hasOwnProperty("hints")) {
complete = true;
hintList = hintObj.hints;
} else {
hintObj.done(function (obj) {
complete = true;
hintList = obj.hints;
});
}
waitsFor(function () {
return complete;
}, "Expected hints did not resolve", 3000);
runs(function () { callback(hintList); });
}
/**
* Show a function hint based on the code at the cursor. Verify the
* hint matches the passed in value.
*
* @param {Array<{name: string, type: string, isOptional: boolean}>}
* expectedParams - array of records, where each element of the array
* describes a function parameter. If null, then no hint is expected.
* @param {number} expectedParameter - the parameter at cursor.
*/
function expectParameterHint(expectedParams, expectedParameter) {
var requestStatus = null;
var request,
complete = false;
runs(function () {
request = (new DefaultProviders.ParameterHintsProvider(phpToolingExtension.getClient()))
.getParameterHints();
request.done(function (status) {
complete = true;
requestStatus = status;
}).fail(function(){
complete = true;
});
});
waitsFor(function () {
return complete;
}, "Expected Parameter hints did not resolve", 3000);
if (expectedParams === null) {
expect(requestStatus).toBe(null);
return;
}
function expectHint(hint) {
var params = hint.parameters,
n = params.length,
i;
// compare params to expected params
expect(params.length).toBe(expectedParams.length);
expect(hint.currentIndex).toBe(expectedParameter);
for (i = 0; i < n; i++) {
expect(params[i].label).toBe(expectedParams[i]);
}
}
runs(function() {
expectHint(requestStatus);
});
}
/**
* Show the document/project symbols for a language type.
*
* @param {SymbolProvider} provider The symbol provider to use for the request.
* @param {string} query The query string for the request.
* @param {Array} expectedSymbols Expected results for the request.
*/
function expectSymbols(provider, query, expectedSymbols) {
var requestStatus = null;
var request,
matcher;
runs(function () {
matcher = new StringMatch.StringMatcher();
request = new provider(phpToolingExtension.getClient()).search(query, matcher);
request.done(function (status) {
requestStatus = status;
});
waitsForDone(request, "Expected Symbols did not resolve", 3000);
});
if (expectedSymbols === []) {
expect(requestStatus).toBe([]);
return;
}
function matchSymbols(symbols) {
var n = symbols.length > 4 ? 4 : symbols.length,
i;
for (i = 0; i < n; i++) {
var symbolInfo = symbols[i].symbolInfo;
expect(symbolInfo.label).toBe(expectedSymbols[i].label);
expect(symbolInfo.type).toBe(expectedSymbols[i].type);
expect(symbolInfo.scope).toBe(expectedSymbols[i].scope);
if (expectedSymbols[i].fullPath === null) {
expect(symbolInfo.fullPath).toBe(null);
} else {
expect(symbolInfo.fullPath.includes(expectedSymbols[i].fullPath)).toBe(true);
}
}
}
runs(function() {
matchSymbols(requestStatus);
});
}
/**
* Trigger a jump to definition, and verify that the editor jumped to
* the expected location. The new location is the variable definition
* or function definition of the variable or function at the current
* cursor location. Jumping to the new location will cause a new editor
* to be opened or open an existing editor.
*
* @param {{line:number, ch:number, file:string}} expectedLocation - the
* line, column, and optionally the new file the editor should jump to. If the
* editor is expected to stay in the same file, then file may be omitted.
*/
function editorJumped(expectedLocation) {
var jumpPromise = (new DefaultProviders.JumpToDefProvider(phpToolingExtension.getClient())).doJumpToDef();
_waitForJump(jumpPromise, function (newCursor) {
expect(newCursor.line).toBe(expectedLocation.line);
expect(newCursor.ch).toBe(expectedLocation.ch);
if (expectedLocation.file) {
var activeEditor = EditorManager.getActiveEditor();
expect(activeEditor.document.file.name).toBe(expectedLocation.file);
}
});
}
function expectReferences(referencesExpected) {
var refPromise,
results = null,
complete = false;
runs(function () {
refPromise = (new DefaultProviders.ReferencesProvider(phpToolingExtension.getClient())).getReferences();
refPromise.done(function (resp) {
complete = true;
results = resp;
}).fail(function(){
complete = true;
});
});
waitsFor(function () {
return complete;
}, "Expected Reference Promise did not resolve", 3000);
if(referencesExpected === null) {
expect(results).toBeNull();
return;
}
runs(function() {
expect(results.numFiles).toBe(referencesExpected.numFiles);
expect(results.numMatches).toBe(referencesExpected.numMatches);
expect(results.allResultsAvailable).toBe(referencesExpected.allResultsAvailable);
expect(results.results).not.toBeNull();
for(var key in results.keys) {
expect(results.results.key).toBe(referencesExpected.results.key);
}
});
}
/**
* Check the presence of Error Prompt on Brackets Window
*/
function checkErrorPopUp() {
var doc = $(testWindow.document),
errorPopUp = doc.find(".error-dialog.instance"),
errorPopUpHeader = errorPopUp.find(".modal-header"),
errorPopUpBody = errorPopUp.find(".modal-body"),
errorPopUpFooter = errorPopUp.find(".modal-footer"),
errorPopUpPresent = false;
runs(function () {
expect(errorPopUp.length).toBe(1);
expect(errorPopUpHeader).not.toBeNull();
expect(errorPopUpBody).not.toBeNull();
expect(errorPopUpFooter).not.toBeNull();
});
if (errorPopUp && errorPopUp.length > 0) {
errorPopUpPresent = true;
}
return errorPopUpPresent;
}
it("phpTooling Exiension should be loaded Successfully", function () {
waitForMilliSeconds(5000);
runs(function () {
expect(phpToolingExtension).not.toBeNull();
});
});
it("should attempt to start php server and fail due to lower version of php", function () {
var phpExecutable = testWindow.brackets.platform === "mac" ? "/mac/invalidphp" : "/win/invalidphp";
PreferencesManager.set("php", {
"executablePath": testFolder + phpExecutable
}, {
locations: {scope: "session"}
});
waitForMilliSeconds(5000);
runs(function () {
checkErrorPopUp();
checkPopUpString(Strings.PHP_SERVER_ERROR_TITLE,
StringUtils.format(Strings.PHP_UNSUPPORTED_VERSION, "5.6.30"));
checkPopUpButton("CANCEL");
});
});
it("should attempt to start php server and fail due to invaild executable", function () {
PreferencesManager.set("php", {"executablePath": "/invalidPath/php"}, {locations: {scope: "session"}});
waitForMilliSeconds(5000);
runs(function () {
checkErrorPopUp();
checkPopUpString(Strings.PHP_SERVER_ERROR_TITLE, Strings.PHP_EXECUTABLE_NOT_FOUND);
checkPopUpButton("CANCEL");
});
});
it("should attempt to start php server and fail due to invaild memory limit in prefs settings", function () {
PreferencesManager.set("php", {"memoryLimit": "invalidValue"}, {locations: {scope: "session"}});
waitForMilliSeconds(5000);
runs(function () {
checkErrorPopUp();
checkPopUpString(Strings.PHP_SERVER_ERROR_TITLE, Strings.PHP_SERVER_MEMORY_LIMIT_INVALID);
checkPopUpButton("CANCEL");
});
runs(function () {
SpecRunnerUtils.loadProjectInTestWindow(testFolder + "test");
});
});
it("should attempt to start php server and success", function () {
PreferencesManager.set("php", {"memoryLimit": "4095M"}, {locations: {scope: "session"}});
waitsForDone(SpecRunnerUtils.openProjectFiles([testFile1]), "open test file: " + testFile1);
waitForMilliSeconds(5000);
runs(function () {
toggleDiagnosisResults(false);
toggleDiagnosisResults(true);
});
});
it("should filter hints by query", function () {
waitsForDone(SpecRunnerUtils.openProjectFiles([testFile2]), "open test file: " + testFile2);
runs(function() {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos({ line: 15, ch: 3 });
expecthintsPresent(["$A11", "$A12", "$A13"]);
});
});
it("should show inbuilt functions in hints", function () {
runs(function() {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos({ line: 17, ch: 2 });
expecthintsPresent(["fopen", "for", "foreach"]);
});
});
it("should show static global variables in hints", function () {
runs(function() {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos({ line: 20, ch: 1 });
expecthintsPresent(["$_COOKIE", "$_ENV"]);
});
});
it("should not show parameter hints", function () {
runs(function() {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos({ line: 25, ch: 5 });
expectParameterHint(null);
});
});
it("should show no parameter as a hint", function () {
runs(function() {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos({ line: 27, ch: 19 });
expectParameterHint([], 0);
});
});
it("should show parameters hints", function () {
runs(function() {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos({ line: 26, ch: 9 });
expectParameterHint([
"string $filename",
"string $mode",
"bool $use_include_path = null",
"resource $context = null"], 1);
});
});
it("should not show any references", function () {
var start = { line: 6, ch: 4 };
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(start);
expectReferences(null);
});
});
it("should show reference present in single file", function () {
var start = { line: 22, ch: 18 },
results = {};
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(start);
results[testFolder + "test/test2.php"] = {matches: [
{
start: {line: 27, ch: 0},
end: {line: 27, ch: 18},
line: "watchparameterhint()"
}
]
};
expectReferences({
numFiles: 1,
numMatches: 1,
allResultsAvailable: true,
queryInfo: "watchparameterhint",
keys: [testFolder + "test/test2.php"],
results: results
});
});
});
it("should show references present in single file", function () {
var start = { line: 34, ch: 8 },
results = {};
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(start);
results[testFolder + "test/test2.php"] = {matches: [
{
start: {line: 34, ch: 0},
end: {line: 34, ch: 17},
line: "watchReferences();"
},
{
start: {line: 36, ch: 0},
end: {line: 36, ch: 17},
line: "watchReferences();"
}
]
};
expectReferences({
numFiles: 1,
numMatches: 2,
allResultsAvailable: true,
queryInfo: "watchparameterhint",
keys: [testFolder + "test/test2.php"],
results: results
});
});
});
it("should show references present in multiple files", function () {
var start = { line: 39, ch: 21 },
results = {};
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(start);
results[testFolder + "test/test2.php"] = {matches: [
{
start: {line: 34, ch: 0},
end: {line: 34, ch: 26},
line: "watchReferences();"
},
{
start: {line: 36, ch: 0},
end: {line: 36, ch: 26},
line: "watchReferences();"
}
]
};
results[testFolder + "test/test3.php"] = {matches: [
{
start: {line: 11, ch: 0},
end: {line: 11, ch: 26},
line: "watchReferences();"
}
]
};
expectReferences({
numFiles: 2,
numMatches: 3,
allResultsAvailable: true,
queryInfo: "watchparameterhint",
keys: [testFolder + "test/test2.php", testFolder + "test/test3.php"],
results: results
});
});
});
it("should jump to earlier defined variable", function () {
var start = { line: 4, ch: 2 };
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(start);
editorJumped({line: 2, ch: 0});
});
});
it("should jump to class declared in other module file", function () {
var start = { line: 9, ch: 11 };
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(start);
editorJumped({line: 4, ch: 0, file: "test3.php"});
});
});
it("should fetch document symbols for a given file", function () {
waitsForDone(SpecRunnerUtils.openProjectFiles([testFile4]), "open test file: " + testFile4);
runs(function () {
var provider = SymbolProviders.DocumentSymbolsProvider,
query = "@",
expectedSymbols = [
{
"label": "constantValue",
"fullPath": null,
"type": "Constant",
"scope": "MyClass"
},
{
"label": "MyClass",
"fullPath": null,
"type": "Class",
"scope": ""
},
{
"label": "publicFunction",
"fullPath": null,
"type": "Method",
"scope": "MyClass"
},
{
"label": "publicValue",
"fullPath": null,
"type": "Property",
"scope": "MyClass"
}
];
expectSymbols(provider, query, expectedSymbols);
});
});
it("should fetch no document symbols for a given file", function () {
waitsForDone(SpecRunnerUtils.openProjectFiles([testFile1]), "open test file: " + testFile1);
runs(function () {
var provider = SymbolProviders.DocumentSymbolsProvider,
query = "@",
expectedSymbols = [];
expectSymbols(provider, query, expectedSymbols);
});
});
it("should fetch project symbols for a given file", function () {
runs(function () {
var provider = SymbolProviders.ProjectSymbolsProvider,
query = "#as",
expectedSymbols = [
{
"label": "MyClass",
"fullPath": "test4.php",
"type": "Class",
"scope": ""
},
{
"label": "TestCase",
"fullPath": "test2.php",
"type": "Class",
"scope": "test"
}
];
expectSymbols(provider, query, expectedSymbols);
});
});
});
});
|
'use strict';
// Huts controller
angular.module('huts').controller('HutsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Huts', 'MyHuts', 'Servers', 'Products', 'Socket',
function($scope, $stateParams, $location, Authentication, Huts, MyHuts, Servers, Products, Socket) {
$scope.authentication = Authentication;
$scope.servers = Servers.query();
$scope.products = Products.query();
// Create new Hut
$scope.create = function() {
// Create new Hut object
var hut = new Huts({
name: this.name,
product: this.product,
server: this.server
});
// Redirect after save
hut.$save(function(response) {
$location.path('huts/' + response._id);
// Clear form fields
$scope.name = '';
$scope.product = '';
$scope.server = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Hut
$scope.remove = function(hut) {
if (hut) {
hut.$remove();
for (var i in $scope.huts) {
if ($scope.huts[i] === hut) {
$scope.huts.splice(i, 1);
}
}
} else {
$scope.hut.$remove(function() {
$location.path('dashboard');
});
}
};
// Update existing Hut
$scope.update = function() {
var hut = $scope.hut;
hut.$update(function() {
$location.path('huts/' + hut._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Huts
$scope.find = function() {
$scope.huts = Huts.query();
};
// Find a list of Huts by user
$scope.findMyHuts = function() {
$scope.huts = MyHuts.query();
};
// Find existing Hut
$scope.findOne = function() {
$scope.hut = Huts.get({
hutId: $stateParams.hutId
});
};
$scope.createHut = function() {
var name = document.getElementById('name').value;
// var dbType = document.getElementById('dbtype').value;
// var dbName = 'lovell',
var dbType = 'monogodb';
Socket.emit('createHut', {
name: name,
type: dbType
});
};
// Delete application container
$scope.deleteHut = function(name) {
Socket.emit('deleteHut', {
name: name
});
};
// Remove the event listener when the controller instance is destroyed
$scope.$on('$destroy', function() {
Socket.removeListener('createHut');
Socket.removeListener('deleteHut');
});
}
]);
|
define({
"_widgetLabel": "Аналіз інцидентів",
"_featureAction_SetAsIncident": "Задати як інцидент",
"incident": "Інцидент",
"weather": "Погода",
"locate_incident": "Знайти інцидент",
"clear_incidents": "Очистити інциденти",
"reverse_geocoded_address": "Найближча адреса",
"reverse_geocoded_error": "Не доступно",
"miles": "Милі",
"kilometers": "Кілометри",
"feet": "Фути",
"meters": "Метри",
"yards": "Ярди",
"nauticalMiles": "Морські милі",
"now": "ЗАРАЗ",
"wind": "ВІТЕР",
"SUN": "НД",
"MON": "ПН",
"TUE": "ВТ",
"WED": "СР",
"THU": "ЧТ",
"FRI": "ПТ",
"SAT": "СБ",
"defaultTabMsg": "Інциденти не визначено.",
"useMapExtent": "Використовувати поточний екстент карти",
"noFeaturesFound": "Об'єкти не знайдено.",
"downloadCSV": "ЗАВАНТАЖИТИ CSV",
"sum": "СУМА",
"min": "МІН.",
"max": "МАКС.",
"avg": "СЕР.",
"count": "ЛІЧИЛЬНИК",
"area": "ПЛОЩА",
"length": "ДОВЖИНА"
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:f467f9a89b6143287985a1c81cb478bf32ebe64da135be6e7c8c0ec0a1e3e4bd
size 5532
|
module("core.Selection");
test('getRange--闭合选区的边界情况', function () {
var div_new = document.createElement('div');
document.body.appendChild(div_new);
var editor = new UM.Editor({'autoFloatEnabled': false});
stop();
setTimeout(function () {
editor.render(div_new);
editor.ready(function () {
setTimeout(function () {
var range = new UM.dom.Range(editor.document,editor.body);
editor.setContent('<p><strong>xxx</strong></p>');
range.setStart(editor.body.firstChild.firstChild, 0).collapse(true).select();
range = editor.selection.getRange();
var strong = editor.body.firstChild.firstChild;
if(ua.browser.ie&&ua.browser.ie>8){//todo ie9,10改range
ok(range.startContainer === strong,'startContainer是strong');
ok(range.startOffset == 1,'startOffset是1')
}
else{
ok(range.startContainer.nodeType == 3, 'startContainer是文本节点');
/*startContainer:ie is xxx,others are strong.firstChild*/
ok(( range.startContainer === strong.firstChild) && strong.firstChild.length == 1 || (range.startContainer.nodeValue.length == 3 && range.startContainer === strong.lastChild), 'startContainer是xxx左边的占位符或者xxx');
}
ua.manualDeleteFillData(editor.body);
range.setStart(editor.body.firstChild.firstChild, 1).collapse(true).select();
/*去掉占位符*/
range = editor.selection.getRange();
/*可能为(strong,1)或者(xxx,3)*/
ok(( range.startContainer === strong) || ( range.startContainer === strong.lastChild) && strong.lastChild.length == 1 || (range.startContainer.nodeValue.length == 3 && range.startContainer === strong.firstChild), 'startContainer是xxx或者xxx右边的占位符');
// ok( range.startContainer.nodeType == 1 ? range.startContainer.tagName.toLowerCase() == 'strong' && range.startOffset == 1 : range.startContainer.data == 'xxx' && range.startOffset == 3, 'strong,1或xxx,3' );
ua.manualDeleteFillData(editor.body);
/*p,0*/
range.setStart(editor.body.firstChild, 0).collapse(true).select();
range = editor.selection.getRange();
/*startContainer:ie is xxx,ff is p, chrome is strong*/
// ok( ( range.startContainer === strong.parentNode.firstChild)&& strong.parentNode.firstChild.length == 1 || (range.startContainer.nodeValue.length == 3 && range.startContainer === strong.firstChild.nextSibling), 'startContainer是第一个占位符或者xxx' );
// ua.manualDeleteFillData( editor.body );
// range.setStart( editor.body.firstChild, 1 ).collapse( true ).select();
// equal( range.startContainer.tagName.toLowerCase(), 'p', 'p,1' );
te.dom.push(div_new);
te.obj.push(editor);
start();
}, 50);
});
}, 50);
});
test('trace 3628 isFocus', function () {
if(ua.browser.ie==8)return; //todo trace 3628
if (!ua.browser.opera) {
var div1 = document.createElement('div');
var div2 = document.createElement('div');
document.body.appendChild(div1);
document.body.appendChild(div2);
var editor1 = new UM.Editor({'initialContent': '<span>hello</span>', 'autoFloatEnabled': false});
var editor2 = new UM.Editor({'initialContent': '<span>hello</span>', 'autoFloatEnabled': false});
editor1.render(div1);
stop();
editor1.ready(function () {
editor2.render(div2);
editor2.ready(function () {
editor1.focus();
ok(editor1.selection.isFocus(), '设editor内容是<span> editor1 is focused');
ok(!editor2.selection.isFocus(), '设editor内容是<span> editor2 is not focused');
editor2.focus();
ok(editor2.selection.isFocus(), '设editor内容是<span> editor2 is focused');
ok(!editor1.selection.isFocus(), '设editor内容是<span> editor1 is not focused');
div1.parentNode.removeChild(div1);
div2.parentNode.removeChild(div2);
var div3 = document.createElement('div');
var div4 = document.createElement('div');
document.body.appendChild(div3);
document.body.appendChild(div4);
var editor3 = new UM.Editor({'initialContent': '<h1>hello</h1>', 'autoFloatEnabled': false});
var editor4 = new UM.Editor({'initialContent': '<h1>hello</h1>', 'autoFloatEnabled': false});
editor3.render(div3);
editor3.ready(function () {
editor4.render(div4);
editor4.ready(function () {
editor3.focus();
ok(editor3.selection.isFocus(), '设editor内容是<h1> editor1 is focused');
ok(!editor4.selection.isFocus(), '设editor内容是<h1> editor2 is not focused');
editor4.focus();
ok(editor4.selection.isFocus(), '设editor内容是<h1> editor2 is focused');
ok(!editor3.selection.isFocus(), '设editor内容是<h1> editor1 is not focused');
setTimeout(function () {
div3.parentNode.removeChild(div3);
div4.parentNode.removeChild(div4);
start();
}, 50);
});
});
});
});
}
});
test( 'getText', function() {
stop();
setTimeout( function() {
var doc = te.dom[1].contentWindow.document;
var range = new UM.dom.Range( doc ,doc.body);
var div = doc.createElement( 'div' );
doc.body.appendChild( div );
div.innerHTML = '<em></em><span>spanText</span><strong>first</strong>second';
range.setStart( div.firstChild, 0 ).setEnd( div.lastChild, 1 ).select();
var selection = new UM.dom.Selection( doc,doc.body );
var text = selection.getText();
equal( text, 'spanTextfirsts', 'check getText function' );
start();
}, 20 );
} );
test('hasNativeRange', function () {
var div_new = document.createElement('div');
document.body.appendChild(div_new);
var editor = new UM.Editor({'autoFloatEnabled': false});
stop();
setTimeout(function () {
editor.render(div_new);
editor.ready(function () {
setTimeout(function () {
editor.focus();
if(ua.browser.ie==8){//todo trace 3628 focus有问题,select代替
var range = new UM.dom.Range( editor.document ,editor.body);
range.setStart(editor.body,0).collapse(true).select();
}
ok(editor.selection.hasNativeRange());
var rng = new UM.dom.Range(document,document.body);
rng.setStart(document.body,0).setCursor();
ok(!editor.selection.hasNativeRange());
start();
}, 50);
});
}, 50);
});
|
import CreateAccount from "../create_account"
import PropTypes from "prop-types"
import React from "react"
import UploadPhoto from "../upload_photo"
import block from "bem-cn-lite"
import { connect } from "react-redux"
function UploadPhotoLanding({ isMobile, user }) {
const b = block("consignments-submission-upload-photo-landing")
return (
<div className={b({ mobile: isMobile })}>
{user ? (
<div>
<div className={b("title")}>
Add photos to your consignment submission
</div>
<div className={b("step-form")}>
<UploadPhoto hideCheckbox />
</div>
</div>
) : (
<div className={b("step-form")}>
<CreateAccount />
</div>
)}
</div>
)
}
const mapStateToProps = state => {
return {
isMobile: state.submissionFlow.isMobile,
user: state.submissionFlow.user,
}
}
export default connect(mapStateToProps)(UploadPhotoLanding)
UploadPhotoLanding.propTypes = {
isMobile: PropTypes.bool.isRequired,
user: PropTypes.object,
}
|
var platform = window.navigator.platform;
var cookieEnabled = window.navigator.cookieEnabled? "yes" : "no";
var doNotTrack = "";
if (window.navigator.doNotTrack != null && window.navigator.doNotTrack != "unspecified"){
if(window.navigator.doNotTrack == "1" || window.navigator.doNotTrack == "yes"){
doNotTrack = "yes";
} else {
doNotTrack = "no";
}
} else {
doNotTrack = "NC";
}
var timezone = new Date().getTimezoneOffset();
var resolution = window.screen.width+"x"+window.screen.height+"x"+window.screen.colorDepth;
//Enumeration of navigator.plugins or use of Plugin detect
var plugins = "";
if(PluginDetect.browser.isIE){
var nbPlugins = 1;
var pluginsList = ["QuickTime", "Java", "DevalVR", "Flash", "Shockwave",
"WindowsMediaPlayer", "Silverlight", "VLC", "AdobeReader", "PDFReader",
"RealPlayer", "PDFjs"];
PluginDetect.getVersion(".");
for (i = 0; i < pluginsList.length; i++) {
var ver = PluginDetect.getVersion(pluginsList[i]);
if(ver != null){
plugins+="Plugin "+nbPlugins+": "+pluginsList[i]+" "+ver+"; ";
nbPlugins++;
}
}
} else {
var np = window.navigator.plugins;
var plist = new Array();
for (var i = 0; i < np.length; i++) {
plist[i] = np[i].name + "; ";
plist[i] += np[i].description + "; ";
plist[i] += np[i].filename;
plist[i] += ". ";
}
plist.sort();
for (i = 0; i < np.length; i++)
plugins+= "Plugin "+i+": " + plist[i];
}
try {
ieUserData = "";
oPersistDiv.setAttribute("testStorage", "value remembered");
oPersistDiv.save("oXMLStore");
oPersistDiv.setAttribute("testStorage", "overwritten!");
oPersistDiv.load("oXMLStore");
if ("value remembered" == (oPersistDiv.getAttribute("testStorage"))) {
ieUserData= "yes";
} else {
ieUserData = "no";
}
} catch (ex) {
ieUserData = "no";
}
try {
localStorage.fp = "test";
sessionStorage.fp = "test";
} catch (ex) {
}
try {
domLocalStorage = "";
if (localStorage.fp == "test") {
domLocalStorage = "yes";
} else {
domLocalStorage = "no";
}
} catch (ex) {
domLocalStorage = "no";
}
try {
domSessionStorage = "";
if (sessionStorage.fp == "test") {
domSessionStorage = "yes";
} else {
domSessionStorage = "no";
}
} catch (ex) {
domSessionStorage = "no";
}
|
'use strict';
var iteratorSymbol = require('es6-symbol').iterator
, isArguments = require('../../function/is-arguments')
, toPosInt = require('../../number/to-pos-integer')
, callable = require('../../object/valid-callable')
, validValue = require('../../object/valid-value')
, isString = require('../../string/is-string')
, isArray = Array.isArray, call = Function.prototype.call;
module.exports = function (arrayLike/*, mapFn, thisArg*/) {
var mapFn = arguments[1], thisArg = arguments[2], Constructor, i, j, arr, l, char, code, iterator
, result, getIterator;
arrayLike = Object(validValue(arrayLike));
if (!this || !Array.isPrototypeOf(this)) Constructor = Array;
else Constructor = this;
if (mapFn != null) callable(mapFn);
if (!isArray(arrayLike)) {
if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
arr = new Constructor();
iterator = callable(getIterator).call(arrayLike);
result = iterator.next();
i = 0;
while (!result.done) {
arr[i] = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value;
result = iterator.next();
++i;
}
return arr;
}
if (isString(arrayLike)) {
l = arrayLike.length;
arr = new Constructor();
for (i = 0, j = 0; i < l; ++i) {
char = arrayLike[i];
if ((i + 1) < l) {
code = char.charCodeAt(0);
if ((code >= 0xD800) && (code <= 0xDBFF)) char += arrayLike[++i];
}
arr.push(mapFn ? call.call(mapFn, thisArg, char, j++) : char);
}
return arr;
}
}
l = toPosInt(arrayLike.length);
if (mapFn != null) {
arr = new Constructor(l);
for (i = 0; i < l; ++i) arr[i] = call.call(mapFn, thisArg, arrayLike[i], i);
return arr;
}
if (isArguments(arrayLike)) {
if (l !== 1) return Constructor.apply(null, arrayLike);
arr = new Constructor(1);
arr[0] = arrayLike[0];
return arr;
}
arr = new Constructor(l);
for (i = 0; i < l; ++i) arr[i] = arrayLike[i];
return arr;
};
|
'use strict';
/**
* This contains all the core commands that kalabox can run on every machine
*/
module.exports = function(kbox) {
var _ = require('lodash');
var async = require('async');
var Promise = kbox.Promise;
var util = require('../util.js')(kbox);
// Display list of apps.
kbox.tasks.add(function(task) {
task.path = ['apps'];
task.description = 'Display list of apps.';
task.options.push({
name: 'names',
alias: 'n',
description: 'Only display app names.'
});
task.func = function(done) {
// Keep refernece for later.
var self = this;
// Get list of app names.
util.getAppNames()
// Map app names to an object.
.then(function(appNames) {
if (self.options.names) {
// Just return app names.
return appNames;
} else {
// Reduce app names to an object of app stats.
return Promise.reduce(appNames, function(obj, appName) {
return util.getAppStats(appName)
.then(function(stats) {
obj[appName] = stats;
return obj;
});
}, {});
}
})
// Output object.
.then(function(result) {
console.log(JSON.stringify(result, null, ' '));
})
// Return.
.nodeify(done);
};
});
};
|
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {MDCFoundation} from '@material/base';
import {cssClasses, strings, numbers} from './constants';
const CB_PROTO_PROPS = ['checked', 'indeterminate'];
export default class MDCCheckboxFoundation extends MDCFoundation {
static get cssClasses() {
return cssClasses;
}
static get strings() {
return strings;
}
static get numbers() {
return numbers;
}
static get defaultAdapter() {
return {
addClass: (/* className: string */) => {},
removeClass: (/* className: string */) => {},
registerAnimationEndHandler: (/* handler: EventListener */) => {},
deregisterAnimationEndHandler: (/* handler: EventListener */) => {},
registerChangeHandler: (/* handler: EventListener */) => {},
deregisterChangeHandler: (/* handler: EventListener */) => {},
getNativeControl: () => /* HTMLInputElement */ {},
forceLayout: () => {},
isAttachedToDOM: () => /* boolean */ {},
};
}
constructor(adapter) {
super(Object.assign(MDCCheckboxFoundation.defaultAdapter, adapter));
this.currentCheckState_ = strings.TRANSITION_STATE_INIT;
this.currentAnimationClass_ = '';
this.animEndLatchTimer_ = 0;
this.animEndHandler_ = () => {
clearTimeout(this.animEndLatchTimer_);
this.animEndLatchTimer_ = setTimeout(() => {
this.adapter_.removeClass(this.currentAnimationClass_);
this.adapter_.deregisterAnimationEndHandler(this.animEndHandler_);
}, numbers.ANIM_END_LATCH_MS);
};
this.changeHandler_ = () => this.transitionCheckState_();
}
init() {
this.adapter_.addClass(cssClasses.UPGRADED);
this.adapter_.registerChangeHandler(this.changeHandler_);
this.installPropertyChangeHooks_();
}
destroy() {
this.adapter_.deregisterChangeHandler(this.changeHandler_);
this.uninstallPropertyChangeHooks_();
}
isChecked() {
return this.getNativeControl_().checked;
}
setChecked(checked) {
this.getNativeControl_().checked = checked;
}
isIndeterminate() {
return this.getNativeControl_().indeterminate;
}
setIndeterminate(indeterminate) {
this.getNativeControl_().indeterminate = indeterminate;
}
isDisabled() {
return this.getNativeControl_().disabled;
}
setDisabled(disabled) {
this.getNativeControl_().disabled = disabled;
}
installPropertyChangeHooks_() {
const nativeCb = this.getNativeControl_();
const cbProto = Object.getPrototypeOf(nativeCb);
CB_PROTO_PROPS.forEach((controlState) => {
const desc = Object.getOwnPropertyDescriptor(cbProto, controlState);
// We have to check for this descriptor, since some browsers (Safari) don't support its return.
// See: https://bugs.webkit.org/show_bug.cgi?id=49739
if (validDescriptor(desc)) {
Object.defineProperty(nativeCb, controlState, {
get: desc.get,
set: (state) => {
desc.set.call(nativeCb, state);
this.transitionCheckState_();
},
configurable: desc.configurable,
enumerable: desc.enumerable,
});
}
});
}
uninstallPropertyChangeHooks_() {
const nativeCb = this.getNativeControl_();
const cbProto = Object.getPrototypeOf(nativeCb);
CB_PROTO_PROPS.forEach((controlState) => {
const desc = Object.getOwnPropertyDescriptor(cbProto, controlState);
if (validDescriptor(desc)) {
Object.defineProperty(nativeCb, controlState, desc);
}
});
}
transitionCheckState_() {
const nativeCb = this.adapter_.getNativeControl();
if (!nativeCb) {
return;
}
const oldState = this.currentCheckState_;
const newState = this.determineCheckState_(nativeCb);
if (oldState === newState) {
return;
}
// Check to ensure that there isn't a previously existing animation class, in case for example
// the user interacted with the checkbox before the animation was finished.
if (this.currentAnimationClass_.length > 0) {
clearTimeout(this.animEndLatchTimer_);
this.adapter_.forceLayout();
this.adapter_.removeClass(this.currentAnimationClass_);
}
this.currentAnimationClass_ = this.getTransitionAnimationClass_(oldState, newState);
this.currentCheckState_ = newState;
// Check for parentNode so that animations are only run when the element is attached
// to the DOM.
if (this.adapter_.isAttachedToDOM() && this.currentAnimationClass_.length > 0) {
this.adapter_.addClass(this.currentAnimationClass_);
this.adapter_.registerAnimationEndHandler(this.animEndHandler_);
}
}
determineCheckState_(nativeCb) {
const {
TRANSITION_STATE_INDETERMINATE,
TRANSITION_STATE_CHECKED,
TRANSITION_STATE_UNCHECKED,
} = strings;
if (nativeCb.indeterminate) {
return TRANSITION_STATE_INDETERMINATE;
}
return nativeCb.checked ? TRANSITION_STATE_CHECKED : TRANSITION_STATE_UNCHECKED;
}
getTransitionAnimationClass_(oldState, newState) {
const {
TRANSITION_STATE_INIT,
TRANSITION_STATE_CHECKED,
TRANSITION_STATE_UNCHECKED,
} = strings;
const {
ANIM_UNCHECKED_CHECKED,
ANIM_UNCHECKED_INDETERMINATE,
ANIM_CHECKED_UNCHECKED,
ANIM_CHECKED_INDETERMINATE,
ANIM_INDETERMINATE_CHECKED,
ANIM_INDETERMINATE_UNCHECKED,
} = MDCCheckboxFoundation.cssClasses;
switch (oldState) {
case TRANSITION_STATE_INIT:
if (newState === TRANSITION_STATE_UNCHECKED) {
return '';
}
// fallthrough
case TRANSITION_STATE_UNCHECKED:
return newState === TRANSITION_STATE_CHECKED ? ANIM_UNCHECKED_CHECKED : ANIM_UNCHECKED_INDETERMINATE;
case TRANSITION_STATE_CHECKED:
return newState === TRANSITION_STATE_UNCHECKED ? ANIM_CHECKED_UNCHECKED : ANIM_CHECKED_INDETERMINATE;
// TRANSITION_STATE_INDETERMINATE
default:
return newState === TRANSITION_STATE_CHECKED ?
ANIM_INDETERMINATE_CHECKED : ANIM_INDETERMINATE_UNCHECKED;
}
}
getNativeControl_() {
return this.adapter_.getNativeControl() || {
checked: false,
indeterminate: false,
disabled: false,
};
}
}
function validDescriptor(inputPropDesc) {
return inputPropDesc && typeof inputPropDesc.set === 'function';
}
|
'use strict';
var isNumber = require('is-number');
/**
* Returns the last item, or last `n` items of an array.
*
* ```js
* last(['a', 'b', 'c', 'd', 'e'], 2)
* //=> ['d', 'e']
* ```
*
* @name .last
* @param {Array} `array`
* @param {Number} `n` Number of items to return, starting with the last item.
* @return {Array}
* @api public
*/
module.exports = function last_(arr, fn) {
if (!Array.isArray(arr)) {
throw new TypeError('utils#array.last() expects an array.');
}
var len = arr.length;
if (len === 0) {
return [];
}
if (!fn) return arr[arr.length - 1];
if (isNumber(fn)) {
return arr.slice(-fn);
}
if (typeof fn === 'function') {
var val, i = 0;
while (len--) {
val = arr[i++];
if (fn(val, i, arr)) {
return val;
}
}
}
return [];
};
|
'use strict'
var should = require('should')
var path = require('path')
var generateApi = require('../../lib/commands/generateApi/generateApi')
var fs = require('fs')
var xml2js = require('xml2js')
describe('generateApi with headers', function () {
var options = {
source: path.join(__dirname, '/openapi_files/headers.yaml'),
destination: path.join(__dirname, '../../api_bundles'),
apiProxy: 'petStoreHeaders'
}
describe('generate', function (done) {
it('Correct OpenApi file should generate proxy', function (done) {
generateApi.generateApi(options.apiProxy, options, function (err, reply) {
should.equal(err, null)
done()
})
})
})
describe('Add header policy', function () {
it('Headers token policy should be generated', function (done) {
var filePath = path.join(options.destination, options.apiProxy + '/apiproxy/policies/add-headers-token.xml')
var file = fs.lstatSync(filePath)
should.equal(file.isFile(), true)
var fileData = fs.readFileSync(filePath)
var parser = new xml2js.Parser()
parser.parseString(fileData, function (err, result) {
should.equal(err, null)
result.should.have.property('AssignMessage')
result.should.have.property('AssignMessage').property('Set')
var headers = result.AssignMessage.Set[0].Headers[0]
// Check Header name and value
should.equal(headers.Header[0].$.name, 'x-token', 'x-token not found: ')
should.equal(headers.Header[0]._, 'random_token', 'x-token value not correct')
done()
})
})
it('Headers x-api-key policy should be generated', function (done) {
var filePath = path.join(options.destination, options.apiProxy + '/apiproxy/policies/add-headers-x-api-key.xml')
var file = fs.lstatSync(filePath)
should.equal(file.isFile(), true)
var fileData = fs.readFileSync(filePath)
var parser = new xml2js.Parser()
parser.parseString(fileData, function (err, result) {
should.equal(err, null)
result.should.have.property('AssignMessage')
result.should.have.property('AssignMessage').property('Set')
var headers = result.AssignMessage.Set[0].Headers[0]
// Check Header name and value
should.equal(headers.Header[0].$.name, 'x-api-key', 'x-api-key not found: ')
should.equal(headers.Header[0]._, 'random_api_key', 'x-api-key value not correct')
done()
})
})
it('Headers securit headers policy should be generated', function (done) {
var filePath = path.join(options.destination, options.apiProxy + '/apiproxy/policies/add-headers-security.xml')
var file = fs.lstatSync(filePath)
should.equal(file.isFile(), true)
var fileData = fs.readFileSync(filePath)
var parser = new xml2js.Parser()
parser.parseString(fileData, function (err, result) {
should.equal(err, null)
result.should.have.property('AssignMessage')
result.should.have.property('AssignMessage').property('Set')
var headers = result.AssignMessage.Set[0].Headers[0]
// Check Header name and value
should.equal(headers.Header[0].$.name, 'Strict-Transport-Security', 'Strict-Transport-Security not found: ')
should.equal(headers.Header[0]._, 'max-age=31536000; includeSubDomains; preload', 'value not correct')
should.equal(headers.Header[1].$.name, 'X-XSS-Protection', 'X-XSS-Protection header not found: ')
should.equal(headers.Header[1]._, '1; mode=block', 'value not correct')
should.equal(headers.Header[2].$.name, 'X-Content-Type-Options', 'X-Content-Type-Options header not found: ')
should.equal(headers.Header[2]._, 'nosniff', 'value not correct')
should.equal(headers.Header[3].$.name, 'X-Frame-Options', 'X-Frame-Options header not found: ')
should.equal(headers.Header[3]._, 'deny', 'value not correct')
done()
})
})
it('Target should contain header step in PreFlow', function (done) {
var filePath = path.join(options.destination, options.apiProxy, '/apiproxy/targets/default.xml')
var fileData = fs.readFileSync(filePath)
var parser = new xml2js.Parser()
parser.parseString(fileData, function (err, result) {
should.equal(err, null)
result.should.have.property('TargetEndpoint')
result.should.have.property('TargetEndpoint').property('PreFlow')
should.equal(result.TargetEndpoint.PreFlow[0].Request[0].Step[0].Name[0], 'Add AWS api key header', 'Add AWS api key header step in found in PreFlow')
should.equal(result.TargetEndpoint.PreFlow[0].Request[0].Step[1].Name[0], 'Add token header', 'Add token header step in found in PreFlow')
done()
})
})
it('Proxy should contain header step in PostFlow', function (done) {
var filePath = path.join(options.destination, options.apiProxy, '/apiproxy/proxies/default.xml')
var fileData = fs.readFileSync(filePath)
var parser = new xml2js.Parser()
parser.parseString(fileData, function (err, result) {
should.equal(err, null)
result.should.have.property('ProxyEndpoint')
result.should.have.property('ProxyEndpoint').property('PostFlow')
should.equal(result.ProxyEndpoint.PostFlow[0].Response[0].Step[0].Name[0], 'Add security headers', 'Add security headers step in found in PostFlow')
done()
})
})
})
})
|
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import responsivePropType from './responsivePropType';
import { handleBreakpoints } from './breakpoints';
function getPath(obj, path) {
if (!path || typeof path !== 'string') {
return null;
}
return path.split('.').reduce(function (acc, item) {
return acc && acc[item] ? acc[item] : null;
}, obj);
}
function style(options) {
var prop = options.prop,
_options$cssProperty = options.cssProperty,
cssProperty = _options$cssProperty === void 0 ? options.prop : _options$cssProperty,
themeKey = options.themeKey,
transform = options.transform;
var fn = function fn(props) {
if (props[prop] == null) {
return null;
}
var propValue = props[prop];
var theme = props.theme;
var themeMapping = getPath(theme, themeKey) || {};
var styleFromPropValue = function styleFromPropValue(propValueFinal) {
var value;
if (typeof themeMapping === 'function') {
value = themeMapping(propValueFinal);
} else if (Array.isArray(themeMapping)) {
value = themeMapping[propValueFinal] || propValueFinal;
} else {
value = getPath(themeMapping, propValueFinal) || propValueFinal;
if (transform) {
value = transform(value);
}
}
if (cssProperty === false) {
return value;
}
return _defineProperty({}, cssProperty, value);
};
return handleBreakpoints(props, propValue, styleFromPropValue);
};
fn.propTypes = process.env.NODE_ENV !== 'production' ? _defineProperty({}, prop, responsivePropType) : {};
fn.filterProps = [prop];
return fn;
}
export default style;
|
/*
The MIT License (MIT)
Copyright (c) 2017 Microsoft Corporation
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.
*/
"use strict"
var Base = require("./base"),
Constants = require("./constants");
var Regexes = Constants.RegularExpressions,
ResourceTypes = Constants.ResourceTypes;
//SCRIPT START
var Helper = Base.defineClass(
/**************************CONSTRUCTORS**************************/
undefined,
/************************INSTANCE MEMBERS************************/
undefined,
/*************************STATIC METHODS*************************/
{
isStringNullOrEmpty: function (inputString) {
//checks whether string is null, undefined, empty or only contains space
return !inputString || /^\s*$/.test(inputString);
},
trimSlashFromLeftAndRight: function (inputString) {
if (typeof inputString != 'string') {
throw "invalid input: input is not string";
}
return inputString.replace(Regexes.TrimLeftSlashes, "").replace(Regexes.TrimRightSlashes, "");
},
validateResourceId: function (resourceId) {
// if resourceId is not a string or is empty throw an error
if (typeof resourceId !== 'string' || this.isStringNullOrEmpty(resourceId)) {
throw "Resource Id must be a string and cannot be undefined, null or empty";
}
// if resourceId starts or ends with space throw an error
if (resourceId[resourceId.length - 1] == " ") {
throw "Resource Id cannot end with space";
}
// if resource id contains illegal characters throw an error
if (Regexes.IllegalResourceIdCharacters.test(resourceId)) {
throw "Illegal characters ['/', '\\', '?', '#'] cannot be used in resourceId";
}
return true;
},
getResourceIdFromPath: function(resourcePath) {
if (!resourcePath || typeof resourcePath !== "string") {
return null;
}
var trimmedPath = this.trimSlashFromLeftAndRight(resourcePath);
var pathSegments = trimmedPath.split('/');
//number of segments of a path must always be even
if (pathSegments.length % 2 !== 0) {
return null;
}
return pathSegments[pathSegments.length - 1];
}
}
);
//SCRIPT END
if (typeof exports !== "undefined") {
exports.Helper = Helper;
}
|
var nodemailer = require('../lib/nodemailer');
// Create a Direct transport object
var transport = nodemailer.createTransport("Direct", {debug: true});
console.log('Direct transport configured');
// Message object
var message = {
// sender info
from: 'Sender Name <sender@example.com>',
// Comma separated list of recipients
to: '"Receiver Name" <nodemailer@disposebox.com>',
// Subject of the message
subject: 'Nodemailer is unicode friendly ✔', //
// plaintext body
text: 'Hello to myself!',
// HTML body
html:'<p><b>Hello</b> to myself <img src="cid:note@node"/></p>'+
'<p>Here\'s a nyan cat for you as an embedded attachment:<br/><img src="cid:nyan@node"/></p>',
// An array of attachments
attachments:[
// String attachment
{
fileName: 'notes.txt',
contents: 'Some notes about this e-mail',
contentType: 'text/plain' // optional, would be detected from the filename
},
// Binary Buffer attachment
{
fileName: 'image.png',
contents: new Buffer('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
'//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC', 'base64'),
cid: 'note@node' // should be as unique as possible
},
// File Stream attachment
{
fileName: 'nyan cat ✔.gif',
filePath: __dirname+"/nyan.gif",
cid: 'nyan@node' // should be as unique as possible
}
]
};
console.log('Sending Mail');
transport.sendMail(message, function(error, response){
if(error){
console.log('Error occured');
console.log(error.message);
return;
}else{
console.log(response);
console.log('Message sent successfully!');
}
});
|
'use strict';
const _ = require('lodash');
const plugin = require('../index');
/**
* This module exports a function that enrich the interactive command line and return a promise
* @returns {Promise} - a promise that resolve when the operation is done
*/
module.exports = (icli) => {
// Build the lists of choices
const choicesLists = getChoices();
const config = {
section: 'Cloud Formation plugin',
cmd: 'deploy-cf-templates',
description: 'deploy cloud formation templates',
parameters: [{
cmdSpec: '[template-identifiers...]',
type: 'checkbox',
choices: choicesLists.templateIdentifiers,
question: {
message: 'Which Template do you want to deploy?',
when: (answers, cmdParameterValues) => {
return cmdParameterValues.templateIdentifiers.length === 0 && !cmdParameterValues.all;
}
}
}, {
cmdSpec: '--all',
description: 'deploy all templates of the project',
type: 'boolean',
}, {
cmdSpec: '-r, --region <region>',
description: 'select the AWS region',
type: 'list',
choices: choicesLists.region,
validationMsgLabel: 'AWS region',
question: {
message: 'On which AWS region do you want to deploy?'
}
}, {
cmdSpec: '-e, --environment <environment>',
description: 'select the environment',
type: 'input',
default: 'DEV',
question: {
message: 'On which environment do you want to deploy?',
when: (answers, cmdParameterValues) => {
return cmdParameterValues['environment'] === undefined && plugin.myrmex.getConfig('environment') === undefined;
}
}
}
],
execute: executeCommand
};
/**
* Create the command and the prompt
*/
return icli.createSubCommand(config);
/**
* Build the choices for "list" and "checkbox" parameters
* @returns {Object} - collection of lists of choices for "list" and "checkbox" parameters
*/
function getChoices() {
// First, retrieve possible values for the api-identifiers parameter
return {
templateIdentifiers: () => {
return plugin.loadTemplates()
.then(templates => {
if (!templates.length) {
icli.print(icli.format.error('This project does not contain any Cloud Fornation template.'));
process.exit(1);
}
return _.map(templates, template => {
return {
value: template.getIdentifier(),
name: icli.format.info(template.getIdentifier())
};
});
});
},
region: [
{
value: 'us-east-1',
name: icli.format.info('us-east-1') + ' US East (N. Virginia)',
short: 'us-east-1 - US East (N. Virginia)'
}, {
value: 'us-west-2',
name: icli.format.info('us-west-2') + ' US West (Oregon)',
short: 'us-west-2 - US West (Oregon)'
}, {
value: 'eu-west-1',
name: icli.format.info('eu-west-1') + ' EU (Ireland)',
short: 'eu-west-1 - EU (Ireland)'
}, {
value: 'eu-central-1',
name: icli.format.info('eu-central-1') + ' EU (Frankfurt)',
short: 'eu-central-1 - EU (Frankfurt)'
}, {
value: 'ap-northeast-1',
name: icli.format.info('ap-northeast-1') + ' Asia Pacific (Tokyo)',
short: 'ap-northeast-1 - Asia Pacific (Tokyo)'
}, {
value: 'ap-southeast-1',
name: icli.format.info('ap-southeast-2') + ' Asia Pacific (Sydney)',
short: 'ap-southeast-2 - Asia Pacific (Sydney)'
}
]
};
}
/**
* Execute the deployment
* @param {Object} parameters - the parameters provided in the command and in the prompt
* @returns {Promise<null>} - The execution stops here
*/
function executeCommand(parameters) {
if (parameters.environment === undefined) { parameters.environment = plugin.myrmex.getConfig('environment'); }
return plugin.loadTemplates()
.then(templates => {
// If the parameter "all" is set, we deploy all templates
if (!parameters.all) {
templates = _.filter(templates, template => { return parameters.templateIdentifiers.indexOf(template.getIdentifier()) !== -1; });
}
icli.print();
icli.print('Deploying ' + icli.format.info(templates.length) + ' template(s):');
icli.print(' AWS region: ' + icli.format.info(parameters.region));
icli.print(' Environement: ' + icli.format.info(parameters.environment || 'no environment specified'));
icli.print();
icli.print('This operation may last a little');
return Promise.map(templates, template => {
const context = {
environment: parameters.environment
};
return template.deploy(parameters.region, context);
});
})
.then(reports => {
console.log(reports);
})
.catch(e => {
if (e.code === 'AccessDeniedException' && e.cause && e.cause.message) {
icli.print('\n ' + icli.format.error('Insufficient permissions to perform the action\n'));
icli.print('The IAM user/role you are using to perform this action does not have sufficient permissions.\n');
icli.print(e.cause.message + '\n');
icli.print('Please update the policies of the user/role before trying again.\n');
process.exit(1);
}
throw e;
});
}
};
|
// Tour Image Carousel JS
$.get("resources/templates/_carouselPrototype.html", function (data) {
$.carouselPrototype = data;
});
$.get("resources/templates/_loungeCarousel.html", function (data) {
$.lounge = data;
});
$.get("resources/templates/_softwareCarousel.html", function (data) {
$.software = data;
});
$.get("resources/templates/_libraryCarousel.html", function (data) {
$.library = data;
});
$.get("resources/templates/_userCarousel.html", function (data) {
$.user = data;
});
$.get("resources/templates/_conferenceCarousel.html", function (data) {
$.conference = data;
});
$.get("resources/templates/_serverCarousel.html", function (data) {
$.server = data;
});
$.get("resources/templates/_projectCarousel.html", function (data) {
$.project = data;
});
$.get("resources/templates/_dormCarousel.html", function (data) {
$.dorm = data;
});
// Switch image in carousel by room
// Param: room - string - room name to switch to
// Return: None
function switchImage(room){
var imageHTML;
var containerElement = $('#carouselImages');
$('.tourTextActive').hide();
$('.tourTextActive').removeClass('tourTextActive');
if(room == "server"){
imageHTML = $.server;
// Show Photosphere container
containerElement = $('#photosphere-container');
containerElement.show();
// Photosphere, remove carousel
// Part of the workaround for the carousel bug (see below)
$('.carousel').remove();
} else {
// Hide photosphere container
$('#photosphere-container').hide();
if(room == "lounge"){
imageHTML = $.lounge;
}
else if(room == "software"){
imageHTML = $.software;
}
else if(room == "library"){
imageHTML = $.library;
}
else if(room == "user"){
imageHTML = $.user;
}
else if(room == "conference"){
imageHTML = $.conference;
}
else if(room == "project"){
imageHTML = $.project;
}
else if(room == "dorm"){
imageHTML = $.dorm;
}
}
$('.csh-active').removeClass('csh-active');
$("#"+room+"Text").show();
$("#"+room+"Text").addClass("tourTextActive");
// If the carousel doesn't exist in the DOM, add it
// Workaround for this bug: https://github.com/angular-ui/bootstrap/issues/1513
if (room !== 'server' && $('.carousel').length == 0) {
$('.image-container').append($.carouselPrototype.replace('{{images}}', imageHTML));
$('.carousel').carousel();
} else {
containerElement.html(imageHTML);
}
$('#'+room).addClass('csh-active');
}
|
module('lively.tests.NetworkTests').requires('lively.TestFramework').toRun(function() {
TestCase.subclass('lively.tests.NetworkTests.URLTest', {
testEnsureAbsoluteURL1: function() {
var urlString = 'http://livelykernel.sunlabs.com/repository/lively-wiki/index.xhtml';
var result = URL.ensureAbsoluteURL(urlString);
this.assertEquals(urlString, result.toString());
urlString = 'http://localhost/lively/index.xhtml';
result = URL.ensureAbsoluteURL(urlString);
this.assertEquals(urlString, result.toString());
},
testEnsureAbsoluteURL2: function() {
var urlString = 'index.xhtml';
var result = URL.ensureAbsoluteURL(urlString);
var expected = URL.source.getDirectory().toString() + urlString;
this.assertEquals(expected, result.toString());
},
testEnsureAbsoluteURL3: function() {
var urlString = 'bla/http/blupf.xhtml';
var result = URL.ensureAbsoluteURL(urlString);
var expected = URL.source.getDirectory().toString() + urlString;
this.assertEquals(expected, result.toString());
},
testRemoveRelativeParts: function() {
var urlString = 'http://foo.com/bar/../baz/';
var result = new URL(urlString).withRelativePartsResolved();
var expected = 'http://foo.com/baz/';
this.assertEquals(expected, result.toString());
},
testRemoveRelativeParts2: function() {
var urlString = 'http://localhost/webwerkstatt/projects/HTML5/presentation100720/../../../';
var result = new URL(urlString).withRelativePartsResolved();
var expected = 'http://localhost/webwerkstatt/';
this.assertEquals(expected, result.toString());
},
testRemoveRelativeParts3: function() {
var urlString = 'http://localhost/foo//bar';
var result = new URL(urlString).withRelativePartsResolved();
var expected = 'http://localhost/foo/bar';
this.assertEquals(expected, result.toString());
},
testRemoveRelativeParts4: function() {
var urlString = 'http://localhost/foo/./bar';
var result = new URL(urlString).withRelativePartsResolved();
var expected = 'http://localhost/foo/bar';
this.assertEquals(expected, result.toString());
},
testRelativePathFrom1: function() {
var expected = 'test/bar/baz';
var url1 = new URL('http://www.foo.org/test/bar/baz');
var url2 = new URL('http://www.foo.org/');
var result = url1.relativePathFrom(url2);
this.assertEquals(expected, result.toString());
url2 = new URL('http://foo.org/');
result = url1.relativePathFrom(url2);
this.assertEquals(expected, result.toString());
try {
url2 = new URL('http://foo.com/');
result = url1.relativePathFrom(url2);
} catch (e) { return; }
this.assert(false, 'error expected');
},
testRelativePathFrom2: function() {
var expected = '../test/bar/baz';
var url1 = new URL('http://www.foo.org/test/bar/baz');
var url2 = new URL('http://www.foo.org/bar/');
var result = url1.relativePathFrom(url2);
this.assertEquals(expected, result.toString());
expected = '../../bar/';
result = url2.relativePathFrom(url1);
this.assertEquals(expected, result.toString());
},
testRelativePathFrom3: function() {
var url1 = new URL("http://northwestern.itsapirateslife.net:9001/core/lively/bootstrap.js"),
url2 = new URL("http://northwestern.itsapirateslife.net:9001//questions/Worlds/unknown_user_1434404507629_original.html?autosave=true"),
result = url1.relativePathFrom(url2),
expected = "../../core/lively/bootstrap.js";
this.assertEquals(expected, result);
},
testRelativePathFrom3Identity: function() {
var url = new URL('http://www.foo.org/bar/'),
result = url.relativePathFrom(url);
this.assertEquals('', result.toString());
},
testMakeProxy: function() {
var originalProxy = URL.proxy;
URL.proxy = new URL('http://foo.com/proxy/');
try { // FIXME
// normal behavior
var result = URL.makeProxied('http://bar.com/');
var expected = 'http://foo.com/proxy/bar.com/';
this.assertEquals(expected, result.toString());
// normal behavior with port
result = URL.makeProxied('http://bar.com:1234/');
expected = 'http://foo.com/proxy/bar.com:1234/';
this.assertEquals(expected, result.toString());
// normal behavior, same URL and another port
result = URL.makeProxied('http://foo.com:1234/');
expected = 'http://foo.com/proxy/foo.com:1234/';
this.assertEquals(expected, result.toString());
// don't proxy yourself
result = URL.makeProxied(URL.proxy);
this.assertEquals(URL.proxy.toString(), result.toString());
// don't proxy yourself 2
result = URL.makeProxied('http://www.foo.com/proxy/');
this.assertEquals(URL.proxy.toString(), result.toString());
} finally {
URL.proxy = originalProxy;
}
},
testAsDirectory: function() {
var url = new URL('http://foo.com/bar/');
this.assertEquals('http://foo.com/bar/', url.asDirectory().toString());
url = new URL('http://foo.com/bar');
this.assertEquals('http://foo.com/bar/', url.asDirectory().toString());
url = new URL('http://foo.com/bar?foo=bar');
this.assertEquals('http://foo.com/bar/', url.asDirectory().toString());
},
testIsIn: function() {
var url1, url2;
url1 = new URL('http://foo.com/bar/');
url2 = new URL('http://foo.com/bar/baz');
this.assert(url2.isIn(url1), 'isIn not woring');
url1 = new URL('http://bar.com/bar/');
url2 = new URL('http://www.foo.com/bar/baz');
this.assert(!url2.isIn(url1), 'isIn does not recognize differing URLS');
url1 = new URL('http://foo.com/bar/');
url2 = new URL('http://www.foo.com/bar/baz');
this.assert(url2.isIn(url1), 'www url not recognized');
},
testAsModuleName: function() {
var url = URL.codeBase.withFilename('foo/bar/Baz.js');
this.assertEquals('foo.bar.Baz', url.asModuleName());
},
testExtension: function() {
var url = URL.codeBase.withFilename('foo/bar/Baz.js');
this.assertEquals('js', url.extension());
url = URL.codeBase.withFilename('foo');
this.assertEquals('', url.extension());
url = URL.codeBase.withFilename('foo/');
this.assertEquals('', url.extension());
},
testParseHash: function() {
var url = new URL('http://foo.bar/baz#hello world=34&test=foo - 1');
this.assertEqualState({"hello world": "34", test: "foo - 1"}, url.parseHash());
}
});
TestCase.subclass('lively.tests.NetworkTests.WebResourceTest',
'testing', {
testInitWithURL: function() {
var url = new URL('http://www.foo.com');
url.port = 1234;
var sut = new WebResource(url);
this.assert(url.eq(sut.getURL()), 'Given URL and used URL are not the same');
},
testPutWithRequiredRev: function() {
var url = URL.source.getDirectory().withFilename('testPut'),
localPath = url.relativePathFrom(URL.root),
webR = url.asWebResource();
webR.createXMLHTTPRequest = function(method) {return {request: Functions.Null}}
webR.put('foo', null, {requiredSVNRevision: 23});
this.assertEquals('(["23//' + localPath + '"])', webR.requestHeaders["If"]);
},
testPutWithUnmodifiedSince: function() {
var url = URL.source.getDirectory().withFilename('testPut'),
localPath = url.relativePathFrom(URL.root),
webR = url.asWebResource(),
now = new Date();
webR.createXMLHTTPRequest = function(method) {return {request: Functions.Null}};
webR.put('foo', null, {ifUnmodifiedSince: now});
this.assertEquals(now.toGMTString(), webR.requestHeaders["if-unmodified-since"]);
this.assert(!webR.requestHeaders["If"], 'If header present');
// let it also work with strings
var otherDate = "Sat, 24 Nov 2012 08:10:12 GMT";
webR.put('foo', null, {ifUnmodifiedSince: otherDate});
this.assertEquals(otherDate, webR.requestHeaders["if-unmodified-since"]);
}
});
TestCase.subclass('lively.tests.NetworkTests.ActiveWebResourceTest',
'settings', {
shouldRun: !Config.serverInvokedTest
},
'helper', {
plainTextString: 'this is a test\nfoo\nbar',
xmlString: ['<foo xmlns="http:\/\/www.lively-kernel.org\/fooNS" xmlns:bazNS="http:\/\/www.lively-kernel.org\/fooNS">',
'<bar name="test1"/>',
'<bar name="test2">',
' <bazNS:baz name="test3"/>',
'</bar>',
'</foo>'].join('\n'),
writeFile: function(url, content) {
new WebResource(url).put(content);
},
removeFile: function(url) {
new WebResource(url).del();
},
isWebDAVEnvironment: function() {
return URL.source.normalizedHostname() !== 'localhost';
}
},
'running', {
setUp: function($super) {
$super();
var url = URL.source.getDirectory().withFilename('WebResourceTestDir/');
this.dir = new WebResource(url);
if (!this.dir.exists()) this.dir.create();
this.plainTextFileURL = url.withFilename('TextFileForWebResourceTest.txt');
this.xmlFileURL = url.withFilename('XMLFileForWebResourceTest.xml');
this.writeFile(this.plainTextFileURL, this.plainTextString);
this.writeFile(this.xmlFileURL, this.xmlString);
},
tearDown: function($super) {
$super();
this.dir.del();
}
},
'testing', {
testGet: function() {
var sut = new WebResource(this.plainTextFileURL);
this.assertEquals(this.plainTextString, sut.get().content);
this.assert(sut.status.isSuccess());
var resultXML = new WebResource(this.xmlFileURL).get().contentDocument;
this.assertEquals(this.xmlString, Exporter.stringify(resultXML));
},
testPut: function() {
var sut = new WebResource(this.plainTextFileURL);
sut.put('test');
this.assert(sut.status.isSuccess());
this.assertEquals('test', sut.get().content);
},
testDel: function() {
var sut = new WebResource(this.plainTextFileURL);
sut.del();
this.assert(sut.status.isSuccess());
this.assert(!sut.get().isExisting);
},
testSubElements: function() {
var subDir = new WebResource(this.dir.getURL().withFilename('foo/'));
subDir.create();
this.dir.getSubElements();
this.assertEquals(1, this.dir.subCollections.length);
this.assertEquals(2, this.dir.subDocuments.length);
},
testExists: function() {
var sut = new WebResource(this.plainTextFileURL);
sut.get();
this.assert(sut.status.isSuccess());
this.assert(sut.isExisting);
this.assert(sut.exists());
sut = new WebResource(this.plainTextFileURL + 'abc');
this.assert(!sut.exists());
},
testCopy: function() {
var url2 = this.plainTextFileURL.withFilename('copiedFile.txt'),
other = new WebResource(url2),
sut = new WebResource(this.plainTextFileURL);
sut.copyTo(url2);
this.assert(sut.status.isSuccess());
this.assert(other.exists());
this.assertEquals(sut.get().content, other.get().content);
},
testCopyAndGetVersion: function() {
if (!this.isWebDAVEnvironment()) return;
var url2 = this.plainTextFileURL.withFilename('copiedFile.txt'),
other = new WebResource(url2),
sut = new WebResource(this.plainTextFileURL);
sut.copyTo(url2);
var versions = other.getVersions().versions;
this.assertEquals(2, versions.length);
this.assert(versions[0].rev > versions[1].rev, 'second not the older verions');
this.assertEquals(sut.get().content, other.get(versions[1].rev).content);
},
testGetVersions: function() {
if (!this.isWebDAVEnvironment()) return;
var sut = new WebResource(this.plainTextFileURL);
sut.getVersions();
this.assert(sut.headRevision);
this.assertEquals(1, sut.versions.length);
},
testGetWithVersion: function() {
if (!this.isWebDAVEnvironment()) return;
this.writeFile(this.plainTextFileURL, 'new version of file');
var sut = new WebResource(this.plainTextFileURL);
var versions = sut.getVersions().versions;
this.assertEquals(2, versions.length);
var rev = versions[0].rev;
this.assert(this.plainTextString, sut.get(rev).content);
},
testGetHeadRevision: function() {
if (!this.isWebDAVEnvironment()) return;
var sut = new WebResource(this.plainTextFileURL);
var rev1 = sut.getHeadRevision().headRevision;
sut.put('new version of file');
var rev2 = sut.getHeadRevision().headRevision;
this.assert(rev1< rev2);
},
testGetResponseHeaders: function() {
var sut = new WebResource(this.plainTextFileURL);
sut.get();
this.assertEquals(typeof sut.responseHeaders, 'object', 'Response headers were not defined.');
var contentType = sut.responseHeaders['content-type'];
if (contentType) contentType = contentType.split(';')[0].trim(); // strip parameter
this.assertEquals(contentType, 'text/plain', 'No response header "Content-Type" with value "text/plain" was found!');
},
testEnsureExistance: function() {
var url = this.dir.getURL().withFilename('foo/bar/baz/'),
webR = new WebResource(url);
webR.ensureExistance();
this.assert(webR.exists(), 'ensure existance did not work');
}
});
});
|
Package.describe({
name: 'gsma-3g',
version: '0.0.1',
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.3');
api.use(['widget', 'underscore', 'country-info', 'momentjs:moment', 'gsma-data']);
api.use(['templating', 'epoch'], 'client');
api.addFiles('gsma.js');
api.addFiles([
'client/info.html',
'client/settings.html',
'client/settings.js',
'client/widget.html',
'client/widget.js',
'client/widget.css'
], 'client');
api.export('GSMA3G');
});
|
/*!
* jQuery JavaScript Library v2.1.0 -dimensions,-effects,-effects/Tween,-effects/animatedSelector,-event-alias
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-09-28T03:35Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// 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+
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var trim = "".trim;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.0 -dimensions,-effects,-effects/Tween,-effects/animatedSelector,-event-alias",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return 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
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return just the object
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( 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] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return obj - parseFloat( obj ) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// 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;
},
trim: function( text ) {
return text == null ? "" : trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// 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 new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return 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 tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.16
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-01-13
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
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 hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select t=''><option selected=''></option></select>";
// Support: IE8, Opera 10-12
// Nothing should be selected when empty strings follow ^= or $= or *=
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + 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 = rnative.test( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[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 (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
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;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// 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;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// 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 );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
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 oldCache, outerCache,
newCache = [ 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 ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (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;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
}
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// 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 indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// 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 = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
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 data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) );
// #11217 - WebKit loses check when the name is after the checked attribute
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
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 process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// 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 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;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
// Support: Android < 4.0
src.defaultPrevented === undefined &&
src.getPreventDefault && src.getPreventDefault() ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/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 = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.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;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.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 );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
});
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (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 !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;" +
"-moz-box-sizing:content-box;box-sizing:content-box",
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;" +
"margin-top:1px";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" +
"position:absolute;top:1%";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
jQuery.extend(support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
// Clean up the div for other support tests.
div.innerHTML = "";
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.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;
};
var
// 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]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
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[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 setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.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 &&
( 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";
}
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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": 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": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !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 ) {
// Support: Chrome, Safari
// Setting style to blank string required to delete "style: x !important;"
style[ name ] = "";
style[ name ] = value;
}
} 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 val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// 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;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( 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 + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( 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 + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( 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 ? "" : data_priv.get( 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;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
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 ];
// IE6-9 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
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* 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 jQuery.ajaxPrefilter and jQuery.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( rnotwhite ) || [];
if ( jQuery.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;
jQuery.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 key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// 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
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else 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.unshift( tmp[ 1 ] );
}
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 };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.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",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.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, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.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 transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.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 (prefilters might expect it)
// 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 = jQuery.trim( s.dataType || "*" ).toLowerCase().match( 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 = jQuery.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 && jQuery.active++ === 0 ) {
jQuery.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 += ( 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_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.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;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// 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 ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.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 ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = callback("abort");
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( options.hasContent && options.data || null );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.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 = jQuery.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 += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.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 && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// 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
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.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 ) {
jQuery.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
jQuery("<div>").append( jQuery.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;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// 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
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = require('react');
var StylePropable = require('../mixins/style-propable');
var LinkMenuItem = React.createClass({
displayName: 'LinkMenuItem',
mixins: [StylePropable],
contextTypes: {
muiTheme: React.PropTypes.object
},
propTypes: {
index: React.PropTypes.number.isRequired,
payload: React.PropTypes.string.isRequired,
text: React.PropTypes.string.isRequired,
target: React.PropTypes.string,
disabled: React.PropTypes.bool,
className: React.PropTypes.string },
getDefaultProps: function getDefaultProps() {
return {
disabled: false
};
},
getInitialState: function getInitialState() {
return {
hovered: false
};
},
getTheme: function getTheme() {
return this.context.muiTheme.component.menuItem;
},
getStyles: function getStyles() {
var style = {
root: {
userSelect: 'none',
cursor: 'pointer',
display: 'block',
lineHeight: this.getTheme().height + 'px',
paddingLeft: this.getTheme().padding,
paddingRight: this.getTheme().padding
},
rootWhenHovered: {
backgroundColor: this.getTheme().hoverColor
},
rootWhenSelected: {
color: this.getTheme().selectedTextColor
},
rootWhenDisabled: {
cursor: 'default',
color: this.context.muiTheme.palette.disabledColor
}
};
return style;
},
render: function render() {
var onClickHandler = this.props.disabled ? this._stopLink : undefined;
// Prevent context menu 'Open In New Tab/Window'
var linkAttribute = this.props.disabled ? 'data-href' : 'href';
var link = {};
link[linkAttribute] = this.props.payload;
var styles = this.getStyles();
var linkStyles = this.mergeAndPrefix(styles.root, this.props.selected && styles.rootWhenSelected, this.state.hovered && !this.props.disabled && styles.rootWhenHovered, this.props.style, this.props.disabled && styles.rootWhenDisabled);
return React.createElement(
'a',
_extends({
key: this.props.index,
target: this.props.target,
style: linkStyles }, link, {
className: this.props.className,
onClick: onClickHandler,
onMouseOver: this._handleMouseOver,
onMouseOut: this._handleMouseOut }),
this.props.text
);
},
_stopLink: function _stopLink(event) {
event.preventDefault();
},
_handleMouseOver: function _handleMouseOver(e) {
this.setState({ hovered: true });
if (!this.props.disabled && this.props.onMouseOver) this.props.onMouseOver(e);
},
_handleMouseOut: function _handleMouseOut(e) {
this.setState({ hovered: false });
if (!this.props.disabled && this.props.onMouseOut) this.props.onMouseOut(e);
}
});
module.exports = LinkMenuItem;
|
var constants = require('./constants.js');
var Vector2 = require('ks-vector').Vector2;
var RigidBody = require('./rigid-body.js');
var Contact = require('./contact.js');
var Geometry = require('./geometry.js');
var AABB = require('./aabb.js');
var Ball;
var Matrix = require('./matrix23.js');
var Rectangle = function(mass, x, y, wid, hig) {
RigidBody.call(this, mass, wid, hig, new Vector2(x + wid/2, y + hig/2), new Vector2(0, 0));
Ball = require('./ball.js');
this.halfExtents = new Vector2( this.width/2, this.height/2 );
this.halfExtentsMinus = new Vector2( -this.width/2, -this.height/2);
this.localSpacePoints = [
new Vector2( this.halfExtents.x, -this.halfExtents.y),
new Vector2( -this.halfExtents.x, -this.halfExtents.y),
new Vector2( -this.halfExtents.x, this.halfExtents.y),
new Vector2( this.halfExtents.x, this.halfExtents.y)
];
this.localSpaceNormals = [];
for(var ii = 0; ii < this.localSpacePoints.length; ii++){
var nextNum = (ii + 1) % this.localSpacePoints.length;
this.localSpaceNormals[ii] = this.localSpacePoints[nextNum].copy().subtract(this.localSpacePoints[ii]).getNormal().perp();
}
// calculate the inverse inertia tensor
if(this.invMass > 0){
var I = this.mass * (this.width * this.width + this.height * this.height) / 12;
this.invI = 1 / I;
}else{
this.invI = 0;
}
}
Rectangle.prototype = Object.create(RigidBody.prototype);
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.update = function(dt) {
//this.theta += this.thetaVelocity;
//this.matrix.set(this.theta, 0, 0);
RigidBody.prototype.setGravity.call(this);
RigidBody.prototype.update.call(this, dt);
}
Rectangle.prototype.draw = function(ctx) {
//console.log(this.pos.y);
//console.log(this.pos.x);
ctx.save();
ctx.strokeStyle = "#000000";
ctx.beginPath();
ctx.translate(this.pos.x, this.pos.y);
ctx.rotate(this.angle);
ctx.strokeRect(-this.width/2, -this.height/2, this.width, this.height);
ctx.restore();
//this.debugDraw(ctx);
};
Rectangle.prototype.debugDraw = function(ctx) {
/**
ctx.fillStyle = "#ff0000";
ctx.beginPath();
ctx.arc(this.clamedP.x, this.clamedP.y, 2, 0, 2 * Math.PI);
ctx.fill()
ctx.strokeStyle = "#0000ff";
ctx.beginPath();
ctx.moveTo(this.clamedP.x, this.clamedP.y);
ctx.lineTo(this.clamedP.x + this.d.x, this.clamedP.y + this.d.y);
ctx.stroke();
ctx.fillStyle = "#00ff00";
ctx.beginPath();
ctx.arc(this.pb.x, this.pb.y, 2, 0, 2 * Math.PI);
ctx.fill();
*/
}
Rectangle.prototype.getClosestPoints = function(rBody) {
var contacts = [];
var rectangelA = this;
if( rBody instanceof Ball ){
var ballB = rBody;
var delta = ballB.pos.copy().subtract(rectangelA.pos);
var rotatedVector = delta.rotate(-this.angle);
var dClamped = rotatedVector.clamp(this.halfExtentsMinus, this.halfExtents);
var clamped = dClamped.rotate(this.angle);
var clamedP = this.pos.copy().add(clamped);
var d = new Vector2(ballB.pos.x - clamedP.x, ballB.pos.y - clamedP.y);
var n = d.getNormal();
var pa = clamedP;
var pb = ballB.pos.copy().subtractMultipledVector(ballB.rad, n);
//console.log(pb.x + ", " + pb.y);
var dist = d.getLength() - ballB.rad;
this.clamedP = clamedP;
this.d = d;
this.pb =pb;
contacts.push(new Contact( rectangelA, ballB, pa, pb, n, dist ));
}else if(rBody instanceof Rectangle){
var bRectangle = rBody
return Geometry.rectRectClosestPoints(this, bRectangle);
}else if(rBody instanceof Plane){
/*
var rectangelB = rBody;
var worldP = [];
var worldD = [];
for( var ii = 0; ii < this.localSpacePoints.length; ii++ ){
var worldVector = this.matrix.transformBy(this.localSpacePoints[ii].copy());
worldD.push(worldVector) ;
}
this.worldD = worldD; */
}
return contacts;
};
Rectangle.prototype.generateMotionAABB = function(dt) {
// get bounds now
var boundsNow = AABB.buildAABB( this.localSpacePoints, this.matrix );
var matrixNextFrame = new Matrix();
matrixNextFrame.setAngleAndPos(this.angle + this.angularVel * dt, this.pos.copy().addMultipledVector(dt, this.vel) );
var boundsNextFrame = AABB.buildAABB(this.localSpacePoints, matrixNextFrame);
this.motionBounds = new AABB();
this.motionBounds.setAABB( boundsNow, boundsNextFrame );
};
/**
* @param {Vector2} direction
*/
Rectangle.prototype.getSupportVertices = function(direction) {
// rotate into rectangle space
var v = this.matrix.RotateIntoSpaceOf(direction.copy());
// get axis bits
var closestI = -1;
var secondClosestI = -1;
var closestD = -99999;
var secondClosestD = -99999;
// first support
for(var ii = 0; ii < this.localSpacePoints.length; ii++){
var d = v.copy().dotProduct(this.localSpacePoints[ii]);
if(d > closestD){
closestD = d;
closestI = ii;
}
}
// second support
var num = 1;
for(var ii = 0; ii < this.localSpacePoints.length; ii++){
var d = v.copy().dotProduct(this.localSpacePoints[ii]);
if(ii != closestI && d == closestD){
secondClosestD = d;
secondClosestI = ii;
num++;
break;
}
}
// closest vertices
var spa = [];
spa[0] = {mI: closestI, mV: this.matrix.transformBy( this.localSpacePoints[closestI] )}
if(num > 1){
spa[1] = {mI: secondClosestI, mV: this.matrix.transformBy( this.localSpacePoints[secondClosestI] )};
}
return spa;
}
/**
* @param {Number} v
* @param {Vector2} n
*/
Rectangle.prototype.getSecondSupport = function( v, n) {
var va = this.getWorldSpacePoint( (v - 1 + this.localSpacePoints.length)%this.localSpacePoints.length );
var vb = this.getWorldSpacePoint( v );
var vc = this.getWorldSpacePoint( (v+1)%this.localSpacePoints.length );
var na = vb.copy().subtract(va).perp().getNormal();
var nc = vc.copy().subtract(vb).perp().getNormal();
var support = [];
if(na.dotProduct(n) < nc.dotProduct(n)){
support[0] = va;
support[1] = vb;
}else{
support[0] = vb;
support[1] = vc;
}
return support;
};
/**
* @param {Number} ii
*/
Rectangle.prototype.getWorldSpacePoint = function(ii) {
return this.matrix.transformBy(this.localSpacePoints[ii]);
}
/**
* @param {Number} ii
*/
Rectangle.prototype.getWorldSpaceNormal = function(ii) {
return this.matrix.rotateBy(this.localSpaceNormals[ii]);
}
/**
* @param {context}
*/
Rectangle.prototype.drawAABB = function(ctx) {
//console.log(this.motionBounds);
ctx.fillStyle = "#ff0000";
ctx.beginPath();
ctx.arc( this.motionBounds.mCenter.x, this.motionBounds.mCenter.y, 2, 0, 2 * Math.PI );
ctx.fill();
var startVec = new Vector2( this.motionBounds.mCenter.x - this.motionBounds.mHalfExtents.x, this.motionBounds.mCenter.y - this.motionBounds.mHalfExtents.y );
var endVec = new Vector2( this.motionBounds.mCenter.x + this.motionBounds.mHalfExtents.x, this.motionBounds.mCenter.y + this.motionBounds.mHalfExtents.y );
ctx.strokeStyle = "#0000ff";
ctx.beginPath();
ctx.moveTo(startVec.x, startVec.y);
ctx.lineTo( endVec.x, endVec.y);
ctx.stroke();
}
module.exports = Rectangle;
|
// Vex Flow
// Mohit Muthanna <mohit@muthanna.com>
//
// A rendering context for SVG.
//
// Copyright Mohit Muthanna 2015
// @author Gregory Ristow (2015)
/** @constructor */
Vex.Flow.SVGContext = (function() {
function SVGContext(element) {
if (arguments.length > 0) this.init(element);
}
// The measureTextCache is used in Javascript runtimes where
// there is no proper DOM support for SVG bounding boxes. This
// is currently only useful in the NodeJS visual regression tests.
SVGContext.measureTextCache = {};
// If enabled, will start collecting and indexing getBBox data by
// font name, size, weight, and style. This should be disabled by
// default (or you will find yourself slowly leaking RAM.)
SVGContext.collectMeasurements = false;
// If enabled, will warn if there are new getBBox requests that are
// not in the cache. This is enabled in the VexFlow tests, and if you
// see a warning on the console, you will need to enable collectMeasurements
// above, then update measureTextCache with the new values. See
// tests/measure_text_cache.js for instructions on how to do this.
SVGContext.validateMeasurement = false;
SVGContext.addPrefix = Vex.Prefix;
SVGContext.prototype = {
init: function(element) {
// element is the parent DOM object
this.element = element;
// Create the SVG in the SVG namespace:
this.svgNS = "http://www.w3.org/2000/svg";
var svg = this.create("svg");
// Add it to the canvas:
this.element.appendChild(svg);
// Point to it:
this.svg = svg;
this.groups = [this.svg]; // Create the group stack
this.parent = this.svg;
this.path = "";
this.pen = {x: 0, y: 0};
this.lineWidth = 1.0;
this.state = {
scale: { x: 1, y: 1 },
"font-family": "Arial",
"font-size": "8pt",
"font-weight": "normal"
};
this.attributes = {
"stroke-width": 0.3,
"fill": "black",
"stroke": "black",
"font-family": "Arial",
"font-size" : "10pt",
"font-weight" : "normal",
"font-style" : "normal"
};
this.background_attributes = {
"stroke-width": 0,
"fill": "white",
"stroke": "white",
"font-family": "Arial",
"font-size" : "10pt",
"font-weight": "normal",
"font-style": "normal"
};
this.shadow_attributes = {
width: 0,
color: "black"
};
this.state_stack= [];
// Test for Internet Explorer
this.iePolyfill();
},
create: function(svgElementType) {
return document.createElementNS(this.svgNS, svgElementType);
},
// Allow grouping elements in containers for interactivity.
openGroup: function(cls, id, attrs) {
var group = this.create("g");
this.groups.push(group);
this.parent.appendChild(group);
this.parent = group;
if (cls) group.setAttribute("class", SVGContext.addPrefix(cls));
if (id) group.setAttribute("id", SVGContext.addPrefix(id));
if (attrs && attrs.pointerBBox) {
group.setAttribute("pointer-events", "bounding-box");
}
return group;
},
closeGroup: function() {
var group = this.groups.pop();
this.parent = this.groups[this.groups.length - 1];
},
add: function(elem) {
this.parent.appendChild(elem);
},
// Tests if the browser is Internet Explorer; if it is,
// we do some tricks to improve text layout. See the
// note at ieMeasureTextFix() for details.
iePolyfill: function() {
if (typeof(navigator) !== "undefined") {
this.ie = ( /MSIE 9/i.test(navigator.userAgent) ||
/MSIE 10/i.test(navigator.userAgent) ||
/rv:11\.0/i.test(navigator.userAgent) ||
/Trident/i.test(navigator.userAgent) );
}
},
// ### Styling & State Methods:
setFont: function(family, size, weight) {
// Unlike canvas, in SVG italic is handled by font-style,
// not weight. So: we search the weight argument and
// apply bold and italic to weight and style respectively.
var bold = false;
var italic = false;
var style = "normal";
// Weight might also be a number (200, 400, etc...) so we
// test its type to be sure we have access to String methods.
if( typeof weight == "string" ) {
// look for "italic" in the weight:
if(weight.indexOf("italic") !== -1) {
weight = weight.replace(/italic/g, "");
italic = true;
}
// look for "bold" in weight
if(weight.indexOf("bold") !== -1) {
weight = weight.replace(/bold/g, "");
bold = true;
}
// remove any remaining spaces
weight = weight.replace(/ /g, "");
}
weight = bold ? "bold" : weight;
weight = (typeof weight === "undefined" || weight === "") ? "normal" : weight;
style = italic ? "italic" : style;
var fontAttributes = {
"font-family": family,
"font-size": size + "pt",
"font-weight": weight,
"font-style" : style
};
// Store the font size so that if the browser is Internet
// Explorer we can fix its calculations of text width.
this.fontSize = Number(size);
Vex.Merge(this.attributes, fontAttributes);
Vex.Merge(this.state, fontAttributes);
return this;
},
setRawFont: function(font) {
font=font.trim();
// Assumes size first, splits on space -- which is presently
// how all existing modules are calling this.
var fontArray = font.split(" ");
this.attributes["font-family"] = fontArray[1];
this.state["font-family"] = fontArray[1];
this.attributes["font-size"] = fontArray[0];
this.state["font-size"] = fontArray[0];
// Saves fontSize for IE polyfill
this.fontSize = Number(fontArray[0].match(/\d+/));
return this;
},
setFillStyle: function(style) {
this.attributes.fill = style;
return this;
},
setBackgroundFillStyle: function(style) {
this.background_attributes.fill = style;
this.background_attributes.stroke = style;
return this;
},
setStrokeStyle: function(style) {
this.attributes.stroke = style;
return this;
},
setShadowColor: function(style) {
this.shadow_attributes.color = style;
return this;
},
setShadowBlur: function(blur) {
this.shadow_attributes.width = blur;
return this;
},
setLineWidth: function(width) {
this.attributes["stroke-width"] = width;
this.lineWidth = width;
},
setLineDash: function(lineDash) {
this.attributes["stroke-linedash"] = lineDash;
return this;
},
setLineCap: function(lineCap) {
this.attributes["stroke-linecap"] = lineCap;
return this;
},
// ### Sizing & Scaling Methods:
// TODO (GCR): See note at scale() -- seperate our internal
// conception of pixel-based width/height from the style.width
// and style.height properties eventually to allow users to
// apply responsive sizing attributes to the SVG.
resize: function(width, height) {
this.width = width;
this.height = height;
this.element.style.width = width;
var attributes = {
width : width,
height : height
};
this.applyAttributes(this.svg, attributes);
return this;
},
scale: function(x, y) {
// uses viewBox to scale
// TODO (GCR): we may at some point want to distinguish the
// style.width / style.height properties that are applied to
// the SVG object from our internal conception of the SVG
// width/height. This would allow us to create automatically
// scaling SVG's that filled their containers, for instance.
//
// As this isn't implemented in Canvas or Raphael contexts,
// I've left as is for now, but in using the viewBox to
// handle internal scaling, am trying to make it possible
// for us to eventually move in that direction.
this.state.scale = { x: x, y: y };
var visibleWidth = this.width / x;
var visibleHeight = this.height / y;
this.setViewBox(0,0, visibleWidth, visibleHeight);
return this;
},
setViewBox: function(xMin, yMin, width, height) {
// Override for "x y w h" style:
if(arguments.length == 1) this.svg.setAttribute("viewBox", viewBox);
else {
var viewBoxString = xMin + " " + yMin + " " + width + " " + height;
this.svg.setAttribute("viewBox", viewBoxString);
}
},
// ### Drawing helper methods:
applyAttributes: function(element, attributes) {
for(var propertyName in attributes) {
element.setAttributeNS(null, propertyName, attributes[propertyName]);
}
return element;
},
flipRectangle: function(args) {
// Avoid invalid negative height attributes by
// flipping a rectangle w/ negative height on its head.
// Since args is the actual arguments object from
// one of the rectangle functions, we don't need to
// return it.
// Add negative height to Y
args[1] += args[3];
// Make the negative height positive.
args[3] = -args[3];
},
// ### Shape & Path Methods:
clear: function() {
// Clear the SVG by removing all inner children.
// (This approach is usually slightly more efficient
// than removing the old SVG & adding a new one to
// the container element, since it does not cause the
// container to resize twice. Also, the resize
// triggered by removing the entire SVG can trigger
// a touchcancel event when the element resizes away
// from a touch point.)
while (this.svg.lastChild) {
this.svg.removeChild(this.svg.lastChild);
}
// Replace the viewbox attribute we just removed:
this.scale(this.state.scale.x, this.state.scale.y);
},
// ## Rectangles:
rect: function(x, y, width, height, attributes) {
// Avoid invalid negative height attribs by
// flipping the rectangle on its head:
if (height < 0) this.flipRectangle(arguments);
// Create the rect & style it:
var rect = this.create("rect");
if(typeof attributes === "undefined") attributes = {
fill: "none",
"stroke-width": this.lineWidth,
stroke: "black"
};
Vex.Merge(attributes, {
x: x,
y: y,
width: width,
height: height
});
this.applyAttributes(rect, attributes);
this.add(rect);
return this;
},
fillRect: function(x, y, width, height) {
if(height < 0) this.flipRectangle(arguments);
this.rect(x, y, width - 0.5, height - 0.5, this.attributes);
return this;
},
clearRect: function(x, y, width, height) {
// TODO(GCR): Improve implementation of this...
// Currently it draws a box of the background color, rather
// than creating alpha through lower z-levels.
//
// See the implementation of this in SVGKit:
// http://sourceforge.net/projects/svgkit/
// as a starting point.
//
// Adding a large number of transform paths (as we would
// have to do) could be a real performance hit. Since
// tabNote seems to be the only module that makes use of this
// it may be worth creating a seperate tabStave that would
// draw lines around locations of tablature fingering.
//
if (height < 0) this.flipRectangle(arguments);
this.rect(x, y, width - 0.5, height - 0.5, this.background_attributes);
return this;
},
// ## Paths:
beginPath: function() {
this.path = "";
this.pen.x = 0;
this.pen.y = 0;
return this;
},
moveTo: function(x, y) {
this.path += "M" + x + " " + y;
this.pen.x = x;
this.pen.y = y;
return this;
},
lineTo: function(x, y) {
this.path += "L" + x + " " + y;
this.pen.x = x;
this.pen.y = y;
return this;
},
bezierCurveTo: function(x1, y1, x2, y2, x, y) {
this.path += "C" +
x1 + " " +
y1 + "," +
x2 + " " +
y2 + "," +
x + " " +
y;
this.pen.x = x;
this.pen.y = y;
return this;
},
quadraticCurveTo: function(x1, y1, x, y) {
this.path += "Q" +
x1 + " " +
y1 + "," +
x + " " +
y;
this.pen.x = x;
this.pen.y = y;
return this;
},
// This is an attempt (hack) to simulate the HTML5 canvas
// arc method.
arc: function(x, y, radius, startAngle, endAngle, antiClockwise) {
function normalizeAngle(angle) {
while (angle < 0) {
angle += Math.PI * 2;
}
while (angle > Math.PI * 2) {
angle -= Math.PI * 2;
}
return angle;
}
startAngle = normalizeAngle(startAngle);
endAngle = normalizeAngle(endAngle);
if (startAngle > endAngle) {
var tmp = startAngle;
startAngle = endAngle;
endAngle = tmp;
antiClockwise = !antiClockwise;
}
var delta = endAngle - startAngle;
if (delta > Math.PI) {
this.arcHelper(x, y, radius, startAngle, startAngle + delta / 2,
antiClockwise);
this.arcHelper(x, y, radius, startAngle + delta / 2, endAngle,
antiClockwise);
}
else {
this.arcHelper(x, y, radius, startAngle, endAngle, antiClockwise);
}
return this;
},
arcHelper: function(x, y, radius, startAngle, endAngle, antiClockwise) {
var x1 = x + radius * Math.cos(startAngle);
var y1 = y + radius * Math.sin(startAngle);
var x2 = x + radius * Math.cos(endAngle);
var y2 = y + radius * Math.sin(endAngle);
var largeArcFlag = 0;
var sweepFlag = 0;
if (antiClockwise) {
sweepFlag = 1;
if (endAngle - startAngle < Math.PI)
largeArcFlag = 1;
}
else if (endAngle - startAngle > Math.PI) {
largeArcFlag = 1;
}
this.path += "M" + x1 + " " + y1 + " " + "A" +
radius + " " + radius + " " + "0 " + largeArcFlag + " " + sweepFlag + " " +
x2 + " " + y2 + "M" + this.pen.x + " " + this.pen.y;
},
closePath: function() {
this.path += "Z";
return this;
},
// Adapted from the source for Raphael's Element.glow
glow: function() {
// Calculate the width & paths of the glow:
if (this.shadow_attributes.width > 0) {
var sa = this.shadow_attributes;
var num_paths = sa.width / 2;
// Stroke at varying widths to create effect of gaussian blur:
for (var i = 1; i <= num_paths; i++) {
var attributes = {
stroke: sa.color,
"stroke-linejoin": "round",
"stroke-linecap": "round",
"stroke-width": +((sa.width *0.4) / num_paths * i).toFixed(3),
opacity: +((sa.opacity || 0.3) / num_paths).toFixed(3),
};
var path = this.create("path");
attributes.d = this.path;
this.applyAttributes(path, attributes);
this.add(path);
}
}
return this;
},
fill: function(attributes) {
// If our current path is set to glow, make it glow
this.glow();
var path = this.create("path");
if(typeof attributes === "undefined") {
attributes = {};
Vex.Merge(attributes, this.attributes);
attributes.stroke = "none";
}
attributes.d = this.path;
this.applyAttributes(path, attributes);
this.add(path);
return this;
},
stroke: function() {
// If our current path is set to glow, make it glow.
this.glow();
var path = this.create("path");
var attributes = {};
Vex.Merge(attributes, this.attributes);
attributes.fill = "none";
attributes["stroke-width"] = this.lineWidth;
attributes.d = this.path;
this.applyAttributes(path, attributes);
this.add(path);
return this;
},
// ## Text Methods:
measureText: function(text) {
var index = text + this.attributes["font-style"] + this.attributes["font-family"] +
this.attributes["font-weight"] + this.attributes["font-size"];
var txt = this.create("text");
if (typeof(txt.getBBox) === "function") {
txt.textContent = text;
this.applyAttributes(txt, this.attributes);
// Temporarily add it to the document for measurement.
this.svg.appendChild(txt);
var bbox = txt.getBBox();
if( this.ie &&
text !== "" &&
this.attributes["font-style"] == "italic") bbox = this.ieMeasureTextFix(bbox, text);
this.svg.removeChild(txt);
// For runtimes that do not have full support of bounding boxes, collect
// some data which can be used later to extrapolate them.
if (SVGContext.collectMeasurements) {
SVGContext.measureTextCache[index] = {
x: bbox.x,
y: bbox.y,
width: bbox.width,
height: bbox.height
};
}
if (SVGContext.validateMeasurements) {
if (!(index in SVGContext.measureTextCache)) {
Vex.W("measureTextCache is stale. Please update tests/measure_text_cache.js: ", index);
}
}
return bbox;
} else {
// Inside NodeJS or other runtimes that don't support getBBox. This
// is currently only useful for the NodeJS visual regression tests.
return SVGContext.measureTextCache[index];
}
},
ieMeasureTextFix: function(bbox, text) {
// Internet Explorer over-pads text in italics,
// resulting in giant width estimates for measureText.
// To fix this, we use this formula, tested against
// ie 11:
// overestimate (in pixels) = FontSize(in pt) * 1.196 + 1.96
// And then subtract the overestimate from calculated width.
var fontSize = Number(this.fontSize);
var m = 1.196;
var b = 1.9598;
var widthCorrection = (m * fontSize) + b;
var width = bbox.width - widthCorrection;
var height = bbox.height - 1.5;
// Get non-protected copy:
var box = {
x : bbox.x,
y : bbox.y,
width : width,
height : height
};
return box;
},
fillText: function(text, x, y) {
var attributes = {};
Vex.Merge(attributes, this.attributes);
attributes.stroke = "none";
attributes.x = x;
attributes.y = y;
var txt = this.create("text");
txt.textContent = text;
this.applyAttributes(txt, attributes);
this.add(txt);
},
save: function() {
// TODO(mmuthanna): State needs to be deep-copied.
this.state_stack.push({
state: {
"font-family": this.state["font-family"],
"font-weight": this.state["font-weight"],
"font-style": this.state["font-style"],
"font-size": this.state["font-size"]
},
attributes: {
"font-family": this.attributes["font-family"],
"font-weight": this.attributes["font-weight"],
"font-style": this.attributes["font-style"],
"font-size": this.attributes["font-size"],
fill: this.attributes.fill,
stroke: this.attributes.stroke,
"stroke-width": this.attributes["stroke-width"]
},
shadow_attributes: {
width: this.shadow_attributes.width,
color: this.shadow_attributes.color
}
});
return this;
},
restore: function() {
// TODO(0xfe): State needs to be deep-restored.
var state = this.state_stack.pop();
this.state["font-family"] = state.state["font-family"];
this.state["font-weight"] = state.state["font-weight"];
this.state["font-style"] = state.state["font-style"];
this.state["font-size"] = state.state["font-size"];
this.attributes["font-family"] = state.attributes["font-family"];
this.attributes["font-weight"] = state.attributes["font-weight"];
this.attributes["font-style"] = state.attributes["font-style"];
this.attributes["font-size"] = state.attributes["font-size"];
this.attributes.fill = state.attributes.fill;
this.attributes.stroke = state.attributes.stroke;
this.attributes["stroke-width"] = state.attributes["stroke-width"];
this.shadow_attributes.width = state.shadow_attributes.width;
this.shadow_attributes.color = state.shadow_attributes.color;
return this;
}
};
return SVGContext;
}());
|
'use strict';
// Initialize App
angular.module('ngDirectiveForms', []);
|
module.exports = {
enable,
disable
}
const electron = require('electron')
const log = require('./log')
let blockId = 0
/**
* Block the system from entering low-power (sleep) mode or turning off the
* display.
*/
function enable () {
if (electron.powerSaveBlocker.isStarted(blockId)) {
// If a power saver block already exists, do nothing.
return
}
blockId = electron.powerSaveBlocker.start('prevent-display-sleep')
log(`powerSaveBlocker.enable: ${blockId}`)
}
/**
* Stop blocking the system from entering low-power mode.
*/
function disable () {
if (!electron.powerSaveBlocker.isStarted(blockId)) {
// If a power saver block does not exist, do nothing.
return
}
electron.powerSaveBlocker.stop(blockId)
log(`powerSaveBlocker.disable: ${blockId}`)
}
|
import { IfObservable } from './IfObservable';
export const /** @type {?} */ _if = IfObservable.create;
|
/**@license
* __ _____ ________ __
* / // _ /__ __ _____ ___ __ _/__ ___/__ ___ ______ __ __ __ ___ / /
* __ / // // // // // _ // _// // / / // _ // _// // // \/ // _ \/ /
* / / // // // // // ___// / / // / / // ___// / / / / // // /\ // // / /__
* \___//____ \\___//____//_/ _\_ / /_//____//_/ /_/ /_//_//_/ /_/ \__\_\___/
* \/ /____/
* Example plugin using JQuery Terminal Emulator
* Copyright (c) 2014-2020 Jakub Jankiewicz <https://jcubic.pl/me>
* Released under the MIT license
*
*/
/* global define */
(function(factory, undefined) {
var root = typeof window !== 'undefined' ? window : global;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
// istanbul ignore next
define(['jquery', 'jquery.terminal'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function(root, jQuery) {
if (jQuery === undefined) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if (window !== undefined) {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
if (!jQuery.fn.terminal) {
if (window !== undefined) {
require('jquery.terminal');
} else {
require('jquery.terminal')(jQuery);
}
}
factory(jQuery);
return jQuery;
};
} else {
// Browser
// istanbul ignore next
factory(root.jQuery);
}
})(function($) {
$.extend_if_has = function(desc, source, array) {
for (var i = array.length; i--;) {
if (typeof source[array[i]] !== 'undefined') {
desc[array[i]] = source[array[i]];
}
}
return desc;
};
var defaults = Object.keys($.terminal.defaults).concat(['greetings']);
$.fn.dterm = function(interpreter, options) {
var op = $.extend_if_has({}, options, defaults);
op.enabled = false;
this.addClass('dterm');
var terminal = $('<div/>').appendTo(this).terminal(interpreter, op);
if (!options.title) {
options.title = 'JQuery Terminal Emulator';
}
var close = options.close || $.noop;
if (options.logoutOnClose) {
options.close = function() {
terminal.logout();
terminal.clear();
close();
};
} else {
options.close = function() {
terminal.disable();
close();
};
}
var self = this;
if (window.IntersectionObserver) {
var visibility_observer = new IntersectionObserver(function() {
if (self.is(':visible')) {
terminal.focus().resize();
} else {
terminal.disable();
}
}, {
root: null
});
visibility_observer.observe(terminal[0]);
}
this.dialog($.extend({}, options, {
open: function(event, ui) {
if (!window.IntersectionObserver) {
setTimeout(function() {
terminal.enable().resize();
}, 100);
}
if (typeof options.open === 'function') {
options.open(event, ui);
}
},
show: 'fade',
closeOnEscape: false
}));
self.terminal = terminal;
return self;
};
});
|
/*
* Globalize Culture tt
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined"
&& typeof exports !== "undefined"
&& typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "tt", "default", {
name: "tt",
englishName: "Tatar",
nativeName: "Татар",
language: "tt",
numberFormat: {
",": " ",
".": ",",
percent: {
pattern: ["-n%","n%"],
",": " ",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": " ",
".": ",",
symbol: "р."
}
},
calendars: {
standard: {
"/": ".",
firstDay: 1,
days: {
names: ["Якшәмбе","Дүшәмбе","Сишәмбе","Чәршәмбе","Пәнҗешәмбе","Җомга","Шимбә"],
namesAbbr: ["Якш","Дүш","Сиш","Чәрш","Пәнҗ","Җом","Шим"],
namesShort: ["Я","Д","С","Ч","П","Җ","Ш"]
},
months: {
names: ["Гыйнвар","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь",""],
namesAbbr: ["Гыйн.","Фев.","Мар.","Апр.","Май","Июнь","Июль","Авг.","Сен.","Окт.","Нояб.","Дек.",""]
},
monthsGenitive: {
names: ["Гыйнварның","Февральнең","Мартның","Апрельнең","Майның","Июньнең","Июльнең","Августның","Сентябрьның","Октябрьның","Ноябрьның","Декабрьның",""],
namesAbbr: ["Гыйн.-ның","Фев.-нең","Мар.-ның","Апр.-нең","Майның","Июньнең","Июльнең","Авг.-ның","Сен.-ның","Окт.-ның","Нояб.-ның","Дек.-ның",""]
},
AM: null,
PM: null,
patterns: {
d: "dd.MM.yyyy",
D: "d MMMM yyyy",
t: "H:mm",
T: "H:mm:ss",
f: "d MMMM yyyy H:mm",
F: "d MMMM yyyy H:mm:ss",
M: "d MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var mr = require('npm-registry-mock')
var test = require('tap').test
var common = require('../common-tap.js')
var opts = { cwd: __dirname }
var pkg = path.resolve(__dirname, 'adduser-legacy-auth')
var outfile = path.resolve(pkg, '_npmrc')
var contents = '_auth=' + new Buffer('u:x').toString('base64') + '\n' +
'registry=https://nonexistent.lvh.me/registry\n' +
'email=u@p.me\n'
var responses = {
'Username': 'u\n',
'Password': 'p\n',
'Email': 'u@p.me\n'
}
function mocks (server) {
server.filteringRequestBody(function (r) {
if (r.match(/"_id":"org\.couchdb\.user:u"/)) {
return 'auth'
}
})
server.put('/-/user/org.couchdb.user:u', 'auth')
.reply(409, { error: 'user exists' })
server.get('/-/user/org.couchdb.user:u?write=true')
.reply(200, { _rev: '3-deadcafebabebeef' })
server.put(
'/-/user/org.couchdb.user:u/-rev/3-deadcafebabebeef',
'auth',
{ authorization: 'Basic dTpw' }
).reply(201, { username: 'u', password: 'p', email: 'u@p.me' })
}
test('setup', function (t) {
mkdirp(pkg, function (er) {
t.ifError(er, pkg + ' made successfully')
fs.writeFile(outfile, contents, function (er) {
t.ifError(er, 'wrote legacy config')
t.end()
})
})
})
test('npm login', function (t) {
mr({ port: common.port, plugin: mocks }, function (er, s) {
var runner = common.npm(
[
'login',
'--registry', common.registry,
'--loglevel', 'error',
'--userconfig', outfile
],
opts,
function (err, code, stdout, stderr) {
if (err) throw err
t.is(code, 0, 'exited OK')
t.is(stderr, '', 'no error output')
var config = fs.readFileSync(outfile, 'utf8')
t.like(config, /:always-auth=false/, 'always-auth is scoped and false (by default)')
s.close()
rimraf(outfile, function (err) {
t.ifError(err, 'removed config file OK')
t.end()
})
}
)
var remaining = Object.keys(responses).length
runner.stdout.on('data', function (chunk) {
if (remaining > 0) {
remaining--
var label = chunk.toString('utf8').split(':')[0]
if (responses[label]) runner.stdin.write(responses[label])
if (remaining === 0) runner.stdin.end()
} else {
var message = chunk.toString('utf8').trim()
t.equal(message, 'Logged in as u on ' + common.registry + '/.')
}
})
})
})
test('cleanup', function (t) {
rimraf.sync(pkg)
t.pass('cleaned up')
t.end()
})
|
/*global define*/
/*jslint white:true,browser:true*/
define([
'bluebird',
'kb_common/html',
'../validation',
'common/events',
'common/dom',
'common/runtime',
'bootstrap',
'css!font-awesome'
], function (
Promise,
html,
Validation,
Events,
Dom,
Runtime
) {
'use strict';
// Constants
var t = html.tag,
div = t('div'), button = t('button'), span = t('span'), input = t('input');
function factory(config) {
var options = {},
spec = config.parameterSpec,
container,
parent,
bus = config.bus,
dom,
model = {
value: {}
},
runtime = Runtime.make(),
widgets = [];
// MODEL
function setModel(value) {
model.value = value;
}
function unsetModel() {
setModel({});
}
function resetModel() {
if (spec.defaultValue) {
setModel(spec.defaultValue);
} else {
unsetModel();
}
}
function exportModel() {
var kvMap = {};
Object.keys(model.value).forEach(function (id) {
var kv = model.value[id];
kvMap[kv.key] = kv.value;
});
return kvMap;
}
// MODEL ITEMS
function setModelValue(key, value, id) {
return Promise.try(function () {
if (!key || key.length === 0) {
delete model.value[id];
}
model.value[id] = {
key: key,
value: value
};
})
.then(function () {
render();
});
}
function addModelValue(key, value, id) {
return Promise.try(function () {
if (model.value.hasOwnProperty(key)) {
throw new Error('Key value already exists');
}
model.value[id] = {
key: key,
value: value
};
});
}
function copyProps(from, props) {
var newObj = {};
props.forEach(function (prop) {
newObj[prop] = from[prop];
});
return newObj;
}
function validate(rawValue) {
return Promise.try(function () {
if (!options.enabled) {
return {
isValid: true,
validated: false,
diagnosis: 'disabled'
};
}
var validationOptions = copyProps(spec.spec.text_options, ['regexp_constraint', 'min_length', 'max_length']);
validationOptions.required = spec.required();
return Validation.validateTextString(rawValue, validationOptions);
});
}
function setKeyValue(id, newKeyValue) {
model.value[id].key = newKeyValue;
}
function doChangeKey(id, newKeyValue) {
try {
setKeyValue(id, newKeyValue);
bus.emit('changed', {
newValue: model.value
});
render();
} catch (err) {
alert('Error saving key:' + err.message);
}
}
/*
* Creates the markup
* Places it into the dom node
* Hooks up event listeners
*/
function makeKeyValueControl(key, value, id, events) {
return div({style: {
dataElement: 'control',
border: '1px orange dashed',
dataId: id
}}, [
div({}, [
span({style: {width: '30%'}}, 'k:'),
input({
style: {
width: '70%'
},
dataElement: 'key',
value: key,
id: events.addEvent({
type: 'change',
handler: function (e) {
doChangeKey(id, e.target.value);
}
})
})
]),
div({}, [
span({style: {width: '30%'}}, 'v:'),
input({
style: {
width: '50%'
},
dataElement: 'value',
value: value
})
])
]);
}
function makeNewKeyValueControl(key, value, events) {
return div({style: {
dataElement: 'control',
border: '1px orange dashed'
}}, [
div({}, [
span({style: {width: '30%'}}, 'k:'),
input({
style: {
width: '70%'
},
dataElement: 'key',
value: key
})
]),
div({}, [
span({style: {width: '30%'}}, 'v:'),
input({
style: {
width: '50%'
},
dataElement: 'value',
value: value
})
])
]);
}
function makeSingleInputControl(key, value, id, index, events, bus) {
// CONTROL
var preButton, postButton,
widgetId = html.genId(),
inputBus = runtime.bus().makeChannelBus(null, 'Multi int input bus'),
// inputWidget = SingleIntInputWidget.make({
// bus: inputBus,
// parameterSpec: spec,
// spec: spec,
// fieldSpec: config.fieldSpec,
// showOwnMessages: true
// }),
// widgetWrapper = {
// id: widgetId,
// instance: inputWidget,
// bus: inputBus,
// key: key
// },
// placeholder = div({id: widgetId}),
control = makeKeyValueControl(key, value, id, events),
errorRow;
// widgets.push(widgetWrapper);
// set up listeners for the input
// inputBus.on('sync', function (message) {
// var value = model.value[key];
// if (value) {
// inputBus.emit('update', {
// value: value
// });
// }
// });
// inputBus.on('validation', function (message) {
// if (message.diagnosis === 'optional-empty') {
// // alert('delete me!');
// model.value.splice(widgetWrapper.index, 1);
// bus.emit('changed', {
// newValue: model.value
// });
// render();
// }
// });
// inputBus.on('changed', function (message) {
// model.value[index] = message.newValue;
// // TODO: validate the main control...
// bus.emit('changed', {
// newValue: model.value
// });
// });
preButton = div({class: 'input-group-addon kb-input-group-addon', style: {width: '5ex', padding: '0'}}, String(index + 1) + '.');
postButton = div({class: 'input-group-addon kb-input-group-addon', style: {padding: '0'}}, button({
class: 'btn btn-danger btn-link btn-xs',
type: 'button',
style: {width: '4ex'},
dataKey: key,
id: events.addEvent({type: 'click', handler: function (e) {
// no, we don't need to consult the control, we just remove
// it...
delete model.value[id];
// model.value.splice(widgetWrapper.index, 1);
//var index = e.target.getAttribute('data-index'),
// control = container.querySelector('input[data-index="' + index + '"]');
//control.value = '';
//control.dispatchEvent(new Event('change'));
bus.emit('changed', {
newValue: exportModel()
});
render();
}})
}, 'x'));
return div({dataElement: 'input-row', dataKey: String(key), style: {width: '100%'}}, [
div({class: 'input-group'}, [
preButton,
control,
postButton
])
]);
}
function findParent(node, matcher) {
var parent = node.parentNode;
while (parent) {
if (matcher(parent)) {
return parent;
}
parent = parent.parentNode;
}
}
function doAddNewItem(event) {
var control = findParent(event.target, function (node) {
return node.getAttribute('data-element') === 'input-row';
}),
id = html.genId(),
key = control.querySelector('[data-element="key"]').value,
value = control.querySelector('[data-element="value"]').value;
addModelValue(key, value, id)
.then(function() {
bus.emit('changed', {
newValue: exportModel()
});
})
.then(function () {
render();
})
.catch(function (err) {
alert(err.message);
});
}
function makeNewInputControl(key, value, events, bus) {
// CONTROL
var preButton, postButton,
widgetId = html.genId(),
// inputBus = runtime.bus().makeChannelBus(null, '"new input" parent comm bus'),
// inputWidget = SingleIntInputWidget.make({
// bus: inputBus,
// // initialValue: config.initialValue,
// parameterSpec: spec,
// spec: spec,
// fieldSpec: config.fieldSpec,
// showOwnMessages: true
// }),
errorRow,
control = makeNewKeyValueControl(key, value, events);
// placeholder = div({id: widgetId});
// widgets.push({
// id: widgetId,
// instance: inputWidget,
// bus: inputBus
// });
// inputBus.on('changed', function (message) {
// model.value.push(message.newValue);
//
// // TODO: and insert a new row ...
//
// // first attempt, re-render the whole shebang.
// render();
//
// // TODO: validate the main control...
// bus.emit('changed', {
// newValue: model.value
// });inputBus
// });
preButton = div({class: 'input-group-addon kb-input-group-addon', style: {width: '5ex', padding: '0'}}, '');
postButton = div({class: 'input-group-addon kb-input-group-addon', style: {padding: '0'}}, button({
class: 'btn btn-primary btn-link btn-xs',
type: 'button',
style: {width: '4ex'},
id: events.addEvent({type: 'click', handler: doAddNewItem})
}, '+'));
return div({dataElement: 'input-row', style: {width: '100%'}}, [
div({class: 'input-group'}, [
preButton,
control,
postButton
])
]);
}
function makeInputControl(events, bus) {
// get all keys
var kvs = Object.keys(model.value).map(function (id) {
var kv = model.value[id];
return {
id: id,
key: kv.key,
value: kv.value
};
}).sort(function (a, b) {
if (a.key < b.key) {
return -1;
}
if (a.key > b.key) {
return 1;
}
return 0;
});
console.log('kvs?', kvs);
// order them
// iterate, over them, adding one input control at a time.
var items = kvs.map(function (kv, index) {
return makeSingleInputControl(kv.key, kv.value, kv.id, index, events, bus);
});
items = items.concat(makeNewInputControl('', '', events, bus));
var content = items.join('\n');
return content;
}
function render() {
// if we have input widgets already, tear them down.
widgets.forEach(function (widget) {
widget.bus.emit('stop');
// TODO figure out how to remove unused channels.
// widget.bus.done();
});
widgets = [];
// we don't have to wait for anything...
var events = Events.make(),
control = makeInputControl(events, bus);
dom.setContent('input-container', control);
widgets.forEach(function (widget) {
widget.instance.start()
.then(function () {
widget.bus.emit('run', {
debug: true,
node: document.querySelector('#' + widget.id)
});
});
});
events.attachEvents(container);
}
function layout(events) {
var content = div({
dataElement: 'main-panel'
}, [
div({dataElement: 'input-container'})
]);
return {
content: content,
events: events
};
}
function autoValidate() {
return Promise.all(model.value.map(function (value, index) {
// could get from DOM, but the model is the same.
var rawValue = container.querySelector('[data-index="' + index + '"]').value;
// console.log('VALIDATE', value);
return validate(rawValue);
}))
.then(function (results) {
// a bit of a hack -- we need to handle the
// validation here, and update the individual rows
// for now -- just create one mega message.
var errorMessages = [],
validationMessage;
results.forEach(function (result, index) {
if (result.errorMessage) {
errorMessages.push(result.errorMessage + ' in item ' + index);
}
});
if (errorMessages.length) {
validationMessage = {
diagnosis: 'invalid',
errorMessage: errorMessages.join('<br/>')
};
} else {
validationMessage = {
diagnosis: 'valid'
};
}
bus.emit('validation', validationMessage);
});
}
// LIFECYCLE API
function start() {
return Promise.try(function () {
// runtime.bus().logMessages(true);
bus.on('run', function (message) {
parent = message.node;
container = parent.appendChild(document.createElement('div'));
dom = Dom.make({node: container});
var events = Events.make(),
theLayout = layout(events);
container.innerHTML = theLayout.content;
events.attachEvents(container);
bus.on('reset-to-defaults', function (message) {
resetModel();
render();
});
bus.on('update', function (message) {
setModel(message.value);
render();
});
bus.on('refresh', function () {
});
bus.emit('sync');
});
});
}
return {
start: start
};
}
return {
make: function (config) {
return factory(config);
}
};
});
|
#!/usr/bin/env node
'use strict'
const spawn = require('child_process').spawn
const pkg = require('./package.json')
const { dependencies, devDependencies } = pkg
const installDependencies = (deps, command) => spawn(
'npm', [ 'install', command, ...Object.keys(deps) ],
{ stdio: 'inherit' }
)
installDependencies(dependencies, '--save')
installDependencies(devDependencies, '--save-dev')
|
// The configuration for Require.js
// that specifies where to load modules from.
//
// Curran Kelleher, August 2014
require.config({
paths: {
model: '../../src/model',
d3: '../../lib/d3/d3.min',
barChart: '../d3BarChart/barChart'
}
});
|
/*
* @name Rotate
* @description Rotating a square around the Z axis.
* To get the results you expect, send the rotate function angle
* parameters that are values between 0 and PI*2 (TWO_PI which is
* roughly 6.28). If you prefer to think about angles as degrees
* (0-360), you can use the radians() method to convert your values.
* For example: scale(radians(90)) is identical to the statement
* scale(PI/2). In this example, every even numbered second a jitter
* is added to the rotation. During odd seconds rotation moves CW and
* CCW at the speed determined by the last jitter value.
*/
let angle = 0.0;
let jitter = 0.0;
function setup() {
createCanvas(720, 400);
noStroke();
fill(255);
//Draw the rectangle from the center and it will also be the
//rotate around that center
rectMode(CENTER);
}
function draw() {
background(51);
// during even-numbered seconds (0, 2, 4, 6...) add jitter to
// the rotation
if (second() % 2 === 0) {
jitter = random(-0.1, 0.1);
}
//increase the angle value using the most recent jitter value
angle = angle + jitter;
//use cosine to get a smooth CW and CCW motion when not jittering
let c = cos(angle);
//move the shape to the center of the canvas
translate(width / 2, height / 2);
//apply the final rotation
rotate(c);
rect(0, 0, 180, 180);
}
|
var registerComponent = require('../../core/component').registerComponent;
var shouldCaptureKeyEvent = require('../../utils/').shouldCaptureKeyEvent;
var THREE = require('../../lib/three');
var controls = new THREE.VRControls(new THREE.Object3D());
module.exports.Component = registerComponent('keyboard-shortcuts', {
schema: {
enterVR: {default: true},
exitVR: {default: true},
resetSensor: {default: true}
},
init: function () {
var self = this;
var scene = this.el;
this.listener = window.addEventListener('keyup', function (event) {
if (!shouldCaptureKeyEvent(event)) { return; }
if (self.enterVREnabled && event.keyCode === 70) { // f.
scene.enterVR();
}
if (self.enterVREnabled && event.keyCode === 27) { // escape.
scene.exitVR();
}
if (self.resetSensorEnabled && event.keyCode === 90) { // z.
controls.resetSensor();
}
}, false);
},
update: function (oldData) {
var data = this.data;
this.enterVREnabled = data.enterVR;
this.resetSensorEnabled = data.resetSensor;
},
remove: function () {
window.removeEventListener('keyup', this.listener);
}
});
|
// Tutorial derived from http://blog.cognitect.com/blog/2016/10/5/interactive-development-with-clojureclause
/*
Problem
We want a function that accepts a secret code and a guess, and returns a score
for that guess. Codes are made of 4 to 6 colored pegs, selected from six colors:
[r]ed, [y]ellow, [g]reen, [c]yan, [b]lack, and [w]hite. The score is based on
the number of pegs in the guess that match the secret code. A peg in the guess
that matches the color of the peg in the same position in the secret code is
considered an exact match, and a peg that matches a peg in a different position
in the secret code is considered a loose match.
For example, if the secret code is ['r', 'y', 'g', 'c'] and the guess is
['c', 'y', 'g'. 'b'], the score would be { exactMatches: 2, looseMatches: 1 }
because 'y' and 'g' appear in the same positions and 'c' appears in a different
position.
*/
var s = require('../../src');
var _ = require('lodash');
var isPeg = function(x) {
return ['r', 'y', 'c', 'g'].indexOf(x) >= 0;
}
var CodeClause = s.collOf(isPeg, { minCount: 4, maxCount: 6 });
var ScoreFnClause = s.fclause({
args: s.cat('secret', CodeClause, 'guess', CodeClause),
});
// TODO: implement
// ScoreFnClause.args.exercise()
ScoreFnClause = s.fclause({
args: s.and(
s.cat('secret', CodeClause, 'guess', CodeClause),
({secret, guess}) => secret.length === guess.length
)
});
// ScoreFnClause.args.exercise()
ScoreFnClause = s.fclause({
args: s.and(
s.cat('secret', CodeClause, 'guess', CodeClause),
({secret, guess}) => secret.length === guess.length
),
ret: s.shape({
req: {
exactMatches: s.isNatInt,
looseMatches: s.isNatInt,
}
}),
});
// ScoreFnClause.ret.exercise()
ScoreFnClause = s.fclause({
args: s.and(
s.cat('secret', CodeClause, 'guess', CodeClause),
({secret, guess}) => secret.length === guess.length
),
ret: s.shape({
req: {
exactMatches: s.isNatInt,
looseMatches: s.isNatInt,
}
}),
fn: ({args: {secret}, ret}) => {
var sums = _.sum(_.values(ret));
var secretCounts = secret.length;
return secretCounts >= sums && sums >= 0;
}
});
|
'use strict'
module.exports = {
extends: 'recommended',
}
|
var renderer = PIXI.autoDetectRenderer(800, 600);
document.body.appendChild(renderer.view);
// create the root of the scene graph
var stage = new PIXI.Container();
// load spine data
PIXI.loader
.add('dragon', '_assets/spine/dragon.json')
.load(onAssetsLoaded);
var dragon = null;
function onAssetsLoaded(loader,res)
{
// instantiate the spine animation
dragon = new PIXI.spine.Spine(res.dragon.spineData);
dragon.skeleton.setToSetupPose();
dragon.update(0);
dragon.autoUpdate = false;
// create a container for the spine animation and add the animation to it
var dragonCage = new PIXI.Container();
dragonCage.addChild(dragon);
// measure the spine animation and position it inside its container to align it to the origin
var localRect = dragon.getLocalBounds();
dragon.position.set(-localRect.x, -localRect.y);
// now we can scale, position and rotate the container as any other display object
var scale = Math.min((renderer.width * 0.7) / dragonCage.width, (renderer.height * 0.7) / dragonCage.height);
dragonCage.scale.set(scale, scale);
dragonCage.position.set((renderer.width - dragonCage.width) * 0.5, (renderer.height - dragonCage.height) * 0.5);
// add the container to the stage
stage.addChild(dragonCage);
// once position and scaled, set the animation to play
dragon.state.setAnimationByName(0, 'flying', true);
animate();
}
function animate() {
requestAnimationFrame(animate);
// update the spine animation, only needed if dragon.autoupdate is set to false
dragon.update(0.01666666666667); // HARDCODED FRAMERATE!
renderer.render(stage);
}
|
var searchData=
[
['load',['load',['../classep___object.html#a4dcaa8f72c8423d4de25a9e87fa6f3e4',1,'ep_Object']]],
['load_5ffrom_5fdb',['load_from_db',['../classep___object.html#a16e862a2b83507e636da4d2255935e78',1,'ep_Object']]],
['load_5flayer',['load_layer',['../classep___object.html#a2a98b8e18d13cdc780c0eb53a77985b2',1,'ep_Object']]]
];
|
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports['dox'] = {
setUp: function(done) {
// setup here
done();
},
'helper': function(test) {
test.expect(1);
// tests here
test.ok(true);
// test.equal(grunt.helper('dox'), 'dox!!!', 'should return the correct value.');
test.done();
}
};
|
'use strict';
// smtp network server
var net = require('./tls_socket');
var logger = require('./logger');
var config = require('./config');
var conn = require('./connection');
var out = require('./outbound');
var plugins = require('./plugins');
var constants = require('./constants');
var os = require('os');
var cluster = require('cluster');
var async = require('async');
var daemon = require('daemon');
var path = require('path');
// Need these here so we can run hooks
logger.add_log_methods(exports, 'server');
var Server = exports;
Server.load_smtp_ini = function () {
Server.cfg = config.get('smtp.ini', {
booleans: [
'-main.daemonize',
],
}, function () {
Server.load_smtp_ini();
});
var defaults = {
inactivity_timeout: 600,
daemon_log_file: '/var/log/haraka.log',
daemon_pid_file: '/var/run/haraka.pid'
};
for (var key in defaults) {
if (Server.cfg.main[key] !== undefined) continue;
Server.cfg.main[key] = defaults[key];
}
};
Server.load_http_ini = function () {
Server.http = {};
Server.http.cfg = config.get('http.ini', function () {
Server.load_http_ini();
}).main;
};
Server.load_smtp_ini();
Server.load_http_ini();
Server.daemonize = function () {
var c = this.cfg.main;
if (!c.daemonize) return;
if (!process.env.__daemon) {
// Remove process.on('exit') listeners otherwise
// we get a spurious 'Exiting' log entry.
process.removeAllListeners('exit');
logger.lognotice('Daemonizing...');
}
var log_fd = require('fs').openSync(c.daemon_log_file, 'a');
daemon({stdout: log_fd});
// We are the daemon from here on...
var npid = require('npid');
try {
npid.create(c.daemon_pid_file).removeOnExit();
}
catch (err) {
logger.logerror(err.message);
process.exit(1);
}
};
Server.flushQueue = function () {
if (!Server.cluster) {
out.flush_queue();
return;
}
for (var id in cluster.workers) {
cluster.workers[id].send({event: 'outbound.flush_queue'});
}
};
Server.get_listen_addrs = function (cfg, port) {
if (!port) port = 25;
var listeners = [];
if (cfg && cfg.listen) {
listeners = cfg.listen.split(/\s*,\s*/);
if (listeners[0] === '') listeners = [];
for (var i=0; i < listeners.length; i++) {
if (/:[0-9]{1,5}$/.test(listeners[i])) continue;
listeners[i] = listeners[i] + ':' + port;
}
}
if (cfg.port) {
var host = cfg.listen_host;
if (!host) {
host = '[::0]';
Server.default_host = true;
}
listeners.unshift(host + ':' + cfg.port);
}
if (listeners.length) return listeners;
Server.default_host = true;
listeners.push('[::0]:' + port);
return listeners;
};
Server.createServer = function (params) {
var c = Server.cfg.main;
for (var key in params) {
if (typeof params[key] === 'function') continue;
c[key] = params[key];
}
Server.notes = {};
plugins.server = Server;
plugins.load_plugins();
var inactivity_timeout = (c.inactivity_timeout || 300) * 1000;
if (!cluster || !c.nodes) {
Server.daemonize(c);
Server.setup_smtp_listeners(plugins, 'master', inactivity_timeout);
return;
}
// Cluster
Server.cluster = cluster;
// Cluster Workers
if (!cluster.isMaster) {
Server.setup_smtp_listeners(plugins, 'child', inactivity_timeout);
return;
}
// Cluster Master
// We fork workers in init_master_respond so that plugins
// can put handlers on cluster events before they are emitted.
plugins.run_hooks('init_master', Server);
};
Server.get_smtp_server = function (host, port, inactivity_timeout) {
var server;
var conn_cb = function (client) {
client.setTimeout(inactivity_timeout);
conn.createConnection(client, server);
};
if (port !== '465') {
server = net.createServer(conn_cb);
return server;
}
var options = {
key: config.get('tls_key.pem', 'binary'),
cert: config.get('tls_cert.pem', 'binary'),
};
if (!options.key) {
logger.logerror("Missing tls_key.pem for port 465");
return;
}
if (!options.cert) {
logger.logerror("Missing tls_cert.pem for port 465");
return;
}
logger.logdebug("Creating TLS server on " + host + ':' + port);
server = require('tls').createServer(options, conn_cb);
server.has_tls=true;
return server;
};
Server.setup_smtp_listeners = function (plugins, type, inactivity_timeout) {
var listeners = Server.get_listen_addrs(Server.cfg.main);
var runInitHooks = function (err) {
if (err) {
logger.logerror("Failed to setup listeners: " + err.message);
return process.exit(-1);
}
Server.listening();
plugins.run_hooks('init_' + type, Server);
};
var setupListener = function (host_port, cb) {
var hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
if (!hp) {
return cb(new Error(
'Invalid format for listen parameter in smtp.ini'));
}
var host = hp[1];
var port = hp[2];
var server = Server.get_smtp_server(host, port, inactivity_timeout);
if (!server) return cb();
server.notes = Server.notes;
if (Server.cluster) server.cluster = Server.cluster;
server.on('listening', function () {
var addr = this.address();
logger.lognotice("Listening on " + addr.address + ':' + addr.port);
cb();
});
// Fallback from IPv6 to IPv4 if not supported
// But only if we supplied the default of [::0]:25
server.on('error', function (e) {
if (e.code === 'EAFNOSUPPORT' &&
/^::0/.test(host) &&
Server.default_host) {
server.listen(port, '0.0.0.0');
}
else {
// Pass error to callback
cb(e);
}
});
server.listen(port, host);
};
async.each(listeners, setupListener, runInitHooks);
};
Server.setup_http_listeners = function () {
if (!Server.http.cfg) return;
if (!Server.http.cfg.listen) return;
var listeners = Server.get_listen_addrs(Server.http.cfg, 80);
if (!listeners.length) return;
try {
Server.http.express = require('express');
logger.loginfo('express loaded at Server.http.express');
}
catch (err) {
logger.logerror('express failed to load. No http server. ' +
' Try installing express with: npm install -g express');
return;
}
var app = Server.http.express();
Server.http.app = app;
logger.loginfo('express app is at Server.http.app');
var setupListener = function (host_port, cb) {
var hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
if (!hp) {
return cb(new Error('Invalid format for listen in http.ini'));
}
Server.http.server = require('http').createServer(app);
Server.http.server.on('listening', function () {
var addr = this.address();
logger.lognotice('Listening on ' + addr.address + ':' + addr.port);
cb();
});
Server.http.server.on('error', function (e) {
logger.logerror(e);
cb(e);
});
Server.http.server.listen(hp[2], hp[1]);
};
var registerRoutes = function (err) {
if (err) {
logger.logerror('Failed to setup http routes: ' + err.message);
}
plugins.run_hooks('init_http', Server);
app.use(Server.http.express.static(Server.get_http_docroot()));
app.use(Server.handle404);
};
async.each(listeners, setupListener, registerRoutes);
};
Server.init_master_respond = function (retval, msg) {
if (!(retval === constants.ok || retval === constants.cont)) {
Server.logerror("init_master returned error" +
((msg) ? ': ' + msg : ''));
process.exit(1);
}
var c = Server.cfg.main;
Server.ready = 1;
// Load the queue if we're just one process
if (!(cluster && c.nodes)) {
out.load_queue();
Server.setup_http_listeners();
return;
}
// Running under cluster, fork children here, so that
// cluster events can be registered in init_master hooks.
out.scan_queue_pids(function (err, pids) {
if (err) {
Server.logcrit("Scanning queue failed. Shutting down.");
process.exit(1);
}
Server.daemonize();
// Fork workers
var workers = (c.nodes === 'cpus') ? os.cpus().length : c.nodes;
var new_workers = [];
for (var i=0; i<workers; i++) {
new_workers.push(cluster.fork({ CLUSTER_MASTER_PID: process.pid }));
}
for (var j=0; j<pids.length; j++) {
new_workers[j % new_workers.length]
.send({event: 'outbound.load_pid_queue', data: pids[j]});
}
cluster.on('online', function (worker) {
logger.lognotice('worker ' + worker.id + ' started pid=' +
worker.process.pid);
});
cluster.on('listening', function (worker, address) {
logger.lognotice('worker ' + worker.id + ' listening on ' +
address.address + ':' + address.port);
});
cluster.on('exit', function (worker, code, signal) {
if (signal) {
logger.lognotice('worker ' + worker.id +
' killed by signal ' + signal);
}
else if (code !== 0) {
logger.lognotice('worker ' + worker.id +
' exited with error code: ' + code);
}
if (signal || code !== 0) {
// Restart worker
var new_worker = cluster.fork({
CLUSTER_MASTER_PID: process.pid
});
new_worker.send({
event: 'outbound.load_pid_queue', data: worker.process.pid,
});
}
});
});
};
Server.init_child_respond = function (retval, msg) {
switch (retval) {
case constants.ok:
case constants.cont:
Server.setup_http_listeners();
return;
}
var pid = process.env.CLUSTER_MASTER_PID;
Server.logerror("init_child returned error" + ((msg) ? ': ' + msg : ''));
try {
if (pid) {
process.kill(pid);
Server.logerror('Killing master (pid=' + pid + ')');
}
}
catch (err) {
Server.logerror('Terminating child');
}
process.exit(1);
};
Server.listening = function () {
var c = Server.cfg.main;
// Drop privileges
if (c.group) {
Server.lognotice('Switching from current gid: ' + process.getgid());
process.setgid(c.group);
Server.lognotice('New gid: ' + process.getgid());
}
if (c.user) {
Server.lognotice('Switching from current uid: ' + process.getuid());
process.setuid(c.user);
Server.lognotice('New uid: ' + process.getuid());
}
Server.ready = 1;
};
Server.init_http_respond = function () {
logger.loginfo('init_http_respond');
var WebSocketServer;
try { WebSocketServer = require('ws').Server; }
catch (e) {
logger.logerror('unable to load ws.\ndid you: npm install -g ws?');
return;
}
if (!WebSocketServer) {
logger.logerror('ws failed to load');
return;
}
Server.http.wss = new WebSocketServer({ server: Server.http.server });
logger.loginfo('Server.http.wss loaded');
plugins.run_hooks('init_wss', Server);
};
Server.init_wss_respond = function () {
logger.loginfo('init_wss_respond');
// logger.logdebug(arguments);
};
Server.get_http_docroot = function () {
if (Server.http.cfg.docroot) return Server.http.cfg.docroot;
Server.http.cfg.docroot = path.join(
(process.env.HARAKA || __dirname),
'/html'
);
logger.loginfo('using html docroot: ' + Server.http.cfg.docroot);
return Server.http.cfg.docroot;
};
Server.handle404 = function(req, res){
// abandon all hope, serve up a 404
var docroot = Server.get_http_docroot();
// respond with html page
if (req.accepts('html')) {
res.status(404).sendFile('404.html', { root: docroot });
return;
}
// respond with json
if (req.accepts('json')) {
res.status(404).send({ err: 'Not found' });
return;
}
res.status(404).send('Not found!');
};
|
'use strict';
module.exports = {
post: jest.genMockFunction()
};
|
/**
* @fileoverview Tests for no-plusplus.
* @author Ian Christian Myers
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslint = require("../../../lib/eslint"),
ESLintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var eslintTester = new ESLintTester(eslint);
eslintTester.addRuleTest("lib/rules/no-plusplus", {
valid: [
"var foo = 0; foo=+1;"
],
invalid: [
{ code: "var foo = 0; foo++;", errors: [{ message: "Unary operator '++' used.", type: "UpdateExpression"}] },
{ code: "var foo = 0; foo--;", errors: [{ message: "Unary operator '--' used.", type: "UpdateExpression"}] }
]
});
|
module.exports = function(math) {
var util = require('../../util/index'),
BigNumber = require('bignumber.js'),
Complex = require('../../type/Complex'),
Matrix = require('../../type/Matrix'),
Unit = require('../../type/Unit'),
collection = require('../../type/collection'),
isNumber = util.number.isNumber,
toNumber = util.number.toNumber,
toBigNumber = util.number.toBigNumber,
isBoolean = util['boolean'].isBoolean,
isComplex = Complex.isComplex,
isUnit = Unit.isUnit,
isCollection = collection.isCollection;
/**
* Divide two values.
*
* x / y
* divide(x, y)
*
* @param {Number | BigNumber | Boolean | Complex | Unit | Array | Matrix} x
* @param {Number | BigNumber | Boolean | Complex} y
* @return {Number | BigNumber | Complex | Unit | Array | Matrix} res
*/
math.divide = function divide(x, y) {
if (arguments.length != 2) {
throw new math.error.ArgumentsError('divide', arguments.length, 2);
}
if (isNumber(x)) {
if (isNumber(y)) {
// number / number
return x / y;
}
else if (isComplex(y)) {
// number / complex
return _divideComplex(new Complex(x, 0), y);
}
}
if (isComplex(x)) {
if (isComplex(y)) {
// complex / complex
return _divideComplex(x, y);
}
else if (isNumber(y)) {
// complex / number
return _divideComplex(x, new Complex(y, 0));
}
}
if (x instanceof BigNumber) {
// try to convert to big number
if (isNumber(y)) {
y = toBigNumber(y);
}
else if (isBoolean(y)) {
y = new BigNumber(y ? 1 : 0);
}
if (y instanceof BigNumber) {
return x.div(y);
}
// downgrade to Number
return divide(toNumber(x), y);
}
if (y instanceof BigNumber) {
// try to convert to big number
if (isNumber(x)) {
x = toBigNumber(x);
}
else if (isBoolean(x)) {
x = new BigNumber(x ? 1 : 0);
}
if (x instanceof BigNumber) {
return x.div(y)
}
// downgrade to Number
return divide(x, toNumber(y));
}
if (isUnit(x)) {
if (isNumber(y)) {
var res = x.clone();
res.value /= y;
return res;
}
}
if (isCollection(x)) {
if (isCollection(y)) {
// TODO: implement matrix right division using pseudo inverse
// http://www.mathworks.nl/help/matlab/ref/mrdivide.html
// http://www.gnu.org/software/octave/doc/interpreter/Arithmetic-Ops.html
// http://stackoverflow.com/questions/12263932/how-does-gnu-octave-matrix-division-work-getting-unexpected-behaviour
return math.multiply(x, math.inv(y));
}
else {
// matrix / scalar
return collection.deepMap2(x, y, divide);
}
}
if (isCollection(y)) {
// TODO: implement matrix right division using pseudo inverse
return math.multiply(x, math.inv(y));
}
if (isBoolean(x)) {
return divide(+x, y);
}
if (isBoolean(y)) {
return divide(x, +y);
}
throw new math.error.UnsupportedTypeError('divide', x, y);
};
/**
* Divide two complex numbers. x / y or divide(x, y)
* @param {Complex} x
* @param {Complex} y
* @return {Complex} res
* @private
*/
function _divideComplex (x, y) {
var den = y.re * y.re + y.im * y.im;
if (den != 0) {
return new Complex(
(x.re * y.re + x.im * y.im) / den,
(x.im * y.re - x.re * y.im) / den
);
}
else {
// both y.re and y.im are zero
return new Complex(
(x.re != 0) ? (x.re / 0) : 0,
(x.im != 0) ? (x.im / 0) : 0
);
}
}
};
|
var gulp = require('gulp');
var concat = require('gulp-concat');
var notify = require('gulp-notify');
var notifier = require('../../helpers/notifier');
var tarsConfig = require('../../../tars-config');
/**
* conact data for modules to one file
* @param {object} buildOptions
*/
module.exports = function(buildOptions) {
return gulp.task('html:concat-modules-data', function(cb) {
return gulp.src('./markup/modules/**/data/data.js')
.pipe(concat('modulesData.js', {newLine: ',\n\n'}))
.on('error', notify.onError(function (error) {
return '\nAn error occurred while concating module\'s data.\nLook in the console for details.\n' + error;
}))
.pipe(gulp.dest('./dev/temp/'))
.pipe(
notifier('Data for modules ready')
);
});
};
|
/*!
* jQuery JavaScript Library v2.0.1 -event-alias,-effects,-offset,-deprecated
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-27T01:00Z
*/
(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
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Support: IE9
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "2.0.1 -event-alias,-effects,-offset,-deprecated",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler and self cleanup method
completed = function() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
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 );
}
// Support: Safari <= 5.1 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if ( obj.constructor &&
!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
} catch ( e ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: JSON.parse,
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// 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;
},
trim: function( text ) {
return text == null ? "" : core_trim.call( text );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : core_indexOf.call( arr, elem, i );
},
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 tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: Date.now,
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-15
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied if the test fails
* @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler
*/
function addHandle( attrs, handler, test ) {
attrs = attrs.split("|");
var current,
i = attrs.length,
setHandle = test ? null : handler;
while ( i-- ) {
// Don't override a user's handler
if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) {
Expr.attrHandle[ attrs[i] ] = setHandle;
}
}
}
/**
* Fetches boolean attributes by node
* @param {Element} elem
* @param {String} name
*/
function boolHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
var val = elem.getAttributeNode( name );
return val && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
/**
* Fetches attributes without interpolation
* http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
* @param {Element} elem
* @param {String} name
*/
function interpolationHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
/**
* Uses defaultValue to retrieve value in IE6/7
* @param {Element} elem
* @param {String} name
*/
function valueHandler( elem ) {
// Ignore the value *property* on inputs by using defaultValue
// Fallback to Sizzle.attr by returning undefined where appropriate
// XML does not need to be checked as this will not be assigned for XML documents
if ( elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
// Support: IE<8
// Prevent attribute/property "interpolation"
div.innerHTML = "<a href='#'></a>";
addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" );
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
addHandle( booleans, boolHandler, div.getAttribute("disabled") == null );
div.className = "i";
return !div.getAttribute("className");
});
// Support: IE<9
// Retrieving value should defer to defaultValue
support.input = assert(function( div ) {
div.innerHTML = "<input>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
});
// IE6/7 still return empty string for value,
// but are actually retrieving the property
addHandle( "value", valueHandler, support.attributes && support.input );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( doc.createElement("div") ) & 1;
});
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined );
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize against the default document
setDocument();
// Support: Chrome<<14
// Always assume duplicates if they aren't passed to the comparison function
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var input = document.createElement("input"),
fragment = document.createDocumentFragment(),
div = document.createElement("div"),
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Finish early in limited environments
if ( !input.type ) {
return support;
}
input.type = "checkbox";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Will be defined later
support.reliableMarginRight = true;
support.boxSizingReliable = true;
support.pixelPosition = false;
// Make sure checked status is properly cloned
// Support: IE9, IE10
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;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement("input");
input.value = "t";
input.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.appendChild( input );
// Support: Safari 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: Firefox, Chrome, Safari
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
support.focusinBubbles = "onfocusin" in window;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv,
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;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";
// Check box-sizing and margin behavior.
body.appendChild( container ).appendChild( div );
div.innerHTML = "";
// Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// 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 );
}
body.removeChild( container );
});
return support;
})( {} );
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var data_user, data_priv,
rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType ?
owner.nodeType === 1 || owner.nodeType === 9 : true;
};
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
return this.get( owner, key );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// 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 = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( core_rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
// These may be used throughout the jQuery core codebase
data_user = new Data();
data_priv = new Data();
jQuery.extend({
acceptData: Data.accepts,
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[ 0 ],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return jQuery.access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
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 ) ? JSON.parse( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( 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 ? "" : data_priv.get( 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 hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// 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 ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
// Temporarily disable this handler to check existence
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
// Restore handler
jQuery.expr.attrHandle[ name ] = fn;
return ret;
};
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
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 process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// 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 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;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// 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 core_indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return core_indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
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 = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because core_push.apply(_, arraylike) throws
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
i = 0,
l = elems.length,
fragment = context.createDocumentFragment(),
nodes = [];
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.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.firstChild;
}
// Support: QtWebKit
// jQuery.merge because core_push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.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 );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, events, type, key, j,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( Data.accepts( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
events = Object.keys( data.events || {} );
if ( events.length ) {
for ( j = 0; (type = events[j]) !== undefined; j++ ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var l = elems.length,
i = 0;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var curCSS, iframe,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
function getStyles( elem ) {
return window.getComputedStyle( elem, null );
}
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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} 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 val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: Safari 5.1
// A tribute to the "awesome hack by Dean Edwards"
// 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;
};
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
// Support: Android 2.3
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// Support: Android 2.3
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #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 = jQuery.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 jQuery.ajaxPrefilter and jQuery.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 ( jQuery.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;
jQuery.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 key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.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 ) {
jQuery.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
jQuery("<div>").append( jQuery.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
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.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",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.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, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.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 transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.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 (prefilters might expect it)
// 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 = jQuery.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 = jQuery.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 && jQuery.active++ === 0 ) {
jQuery.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 ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.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;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// 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 ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.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 ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// 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
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else 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.unshift( tmp[ 1 ] );
}
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 };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.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 = jQuery.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 ) {
jQuery.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 && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrSupported = jQuery.ajaxSettings.xhr(),
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
// Support: IE9
// We need to keep track of outbound xhr and abort them manually
// because IE is not smart enough to do it all by itself
xhrId = 0,
xhrCallbacks = {};
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
xhrCallbacks = undefined;
});
}
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
jQuery.support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i, id,
xhr = options.xhr();
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file protocol always yields status 0, assume 404
xhr.status || 404,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// #11426: When requesting binary data, IE9 will throw an exception
// on any attempt to access responseText
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[( id = xhrId++ )] = callback("abort");
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( options.hasContent && options.data || null );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
// If there is a window object, that at least has a document property,
// define jQuery and $ identifiers
if ( typeof window === "object" && typeof window.document === "object" ) {
window.jQuery = window.$ = jQuery;
}
})( window );
|
/* eslint-disable */
/* ===========================================================
* bootstrap-modalmanager.js v2.2.5
* ===========================================================
* Copyright 2012 Jordan Schroter.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
!function($) {
"use strict"; // jshint ;_;
/* MODAL MANAGER CLASS DEFINITION
* ====================== */
var ModalManager = function (element, options) {
this.init(element, options);
};
ModalManager.prototype = {
constructor: ModalManager,
init: function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
this.stack = [];
this.backdropCount = 0;
if (this.options.resize) {
var resizeTimeout,
that = this;
$(window).on('resize.modal', function(){
resizeTimeout && clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function(){
for (var i = 0; i < that.stack.length; i++){
that.stack[i].isShown && that.stack[i].layout();
}
}, 10);
});
}
},
createModal: function (element, options) {
$(element).modal($.extend({ manager: this }, options));
},
appendModal: function (modal) {
this.stack.push(modal);
var that = this;
modal.$element.on('show.modalmanager', targetIsSelf(function (e) {
var showModal = function(){
modal.isShown = true;
var transition = $.support.transition && modal.$element.hasClass('fade');
that.$element
.toggleClass('modal-open', that.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < that.$element.height());
modal.$parent = modal.$element.parent();
modal.$container = that.createContainer(modal);
modal.$element.appendTo(modal.$container);
that.backdrop(modal, function () {
modal.$element.show();
if (transition) {
//modal.$element[0].style.display = 'run-in';
modal.$element[0].offsetWidth;
//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
}
modal.layout();
modal.$element
.addClass('in')
.attr('aria-hidden', false);
var complete = function () {
that.setFocus();
modal.$element.trigger('shown');
};
transition ?
modal.$element.one($.support.transition.end, complete) :
complete();
});
};
modal.options.replace ?
that.replace(showModal) :
showModal();
}));
modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {
that.backdrop(modal);
// handle the case when a modal may have been removed from the dom before this callback executes
if (!modal.$element.parent().length) {
that.destroyModal(modal);
} else if (modal.$backdrop){
var transition = $.support.transition && modal.$element.hasClass('fade');
// trigger a relayout due to firebox's buggy transition end event
if (transition) { modal.$element[0].offsetWidth; }
$.support.transition && modal.$element.hasClass('fade') ?
modal.$backdrop.one($.support.transition.end, function () { modal.destroy(); }) :
modal.destroy();
} else {
modal.destroy();
}
}));
modal.$element.on('destroyed.modalmanager', targetIsSelf(function (e) {
that.destroyModal(modal);
}));
},
getOpenModals: function () {
var openModals = [];
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) openModals.push(this.stack[i]);
}
return openModals;
},
hasOpenModal: function () {
return this.getOpenModals().length > 0;
},
setFocus: function () {
var topModal;
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
if (!topModal) return;
topModal.focus();
},
destroyModal: function (modal) {
modal.$element.off('.modalmanager');
if (modal.$backdrop) this.removeBackdrop(modal);
this.stack.splice(this.getIndexOfModal(modal), 1);
var hasOpenModal = this.hasOpenModal();
this.$element.toggleClass('modal-open', hasOpenModal);
if (!hasOpenModal){
this.$element.removeClass('page-overflow');
}
this.removeContainer(modal);
this.setFocus();
},
getModalAt: function (index) {
return this.stack[index];
},
getIndexOfModal: function (modal) {
for (var i = 0; i < this.stack.length; i++){
if (modal === this.stack[i]) return i;
}
},
replace: function (callback) {
var topModal;
for (var i = 0; i < this.stack.length; i++){
if (this.stack[i].isShown) topModal = this.stack[i];
}
if (topModal) {
this.$backdropHandle = topModal.$backdrop;
topModal.$backdrop = null;
callback && topModal.$element.one('hidden',
targetIsSelf( $.proxy(callback, this) ));
topModal.hide();
} else if (callback) {
callback();
}
},
removeBackdrop: function (modal) {
modal.$backdrop.remove();
modal.$backdrop = null;
},
createBackdrop: function (animate, tmpl) {
var $backdrop;
if (!this.$backdropHandle) {
$backdrop = $(tmpl)
.addClass(animate)
.appendTo(this.$element);
} else {
$backdrop = this.$backdropHandle;
$backdrop.off('.modalmanager');
this.$backdropHandle = null;
this.isLoading && this.removeSpinner();
}
return $backdrop;
},
removeContainer: function (modal) {
modal.$container.remove();
modal.$container = null;
},
createContainer: function (modal) {
var $container;
$container = $('<div class="modal-scrollable">')
.css('z-index', getzIndex('modal', this.getOpenModals().length))
.appendTo(this.$element);
if (modal && modal.options.backdrop != 'static') {
$container.on('click.modal', targetIsSelf(function (e) {
modal.hide();
}));
} else if (modal) {
$container.on('click.modal', targetIsSelf(function (e) {
modal.attention();
}));
}
return $container;
},
backdrop: function (modal, callback) {
var animate = modal.$element.hasClass('fade') ? 'fade' : '',
showBackdrop = modal.options.backdrop &&
this.backdropCount < this.options.backdropLimit;
if (modal.isShown && showBackdrop) {
var doAnimate = $.support.transition && animate && !this.$backdropHandle;
modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);
modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));
if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow
modal.$backdrop.addClass('in');
this.backdropCount += 1;
doAnimate ?
modal.$backdrop.one($.support.transition.end, callback) :
callback();
} else if (!modal.isShown && modal.$backdrop) {
modal.$backdrop.removeClass('in');
this.backdropCount -= 1;
var that = this;
$.support.transition && modal.$element.hasClass('fade')?
modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
that.removeBackdrop(modal);
} else if (callback) {
callback();
}
},
removeSpinner: function(){
this.$spinner && this.$spinner.remove();
this.$spinner = null;
this.isLoading = false;
},
removeLoading: function () {
this.$backdropHandle && this.$backdropHandle.remove();
this.$backdropHandle = null;
this.removeSpinner();
},
loading: function (callback) {
callback = callback || function () { };
this.$element
.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
.toggleClass('page-overflow', $(window).height() < this.$element.height());
if (!this.isLoading) {
this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);
this.$backdropHandle[0].offsetWidth; // force reflow
var openModals = this.getOpenModals();
this.$backdropHandle
.css('z-index', getzIndex('backdrop', openModals.length + 1))
.addClass('in');
var $spinner = $(this.options.spinner)
.css('z-index', getzIndex('modal', openModals.length + 1))
.appendTo(this.$element)
.addClass('in');
this.$spinner = $(this.createContainer())
.append($spinner)
.on('click.modalmanager', $.proxy(this.loading, this));
this.isLoading = true;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, callback) :
callback();
} else if (this.isLoading && this.$backdropHandle) {
this.$backdropHandle.removeClass('in');
var that = this;
$.support.transition ?
this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
that.removeLoading();
} else if (callback) {
callback(this.isLoading);
}
}
};
/* PRIVATE METHODS
* ======================= */
// computes and caches the zindexes
var getzIndex = (function () {
var zIndexFactor,
baseIndex = {};
return function (type, pos) {
if (typeof zIndexFactor === 'undefined'){
var $baseModal = $('<div class="modal hide" />').appendTo('body'),
$baseBackdrop = $('<div class="modal-backdrop hide" />').appendTo('body');
baseIndex['modal'] = +$baseModal.css('z-index');
baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];
$baseModal.remove();
$baseBackdrop.remove();
$baseBackdrop = $baseModal = null;
}
return baseIndex[type] + (zIndexFactor * pos);
}
}());
// make sure the event target is the modal itself in order to prevent
// other components such as tabsfrom triggering the modal manager.
// if Boostsrap namespaced events, this would not be needed.
function targetIsSelf(callback){
return function (e) {
if (e && this === e.target){
return callback.apply(this, arguments);
}
}
}
/* MODAL MANAGER PLUGIN DEFINITION
* ======================= */
$.fn.modalmanager = function (option, args) {
return this.each(function () {
var $this = $(this),
data = $this.data('modalmanager');
if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
if (typeof option === 'string') data[option].apply(data, [].concat(args))
})
};
$.fn.modalmanager.defaults = {
backdropLimit: 999,
resize: true,
spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
backdropTemplate: '<div class="modal-backdrop" />'
};
$.fn.modalmanager.Constructor = ModalManager;
// ModalManager handles the modal-open class so we need
// to remove conflicting bootstrap 3 event handlers
$(function () {
$(document).off('show.bs.modal').off('hidden.bs.modal');
});
}(jQuery);
|
/**
* sifter.js
* Copyright (c) 2013 Brian Reavis & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('sifter', factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.Sifter = factory();
}
}(this, function() {
/**
* Textually searches arrays and hashes of objects
* by property (or multiple properties). Designed
* specifically for autocomplete.
*
* @constructor
* @param {array|object} items
* @param {object} items
*/
var Sifter = function(items, settings) {
this.items = items;
this.settings = settings || {
diacritics: true
};
};
/**
* Splits a search string into an array of individual
* regexps to be used to match results.
*
* @param {string} query
* @returns {array}
*/
Sifter.prototype.tokenize = function(query) {
query = trim(String(query || '').toLowerCase());
if (!query || !query.length) return [];
var i, n, regex, letter;
var tokens = [];
var words = query.split(/ +/);
for (i = 0, n = words.length; i < n; i++) {
regex = escape_regex(words[i]);
if (this.settings.diacritics) {
for (letter in DIACRITICS) {
if (DIACRITICS.hasOwnProperty(letter)) {
regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
}
}
}
tokens.push({
string: words[i],
regex: new RegExp(regex, 'i')
});
}
return tokens;
};
/**
* Iterates over arrays and hashes.
*
* ```
* this.iterator(this.items, function(item, id) {
* // invoked for each item
* });
* ```
*
* @param {array|object} object
*/
Sifter.prototype.iterator = function(object, callback) {
var iterator;
if (is_array(object)) {
iterator = Array.prototype.forEach || function(callback) {
for (var i = 0, n = this.length; i < n; i++) {
callback(this[i], i, this);
}
};
} else {
iterator = function(callback) {
for (var key in this) {
if (this.hasOwnProperty(key)) {
callback(this[key], key, this);
}
}
};
}
iterator.apply(object, [callback]);
};
/**
* Returns a function to be used to score individual results.
*
* Good matches will have a higher score than poor matches.
* If an item is not a match, 0 will be returned by the function.
*
* @param {object|string} search
* @param {object} options (optional)
* @returns {function}
*/
Sifter.prototype.getScoreFunction = function(search, options) {
var self, fields, tokens, token_count;
self = this;
search = self.prepareSearch(search, options);
tokens = search.tokens;
fields = search.options.fields;
token_count = tokens.length;
/**
* Calculates how close of a match the
* given value is against a search token.
*
* @param {mixed} value
* @param {object} token
* @return {number}
*/
var scoreValue = function(value, token) {
var score, pos;
if (!value) return 0;
value = String(value || '');
pos = value.search(token.regex);
if (pos === -1) return 0;
score = token.string.length / value.length;
if (pos === 0) score += 0.5;
return score;
};
/**
* Calculates the score of an object
* against the search query.
*
* @param {object} token
* @param {object} data
* @return {number}
*/
var scoreObject = (function() {
var field_count = fields.length;
if (!field_count) {
return function() {
return 0;
};
}
if (field_count === 1) {
return function(token, data) {
return scoreValue(data[fields[0]], token);
};
}
return function(token, data) {
for (var i = 0, sum = 0; i < field_count; i++) {
sum += scoreValue(data[fields[i]], token);
}
return sum / field_count;
};
})();
if (!token_count) {
return function() {
return 0;
};
}
if (token_count === 1) {
return function(data) {
return scoreObject(tokens[0], data);
};
}
if (search.options.conjunction === 'and') {
return function(data) {
var score;
for (var i = 0, sum = 0; i < token_count; i++) {
score = scoreObject(tokens[i], data);
if (score <= 0) return 0;
sum += score;
}
return sum / token_count;
};
} else {
return function(data) {
for (var i = 0, sum = 0; i < token_count; i++) {
sum += scoreObject(tokens[i], data);
}
return sum / token_count;
};
}
};
/**
* Returns a function that can be used to compare two
* results, for sorting purposes. If no sorting should
* be performed, `null` will be returned.
*
* @param {string|object} search
* @param {object} options
* @return function(a,b)
*/
Sifter.prototype.getSortFunction = function(search, options) {
var i, n, self, field, fields, fields_count, multiplier, multipliers, get_field, implicit_score, sort;
self = this;
search = self.prepareSearch(search, options);
sort = (!search.query && options.sort_empty) || options.sort;
/**
* Fetches the specified sort field value
* from a search result item.
*
* @param {string} name
* @param {object} result
* @return {mixed}
*/
get_field = function(name, result) {
if (name === '$score') return result.score;
return self.items[result.id][name];
};
// parse options
fields = [];
if (sort) {
for (i = 0, n = sort.length; i < n; i++) {
if (search.query || sort[i].field !== '$score') {
fields.push(sort[i]);
}
}
}
// the "$score" field is implied to be the primary
// sort field, unless it's manually specified
if (search.query) {
implicit_score = true;
for (i = 0, n = fields.length; i < n; i++) {
if (fields[i].field === '$score') {
implicit_score = false;
break;
}
}
if (implicit_score) {
fields.unshift({
field: '$score',
direction: 'desc'
});
}
} else {
for (i = 0, n = fields.length; i < n; i++) {
if (fields[i].field === '$score') {
fields.splice(i, 1);
break;
}
}
}
multipliers = [];
for (i = 0, n = fields.length; i < n; i++) {
multipliers.push(fields[i].direction === 'desc' ? -1 : 1);
}
// build function
fields_count = fields.length;
if (!fields_count) {
return null;
} else if (fields_count === 1) {
field = fields[0].field;
multiplier = multipliers[0];
return function(a, b) {
return multiplier * cmp(
get_field(field, a),
get_field(field, b)
);
};
} else {
return function(a, b) {
var i, result, a_value, b_value, field;
for (i = 0; i < fields_count; i++) {
field = fields[i].field;
result = multipliers[i] * cmp(
get_field(field, a),
get_field(field, b)
);
if (result) return result;
}
return 0;
};
}
};
/**
* Parses a search query and returns an object
* with tokens and fields ready to be populated
* with results.
*
* @param {string} query
* @param {object} options
* @returns {object}
*/
Sifter.prototype.prepareSearch = function(query, options) {
if (typeof query === 'object') return query;
options = extend({}, options);
var option_fields = options.fields;
var option_sort = options.sort;
var option_sort_empty = options.sort_empty;
if (option_fields && !is_array(option_fields)) options.fields = [option_fields];
if (option_sort && !is_array(option_sort)) options.sort = [option_sort];
if (option_sort_empty && !is_array(option_sort_empty)) options.sort_empty = [option_sort_empty];
return {
options: options,
query: String(query || '').toLowerCase(),
tokens: this.tokenize(query),
total: 0,
items: []
};
};
/**
* Searches through all items and returns a sorted array of matches.
*
* The `options` parameter can contain:
*
* - fields {string|array}
* - sort {array}
* - score {function}
* - filter {bool}
* - limit {integer}
*
* Returns an object containing:
*
* - options {object}
* - query {string}
* - tokens {array}
* - total {int}
* - items {array}
*
* @param {string} query
* @param {object} options
* @returns {object}
*/
Sifter.prototype.search = function(query, options) {
var self = this,
value, score, search, calculateScore;
var fn_sort;
var fn_score;
search = this.prepareSearch(query, options);
options = search.options;
query = search.query;
// generate result scoring function
fn_score = options.score || self.getScoreFunction(search);
// perform search and sort
if (query.length) {
self.iterator(self.items, function(item, id) {
score = fn_score(item);
if (options.filter === false || score > 0) {
search.items.push({
'score': score,
'id': id
});
}
});
} else {
self.iterator(self.items, function(item, id) {
search.items.push({
'score': 1,
'id': id
});
});
}
fn_sort = self.getSortFunction(search, options);
if (fn_sort) search.items.sort(fn_sort);
// apply limits
search.total = search.items.length;
if (typeof options.limit === 'number') {
search.items = search.items.slice(0, options.limit);
}
return search;
};
// utilities
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var cmp = function(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a > b ? 1 : (a < b ? -1 : 0);
}
a = asciifold(String(a || ''));
b = asciifold(String(b || ''));
if (a > b) return 1;
if (b > a) return -1;
return 0;
};
var extend = function(a, b) {
var i, n, k, object;
for (i = 1, n = arguments.length; i < n; i++) {
object = arguments[i];
if (!object) continue;
for (k in object) {
if (object.hasOwnProperty(k)) {
a[k] = object[k];
}
}
}
return a;
};
var trim = function(str) {
return (str + '').replace(/^\s+|\s+$|/g, '');
};
var escape_regex = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
var is_array = Array.isArray || ($ && $.isArray) || function(object) {
return Object.prototype.toString.call(object) === '[object Array]';
};
var DIACRITICS = {
'a': '[aÀÁÂÃÄÅàáâãäåĀāąĄ]',
'c': '[cÇçćĆčČ]',
'd': '[dđĐďĎ]',
'e': '[eÈÉÊËèéêëěĚĒēęĘ]',
'i': '[iÌÍÎÏìíîïĪī]',
'l': '[lłŁ]',
'n': '[nÑñňŇńŃ]',
'o': '[oÒÓÔÕÕÖØòóôõöøŌō]',
'r': '[rřŘ]',
's': '[sŠšśŚ]',
't': '[tťŤ]',
'u': '[uÙÚÛÜùúûüůŮŪū]',
'y': '[yŸÿýÝ]',
'z': '[zŽžżŻźŹ]'
};
var asciifold = (function() {
var i, n, k, chunk;
var foreignletters = '';
var lookup = {};
for (k in DIACRITICS) {
if (DIACRITICS.hasOwnProperty(k)) {
chunk = DIACRITICS[k].substring(2, DIACRITICS[k].length - 1);
foreignletters += chunk;
for (i = 0, n = chunk.length; i < n; i++) {
lookup[chunk.charAt(i)] = k;
}
}
}
var regexp = new RegExp('[' + foreignletters + ']', 'g');
return function(str) {
return str.replace(regexp, function(foreignletter) {
return lookup[foreignletter];
}).toLowerCase();
};
})();
// export
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
return Sifter;
}));
/**
* microplugin.js
* Copyright (c) 2013 Brian Reavis & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('microplugin', factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.MicroPlugin = factory();
}
}(this, function() {
var MicroPlugin = {};
MicroPlugin.mixin = function(Interface) {
Interface.plugins = {};
/**
* Initializes the listed plugins (with options).
* Acceptable formats:
*
* List (without options):
* ['a', 'b', 'c']
*
* List (with options):
* [{'name': 'a', options: {}}, {'name': 'b', options: {}}]
*
* Hash (with options):
* {'a': { ... }, 'b': { ... }, 'c': { ... }}
*
* @param {mixed} plugins
*/
Interface.prototype.initializePlugins = function(plugins) {
var i, n, key;
var self = this;
var queue = [];
self.plugins = {
names: [],
settings: {},
requested: {},
loaded: {}
};
if (utils.isArray(plugins)) {
for (i = 0, n = plugins.length; i < n; i++) {
if (typeof plugins[i] === 'string') {
queue.push(plugins[i]);
} else {
self.plugins.settings[plugins[i].name] = plugins[i].options;
queue.push(plugins[i].name);
}
}
} else if (plugins) {
for (key in plugins) {
if (plugins.hasOwnProperty(key)) {
self.plugins.settings[key] = plugins[key];
queue.push(key);
}
}
}
while (queue.length) {
self.require(queue.shift());
}
};
Interface.prototype.loadPlugin = function(name) {
var self = this;
var plugins = self.plugins;
var plugin = Interface.plugins[name];
if (!Interface.plugins.hasOwnProperty(name)) {
throw new Error('Unable to find "' + name + '" plugin');
}
plugins.requested[name] = true;
plugins.loaded[name] = plugin.fn.apply(self, [self.plugins.settings[name] || {}]);
plugins.names.push(name);
};
/**
* Initializes a plugin.
*
* @param {string} name
*/
Interface.prototype.require = function(name) {
var self = this;
var plugins = self.plugins;
if (!self.plugins.loaded.hasOwnProperty(name)) {
if (plugins.requested[name]) {
throw new Error('Plugin has circular dependency ("' + name + '")');
}
self.loadPlugin(name);
}
return plugins.loaded[name];
};
/**
* Registers a plugin.
*
* @param {string} name
* @param {function} fn
*/
Interface.define = function(name, fn) {
Interface.plugins[name] = {
'name': name,
'fn': fn
};
};
};
var utils = {
isArray: Array.isArray || function(vArg) {
return Object.prototype.toString.call(vArg) === '[object Array]';
}
};
return MicroPlugin;
}));
/**
* selectize.js (v0.12.1)
* Copyright (c) 2013–2015 Brian Reavis & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Brian Reavis <brian@thirdroute.com>
*/
/*jshint curly:false */
/*jshint browser:true */
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('selectize', ['jquery', 'sifter', 'microplugin'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('jquery'), require('sifter'), require('microplugin'));
} else {
root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin);
}
}(this, function($, Sifter, MicroPlugin) {
'use strict';
var highlight = function($element, pattern) {
if (typeof pattern === 'string' && !pattern.length) return;
var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
var highlight = function(node) {
var skip = 0;
if (node.nodeType === 3) {
var pos = node.data.search(regex);
if (pos >= 0 && node.data.length > 0) {
var match = node.data.match(regex);
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(match[0].length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += highlight(node.childNodes[i]);
}
}
return skip;
};
return $element.each(function() {
highlight(this);
});
};
var MicroEvent = function() {};
MicroEvent.prototype = {
on: function(event, fct) {
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
},
off: function(event, fct) {
var n = arguments.length;
if (n === 0) return delete this._events;
if (n === 1) return delete this._events[event];
this._events = this._events || {};
if (event in this._events === false) return;
this._events[event].splice(this._events[event].indexOf(fct), 1);
},
trigger: function(event /* , args... */ ) {
this._events = this._events || {};
if (event in this._events === false) return;
for (var i = 0; i < this._events[event].length; i++) {
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
/**
* Mixin will delegate all MicroEvent.js function in the destination object.
*
* - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent
*
* @param {object} the object which will support MicroEvent
*/
MicroEvent.mixin = function(destObject) {
var props = ['on', 'off', 'trigger'];
for (var i = 0; i < props.length; i++) {
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
}
};
var IS_MAC = /Mac/.test(navigator.userAgent);
var KEY_A = 65;
var KEY_COMMA = 188;
var KEY_RETURN = 13;
var KEY_ESC = 27;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_P = 80;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_N = 78;
var KEY_BACKSPACE = 8;
var KEY_DELETE = 46;
var KEY_SHIFT = 16;
var KEY_CMD = IS_MAC ? 91 : 17;
var KEY_CTRL = IS_MAC ? 18 : 17;
var KEY_TAB = 9;
var TAG_SELECT = 1;
var TAG_INPUT = 2;
// for now, android support in general is too spotty to support validity
var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('form').validity;
var isset = function(object) {
return typeof object !== 'undefined';
};
/**
* Converts a scalar to its best string representation
* for hash keys and HTML attribute values.
*
* Transformations:
* 'str' -> 'str'
* null -> ''
* undefined -> ''
* true -> '1'
* false -> '0'
* 0 -> '0'
* 1 -> '1'
*
* @param {string} value
* @returns {string|null}
*/
var hash_key = function(value) {
if (typeof value === 'undefined' || value === null) return null;
if (typeof value === 'boolean') return value ? '1' : '0';
return value + '';
};
/**
* Escapes a string for use within HTML.
*
* @param {string} str
* @returns {string}
*/
var escape_html = function(str) {
return (str + '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
/**
* Escapes "$" characters in replacement strings.
*
* @param {string} str
* @returns {string}
*/
var escape_replace = function(str) {
return (str + '').replace(/\$/g, '$$$$');
};
var hook = {};
/**
* Wraps `method` on `self` so that `fn`
* is invoked before the original method.
*
* @param {object} self
* @param {string} method
* @param {function} fn
*/
hook.before = function(self, method, fn) {
var original = self[method];
self[method] = function() {
fn.apply(self, arguments);
return original.apply(self, arguments);
};
};
/**
* Wraps `method` on `self` so that `fn`
* is invoked after the original method.
*
* @param {object} self
* @param {string} method
* @param {function} fn
*/
hook.after = function(self, method, fn) {
var original = self[method];
self[method] = function() {
var result = original.apply(self, arguments);
fn.apply(self, arguments);
return result;
};
};
/**
* Wraps `fn` so that it can only be invoked once.
*
* @param {function} fn
* @returns {function}
*/
var once = function(fn) {
var called = false;
return function() {
if (called) return;
called = true;
fn.apply(this, arguments);
};
};
/**
* Wraps `fn` so that it can only be called once
* every `delay` milliseconds (invoked on the falling edge).
*
* @param {function} fn
* @param {int} delay
* @returns {function}
*/
var debounce = function(fn, delay) {
var timeout;
return function() {
var self = this;
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(self, args);
}, delay);
};
};
/**
* Debounce all fired events types listed in `types`
* while executing the provided `fn`.
*
* @param {object} self
* @param {array} types
* @param {function} fn
*/
var debounce_events = function(self, types, fn) {
var type;
var trigger = self.trigger;
var event_args = {};
// override trigger method
self.trigger = function() {
var type = arguments[0];
if (types.indexOf(type) !== -1) {
event_args[type] = arguments;
} else {
return trigger.apply(self, arguments);
}
};
// invoke provided function
fn.apply(self, []);
self.trigger = trigger;
// trigger queued events
for (type in event_args) {
if (event_args.hasOwnProperty(type)) {
trigger.apply(self, event_args[type]);
}
}
};
/**
* A workaround for http://bugs.jquery.com/ticket/6696
*
* @param {object} $parent - Parent element to listen on.
* @param {string} event - Event name.
* @param {string} selector - Descendant selector to filter by.
* @param {function} fn - Event handler.
*/
var watchChildEvent = function($parent, event, selector, fn) {
$parent.on(event, selector, function(e) {
var child = e.target;
while (child && child.parentNode !== $parent[0]) {
child = child.parentNode;
}
e.currentTarget = child;
return fn.apply(this, [e]);
});
};
/**
* Determines the current selection within a text input control.
* Returns an object containing:
* - start
* - length
*
* @param {object} input
* @returns {object}
*/
var getSelection = function(input) {
var result = {};
if ('selectionStart' in input) {
result.start = input.selectionStart;
result.length = input.selectionEnd - result.start;
} else if (document.selection) {
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
result.start = sel.text.length - selLen;
result.length = selLen;
}
return result;
};
/**
* Copies CSS properties from one element to another.
*
* @param {object} $from
* @param {object} $to
* @param {array} properties
*/
var transferStyles = function($from, $to, properties) {
var i, n, styles = {};
if (properties) {
for (i = 0, n = properties.length; i < n; i++) {
styles[properties[i]] = $from.css(properties[i]);
}
} else {
styles = $from.css();
}
$to.css(styles);
};
/**
* Measures the width of a string within a
* parent element (in pixels).
*
* @param {string} str
* @param {object} $parent
* @returns {int}
*/
var measureString = function(str, $parent) {
if (!str) {
return 0;
}
var $test = $('<test>').css({
position: 'absolute',
top: -99999,
left: -99999,
width: 'auto',
padding: 0,
whiteSpace: 'pre'
}).text(str).appendTo('body');
transferStyles($parent, $test, [
'letterSpacing',
'fontSize',
'fontFamily',
'fontWeight',
'textTransform'
]);
var width = $test.width();
$test.remove();
return width;
};
/**
* Sets up an input to grow horizontally as the user
* types. If the value is changed manually, you can
* trigger the "update" handler to resize:
*
* $input.trigger('update');
*
* @param {object} $input
*/
var autoGrow = function($input) {
var currentWidth = null;
var update = function(e, options) {
var value, keyCode, printable, placeholder, width;
var shift, character, selection;
e = e || window.event || {};
options = options || {};
if (e.metaKey || e.altKey) return;
if (!options.force && $input.data('grow') === false) return;
value = $input.val();
if (e.type && e.type.toLowerCase() === 'keydown') {
keyCode = e.keyCode;
printable = (
(keyCode >= 97 && keyCode <= 122) || // a-z
(keyCode >= 65 && keyCode <= 90) || // A-Z
(keyCode >= 48 && keyCode <= 57) || // 0-9
keyCode === 32 // space
);
if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) {
selection = getSelection($input[0]);
if (selection.length) {
value = value.substring(0, selection.start) + value.substring(selection.start + selection.length);
} else if (keyCode === KEY_BACKSPACE && selection.start) {
value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1);
} else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') {
value = value.substring(0, selection.start) + value.substring(selection.start + 1);
}
} else if (printable) {
shift = e.shiftKey;
character = String.fromCharCode(e.keyCode);
if (shift) character = character.toUpperCase();
else character = character.toLowerCase();
value += character;
}
}
placeholder = $input.attr('placeholder');
if (!value && placeholder) {
value = placeholder;
}
width = measureString(value, $input) + 4;
if (width !== currentWidth) {
currentWidth = width;
$input.width(width);
$input.triggerHandler('resize');
}
};
$input.on('keydown keyup update blur', update);
update();
};
var Selectize = function($input, settings) {
var key, i, n, dir, input, self = this;
input = $input[0];
input.selectize = self;
// detect rtl environment
var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null);
dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction;
dir = dir || $input.parents('[dir]:first').attr('dir') || '';
// setup default state
$.extend(self, {
order: 0,
settings: settings,
$input: $input,
tabIndex: $input.attr('tabindex') || '',
tagType: input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT,
rtl: /rtl/i.test(dir),
eventNS: '.selectize' + (++Selectize.count),
highlightedValue: null,
isOpen: false,
isDisabled: false,
isRequired: $input.is('[required]'),
isInvalid: false,
isLocked: false,
isFocused: false,
isInputHidden: false,
isSetup: false,
isShiftDown: false,
isCmdDown: false,
isCtrlDown: false,
ignoreFocus: false,
ignoreBlur: false,
ignoreHover: false,
hasOptions: false,
currentResults: null,
lastValue: '',
caretPos: 0,
loading: 0,
loadedSearches: {},
$activeOption: null,
$activeItems: [],
optgroups: {},
options: {},
userOptions: {},
items: [],
renderCache: {},
onSearchChange: settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle)
});
// search system
self.sifter = new Sifter(this.options, {
diacritics: settings.diacritics
});
// build options table
if (self.settings.options) {
for (i = 0, n = self.settings.options.length; i < n; i++) {
self.registerOption(self.settings.options[i]);
}
delete self.settings.options;
}
// build optgroup table
if (self.settings.optgroups) {
for (i = 0, n = self.settings.optgroups.length; i < n; i++) {
self.registerOptionGroup(self.settings.optgroups[i]);
}
delete self.settings.optgroups;
}
// option-dependent defaults
self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi');
if (typeof self.settings.hideSelected !== 'boolean') {
self.settings.hideSelected = self.settings.mode === 'multi';
}
self.initializePlugins(self.settings.plugins);
self.setupCallbacks();
self.setupTemplates();
self.setup();
};
// mixins
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MicroEvent.mixin(Selectize);
MicroPlugin.mixin(Selectize);
// methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
$.extend(Selectize.prototype, {
/**
* Creates all elements and sets up event bindings.
*/
setup: function() {
var self = this;
var settings = self.settings;
var eventNS = self.eventNS;
var $window = $(window);
var $document = $(document);
var $input = self.$input;
var $wrapper;
var $control;
var $control_input;
var $dropdown;
var $dropdown_content;
var $dropdown_parent;
var inputMode;
var timeout_blur;
var timeout_focus;
var classes;
var classes_plugins;
inputMode = self.settings.mode;
classes = $input.attr('class') || '';
$wrapper = $('<div>').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode);
$control = $('<div>').addClass(settings.inputClass).addClass('items').appendTo($wrapper);
$control_input = $('<input type="text" autocomplete="off" />').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex);
$dropdown_parent = $(settings.dropdownParent || $wrapper);
$dropdown = $('<div>').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent);
$dropdown_content = $('<div>').addClass(settings.dropdownContentClass).appendTo($dropdown);
if (self.settings.copyClassesToDropdown) {
$dropdown.addClass(classes);
}
$wrapper.css({
width: $input[0].style.width
});
if (self.plugins.names.length) {
classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-');
$wrapper.addClass(classes_plugins);
$dropdown.addClass(classes_plugins);
}
if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) {
$input.attr('multiple', 'multiple');
}
if (self.settings.placeholder) {
$control_input.attr('placeholder', settings.placeholder);
}
// if splitOn was not passed in, construct it from the delimiter to allow pasting universally
if (!self.settings.splitOn && self.settings.delimiter) {
var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*');
}
if ($input.attr('autocorrect')) {
$control_input.attr('autocorrect', $input.attr('autocorrect'));
}
if ($input.attr('autocapitalize')) {
$control_input.attr('autocapitalize', $input.attr('autocapitalize'));
}
self.$wrapper = $wrapper;
self.$control = $control;
self.$control_input = $control_input;
self.$dropdown = $dropdown;
self.$dropdown_content = $dropdown_content;
$dropdown.on('mouseenter', '[data-selectable]', function() {
return self.onOptionHover.apply(self, arguments);
});
$dropdown.on('mousedown click', '[data-selectable]', function() {
return self.onOptionSelect.apply(self, arguments);
});
watchChildEvent($control, 'mousedown', '*:not(input)', function() {
return self.onItemSelect.apply(self, arguments);
});
autoGrow($control_input);
$control.on({
mousedown: function() {
return self.onMouseDown.apply(self, arguments);
},
click: function() {
return self.onClick.apply(self, arguments);
}
});
$control_input.on({
mousedown: function(e) {
e.stopPropagation();
},
keydown: function() {
return self.onKeyDown.apply(self, arguments);
},
keyup: function() {
return self.onKeyUp.apply(self, arguments);
},
keypress: function() {
return self.onKeyPress.apply(self, arguments);
},
resize: function() {
self.positionDropdown.apply(self, []);
},
blur: function() {
return self.onBlur.apply(self, arguments);
},
focus: function() {
self.ignoreBlur = false;
return self.onFocus.apply(self, arguments);
},
paste: function() {
return self.onPaste.apply(self, arguments);
}
});
$document.on('keydown' + eventNS, function(e) {
self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey'];
self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
self.isShiftDown = e.shiftKey;
});
$document.on('keyup' + eventNS, function(e) {
if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
if (e.keyCode === KEY_CMD) self.isCmdDown = false;
});
$document.on('mousedown' + eventNS, function(e) {
if (self.isFocused) {
// prevent events on the dropdown scrollbar from causing the control to blur
if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) {
return false;
}
// blur on click outside
if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
self.blur(e.target);
}
}
});
$window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function() {
if (self.isOpen) {
self.positionDropdown.apply(self, arguments);
}
});
$window.on('mousemove' + eventNS, function() {
self.ignoreHover = false;
});
// store original children and tab index so that they can be
// restored when the destroy() method is called.
this.revertSettings = {
$children: $input.children().detach(),
tabindex: $input.attr('tabindex')
};
$input.attr('tabindex', -1).hide().after(self.$wrapper);
if ($.isArray(settings.items)) {
self.setValue(settings.items);
delete settings.items;
}
// feature detect for the validation API
if (SUPPORTS_VALIDITY_API) {
$input.on('invalid' + eventNS, function(e) {
e.preventDefault();
self.isInvalid = true;
self.refreshState();
});
}
self.updateOriginalInput();
self.refreshItems();
self.refreshState();
self.updatePlaceholder();
self.isSetup = true;
if ($input.is(':disabled')) {
self.disable();
}
self.on('change', this.onChange);
$input.data('selectize', self);
$input.addClass('selectized');
self.trigger('initialize');
// preload options
if (settings.preload === true) {
self.onSearchChange('');
}
},
/**
* Sets up default rendering functions.
*/
setupTemplates: function() {
var self = this;
var field_label = self.settings.labelField;
var field_optgroup = self.settings.optgroupLabelField;
var templates = {
'optgroup': function(data) {
return '<div class="optgroup">' + data.html + '</div>';
},
'optgroup_header': function(data, escape) {
return '<div class="optgroup-header">' + escape(data[field_optgroup]) + '</div>';
},
'option': function(data, escape) {
return '<div class="option">' + escape(data[field_label]) + '</div>';
},
'item': function(data, escape) {
return '<div class="item">' + escape(data[field_label]) + '</div>';
},
'option_create': function(data, escape) {
return '<div class="create">Add <strong>' + escape(data.input) + '</strong>…</div>';
}
};
self.settings.render = $.extend({}, templates, self.settings.render);
},
/**
* Maps fired events to callbacks provided
* in the settings used when creating the control.
*/
setupCallbacks: function() {
var key, fn, callbacks = {
'initialize': 'onInitialize',
'change': 'onChange',
'item_add': 'onItemAdd',
'item_remove': 'onItemRemove',
'clear': 'onClear',
'option_add': 'onOptionAdd',
'option_remove': 'onOptionRemove',
'option_clear': 'onOptionClear',
'optgroup_add': 'onOptionGroupAdd',
'optgroup_remove': 'onOptionGroupRemove',
'optgroup_clear': 'onOptionGroupClear',
'dropdown_open': 'onDropdownOpen',
'dropdown_close': 'onDropdownClose',
'type': 'onType',
'load': 'onLoad',
'focus': 'onFocus',
'blur': 'onBlur'
};
for (key in callbacks) {
if (callbacks.hasOwnProperty(key)) {
fn = this.settings[callbacks[key]];
if (fn) this.on(key, fn);
}
}
},
/**
* Triggered when the main control element
* has a click event.
*
* @param {object} e
* @return {boolean}
*/
onClick: function(e) {
var self = this;
// necessary for mobile webkit devices (manual focus triggering
// is ignored unless invoked within a click event)
if (!self.isFocused) {
self.focus();
e.preventDefault();
}
},
/**
* Triggered when the main control element
* has a mouse down event.
*
* @param {object} e
* @return {boolean}
*/
onMouseDown: function(e) {
var self = this;
var defaultPrevented = e.isDefaultPrevented();
var $target = $(e.target);
if (self.isFocused) {
// retain focus by preventing native handling. if the
// event target is the input it should not be modified.
// otherwise, text selection within the input won't work.
if (e.target !== self.$control_input[0]) {
if (self.settings.mode === 'single') {
// toggle dropdown
self.isOpen ? self.close() : self.open();
} else if (!defaultPrevented) {
self.setActiveItem(null);
}
return false;
}
} else {
// give control focus
if (!defaultPrevented) {
window.setTimeout(function() {
self.focus();
}, 0);
}
}
},
/**
* Triggered when the value of the control has been changed.
* This should propagate the event to the original DOM
* input / select element.
*/
onChange: function() {
this.$input.trigger('change');
},
/**
* Triggered on <input> paste.
*
* @param {object} e
* @returns {boolean}
*/
onPaste: function(e) {
var self = this;
if (self.isFull() || self.isInputHidden || self.isLocked) {
e.preventDefault();
} else {
// If a regex or string is included, this will split the pasted
// input and create Items for each separate value
if (self.settings.splitOn) {
setTimeout(function() {
var splitInput = $.trim(self.$control_input.val() || '').split(self.settings.splitOn);
for (var i = 0, n = splitInput.length; i < n; i++) {
self.createItem(splitInput[i]);
}
}, 0);
}
}
},
/**
* Triggered on <input> keypress.
*
* @param {object} e
* @returns {boolean}
*/
onKeyPress: function(e) {
if (this.isLocked) return e && e.preventDefault();
var character = String.fromCharCode(e.keyCode || e.which);
if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) {
this.createItem();
e.preventDefault();
return false;
}
},
/**
* Triggered on <input> keydown.
*
* @param {object} e
* @returns {boolean}
*/
onKeyDown: function(e) {
var isInput = e.target === this.$control_input[0];
var self = this;
if (self.isLocked) {
if (e.keyCode !== KEY_TAB) {
e.preventDefault();
}
return;
}
switch (e.keyCode) {
case KEY_A:
if (self.isCmdDown) {
self.selectAll();
return;
}
break;
case KEY_ESC:
if (self.isOpen) {
e.preventDefault();
e.stopPropagation();
self.close();
}
return;
case KEY_N:
if (!e.ctrlKey || e.altKey) break;
case KEY_DOWN:
if (!self.isOpen && self.hasOptions) {
self.open();
} else if (self.$activeOption) {
self.ignoreHover = true;
var $next = self.getAdjacentOption(self.$activeOption, 1);
if ($next.length) self.setActiveOption($next, true, true);
}
e.preventDefault();
return;
case KEY_P:
if (!e.ctrlKey || e.altKey) break;
case KEY_UP:
if (self.$activeOption) {
self.ignoreHover = true;
var $prev = self.getAdjacentOption(self.$activeOption, -1);
if ($prev.length) self.setActiveOption($prev, true, true);
}
e.preventDefault();
return;
case KEY_RETURN:
if (self.isOpen && self.$activeOption) {
self.onOptionSelect({
currentTarget: self.$activeOption
});
e.preventDefault();
}
return;
case KEY_LEFT:
self.advanceSelection(-1, e);
return;
case KEY_RIGHT:
self.advanceSelection(1, e);
return;
case KEY_TAB:
if (self.settings.selectOnTab && self.isOpen && self.$activeOption) {
self.onOptionSelect({
currentTarget: self.$activeOption
});
// Default behaviour is to jump to the next field, we only want this
// if the current field doesn't accept any more entries
if (!self.isFull()) {
e.preventDefault();
}
}
if (self.settings.create && self.createItem()) {
e.preventDefault();
}
return;
case KEY_BACKSPACE:
case KEY_DELETE:
self.deleteSelection(e);
return;
}
if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) {
e.preventDefault();
return;
}
},
/**
* Triggered on <input> keyup.
*
* @param {object} e
* @returns {boolean}
*/
onKeyUp: function(e) {
var self = this;
if (self.isLocked) return e && e.preventDefault();
var value = self.$control_input.val() || '';
if (self.lastValue !== value) {
self.lastValue = value;
self.onSearchChange(value);
self.refreshOptions();
self.trigger('type', value);
}
},
/**
* Invokes the user-provide option provider / loader.
*
* Note: this function is debounced in the Selectize
* constructor (by `settings.loadDelay` milliseconds)
*
* @param {string} value
*/
onSearchChange: function(value) {
var self = this;
var fn = self.settings.load;
if (!fn) return;
if (self.loadedSearches.hasOwnProperty(value)) return;
self.loadedSearches[value] = true;
self.load(function(callback) {
fn.apply(self, [value, callback]);
});
},
/**
* Triggered on <input> focus.
*
* @param {object} e (optional)
* @returns {boolean}
*/
onFocus: function(e) {
var self = this;
var wasFocused = self.isFocused;
if (self.isDisabled) {
self.blur();
e && e.preventDefault();
return false;
}
if (self.ignoreFocus) return;
self.isFocused = true;
if (self.settings.preload === 'focus') self.onSearchChange('');
if (!wasFocused) self.trigger('focus');
if (!self.$activeItems.length) {
self.showInput();
self.setActiveItem(null);
self.refreshOptions(!!self.settings.openOnFocus);
}
self.refreshState();
},
/**
* Triggered on <input> blur.
*
* @param {object} e
* @param {Element} dest
*/
onBlur: function(e, dest) {
var self = this;
if (!self.isFocused) return;
self.isFocused = false;
if (self.ignoreFocus) {
return;
} else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) {
// necessary to prevent IE closing the dropdown when the scrollbar is clicked
self.ignoreBlur = true;
self.onFocus(e);
return;
}
var deactivate = function() {
self.close();
self.setTextboxValue('');
self.setActiveItem(null);
self.setActiveOption(null);
self.setCaret(self.items.length);
self.refreshState();
// IE11 bug: element still marked as active
(dest || document.body).focus();
self.ignoreFocus = false;
self.trigger('blur');
};
self.ignoreFocus = true;
if (self.settings.create && self.settings.createOnBlur) {
self.createItem(null, false, deactivate);
} else {
deactivate();
}
},
/**
* Triggered when the user rolls over
* an option in the autocomplete dropdown menu.
*
* @param {object} e
* @returns {boolean}
*/
onOptionHover: function(e) {
if (this.ignoreHover) return;
this.setActiveOption(e.currentTarget, false);
},
/**
* Triggered when the user clicks on an option
* in the autocomplete dropdown menu.
*
* @param {object} e
* @returns {boolean}
*/
onOptionSelect: function(e) {
var value, $target, $option, self = this;
if (e.preventDefault) {
e.preventDefault();
e.stopPropagation();
}
$target = $(e.currentTarget);
if ($target.hasClass('create')) {
self.createItem(null, function() {
if (self.settings.closeAfterSelect) {
self.close();
}
});
} else {
value = $target.attr('data-value');
if (typeof value !== 'undefined') {
self.lastQuery = null;
self.setTextboxValue('');
self.addItem(value);
if (self.settings.closeAfterSelect) {
self.close();
} else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) {
self.setActiveOption(self.getOption(value));
}
}
}
},
/**
* Triggered when the user clicks on an item
* that has been selected.
*
* @param {object} e
* @returns {boolean}
*/
onItemSelect: function(e) {
var self = this;
if (self.isLocked) return;
if (self.settings.mode === 'multi') {
e.preventDefault();
self.setActiveItem(e.currentTarget, e);
}
},
/**
* Invokes the provided method that provides
* results to a callback---which are then added
* as options to the control.
*
* @param {function} fn
*/
load: function(fn) {
var self = this;
var $wrapper = self.$wrapper.addClass(self.settings.loadingClass);
self.loading++;
fn.apply(self, [function(results) {
self.loading = Math.max(self.loading - 1, 0);
if (results && results.length) {
self.addOption(results);
self.refreshOptions(self.isFocused && !self.isInputHidden);
}
if (!self.loading) {
$wrapper.removeClass(self.settings.loadingClass);
}
self.trigger('load', results);
}]);
},
/**
* Sets the input field of the control to the specified value.
*
* @param {string} value
*/
setTextboxValue: function(value) {
var $input = this.$control_input;
var changed = $input.val() !== value;
if (changed) {
$input.val(value).triggerHandler('update');
this.lastValue = value;
}
},
/**
* Returns the value of the control. If multiple items
* can be selected (e.g. <select multiple>), this returns
* an array. If only one item can be selected, this
* returns a string.
*
* @returns {mixed}
*/
getValue: function() {
if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
return this.items;
} else {
return this.items.join(this.settings.delimiter);
}
},
/**
* Resets the selected items to the given value.
*
* @param {mixed} value
*/
setValue: function(value, silent) {
var events = silent ? [] : ['change'];
debounce_events(this, events, function() {
this.clear(silent);
this.addItems(value, silent);
});
},
/**
* Sets the selected item.
*
* @param {object} $item
* @param {object} e (optional)
*/
setActiveItem: function($item, e) {
var self = this;
var eventName;
var i, idx, begin, end, item, swap;
var $last;
if (self.settings.mode === 'single') return;
$item = $($item);
// clear the active selection
if (!$item.length) {
$(self.$activeItems).removeClass('active');
self.$activeItems = [];
if (self.isFocused) {
self.showInput();
}
return;
}
// modify selection
eventName = e && e.type.toLowerCase();
if (eventName === 'mousedown' && self.isShiftDown && self.$activeItems.length) {
$last = self.$control.children('.active:last');
begin = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$last[0]]);
end = Array.prototype.indexOf.apply(self.$control[0].childNodes, [$item[0]]);
if (begin > end) {
swap = begin;
begin = end;
end = swap;
}
for (i = begin; i <= end; i++) {
item = self.$control[0].childNodes[i];
if (self.$activeItems.indexOf(item) === -1) {
$(item).addClass('active');
self.$activeItems.push(item);
}
}
e.preventDefault();
} else if ((eventName === 'mousedown' && self.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
if ($item.hasClass('active')) {
idx = self.$activeItems.indexOf($item[0]);
self.$activeItems.splice(idx, 1);
$item.removeClass('active');
} else {
self.$activeItems.push($item.addClass('active')[0]);
}
} else {
$(self.$activeItems).removeClass('active');
self.$activeItems = [$item.addClass('active')[0]];
}
// ensure control has focus
self.hideInput();
if (!this.isFocused) {
self.focus();
}
},
/**
* Sets the selected item in the dropdown menu
* of available options.
*
* @param {object} $object
* @param {boolean} scroll
* @param {boolean} animate
*/
setActiveOption: function($option, scroll, animate) {
var height_menu, height_item, y;
var scroll_top, scroll_bottom;
var self = this;
if (self.$activeOption) self.$activeOption.removeClass('active');
self.$activeOption = null;
$option = $($option);
if (!$option.length) return;
self.$activeOption = $option.addClass('active');
if (scroll || !isset(scroll)) {
height_menu = self.$dropdown_content.height();
height_item = self.$activeOption.outerHeight(true);
scroll = self.$dropdown_content.scrollTop() || 0;
y = self.$activeOption.offset().top - self.$dropdown_content.offset().top + scroll;
scroll_top = y;
scroll_bottom = y - height_menu + height_item;
if (y + height_item > height_menu + scroll) {
self.$dropdown_content.stop().animate({
scrollTop: scroll_bottom
}, animate ? self.settings.scrollDuration : 0);
} else if (y < scroll) {
self.$dropdown_content.stop().animate({
scrollTop: scroll_top
}, animate ? self.settings.scrollDuration : 0);
}
}
},
/**
* Selects all items (CTRL + A).
*/
selectAll: function() {
var self = this;
if (self.settings.mode === 'single') return;
self.$activeItems = Array.prototype.slice.apply(self.$control.children(':not(input)').addClass('active'));
if (self.$activeItems.length) {
self.hideInput();
self.close();
}
self.focus();
},
/**
* Hides the input element out of view, while
* retaining its focus.
*/
hideInput: function() {
var self = this;
self.setTextboxValue('');
self.$control_input.css({
opacity: 0,
position: 'absolute',
left: self.rtl ? 10000 : -10000
});
self.isInputHidden = true;
},
/**
* Restores input visibility.
*/
showInput: function() {
this.$control_input.css({
opacity: 1,
position: 'relative',
left: 0
});
this.isInputHidden = false;
},
/**
* Gives the control focus.
*/
focus: function() {
var self = this;
if (self.isDisabled) return;
self.ignoreFocus = true;
self.$control_input[0].focus();
window.setTimeout(function() {
self.ignoreFocus = false;
self.onFocus();
}, 0);
},
/**
* Forces the control out of focus.
*
* @param {Element} dest
*/
blur: function(dest) {
this.$control_input[0].blur();
this.onBlur(null, dest);
},
/**
* Returns a function that scores an object
* to show how good of a match it is to the
* provided query.
*
* @param {string} query
* @param {object} options
* @return {function}
*/
getScoreFunction: function(query) {
return this.sifter.getScoreFunction(query, this.getSearchOptions());
},
/**
* Returns search options for sifter (the system
* for scoring and sorting results).
*
* @see https://github.com/brianreavis/sifter.js
* @return {object}
*/
getSearchOptions: function() {
var settings = this.settings;
var sort = settings.sortField;
if (typeof sort === 'string') {
sort = [{
field: sort
}];
}
return {
fields: settings.searchField,
conjunction: settings.searchConjunction,
sort: sort
};
},
/**
* Searches through available options and returns
* a sorted array of matches.
*
* Returns an object containing:
*
* - query {string}
* - tokens {array}
* - total {int}
* - items {array}
*
* @param {string} query
* @returns {object}
*/
search: function(query) {
var i, value, score, result, calculateScore;
var self = this;
var settings = self.settings;
var options = this.getSearchOptions();
// validate user-provided result scoring function
if (settings.score) {
calculateScore = self.settings.score.apply(this, [query]);
if (typeof calculateScore !== 'function') {
throw new Error('Selectize "score" setting must be a function that returns a function');
}
}
// perform search
if (query !== self.lastQuery) {
self.lastQuery = query;
result = self.sifter.search(query, $.extend(options, {
score: calculateScore
}));
self.currentResults = result;
} else {
result = $.extend(true, {}, self.currentResults);
}
// filter out selected items
if (settings.hideSelected) {
for (i = result.items.length - 1; i >= 0; i--) {
if (self.items.indexOf(hash_key(result.items[i].id)) !== -1) {
result.items.splice(i, 1);
}
}
}
return result;
},
/**
* Refreshes the list of available options shown
* in the autocomplete dropdown menu.
*
* @param {boolean} triggerDropdown
*/
refreshOptions: function(triggerDropdown) {
var i, j, k, n, groups, groups_order, option, option_html, optgroup, optgroups, html, html_children, has_create_option;
var $active, $active_before, $create;
if (typeof triggerDropdown === 'undefined') {
triggerDropdown = true;
}
var self = this;
var query = $.trim(self.$control_input.val());
var results = self.search(query);
var $dropdown_content = self.$dropdown_content;
var active_before = self.$activeOption && hash_key(self.$activeOption.attr('data-value'));
// build markup
n = results.items.length;
if (typeof self.settings.maxOptions === 'number') {
n = Math.min(n, self.settings.maxOptions);
}
// render and group available options individually
groups = {};
groups_order = [];
for (i = 0; i < n; i++) {
option = self.options[results.items[i].id];
option_html = self.render('option', option);
optgroup = option[self.settings.optgroupField] || '';
optgroups = $.isArray(optgroup) ? optgroup : [optgroup];
for (j = 0, k = optgroups && optgroups.length; j < k; j++) {
optgroup = optgroups[j];
if (!self.optgroups.hasOwnProperty(optgroup)) {
optgroup = '';
}
if (!groups.hasOwnProperty(optgroup)) {
groups[optgroup] = [];
groups_order.push(optgroup);
}
groups[optgroup].push(option_html);
}
}
// sort optgroups
if (this.settings.lockOptgroupOrder) {
groups_order.sort(function(a, b) {
var a_order = self.optgroups[a].$order || 0;
var b_order = self.optgroups[b].$order || 0;
return a_order - b_order;
});
}
// render optgroup headers & join groups
html = [];
for (i = 0, n = groups_order.length; i < n; i++) {
optgroup = groups_order[i];
if (self.optgroups.hasOwnProperty(optgroup) && groups[optgroup].length) {
// render the optgroup header and options within it,
// then pass it to the wrapper template
html_children = self.render('optgroup_header', self.optgroups[optgroup]) || '';
html_children += groups[optgroup].join('');
html.push(self.render('optgroup', $.extend({}, self.optgroups[optgroup], {
html: html_children
})));
} else {
html.push(groups[optgroup].join(''));
}
}
$dropdown_content.html(html.join(''));
// highlight matching terms inline
if (self.settings.highlight && results.query.length && results.tokens.length) {
for (i = 0, n = results.tokens.length; i < n; i++) {
highlight($dropdown_content, results.tokens[i].regex);
}
}
// add "selected" class to selected options
if (!self.settings.hideSelected) {
for (i = 0, n = self.items.length; i < n; i++) {
self.getOption(self.items[i]).addClass('selected');
}
}
// add create option
has_create_option = self.canCreate(query);
if (has_create_option) {
$dropdown_content.prepend(self.render('option_create', {
input: query
}));
$create = $($dropdown_content[0].childNodes[0]);
}
// activate
self.hasOptions = results.items.length > 0 || has_create_option;
if (self.hasOptions) {
if (results.items.length > 0) {
$active_before = active_before && self.getOption(active_before);
if ($active_before && $active_before.length) {
$active = $active_before;
} else if (self.settings.mode === 'single' && self.items.length) {
$active = self.getOption(self.items[0]);
}
if (!$active || !$active.length) {
if ($create && !self.settings.addPrecedence) {
$active = self.getAdjacentOption($create, 1);
} else {
$active = $dropdown_content.find('[data-selectable]:first');
}
}
} else {
$active = $create;
}
self.setActiveOption($active);
if (triggerDropdown && !self.isOpen) {
self.open();
}
} else {
self.setActiveOption(null);
if (triggerDropdown && self.isOpen) {
self.close();
}
}
},
/**
* Adds an available option. If it already exists,
* nothing will happen. Note: this does not refresh
* the options list dropdown (use `refreshOptions`
* for that).
*
* Usage:
*
* this.addOption(data)
*
* @param {object|array} data
*/
addOption: function(data) {
var i, n, value, self = this;
if ($.isArray(data)) {
for (i = 0, n = data.length; i < n; i++) {
self.addOption(data[i]);
}
return;
}
if (value = self.registerOption(data)) {
self.userOptions[value] = true;
self.lastQuery = null;
self.trigger('option_add', value, data);
}
},
/**
* Registers an option to the pool of options.
*
* @param {object} data
* @return {boolean|string}
*/
registerOption: function(data) {
var key = hash_key(data[this.settings.valueField]);
if (!key || this.options.hasOwnProperty(key)) return false;
data.$order = data.$order || ++this.order;
this.options[key] = data;
return key;
},
/**
* Registers an option group to the pool of option groups.
*
* @param {object} data
* @return {boolean|string}
*/
registerOptionGroup: function(data) {
var key = hash_key(data[this.settings.optgroupValueField]);
if (!key) return false;
data.$order = data.$order || ++this.order;
this.optgroups[key] = data;
return key;
},
/**
* Registers a new optgroup for options
* to be bucketed into.
*
* @param {string} id
* @param {object} data
*/
addOptionGroup: function(id, data) {
data[this.settings.optgroupValueField] = id;
if (id = this.registerOptionGroup(data)) {
this.trigger('optgroup_add', id, data);
}
},
/**
* Removes an existing option group.
*
* @param {string} id
*/
removeOptionGroup: function(id) {
if (this.optgroups.hasOwnProperty(id)) {
delete this.optgroups[id];
this.renderCache = {};
this.trigger('optgroup_remove', id);
}
},
/**
* Clears all existing option groups.
*/
clearOptionGroups: function() {
this.optgroups = {};
this.renderCache = {};
this.trigger('optgroup_clear');
},
/**
* Updates an option available for selection. If
* it is visible in the selected items or options
* dropdown, it will be re-rendered automatically.
*
* @param {string} value
* @param {object} data
*/
updateOption: function(value, data) {
var self = this;
var $item, $item_new;
var value_new, index_item, cache_items, cache_options, order_old;
value = hash_key(value);
value_new = hash_key(data[self.settings.valueField]);
// sanity checks
if (value === null) return;
if (!self.options.hasOwnProperty(value)) return;
if (typeof value_new !== 'string') throw new Error('Value must be set in option data');
order_old = self.options[value].$order;
// update references
if (value_new !== value) {
delete self.options[value];
index_item = self.items.indexOf(value);
if (index_item !== -1) {
self.items.splice(index_item, 1, value_new);
}
}
data.$order = data.$order || order_old;
self.options[value_new] = data;
// invalidate render cache
cache_items = self.renderCache['item'];
cache_options = self.renderCache['option'];
if (cache_items) {
delete cache_items[value];
delete cache_items[value_new];
}
if (cache_options) {
delete cache_options[value];
delete cache_options[value_new];
}
// update the item if it's selected
if (self.items.indexOf(value_new) !== -1) {
$item = self.getItem(value);
$item_new = $(self.render('item', data));
if ($item.hasClass('active')) $item_new.addClass('active');
$item.replaceWith($item_new);
}
// invalidate last query because we might have updated the sortField
self.lastQuery = null;
// update dropdown contents
if (self.isOpen) {
self.refreshOptions(false);
}
},
/**
* Removes a single option.
*
* @param {string} value
* @param {boolean} silent
*/
removeOption: function(value, silent) {
var self = this;
value = hash_key(value);
var cache_items = self.renderCache['item'];
var cache_options = self.renderCache['option'];
if (cache_items) delete cache_items[value];
if (cache_options) delete cache_options[value];
delete self.userOptions[value];
delete self.options[value];
self.lastQuery = null;
self.trigger('option_remove', value);
self.removeItem(value, silent);
},
/**
* Clears all options.
*/
clearOptions: function() {
var self = this;
self.loadedSearches = {};
self.userOptions = {};
self.renderCache = {};
self.options = self.sifter.items = {};
self.lastQuery = null;
self.trigger('option_clear');
self.clear();
},
/**
* Returns the jQuery element of the option
* matching the given value.
*
* @param {string} value
* @returns {object}
*/
getOption: function(value) {
return this.getElementWithValue(value, this.$dropdown_content.find('[data-selectable]'));
},
/**
* Returns the jQuery element of the next or
* previous selectable option.
*
* @param {object} $option
* @param {int} direction can be 1 for next or -1 for previous
* @return {object}
*/
getAdjacentOption: function($option, direction) {
var $options = this.$dropdown.find('[data-selectable]');
var index = $options.index($option) + direction;
return index >= 0 && index < $options.length ? $options.eq(index) : $();
},
/**
* Finds the first element with a "data-value" attribute
* that matches the given value.
*
* @param {mixed} value
* @param {object} $els
* @return {object}
*/
getElementWithValue: function(value, $els) {
value = hash_key(value);
if (typeof value !== 'undefined' && value !== null) {
for (var i = 0, n = $els.length; i < n; i++) {
if ($els[i].getAttribute('data-value') === value) {
return $($els[i]);
}
}
}
return $();
},
/**
* Returns the jQuery element of the item
* matching the given value.
*
* @param {string} value
* @returns {object}
*/
getItem: function(value) {
return this.getElementWithValue(value, this.$control.children());
},
/**
* "Selects" multiple items at once. Adds them to the list
* at the current caret position.
*
* @param {string} value
* @param {boolean} silent
*/
addItems: function(values, silent) {
var items = $.isArray(values) ? values : [values];
for (var i = 0, n = items.length; i < n; i++) {
this.isPending = (i < n - 1);
this.addItem(items[i], silent);
}
},
/**
* "Selects" an item. Adds it to the list
* at the current caret position.
*
* @param {string} value
* @param {boolean} silent
*/
addItem: function(value, silent) {
var events = silent ? [] : ['change'];
debounce_events(this, events, function() {
var $item, $option, $options;
var self = this;
var inputMode = self.settings.mode;
var i, active, value_next, wasFull;
value = hash_key(value);
if (self.items.indexOf(value) !== -1) {
if (inputMode === 'single') self.close();
return;
}
if (!self.options.hasOwnProperty(value)) return;
if (inputMode === 'single') self.clear(silent);
if (inputMode === 'multi' && self.isFull()) return;
$item = $(self.render('item', self.options[value]));
wasFull = self.isFull();
self.items.splice(self.caretPos, 0, value);
self.insertAtCaret($item);
if (!self.isPending || (!wasFull && self.isFull())) {
self.refreshState();
}
if (self.isSetup) {
$options = self.$dropdown_content.find('[data-selectable]');
// update menu / remove the option (if this is not one item being added as part of series)
if (!self.isPending) {
$option = self.getOption(value);
value_next = self.getAdjacentOption($option, 1).attr('data-value');
self.refreshOptions(self.isFocused && inputMode !== 'single');
if (value_next) {
self.setActiveOption(self.getOption(value_next));
}
}
// hide the menu if the maximum number of items have been selected or no options are left
if (!$options.length || self.isFull()) {
self.close();
} else {
self.positionDropdown();
}
self.updatePlaceholder();
self.trigger('item_add', value, $item);
self.updateOriginalInput({
silent: silent
});
}
});
},
/**
* Removes the selected item matching
* the provided value.
*
* @param {string} value
*/
removeItem: function(value, silent) {
var self = this;
var $item, i, idx;
$item = (typeof value === 'object') ? value : self.getItem(value);
value = hash_key($item.attr('data-value'));
i = self.items.indexOf(value);
if (i !== -1) {
$item.remove();
if ($item.hasClass('active')) {
idx = self.$activeItems.indexOf($item[0]);
self.$activeItems.splice(idx, 1);
}
self.items.splice(i, 1);
self.lastQuery = null;
if (!self.settings.persist && self.userOptions.hasOwnProperty(value)) {
self.removeOption(value, silent);
}
if (i < self.caretPos) {
self.setCaret(self.caretPos - 1);
}
self.refreshState();
self.updatePlaceholder();
self.updateOriginalInput({
silent: silent
});
self.positionDropdown();
self.trigger('item_remove', value, $item);
}
},
/**
* Invokes the `create` method provided in the
* selectize options that should provide the data
* for the new item, given the user input.
*
* Once this completes, it will be added
* to the item list.
*
* @param {string} value
* @param {boolean} [triggerDropdown]
* @param {function} [callback]
* @return {boolean}
*/
createItem: function(input, triggerDropdown) {
var self = this;
var caret = self.caretPos;
input = input || $.trim(self.$control_input.val() || '');
var callback = arguments[arguments.length - 1];
if (typeof callback !== 'function') callback = function() {};
if (typeof triggerDropdown !== 'boolean') {
triggerDropdown = true;
}
if (!self.canCreate(input)) {
callback();
return false;
}
self.lock();
var setup = (typeof self.settings.create === 'function') ? this.settings.create : function(input) {
var data = {};
data[self.settings.labelField] = input;
data[self.settings.valueField] = input;
return data;
};
var create = once(function(data) {
self.unlock();
if (!data || typeof data !== 'object') return callback();
var value = hash_key(data[self.settings.valueField]);
if (typeof value !== 'string') return callback();
self.setTextboxValue('');
self.addOption(data);
self.setCaret(caret);
self.addItem(value);
self.refreshOptions(triggerDropdown && self.settings.mode !== 'single');
callback(data);
});
var output = setup.apply(this, [input, create]);
if (typeof output !== 'undefined') {
create(output);
}
return true;
},
/**
* Re-renders the selected item lists.
*/
refreshItems: function() {
this.lastQuery = null;
if (this.isSetup) {
this.addItem(this.items);
}
this.refreshState();
this.updateOriginalInput();
},
/**
* Updates all state-dependent attributes
* and CSS classes.
*/
refreshState: function() {
var invalid, self = this;
if (self.isRequired) {
if (self.items.length) self.isInvalid = false;
self.$control_input.prop('required', invalid);
}
self.refreshClasses();
},
/**
* Updates all state-dependent CSS classes.
*/
refreshClasses: function() {
var self = this;
var isFull = self.isFull();
var isLocked = self.isLocked;
self.$wrapper
.toggleClass('rtl', self.rtl);
self.$control
.toggleClass('focus', self.isFocused)
.toggleClass('disabled', self.isDisabled)
.toggleClass('required', self.isRequired)
.toggleClass('invalid', self.isInvalid)
.toggleClass('locked', isLocked)
.toggleClass('full', isFull).toggleClass('not-full', !isFull)
.toggleClass('input-active', self.isFocused && !self.isInputHidden)
.toggleClass('dropdown-active', self.isOpen)
.toggleClass('has-options', !$.isEmptyObject(self.options))
.toggleClass('has-items', self.items.length > 0);
self.$control_input.data('grow', !isFull && !isLocked);
},
/**
* Determines whether or not more items can be added
* to the control without exceeding the user-defined maximum.
*
* @returns {boolean}
*/
isFull: function() {
return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
},
/**
* Refreshes the original <select> or <input>
* element to reflect the current state.
*/
updateOriginalInput: function(opts) {
var i, n, options, label, self = this;
opts = opts || {};
if (self.tagType === TAG_SELECT) {
options = [];
for (i = 0, n = self.items.length; i < n; i++) {
label = self.options[self.items[i]][self.settings.labelField] || '';
options.push('<option value="' + escape_html(self.items[i]) + '" selected="selected">' + escape_html(label) + '</option>');
}
if (!options.length && !this.$input.attr('multiple')) {
options.push('<option value="" selected="selected"></option>');
}
self.$input.html(options.join(''));
} else {
self.$input.val(self.getValue());
self.$input.attr('value', self.$input.val());
}
if (self.isSetup) {
if (!opts.silent) {
self.trigger('change', self.$input.val());
}
}
},
/**
* Shows/hide the input placeholder depending
* on if there items in the list already.
*/
updatePlaceholder: function() {
if (!this.settings.placeholder) return;
var $input = this.$control_input;
if (this.items.length) {
$input.removeAttr('placeholder');
} else {
$input.attr('placeholder', this.settings.placeholder);
}
$input.triggerHandler('update', {
force: true
});
},
/**
* Shows the autocomplete dropdown containing
* the available options.
*/
open: function() {
var self = this;
if (self.isLocked || self.isOpen || (self.settings.mode === 'multi' && self.isFull())) return;
self.focus();
self.isOpen = true;
self.refreshState();
self.$dropdown.css({
visibility: 'hidden',
display: 'block'
});
self.positionDropdown();
self.$dropdown.css({
visibility: 'visible'
});
self.trigger('dropdown_open', self.$dropdown);
},
/**
* Closes the autocomplete dropdown menu.
*/
close: function() {
var self = this;
var trigger = self.isOpen;
if (self.settings.mode === 'single' && self.items.length) {
self.hideInput();
}
self.isOpen = false;
self.$dropdown.hide();
self.setActiveOption(null);
self.refreshState();
if (trigger) self.trigger('dropdown_close', self.$dropdown);
},
/**
* Calculates and applies the appropriate
* position of the dropdown.
*/
positionDropdown: function() {
var $control = this.$control;
var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position();
offset.top += $control.outerHeight(true);
this.$dropdown.css({
width: $control.outerWidth(),
top: offset.top,
left: offset.left
});
},
/**
* Resets / clears all selected items
* from the control.
*
* @param {boolean} silent
*/
clear: function(silent) {
var self = this;
if (!self.items.length) return;
self.$control.children(':not(input)').remove();
self.items = [];
self.lastQuery = null;
self.setCaret(0);
self.setActiveItem(null);
self.updatePlaceholder();
self.updateOriginalInput({
silent: silent
});
self.refreshState();
self.showInput();
self.trigger('clear');
},
/**
* A helper method for inserting an element
* at the current caret position.
*
* @param {object} $el
*/
insertAtCaret: function($el) {
var caret = Math.min(this.caretPos, this.items.length);
if (caret === 0) {
this.$control.prepend($el);
} else {
$(this.$control[0].childNodes[caret]).before($el);
}
this.setCaret(caret + 1);
},
/**
* Removes the current selected item(s).
*
* @param {object} e (optional)
* @returns {boolean}
*/
deleteSelection: function(e) {
var i, n, direction, selection, values, caret, option_select, $option_select, $tail;
var self = this;
direction = (e && e.keyCode === KEY_BACKSPACE) ? -1 : 1;
selection = getSelection(self.$control_input[0]);
if (self.$activeOption && !self.settings.hideSelected) {
option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value');
}
// determine items that will be removed
values = [];
if (self.$activeItems.length) {
$tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
caret = self.$control.children(':not(input)').index($tail);
if (direction > 0) {
caret++;
}
for (i = 0, n = self.$activeItems.length; i < n; i++) {
values.push($(self.$activeItems[i]).attr('data-value'));
}
if (e) {
e.preventDefault();
e.stopPropagation();
}
} else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) {
if (direction < 0 && selection.start === 0 && selection.length === 0) {
values.push(self.items[self.caretPos - 1]);
} else if (direction > 0 && selection.start === self.$control_input.val().length) {
values.push(self.items[self.caretPos]);
}
}
// allow the callback to abort
if (!values.length || (typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false)) {
return false;
}
// perform removal
if (typeof caret !== 'undefined') {
self.setCaret(caret);
}
while (values.length) {
self.removeItem(values.pop());
}
self.showInput();
self.positionDropdown();
self.refreshOptions(true);
// select previous option
if (option_select) {
$option_select = self.getOption(option_select);
if ($option_select.length) {
self.setActiveOption($option_select);
}
}
return true;
},
/**
* Selects the previous / next item (depending
* on the `direction` argument).
*
* > 0 - right
* < 0 - left
*
* @param {int} direction
* @param {object} e (optional)
*/
advanceSelection: function(direction, e) {
var tail, selection, idx, valueLength, cursorAtEdge, $tail;
var self = this;
if (direction === 0) return;
if (self.rtl) direction *= -1;
tail = direction > 0 ? 'last' : 'first';
selection = getSelection(self.$control_input[0]);
if (self.isFocused && !self.isInputHidden) {
valueLength = self.$control_input.val().length;
cursorAtEdge = direction < 0 ? selection.start === 0 && selection.length === 0 : selection.start === valueLength;
if (cursorAtEdge && !valueLength) {
self.advanceCaret(direction, e);
}
} else {
$tail = self.$control.children('.active:' + tail);
if ($tail.length) {
idx = self.$control.children(':not(input)').index($tail);
self.setActiveItem(null);
self.setCaret(direction > 0 ? idx + 1 : idx);
}
}
},
/**
* Moves the caret left / right.
*
* @param {int} direction
* @param {object} e (optional)
*/
advanceCaret: function(direction, e) {
var self = this,
fn, $adj;
if (direction === 0) return;
fn = direction > 0 ? 'next' : 'prev';
if (self.isShiftDown) {
$adj = self.$control_input[fn]();
if ($adj.length) {
self.hideInput();
self.setActiveItem($adj);
e && e.preventDefault();
}
} else {
self.setCaret(self.caretPos + direction);
}
},
/**
* Moves the caret to the specified index.
*
* @param {int} i
*/
setCaret: function(i) {
var self = this;
if (self.settings.mode === 'single') {
i = self.items.length;
} else {
i = Math.max(0, Math.min(self.items.length, i));
}
if (!self.isPending) {
// the input must be moved by leaving it in place and moving the
// siblings, due to the fact that focus cannot be restored once lost
// on mobile webkit devices
var j, n, fn, $children, $child;
$children = self.$control.children(':not(input)');
for (j = 0, n = $children.length; j < n; j++) {
$child = $($children[j]).detach();
if (j < i) {
self.$control_input.before($child);
} else {
self.$control.append($child);
}
}
}
self.caretPos = i;
},
/**
* Disables user input on the control. Used while
* items are being asynchronously created.
*/
lock: function() {
this.close();
this.isLocked = true;
this.refreshState();
},
/**
* Re-enables user input on the control.
*/
unlock: function() {
this.isLocked = false;
this.refreshState();
},
/**
* Disables user input on the control completely.
* While disabled, it cannot receive focus.
*/
disable: function() {
var self = this;
self.$input.prop('disabled', true);
self.$control_input.prop('disabled', true).prop('tabindex', -1);
self.isDisabled = true;
self.lock();
},
/**
* Enables the control so that it can respond
* to focus and user input.
*/
enable: function() {
var self = this;
self.$input.prop('disabled', false);
self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex);
self.isDisabled = false;
self.unlock();
},
/**
* Completely destroys the control and
* unbinds all event listeners so that it can
* be garbage collected.
*/
destroy: function() {
var self = this;
var eventNS = self.eventNS;
var revertSettings = self.revertSettings;
self.trigger('destroy');
self.off();
self.$wrapper.remove();
self.$dropdown.remove();
self.$input
.html('')
.append(revertSettings.$children)
.removeAttr('tabindex')
.removeClass('selectized')
.attr({
tabindex: revertSettings.tabindex
})
.show();
self.$control_input.removeData('grow');
self.$input.removeData('selectize');
$(window).off(eventNS);
$(document).off(eventNS);
$(document.body).off(eventNS);
delete self.$input[0].selectize;
},
/**
* A helper method for rendering "item" and
* "option" templates, given the data.
*
* @param {string} templateName
* @param {object} data
* @returns {string}
*/
render: function(templateName, data) {
var value, id, label;
var html = '';
var cache = false;
var self = this;
var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i;
if (templateName === 'option' || templateName === 'item') {
value = hash_key(data[self.settings.valueField]);
cache = !!value;
}
// pull markup from cache if it exists
if (cache) {
if (!isset(self.renderCache[templateName])) {
self.renderCache[templateName] = {};
}
if (self.renderCache[templateName].hasOwnProperty(value)) {
return self.renderCache[templateName][value];
}
}
// render markup
html = self.settings.render[templateName].apply(this, [data, escape_html]);
// add mandatory attributes
if (templateName === 'option' || templateName === 'option_create') {
html = html.replace(regex_tag, '<$1 data-selectable');
}
if (templateName === 'optgroup') {
id = data[self.settings.optgroupValueField] || '';
html = html.replace(regex_tag, '<$1 data-group="' + escape_replace(escape_html(id)) + '"');
}
if (templateName === 'option' || templateName === 'item') {
html = html.replace(regex_tag, '<$1 data-value="' + escape_replace(escape_html(value || '')) + '"');
}
// update cache
if (cache) {
self.renderCache[templateName][value] = html;
}
return html;
},
/**
* Clears the render cache for a template. If
* no template is given, clears all render
* caches.
*
* @param {string} templateName
*/
clearCache: function(templateName) {
var self = this;
if (typeof templateName === 'undefined') {
self.renderCache = {};
} else {
delete self.renderCache[templateName];
}
},
/**
* Determines whether or not to display the
* create item prompt, given a user input.
*
* @param {string} input
* @return {boolean}
*/
canCreate: function(input) {
var self = this;
if (!self.settings.create) return false;
var filter = self.settings.createFilter;
return input.length && (typeof filter !== 'function' || filter.apply(self, [input])) && (typeof filter !== 'string' || new RegExp(filter).test(input)) && (!(filter instanceof RegExp) || filter.test(input));
}
});
Selectize.count = 0;
Selectize.defaults = {
options: [],
optgroups: [],
plugins: [],
delimiter: ',',
splitOn: null, // regexp or string for splitting up values from a paste command
persist: true,
diacritics: true,
create: false,
createOnBlur: false,
createFilter: null,
highlight: true,
openOnFocus: true,
maxOptions: 1000,
maxItems: null,
hideSelected: null,
addPrecedence: false,
selectOnTab: false,
preload: false,
allowEmptyOption: false,
closeAfterSelect: false,
scrollDuration: 60,
loadThrottle: 300,
loadingClass: 'loading',
dataAttr: 'data-data',
optgroupField: 'optgroup',
valueField: 'value',
labelField: 'text',
optgroupLabelField: 'label',
optgroupValueField: 'value',
lockOptgroupOrder: false,
sortField: '$order',
searchField: ['text'],
searchConjunction: 'and',
mode: null,
wrapperClass: 'selectize-control',
inputClass: 'selectize-input',
dropdownClass: 'selectize-dropdown',
dropdownContentClass: 'selectize-dropdown-content',
dropdownParent: null,
copyClassesToDropdown: true,
/*
load : null, // function(query, callback) { ... }
score : null, // function(search) { ... }
onInitialize : null, // function() { ... }
onChange : null, // function(value) { ... }
onItemAdd : null, // function(value, $item) { ... }
onItemRemove : null, // function(value) { ... }
onClear : null, // function() { ... }
onOptionAdd : null, // function(value, data) { ... }
onOptionRemove : null, // function(value) { ... }
onOptionClear : null, // function() { ... }
onOptionGroupAdd : null, // function(id, data) { ... }
onOptionGroupRemove : null, // function(id) { ... }
onOptionGroupClear : null, // function() { ... }
onDropdownOpen : null, // function($dropdown) { ... }
onDropdownClose : null, // function($dropdown) { ... }
onType : null, // function(str) { ... }
onDelete : null, // function(values) { ... }
*/
render: {
/*
item: null,
optgroup: null,
optgroup_header: null,
option: null,
option_create: null
*/
}
};
$.fn.selectize = function(settings_user) {
var defaults = $.fn.selectize.defaults;
var settings = $.extend({}, defaults, settings_user);
var attr_data = settings.dataAttr;
var field_label = settings.labelField;
var field_value = settings.valueField;
var field_optgroup = settings.optgroupField;
var field_optgroup_label = settings.optgroupLabelField;
var field_optgroup_value = settings.optgroupValueField;
/**
* Initializes selectize from a <input type="text"> element.
*
* @param {object} $input
* @param {object} settings_element
*/
var init_textbox = function($input, settings_element) {
var i, n, values, option;
var data_raw = $input.attr(attr_data);
if (!data_raw) {
var value = $.trim($input.val() || '');
if (!settings.allowEmptyOption && !value.length) return;
values = value.split(settings.delimiter);
for (i = 0, n = values.length; i < n; i++) {
option = {};
option[field_label] = values[i];
option[field_value] = values[i];
settings_element.options.push(option);
}
settings_element.items = values;
} else {
settings_element.options = JSON.parse(data_raw);
for (i = 0, n = settings_element.options.length; i < n; i++) {
settings_element.items.push(settings_element.options[i][field_value]);
}
}
};
/**
* Initializes selectize from a <select> element.
*
* @param {object} $input
* @param {object} settings_element
*/
var init_select = function($input, settings_element) {
var i, n, tagName, $children, order = 0;
var options = settings_element.options;
var optionsMap = {};
var readData = function($el) {
var data = attr_data && $el.attr(attr_data);
if (typeof data === 'string' && data.length) {
return JSON.parse(data);
}
return null;
};
var addOption = function($option, group) {
$option = $($option);
var value = hash_key($option.attr('value'));
if (!value && !settings.allowEmptyOption) return;
// if the option already exists, it's probably been
// duplicated in another optgroup. in this case, push
// the current group to the "optgroup" property on the
// existing option so that it's rendered in both places.
if (optionsMap.hasOwnProperty(value)) {
if (group) {
var arr = optionsMap[value][field_optgroup];
if (!arr) {
optionsMap[value][field_optgroup] = group;
} else if (!$.isArray(arr)) {
optionsMap[value][field_optgroup] = [arr, group];
} else {
arr.push(group);
}
}
return;
}
var option = readData($option) || {};
option[field_label] = option[field_label] || $option.text();
option[field_value] = option[field_value] || value;
option[field_optgroup] = option[field_optgroup] || group;
optionsMap[value] = option;
options.push(option);
if ($option.is(':selected')) {
settings_element.items.push(value);
}
};
var addGroup = function($optgroup) {
var i, n, id, optgroup, $options;
$optgroup = $($optgroup);
id = $optgroup.attr('label');
if (id) {
optgroup = readData($optgroup) || {};
optgroup[field_optgroup_label] = id;
optgroup[field_optgroup_value] = id;
settings_element.optgroups.push(optgroup);
}
$options = $('option', $optgroup);
for (i = 0, n = $options.length; i < n; i++) {
addOption($options[i], id);
}
};
settings_element.maxItems = $input.attr('multiple') ? null : 1;
$children = $input.children();
for (i = 0, n = $children.length; i < n; i++) {
tagName = $children[i].tagName.toLowerCase();
if (tagName === 'optgroup') {
addGroup($children[i]);
} else if (tagName === 'option') {
addOption($children[i]);
}
}
};
return this.each(function() {
if (this.selectize) return;
var instance;
var $input = $(this);
var tag_name = this.tagName.toLowerCase();
var placeholder = $input.attr('placeholder') || $input.attr('data-placeholder');
if (!placeholder && !settings.allowEmptyOption) {
placeholder = $input.children('option[value=""]').text();
}
var settings_element = {
'placeholder': placeholder,
'options': [],
'optgroups': [],
'items': []
};
if (tag_name === 'select') {
init_select($input, settings_element);
} else {
init_textbox($input, settings_element);
}
instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings_user));
});
};
$.fn.selectize.defaults = Selectize.defaults;
$.fn.selectize.support = {
validity: SUPPORTS_VALIDITY_API
};
Selectize.define('drag_drop', function(options) {
if (!$.fn.sortable) throw new Error('The "drag_drop" plugin requires jQuery UI "sortable".');
if (this.settings.mode !== 'multi') return;
var self = this;
self.lock = (function() {
var original = self.lock;
return function() {
var sortable = self.$control.data('sortable');
if (sortable) sortable.disable();
return original.apply(self, arguments);
};
})();
self.unlock = (function() {
var original = self.unlock;
return function() {
var sortable = self.$control.data('sortable');
if (sortable) sortable.enable();
return original.apply(self, arguments);
};
})();
self.setup = (function() {
var original = self.setup;
return function() {
original.apply(this, arguments);
var $control = self.$control.sortable({
items: '[data-value]',
forcePlaceholderSize: true,
disabled: self.isLocked,
start: function(e, ui) {
ui.placeholder.css('width', ui.helper.css('width'));
$control.css({
overflow: 'visible'
});
},
stop: function() {
$control.css({
overflow: 'hidden'
});
var active = self.$activeItems ? self.$activeItems.slice() : null;
var values = [];
$control.children('[data-value]').each(function() {
values.push($(this).attr('data-value'));
});
self.setValue(values);
self.setActiveItem(active);
}
});
};
})();
});
Selectize.define('dropdown_header', function(options) {
var self = this;
options = $.extend({
title: 'Untitled',
headerClass: 'selectize-dropdown-header',
titleRowClass: 'selectize-dropdown-header-title',
labelClass: 'selectize-dropdown-header-label',
closeClass: 'selectize-dropdown-header-close',
html: function(data) {
return (
'<div class="' + data.headerClass + '">' +
'<div class="' + data.titleRowClass + '">' +
'<span class="' + data.labelClass + '">' + data.title + '</span>' +
'<a href="javascript:void(0)" class="' + data.closeClass + '">×</a>' +
'</div>' +
'</div>'
);
}
}, options);
self.setup = (function() {
var original = self.setup;
return function() {
original.apply(self, arguments);
self.$dropdown_header = $(options.html(options));
self.$dropdown.prepend(self.$dropdown_header);
};
})();
});
Selectize.define('optgroup_columns', function(options) {
var self = this;
options = $.extend({
equalizeWidth: true,
equalizeHeight: true
}, options);
this.getAdjacentOption = function($option, direction) {
var $options = $option.closest('[data-group]').find('[data-selectable]');
var index = $options.index($option) + direction;
return index >= 0 && index < $options.length ? $options.eq(index) : $();
};
this.onKeyDown = (function() {
var original = self.onKeyDown;
return function(e) {
var index, $option, $options, $optgroup;
if (this.isOpen && (e.keyCode === KEY_LEFT || e.keyCode === KEY_RIGHT)) {
self.ignoreHover = true;
$optgroup = this.$activeOption.closest('[data-group]');
index = $optgroup.find('[data-selectable]').index(this.$activeOption);
if (e.keyCode === KEY_LEFT) {
$optgroup = $optgroup.prev('[data-group]');
} else {
$optgroup = $optgroup.next('[data-group]');
}
$options = $optgroup.find('[data-selectable]');
$option = $options.eq(Math.min($options.length - 1, index));
if ($option.length) {
this.setActiveOption($option);
}
return;
}
return original.apply(this, arguments);
};
})();
var getScrollbarWidth = function() {
var div;
var width = getScrollbarWidth.width;
var doc = document;
if (typeof width === 'undefined') {
div = doc.createElement('div');
div.innerHTML = '<div style="width:50px;height:50px;position:absolute;left:-50px;top:-50px;overflow:auto;"><div style="width:1px;height:100px;"></div></div>';
div = div.firstChild;
doc.body.appendChild(div);
width = getScrollbarWidth.width = div.offsetWidth - div.clientWidth;
doc.body.removeChild(div);
}
return width;
};
var equalizeSizes = function() {
var i, n, height_max, width, width_last, width_parent, $optgroups;
$optgroups = $('[data-group]', self.$dropdown_content);
n = $optgroups.length;
if (!n || !self.$dropdown_content.width()) return;
if (options.equalizeHeight) {
height_max = 0;
for (i = 0; i < n; i++) {
height_max = Math.max(height_max, $optgroups.eq(i).height());
}
$optgroups.css({
height: height_max
});
}
if (options.equalizeWidth) {
width_parent = self.$dropdown_content.innerWidth() - getScrollbarWidth();
width = Math.round(width_parent / n);
$optgroups.css({
width: width
});
if (n > 1) {
width_last = width_parent - width * (n - 1);
$optgroups.eq(n - 1).css({
width: width_last
});
}
}
};
if (options.equalizeHeight || options.equalizeWidth) {
hook.after(this, 'positionDropdown', equalizeSizes);
hook.after(this, 'refreshOptions', equalizeSizes);
}
});
Selectize.define('remove_button', function(options) {
if (this.settings.mode === 'single') return;
options = $.extend({
label: '×',
title: 'Remove',
className: 'remove',
append: true
}, options);
var self = this;
var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
/**
* Appends an element as a child (with raw HTML).
*
* @param {string} html_container
* @param {string} html_element
* @return {string}
*/
var append = function(html_container, html_element) {
var pos = html_container.search(/(<\/[^>]+>\s*)$/);
return html_container.substring(0, pos) + html_element + html_container.substring(pos);
};
this.setup = (function() {
var original = self.setup;
return function() {
// override the item rendering method to add the button to each
if (options.append) {
var render_item = self.settings.render.item;
self.settings.render.item = function(data) {
return append(render_item.apply(this, arguments), html);
};
}
original.apply(this, arguments);
// add event listener
this.$control.on('click', '.' + options.className, function(e) {
e.preventDefault();
if (self.isLocked) return;
var $item = $(e.currentTarget).parent();
self.setActiveItem($item);
if (self.deleteSelection()) {
self.setCaret(self.items.length);
}
});
};
})();
});
Selectize.define('restore_on_backspace', function(options) {
var self = this;
options.text = options.text || function(option) {
return option[this.settings.labelField];
};
this.onKeyDown = (function() {
var original = self.onKeyDown;
return function(e) {
var index, option;
if (e.keyCode === KEY_BACKSPACE && this.$control_input.val() === '' && !this.$activeItems.length) {
index = this.caretPos - 1;
if (index >= 0 && index < this.items.length) {
option = this.options[this.items[index]];
if (this.deleteSelection(e)) {
this.setTextboxValue(options.text.apply(this, [option]));
this.refreshOptions(true);
}
e.preventDefault();
return;
}
}
return original.apply(this, arguments);
};
})();
});
return Selectize;
}));
|
/***
* Excerpted from "Mastering Dojo",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/rgdojo for more book information.
***/
dojo.provide("obe.test.data.command.set001");
dojo.require("baf.command.ItemManager");
(function(){
obe.test.data.command.set001.commandItems= {
identifier: "id",
label: "text",
items: [{
id: "file",
type: baf.commandType.submenu,
text: "File",
order: 1000
},{
id: "save",
type: baf.commandType.command,
text: "Save",
order: 1520,
group: "save"
},{
id: "saveAs",
type: baf.commandType.command,
text: "Save As...",
order: 1530,
group: "save"
},{
id: "saveAll",
type: baf.commandType.command,
text: "Save All",
order: 1540,
group: "save"
},{
id: "close",
type: baf.commandType.submenu,
text: "Close",
order: 1420,
group: "close"
},{
id: "closeAll",
type: baf.commandType.command,
text: "Close All",
order: 1430,
group: "close"
},{
id: "logoff",
type: baf.commandType.command,
text: "Logoff",
order: 2020,
group: "exit"
},{
id: "switchUser",
type: baf.commandType.command,
text: "Switch User",
order: 2030,
group: "exit"
},{
id: "edit",
type: baf.commandType.submenu,
text: "Edit",
order: 4000
},{
id: "navigate",
type: baf.commandType.submenu,
text: "Navigate",
order: 6000
},{
id: "search",
type: baf.commandType.submenu,
text: "Search",
order: 8000
},{
id: "project",
type: baf.commandType.submenu,
text: "Project",
order: 10000
},{
id: "help",
type: baf.commandType.submenu,
text: "Help",
order: 12000
}]
};
obe.test.data.command.set001.mainMenu= {
file: {
save: 0,
saveAll: 0,
saveAll: 0,
close: {
save: 0,
saveAll: 0,
saveAll: 0
},
closeAll: 0,
logoff: 0,
switchUser: 0
},
edit: 0,
navigate: 0,
search: 0,
project: 0,
help: 0
};
})();//(function(){
|
var outcome = require('../');
var onResult = outcome({
success: function() {
console.log("SUCCESS")
},
callback: function() {
console.log("CB")
}
});
var onResult2 = outcome({
success: function() {
console.log("SUCCESS2")
},
callback: function() {
console.log("CB2")
}
});
onResult();
onResult2();
|
define([
'comindware/core', 'demoPage/views/ListCanvasView'
], function (core, ListCanvasView) {
'use strict';
return function () {
// Most of this steps came from 'Basic Usage' example.
// New steps required for group-by feature marked with 'NEW'
// 1. Create Backbone.Model that implement ListItemBehavior
var ListItemModel = Backbone.Model.extend({
initialize: function () {
core.utils.helpers.applyBehavior(this, core.list.models.behaviors.ListItemBehavior);
}
});
// 2. Create VirtualCollection that use this model (and do other stuff maybe)
var ListItemCollection = core.collections.VirtualCollection.extend({
model: ListItemModel
});
// 3. Create Backbone.Model that implement ListGroupBehavior. It's gonna be your group model
var ListGroupItemModel = Backbone.Model.extend({
initialize: function () {
core.utils.helpers.applyBehavior(this, core.list.models.behaviors.ListGroupBehavior);
}
});
// 4. Get some data (inline or by collection.fetch)
var collection = new ListItemCollection();
collection.reset(_.times(1000, function (i) {
return {
id: i + 1,
title: 'My Task ' + (i + 1)
};
}));
// 4. [NEW] Group the collection
collection.group([
{
// iterator - the function that splits the collection into groups
iterator: function (model) {
return model.id % 100;
},
// modelFactory - factory function that create grouping model, a virtual model that presents group in VirtualCollection
modelFactory: function (model) {
return new ListGroupItemModel({
displayText: 'Group ' + model.id % 100
});
}
}
]);
// 5. Create child view that display list rows.
// - you MUST implement ListItemViewBehavior
var ListItemView = Marionette.ItemView.extend({
template: Handlebars.compile('<div class="dd-list__i"><span class="js-title">{{title}}</span></div>'),
behaviors: {
ListItemViewBehavior: {
behaviorClass: core.list.views.behaviors.ListItemViewBehavior
}
}
});
// 5. Create child view that display grouping rows.
var ListGroupItemView = Marionette.ItemView.extend({
template: Handlebars.compile('<div class="dd-list__i dd-list__i_group"> {{displayText}}</div>'),
className: 'mselect__group',
behaviors: {
ListItemViewBehavior: {
behaviorClass: core.list.views.behaviors.ListItemViewBehavior
}
}
});
// 6. At last, create list view bundle (ListView and ScrollbarView)
var bundle = core.list.factory.createDefaultList({
collection: collection, // Take a note that in simple scenario you can pass in
// a regular Backbone.Collection or even plain javascript array
listViewOptions: {
childViewSelector: function(model) {
// We use different views based on is it grouping row or a regular one
if (model instanceof ListItemModel) {
return ListItemView;
} else {
return ListGroupItemView;
}
},
childHeight: 34
}
});
// 7. Show created views in corresponding regions
return new ListCanvasView({
content: bundle.listView,
scrollbar: bundle.scrollbarView
});
};
});
|
'use strict';
angular
.module( 'app', [
'tc.chartjs',
'app.line',
'app.bar',
'app.radar',
'app.polararea',
'app.pie',
'app.doughnut'
] );
angular
.module( 'app' )
.controller( 'HomeCtrl', HomeCtrl );
function HomeCtrl( $scope ) {
$scope.data = {
labels : [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '' ],
datasets : [
{
fillColor : 'rgba(250, 250, 250, 0.7)',
data : [ 65, 59, 90, 81, 56, 55, 40, 65, 59, 90, 28, 48, 40, 19, 96 ]
},
{
fillColor : 'rgba(0, 140, 186, 0.6)',
data : [ 28, 48, 40, 19, 96, 27, 100, 28, 48, 40, 65, 59, 90, 81, 56 ]
},
{
fillColor : 'rgba(0, 140, 186, 0.3)',
data : [ 55, 40, 65, 59, 90, 65, 59, 90, 81, 56, 27, 100, 28, 48, 40, 28, 48, 40, 19, 96 ]
}
]
};
// 27, 100, 28, 48, 40, 28, 48, 40, 19, 96, 55, 40, 65, 59, 90, 65, 59, 90, 81, 56
$scope.options = {
showTooltips: false,
showScale: false,
scaleBeginAtZero : true,
scaleShowGridLines : false,
scaleGridLineColor : 'rgba(0,0,0,.05)',
scaleGridLineWidth : 1,
barShowStroke : false,
barStrokeWidth : 2,
barValueSpacing : 0,
barDatasetSpacing : 0,
legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].lineColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
onAnimationComplete : function(){},
responsive: true
};
}
|
$(function() {
alert('Hello!');
})
|
(function($) {
$.fn.lifestream.feeds.googleplus = function( config, callback ) {
var template = $.extend({},
{
posted: '<a href="${actor.url}">${actor.displayName}</a>' +
' has posted a new entry <a href="${url}" ' +
'title="${id}">${title}</a> <!--With--> ' +
'${object.replies.totalItems} replies, ' +
'${object.plusoners.totalItems} +1s, ' +
'${object.resharers.totalItems} Reshares'
},
config.template),
parseGooglePlus = function( input ) {
var output = [], i = 0, j, item;
if(input && input.items) {
j = input.items.length;
for( ; i<j; i++) {
item = input.items[i];
output.push({
date: new Date( item.published ),
config: config,
html: $.tmpl( template.posted, item )
});
}
}
return output;
};
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/" + config.user +
"/activities/public",
data: {
key: config.key
},
dataType: 'jsonp',
success: function( data ) {
if (data.error) {
callback([]);
if (console && console.error) {
console.error('Error loading Google+ stream.', data.error);
}
return;
} else {
callback(parseGooglePlus(data));
}
}
});
// Expose the template.
// We use this to check which templates are available
return {
"template" : template
};
};
})(jQuery);
|
'use strict';
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){
a=a(self, locals); b=b(self, locals);
if (isDefined(a)) {
if (isDefined(b)) {
return a + b;
}
return a;
}
return isDefined(b)?b:undefined;},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
'!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
ch3 = ch2 + peek(2),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2],
fn3 = OPERATORS[ch3];
if (fn3) {
tokens.push({index:index, text:ch3, fn:fn3});
index += 3;
} else if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek(i) {
var num = i || 1;
return index + num < text.length ? text.charAt(index + num) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
var ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
value.literal = !!value.literal;
value.constant = !!value.constant;
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return extend(function(self, locals) {
return fn(self, locals, right);
}, {
constant:right.constant
});
}
function binaryFn(left, fn, right) {
return extend(function(self, locals) {
return fn(self, locals, left, right);
}, {
constant:left.constant && right.constant
});
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(self, locals){
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!=','===','!=='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
if (token.json) {
primary.constant = primary.literal = true;
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(
function(self, locals) {
return getter(object(self, locals), locals);
},
{
assign:function(self, value, locals) {
return setter(object(self, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals){
var args = [],
context = contextGetter ? contextGetter(self, locals) : self;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr = fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
var allConstant = true;
if (peekToken().text != ']') {
do {
var elementFn = expression();
elementFns.push(elementFn);
if (!elementFn.constant) {
allConstant = false;
}
} while (expect(','));
}
consume(']');
return extend(function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
}, {
literal:true,
constant:allConstant
});
}
function object () {
var keyValues = [];
var allConstant = true;
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
if (!value.constant) {
allConstant = false;
}
} while (expect(','));
}
consume('}');
return extend(function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self, locals);
object[keyValue.key] = value;
}
return object;
}, {
literal:true,
constant:allConstant
});
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
|
/*jslint nomen: true, undef: true, sloppy: true, white: true, stupid: true, passfail: false, node: true, plusplus: true, indent: 2 */
// now with coverage suport
var i18n = process.env.EXPRESS_COV ? require('../i18n-cov') : require('../i18n'),
should = require("should");
describe('Object Notation', function () {
beforeEach(function () {
i18n.configure({
locales: ['en', 'de'],
directory: './locales',
register: global,
updateFiles:true,
objectNotation:true
});
});
describe('Date/Time patterns', function () {
it('should return en formatting as expected', function () {
i18n.setLocale('en');
should.equal(__('format.date'), 'MM/DD/YYYY');
should.equal(__('format.time'), 'h:mm:ss a');
});
it('should return de formatting as expected', function () {
i18n.setLocale('de');
should.equal(__('format.date'), 'DD.MM.YYYY');
should.equal(__('format.time'), 'hh:mm:ss');
});
});
describe('i18nTranslate', function () {
it('should return en translations as expected, using object traversal notation', function () {
i18n.setLocale('en');
should.equal(__('greeting.formal'), 'Hello');
should.equal(__('greeting.informal'), 'Hi');
should.equal(__('greeting.placeholder.formal', 'Marcus'), 'Hello Marcus');
should.equal(__('greeting.placeholder.informal', 'Marcus'), 'Hi Marcus');
should.throws(__('greeting.placeholder.loud', 'Marcus'));
});
it('should provide proper pluralization support, using object traversal notation', function () {
i18n.setLocale('en');
var singular = __n({singular: "cat", plural: "cat", locale: "de"}, 1),
plural = __n({singular: "cat", plural: "cat", locale: "de"}, 3);
should.equal(singular, '1 Katze');
should.equal(plural, '3 Katzen');
});
it('should allow for simple pluralization', function(){
var singular = __n("nested.deep.plural", 1);
var plural = __n("nested.deep.plural", 3);
should.equal(singular, 'plural');
should.equal(plural, 'plurals');
});
});
});
|
/*!
* connect
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
* @private
*/
var debug = require('debug')('connect:dispatcher');
var EventEmitter = require('events').EventEmitter;
var finalhandler = require('finalhandler');
var http = require('http');
var merge = require('utils-merge');
var parseUrl = require('parseurl');
/**
* Module exports.
* @public
*/
module.exports = createServer;
/**
* Module variables.
* @private
*/
var env = process.env.NODE_ENV || 'development';
var proto = {};
/* istanbul ignore next */
var defer = typeof setImmediate === 'function'
? setImmediate
: function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
/**
* Create a new connect server.
*
* @return {function}
* @public
*/
function createServer() {
function app(req, res, next){ app.handle(req, res, next); }
merge(app, proto);
merge(app, EventEmitter.prototype);
app.route = '/';
app.stack = [];
return app;
}
/**
* Utilize the given middleware `handle` to the given `route`,
* defaulting to _/_. This "route" is the mount-point for the
* middleware, when given a value other than _/_ the middleware
* is only effective when that segment is present in the request's
* pathname.
*
* For example if we were to mount a function at _/admin_, it would
* be invoked on _/admin_, and _/admin/settings_, however it would
* not be invoked for _/_, or _/posts_.
*
* @param {String|Function|Server} route, callback or server
* @param {Function|Server} callback or server
* @return {Server} for chaining
* @public
*/
proto.use = function use(route, fn) {
var handle = fn;
var path = route;
// default route to '/'
if (typeof route !== 'string') {
handle = route;
path = '/';
}
// wrap sub-apps
if (typeof handle.handle === 'function') {
var server = handle;
server.route = path;
handle = function (req, res, next) {
server.handle(req, res, next);
};
}
// wrap vanilla http.Servers
if (handle instanceof http.Server) {
handle = handle.listeners('request')[0];
}
// strip trailing slash
if (path[path.length - 1] === '/') {
path = path.slice(0, -1);
}
// add the middleware
debug('use %s %s', path || '/', handle.name || 'anonymous');
this.stack.push({ route: path, handle: handle });
return this;
};
/**
* Handle server requests, punting them down
* the middleware stack.
*
* @private
*/
proto.handle = function handle(req, res, out) {
var index = 0;
var protohost = getProtohost(req.url) || '';
var removed = '';
var slashAdded = false;
var stack = this.stack;
// final function handler
var done = out || finalhandler(req, res, {
env: env,
onerror: logerror
});
// store the original URL
req.originalUrl = req.originalUrl || req.url;
function next(err) {
if (slashAdded) {
req.url = req.url.substr(1);
slashAdded = false;
}
if (removed.length !== 0) {
req.url = protohost + removed + req.url.substr(protohost.length);
removed = '';
}
// next callback
var layer = stack[index++];
// all done
if (!layer) {
defer(done, err);
return;
}
// route data
var path = parseUrl(req).pathname || '/';
var route = layer.route;
// skip this layer if the route doesn't match
if (path.toLowerCase().substr(0, route.length) !== route.toLowerCase()) {
return next(err);
}
// skip if route match does not border "/", ".", or end
var c = path[route.length];
if (c !== undefined && '/' !== c && '.' !== c) {
return next(err);
}
// trim off the part of the url that matches the route
if (route.length !== 0 && route !== '/') {
removed = route;
req.url = protohost + req.url.substr(protohost.length + removed.length);
// ensure leading slash
if (!protohost && req.url[0] !== '/') {
req.url = '/' + req.url;
slashAdded = true;
}
}
// call the layer handle
call(layer.handle, route, err, req, res, next);
}
next();
};
/**
* Listen for connections.
*
* This method takes the same arguments
* as node's `http.Server#listen()`.
*
* HTTP and HTTPS:
*
* If you run your application both as HTTP
* and HTTPS you may wrap them individually,
* since your Connect "server" is really just
* a JavaScript `Function`.
*
* var connect = require('connect')
* , http = require('http')
* , https = require('https');
*
* var app = connect();
*
* http.createServer(app).listen(80);
* https.createServer(options, app).listen(443);
*
* @return {http.Server}
* @api public
*/
proto.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
/**
* Invoke a route handle.
* @private
*/
function call(handle, route, err, req, res, next) {
var arity = handle.length;
var error = err;
var hasError = Boolean(err);
debug('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
try {
if (hasError && arity === 4) {
// error-handling middleware
handle(err, req, res, next);
return;
} else if (!hasError && arity < 4) {
// request-handling middleware
handle(req, res, next);
return;
}
} catch (e) {
// replace the error
error = e;
}
// continue
next(error);
}
/**
* Log error using console.error.
*
* @param {Error} err
* @private
*/
function logerror(err) {
if (env !== 'test') console.error(err.stack || err.toString());
}
/**
* Get get protocol + host for a URL.
*
* @param {string} url
* @private
*/
function getProtohost(url) {
if (url.length === 0 || url[0] === '/') {
return undefined;
}
var searchIndex = url.indexOf('?');
var pathLength = searchIndex !== -1
? searchIndex
: url.length;
var fqdnIndex = url.substr(0, pathLength).indexOf('://');
return fqdnIndex !== -1
? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
: undefined;
}
|
require.paths.unshift("../../lib");
var sys = require('sys'),
Buffer = require('buffer').Buffer,
BSON = require('./bson').BSON,
Buffer = require('buffer').Buffer,
BSONJS = require('mongodb/bson/bson').BSON,
BinaryParser = require('mongodb/bson/binary_parser').BinaryParser,
Long = require('mongodb/goog/math/long').Long,
ObjectID = require('mongodb/bson/bson').ObjectID,
Binary = require('mongodb/bson/bson').Binary,
Code = require('mongodb/bson/bson').Code,
DBRef = require('mongodb/bson/bson').DBRef,
assert = require('assert');
var Long2 = require('./bson').Long,
ObjectID2 = require('./bson').ObjectID,
Binary2 = require('./bson').Binary,
Code2 = require('./bson').Code,
DBRef2 = require('./bson').DBRef;
sys.puts("=== EXCEUTING TEST_BSON ===");
// Long data type tests
var l2_string = Long2.fromNumber(100);
var l_string = Long.fromNumber(100);
assert.equal(l_string.toNumber(), l2_string.toNumber());
var l2_string = Long2.fromNumber(9223372036854775807).toString();
var l_string = Long.fromNumber(9223372036854775807).toString();
assert.equal(l_string, l2_string);
l2_string = Long2.fromNumber(9223372036800).toString();
l_string = Long.fromNumber(9223372036800).toString();
assert.equal(l_string, l2_string);
l2_string = Long2.fromNumber(2355).toString();
l_string = Long.fromNumber(2355).toString();
assert.equal(l_string, l2_string);
l_string = Long.fromNumber(-9223372036854775807).toString();
l2_string = Long2.fromNumber(-9223372036854775807).toString();
assert.equal(l_string, l2_string);
l2_string = Long2.fromNumber(-2355).toString();
l_string = Long.fromNumber(-2355).toString();
assert.equal(l_string, l2_string);
l2_string = Long2.fromNumber(-1).toString();
l_string = Long.fromNumber(-1).toString();
assert.equal(l_string, l2_string);
l2_string = Long2.fromNumber(1).toString();
l_string = Long.fromNumber(1).toString();
assert.equal(l_string, l2_string);
var a = Long2.fromNumber(10);
assert.equal(10, a);
var a = Long2.fromNumber(9223372036854775807);
assert.equal(9223372036854775807, a);
// Simple serialization and deserialization test for a Single String value
var simple_string_serialized = BSON.serialize({doc:'Serialize'});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple integer serialization/deserialization test, including testing boundary conditions
var simple_string_serialized = BSON.serialize({doc:-1});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
var simple_string_serialized = BSON.serialize({doc:2147483648});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
var simple_string_serialized = BSON.serialize({doc:-2147483648});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple serialization and deserialization test for a Long value
var simple_string_serialized = BSON.serialize({doc:Long2.fromNumber(9223372036854775807)});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
var simple_string_serialized = BSON.serialize({doc:Long2.fromNumber(-9223372036854775807)});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple serialization and deserialization for a Float value
var simple_string_serialized = BSON.serialize({doc:2222.3333});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
var simple_string_serialized = BSON.serialize({doc:-2222.3333});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple serialization and deserialization for a null value
var simple_string_serialized = BSON.serialize({doc:null});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple serialization and deserialization for a boolean value
var simple_string_serialized = BSON.serialize({doc:true});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple serialization and deserialization for a date value
var date = new Date();
var simple_string_serialized = BSON.serialize({doc:date});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')));
assert.deepEqual(BSONJS.deserialize(simple_string_serialized), BSON.deserialize(simple_string_serialized));
// Simple serialization and deserialization for a boolean value
var simple_string_serialized = BSON.serialize({doc:/abcd/mi});
assert.equal(BSONJS.deserialize(simple_string_serialized).doc.toString(), BSON.deserialize(simple_string_serialized).doc.toString());
assert.equal(BSONJS.deserialize(simple_string_serialized).doc.toString(), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString());
var simple_string_serialized = BSON.serialize({doc:/abcd/});
assert.equal(BSONJS.deserialize(simple_string_serialized).doc.toString(), BSON.deserialize(simple_string_serialized).doc.toString());
assert.equal(BSONJS.deserialize(simple_string_serialized).doc.toString(), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString());
// Simple serialization and deserialization for a objectId value
var simple_string_serialized = BSON.serialize({doc:new ObjectID2()});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized).doc.toString(), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.toString());
assert.deepEqual(BSONJS.deserialize(simple_string_serialized).doc.toString(), BSON.deserialize(simple_string_serialized).doc.toString());
// Simple serialization and deserialization for a Binary value
var binary = new Binary2();
var string = 'binstring'
for(var index = 0; index < string.length; index++) { binary.put(string.charAt(index)); }
var simple_string_serialized = BSON.serialize({doc:binary});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized).doc.value(), BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.value());
assert.deepEqual(BSONJS.deserialize(simple_string_serialized).doc.value(), BSON.deserialize(simple_string_serialized).doc.value());
// Simple serialization and deserialization for a Code value
var code = new Code2('this.a > i', {'i': 1});
var code2 = new Code('this.a > i', {'i': 1});
var simple_string_serialized_2 = BSONJS.serialize({doc:code2});
var simple_string_serialized = BSON.serialize({doc:code});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized_2).doc.scope, BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc.scope);
assert.deepEqual(BSONJS.deserialize(simple_string_serialized_2).doc.code, BSON.deserialize(simple_string_serialized).doc.code);
// Simple serialization and deserialization for an Object
var simple_string_serialized = BSON.serialize({doc:{a:1, b:{c:2}}});
var simple_string_serialized_2 = BSONJS.serialize({doc:{a:1, b:{c:2}}});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized_2).doc, BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc);
assert.deepEqual(BSONJS.deserialize(simple_string_serialized_2).doc, BSON.deserialize(simple_string_serialized).doc);
// Simple serialization and deserialization for an Array
var simple_string_serialized = BSON.serialize({doc:[9, 9, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1]});
var simple_string_serialized_2 = BSONJS.serialize({doc:[9, 9, 1, 2, 3, 1, 1, 1, 1, 1, 1, 1]});
assert.deepEqual(BSONJS.deserialize(simple_string_serialized_2).doc, BSON.deserialize(new Buffer(simple_string_serialized, 'binary')).doc);
assert.deepEqual(BSONJS.deserialize(simple_string_serialized_2).doc, BSON.deserialize(simple_string_serialized).doc);
// Simple serialization and deserialization for a DBRef
var oid = new ObjectID2()
var simple_string_serialized = BSONJS.serialize({doc:new DBRef('namespace', oid, 'integration_tests_')});
var simple_string_serialized_2 = BSON.serialize({doc:new DBRef2('namespace', oid, 'integration_tests_')});
// Ensure we have the same values for the dbref
var object_js = BSONJS.deserialize(simple_string_serialized_2);
var object_c = BSON.deserialize(simple_string_serialized);
assert.equal(object_js.doc.namespace, object_c.doc.namespace);
assert.equal(object_js.doc.oid.toHexString(), object_c.doc.oid.toHexString());
assert.equal(object_js.doc.db, object_c.doc.db);
// Serialized document
var bytes = [47,0,0,0,2,110,97,109,101,0,6,0,0,0,80,97,116,116,121,0,16,97,103,101,0,34,0,0,0,7,95,105,100,0,76,100,12,23,11,30,39,8,89,0,0,1,0];
var serialized_data = '';
// Convert to chars
for(var i = 0; i < bytes.length; i++) {
serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]);
}
var object = BSON.deserialize(serialized_data);
assert.equal('Patty', object.name)
assert.equal(34, object.age)
assert.equal('4c640c170b1e270859000001', object._id.toHexString())
// Serialize utf8
var doc = { "name" : "本荘由利地域に洪水警報", "name1" : "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "name2" : "abcdedede"};
var simple_string_serialized = BSON.serialize(doc);
var object = BSON.deserialize(simple_string_serialized);
assert.equal(doc.name, object.name)
assert.equal(doc.name1, object.name1)
assert.equal(doc.name2, object.name2)
// Serialize object with array
var doc = {b:[1, 2, 3]};
var simple_string_serialized = BSON.serialize(doc);
var simple_string_serialized_2 = BSONJS.serialize(doc);
var object = BSON.deserialize(simple_string_serialized);
assert.deepEqual(doc, object)
// Test equality of an object ID
var object_id = new ObjectID2();
var object_id_2 = new ObjectID2();
assert.ok(object_id.equals(object_id));
assert.ok(!(object_id.equals(object_id_2)))
|
__UNBOUND0__["__STRING0__"] = (function() {})();
|
const express = require("express")
const router = express()
const { createWebAPIRequest } = require("../util/util")
router.get("/", (req, res) => {
const cookie = req.get('Cookie') ? req.get('Cookie') : ''
const data = {
'id': req.query.id,
"csrf_token": ""
}
createWebAPIRequest(
'music.163.com',
'/weapi/dj/program/detail',
'POST',
data,
cookie,
music_req => {
res.send(music_req)
},
err => res.status(502).send('fetch error')
)
})
module.exports = router
|
export const EVENT_TARGET_SEPARATOR = ':';
export class EventConfig {
constructor(fieldName, eventName, isLongForm) {
this.fieldName = fieldName;
this.eventName = eventName;
this.isLongForm = isLongForm;
}
static parse(eventConfig) {
var fieldName = eventConfig, eventName = eventConfig, isLongForm = false;
var separatorIdx = eventConfig.indexOf(EVENT_TARGET_SEPARATOR);
if (separatorIdx > -1) {
// long format: 'fieldName: eventName'
fieldName = eventConfig.substring(0, separatorIdx).trim();
eventName = eventConfig.substring(separatorIdx + 1).trim();
isLongForm = true;
}
return new EventConfig(fieldName, eventName, isLongForm);
}
getFullName() {
return this.isLongForm ? `${this.fieldName}${EVENT_TARGET_SEPARATOR}${this.eventName}` :
this.eventName;
}
}
//# sourceMappingURL=event_config.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.