AMD-ify jQuery sourcegit s! Woo! Fixes #14113, #14163.

Conflicts:
	Gruntfile.js
	README.md
	src/ajax.js
	src/ajax/xhr.js
	src/attributes.js
	src/core.js
	src/css.js
	src/data.js
	src/effects.js
	src/event.js
	src/manipulation.js
	src/offset.js
	src/selector-native.js
	src/traversing.js
	test/unit/core.js
	test/unit/data.js
This commit is contained in:
Timmy Willison 2013-08-15 14:15:49 -04:00
parent 144837afdf
commit 217cbb7109
73 changed files with 27840 additions and 1659 deletions

2
.gitignore vendored
View File

@ -1,5 +1,3 @@
src/selector-sizzle.js
src/selector.js
dist
.project
.settings

View File

@ -2,6 +2,9 @@ module.exports = function( grunt ) {
"use strict";
// Integrate build task
require( "./build/build" )( grunt );
var distpaths = [
"dist/jquery.js",
"dist/jquery.min.map",
@ -36,41 +39,17 @@ module.exports = function( grunt ) {
cache: "dist/.sizecache.json"
}
},
selector: {
destFile: "src/selector-sizzle.js",
apiFile: "src/sizzle-jquery.js",
srcFile: "bower_components/sizzle/dist/sizzle.js"
},
build: {
all: {
dest: "dist/jquery.js",
src: [
"src/intro.js",
"src/core.js",
"src/selector-sizzle.js",
"src/callbacks.js",
"src/deferred.js",
"src/support.js",
"src/data.js",
"src/queue.js",
"src/attributes.js",
"src/event.js",
"src/traversing.js",
"src/manipulation.js",
{ flag: "wrap", src: "src/wrap.js" },
{ flag: "css", src: "src/css.js" },
"src/serialize.js",
{ flag: "event-alias", src: "src/event-alias.js" },
{ flag: "ajax", src: "src/ajax.js" },
{ flag: "ajax/script", src: "src/ajax/script.js", needs: ["ajax"] },
{ flag: "ajax/jsonp", src: "src/ajax/jsonp.js", needs: [ "ajax", "ajax/script" ] },
{ flag: "ajax/xhr", src: "src/ajax/xhr.js", needs: ["ajax"] },
{ flag: "effects", src: "src/effects.js", needs: ["css"] },
{ flag: "offset", src: "src/offset.js", needs: ["css"] },
{ flag: "dimensions", src: "src/dimensions.js", needs: ["css"] },
{ flag: "deprecated", src: "src/deprecated.js" },
"src/outro.js"
]
minimum: [
"core",
"selector"
],
removeWith: {
callbacks: [ "deferred" ],
css: [ "effects", "dimensions", "offset" ]
}
}
},
jsonlint: {
@ -87,7 +66,7 @@ module.exports = function( grunt ) {
options: srcHintOptions
},
grunt: {
src: [ "Gruntfile.js" ],
src: [ "Gruntfile.js", "build/build.js" ],
options: {
jshintrc: ".jshintrc"
}
@ -203,252 +182,6 @@ module.exports = function( grunt ) {
);
});
grunt.registerTask( "selector", "Build Sizzle-based selector module", function() {
var cfg = grunt.config("selector"),
name = cfg.destFile,
sizzle = {
api: grunt.file.read( cfg.apiFile ),
src: grunt.file.read( cfg.srcFile )
},
compiled, parts;
/**
sizzle-jquery.js -> sizzle between "EXPOSE" blocks,
replace define & window.Sizzle assignment
// EXPOSE
if ( typeof define === "function" && define.amd ) {
define(function() { return Sizzle; });
} else {
window.Sizzle = Sizzle;
}
// EXPOSE
Becomes...
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
*/
// Break into 3 pieces
parts = sizzle.src.split("// EXPOSE");
// Replace the if/else block with api
parts[1] = sizzle.api;
// Rejoin the pieces
compiled = parts.join("");
grunt.verbose.writeln("Injected " + cfg.apiFile + " into " + cfg.srcFile);
// Write concatenated source to file, and ensure newline-only termination
grunt.file.write( name, compiled.replace( /\x0d\x0a/g, "\x0a" ) );
// Fail task if errors were logged.
if ( this.errorCount ) {
return false;
}
// Otherwise, print a success message.
grunt.log.writeln( "File '" + name + "' created." );
});
// Special "alias" task to make custom build creation less grawlix-y
grunt.registerTask( "custom", function() {
var done = this.async(),
args = [].slice.call(arguments),
modules = args.length ? args[0].replace(/,/g, ":") : "";
// Translation example
//
// grunt custom:+ajax,-dimensions,-effects,-offset
//
// Becomes:
//
// grunt build:*:*:+ajax:-dimensions:-effects:-offset
grunt.log.writeln( "Creating custom build...\n" );
grunt.util.spawn({
grunt: true,
args: [ "build:*:*:" + modules, "pre-uglify", "uglify", "dist" ]
}, function( err, result ) {
if ( err ) {
grunt.verbose.error();
done( err );
return;
}
grunt.log.writeln( result.stdout.replace("Done, without errors.", "") );
done();
});
});
// Special concat/build task to handle various jQuery build requirements
grunt.registerMultiTask(
"build",
"Concatenate source (include/exclude modules with +/- flags), embed date/version",
function() {
// Concat specified files.
var compiled = "",
modules = this.flags,
optIn = !modules["*"],
explicit = optIn || Object.keys(modules).length > 1,
name = this.data.dest,
src = this.data.src,
deps = {},
excluded = {},
version = grunt.config( "pkg.version" ),
excluder = function( flag, needsFlag ) {
// optIn defaults implicit behavior to weak exclusion
if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
excluded[ flag ] = false;
}
// explicit or inherited strong exclusion
if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
excluded[ flag ] = true;
// explicit inclusion overrides weak exclusion
} else if ( excluded[ needsFlag ] === false &&
( modules[ flag ] || modules[ "+" + flag ] ) ) {
delete excluded[ needsFlag ];
// ...all the way down
if ( deps[ needsFlag ] ) {
deps[ needsFlag ].forEach(function( subDep ) {
modules[ needsFlag ] = true;
excluder( needsFlag, subDep );
});
}
}
};
// append commit id to version
if ( process.env.COMMIT ) {
version += " " + process.env.COMMIT;
}
// figure out which files to exclude based on these rules in this order:
// dependency explicit exclude
// > explicit exclude
// > explicit include
// > dependency implicit exclude
// > implicit exclude
// examples:
// * none (implicit exclude)
// *:* all (implicit include)
// *:*:-css all except css and dependents (explicit > implicit)
// *:*:-css:+effects same (excludes effects because explicit include is trumped by explicit exclude of dependency)
// *:+effects none except effects and its dependencies (explicit include trumps implicit exclude of dependency)
src.forEach(function( filepath ) {
var flag = filepath.flag;
if ( flag ) {
excluder(flag);
// check for dependencies
if ( filepath.needs ) {
deps[ flag ] = filepath.needs;
filepath.needs.forEach(function( needsFlag ) {
excluder( flag, needsFlag );
});
}
}
});
// append excluded modules to version
if ( Object.keys( excluded ).length ) {
version += " -" + Object.keys( excluded ).join( ",-" );
// set pkg.version to version with excludes, so minified file picks it up
grunt.config.set( "pkg.version", version );
}
// conditionally concatenate source
src.forEach(function( filepath ) {
var flag = filepath.flag,
specified = false,
omit = false,
messages = [];
if ( flag ) {
if ( excluded[ flag ] !== undefined ) {
messages.push([
( "Excluding " + flag ).red,
( "(" + filepath.src + ")" ).grey
]);
specified = true;
omit = !filepath.alt;
if ( !omit ) {
flag += " alternate";
filepath.src = filepath.alt;
}
}
if ( excluded[ flag ] === undefined ) {
messages.push([
( "Including " + flag ).green,
( "(" + filepath.src + ")" ).grey
]);
// If this module was actually specified by the
// builder, then set the flag to include it in the
// output list
if ( modules[ "+" + flag ] ) {
specified = true;
}
}
filepath = filepath.src;
// Only display the inclusion/exclusion list when handling
// an explicit list.
//
// Additionally, only display modules that have been specified
// by the user
if ( explicit && specified ) {
messages.forEach(function( message ) {
grunt.log.writetableln( [ 27, 30 ], message );
});
}
}
if ( !omit ) {
compiled += grunt.file.read( filepath );
}
});
// Embed Version
// Embed Date
compiled = compiled.replace( /@VERSION/g, version )
// yyyy-mm-ddThh:mmZ
.replace( /@DATE/g, ( new Date() ).toISOString().replace( /:\d+\.\d+Z$/, "Z" ) );
// Write concatenated source to file
grunt.file.write( name, compiled );
// Fail task if errors were logged.
if ( this.errorCount ) {
return false;
}
// Otherwise, print a success message.
grunt.log.writeln( "File '" + name + "' created." );
});
// Process files for distribution
grunt.registerTask( "dist", function() {
var stored, flags, paths, nonascii;
@ -540,7 +273,7 @@ module.exports = function( grunt ) {
// Strip banners
return contents
// Remove the main jQuery banner, it'll be replaced by the new banner anyway.
.replace( /^\/\*!(?:.|\n)*?\*\/\n?/g, "" )
.replace( /^\/\*![\W\w]*?\*\/\n?/g, "" )
// Strip other banners preserving line count.
.replace( /^\/\*!(?:.|\n)*?\*\/\n?/gm, function ( match ) {
return match.replace( /[^\n]/gm, "" );
@ -585,7 +318,7 @@ module.exports = function( grunt ) {
grunt.loadNpmTasks("grunt-jsonlint");
// Short list as a high frequency watch task
grunt.registerTask( "dev", [ "selector", "build:*:*", "jshint" ] );
grunt.registerTask( "dev", [ "build:*:*", "jshint" ] );
// Default grunt
grunt.registerTask( "default", [ "jsonlint", "dev", "pre-uglify", "uglify", "post-uglify", "dist:*", "compare_size" ] );

View File

@ -67,21 +67,34 @@ The built version of jQuery will be put in the `dist/` subdirectory, along with
Special builds can be created that exclude subsets of jQuery functionality.
This allows for smaller custom builds when the builder is certain that those parts of jQuery are not being used.
For example, an app that only used JSONP for `$.ajax()` and did not need to calculate offsets or positions of elements could exclude the offset and ajax/xhr modules. The current modules that can be excluded are:
For example, an app that only used JSONP for `$.ajax()` and did not need to calculate offsets or positions of elements could exclude the offset and ajax/xhr modules.
Any module may be excluded except for `core`, and `selector`. To exclude a module, pass its path relative to the `src` folder (without the `.js` extension).
Some example modules that can be excluded are:
- **ajax**: All AJAX functionality: `$.ajax()`, `$.get()`, `$.post()`, `$.ajaxSetup()`, `.load()`, transports, and ajax event shorthands such as `.ajaxStart()`.
- **ajax/xhr**: The XMLHTTPRequest AJAX transport only.
- **ajax/script**: The `<script>` AJAX transport only; used to retrieve scripts.
- **ajax/jsonp**: The JSONP AJAX transport only; depends on the ajax/script transport.
- **css**: The `.css()` method plus non-animated `.show()`, `.hide()` and `.toggle()`.
- **css**: The `.css()` method plus non-animated `.show()`, `.hide()` and `.toggle()`. Also removes **all** modules depending on css (including **effects**, **dimensions**, and **offset**).
- **deprecated**: Methods documented as deprecated but not yet removed; currently only `.andSelf()`.
- **dimensions**: The `.width()` and `.height()` methods, including `inner-` and `outer-` variations.
- **effects**: The `.animate()` method and its shorthands such as `.slideUp()` or `.hide("slow")`.
- **event-alias**: All event attaching/triggering shorthands like `.click()` or `.mouseover()`.
- **event**: The `.on()` and `.off()` methods and all event functionality. Also removes `event/alias`.
- **event/alias**: All event attaching/triggering shorthands like `.click()` or `.mouseover()`.
- **offset**: The `.offset()`, `.position()`, `.offsetParent()`, `.scrollLeft()`, and `.scrollTop()` methods.
- **wrap**: The `.wrap()`, `.wrapAll()`, `.wrapInner()`, and `.unwrap()` methods.
- **exports/amd**: Exclude the AMD definition.
- **core/ready**: Exclude the ready module if you place your scripts at the end of the body. Any ready callbacks will simply be called immediately.
- **deferred**: Exclude jQuery.Deferred. This also removes jQuery.Callbacks. *Note* that modules that depend on jQuery.Deferred(AJAX, effects, core/ready) will not be removed and will still expect jQuery.Deferred to be there. Include your own jQuery.Deferred implementation or exclude those modules as well (`grunt custom:-deferred,-ajax,-effects,-core/ready`).
- **support**: Excluding the support module is not recommended, but possible. It's your responsibility to either remove modules that use jQuery.support (many of them) or replace the values wherever jQuery.support is used. This is mainly only useful when building a barebones version of jQuery.
The grunt build process is aware of dependencies across modules. If you explicitly remove a module, its dependent modules will be removed as well. For example, excluding the css module also excludes effects, since the effects module uses `.css()` to animate CSS properties. These dependencies are listed in Gruntfile.js and the build process shows a message for each dependent module it excludes.
Removing sizzle is not supported on the 1.x branch.
*Note*: Excluding Sizzle will also exclude all jQuery selector extensions (such as `effects/animated-selector` and `css/hidden-visible-selectors`).
The build process shows a message for each dependent module it excludes or includes.
To create a custom build of the latest stable version, first check out the version:
@ -103,16 +116,16 @@ Exclude all **ajax** functionality:
grunt custom:-ajax
```
Exclude **css**, **effects**, **offset**, **dimensions**, and **position**. Excluding **css** automatically excludes its dependent modules:
Excluding **css** removes modules depending on CSS: **effects**, **offset**, **dimensions**.
```bash
grunt custom:-css,-position
grunt custom:-css
```
Exclude **all** optional modules:
Exclude a bunch of modules:
```bash
grunt custom:-ajax,-css,-deprecated,-dimensions,-effects,-event-alias,-offset,-wrap
grunt custom:-ajax,-css,-deprecated,-dimensions,-effects,-event/alias,-offset,-wrap
```
For questions or requests regarding custom builds, please start a thread on the [Developing jQuery Core](https://forum.jquery.com/developing-jquery-core) section of the forum. Due to the combinatorics and custom nature of these builds, they are not regularly tested in jQuery's unit test process.

View File

@ -11,7 +11,8 @@
"bower.json"
],
"dependencies": {
"sizzle": "~1.10.5"
"sizzle": "~1.10.5",
"requirejs": "~2.1.8"
},
"devDependencies": {
"qunit": "~1.12.0"

226
build/build.js Normal file
View File

@ -0,0 +1,226 @@
/**
* Special concat/build task to handle various jQuery build requirements
* Concats AMD modules, removes their definitions, and includes/excludes specified modules
*/
module.exports = function( grunt ) {
var fs = require("fs"),
srcFolder = __dirname + "/../src/",
rdefineEnd = /\}\);[^}\w]*$/,
// This is temporary until the skipSemiColonInsertion option makes it to NPM
requirejs = require("./r"),
config = {
baseUrl: "src",
name: "jquery",
out: "dist/jquery.js",
// We have multiple minify steps
optimize: "none",
skipSemiColonInsertion: true,
wrap: {
startFile: "src/intro.js",
endFile: "src/outro.js"
},
onBuildWrite: convert
};
/**
* Strip all definitions generated by requirejs
* Convert "var" modules to var declarations
* "var module" means the module only contains a return statement that should be converted to a var declaration
* This is indicated by including the file in any "var" folder
* @param {String} name
* @param {String} path
* @param {String} contents The contents to be written (including their AMD wrappers)
*/
function convert( name, path, contents ) {
// Convert var modules
if ( /\/var\//.test( path ) ) {
contents = contents
.replace( /define\([\w\W]*?return/, "var " + (/var\/([\w-]+)/.exec(name)[1]) + " =" )
.replace( rdefineEnd, "" );
// Sizzle treatment
} else if ( /\/sizzle$/.test( name ) ) {
contents = "var Sizzle =\n" + contents
// Remove EXPOSE lines from Sizzle
.replace( /\/\/\s*EXPOSE[\w\W]*\/\/\s*EXPOSE/, "return Sizzle;" );
} else {
// Ignore jQuery's return statement (the only necessary one)
if ( name !== "jquery" ) {
contents = contents
.replace( /return\s+[^\}]+(\}\);[^\w\}]*)$/, "$1" );
}
// Remove define wrappers, closure ends, and empty declarations
contents = contents
.replace( /define\([^{]*?{/, "" )
.replace( rdefineEnd, "" )
// Remove empty definitions
.replace( /define\(\[[^\]]+\]\)[\W\n]+$/, "" );
}
return contents;
}
grunt.registerMultiTask(
"build",
"Concatenate source, remove sub AMD definitions, (include/exclude modules with +/- flags), embed date/version",
function() {
var flag,
done = this.async(),
flags = this.flags,
name = this.data.dest,
minimum = this.data.minimum,
removeWith = this.data.removeWith,
excluded = [],
included = [],
version = grunt.config( "pkg.version" ),
/**
* Recursively calls the excluder to remove on all modules in the list
* @param {Array} list
* @param {String} [prepend] Prepend this to the module name. Indicates we're walking a directory
*/
excludeList = function( list, prepend ) {
if ( list ) {
prepend = prepend ? prepend + "/" : "";
list.forEach(function( module ) {
// Exclude var modules as well
if ( module === "var" ) {
excludeList( fs.readdirSync( srcFolder + prepend + module ), prepend + module );
return;
}
if ( prepend ) {
// Skip if this is not a js file and we're walking files in a dir
if ( !(module = /([\w-\/]+)\.js$/.exec( module )) ) {
return;
}
// Prepend folder name if passed
// Remove .js extension
module = prepend + module[1];
}
// Avoid infinite recursion
if ( excluded.indexOf( module ) === -1 ) {
excluder( "-" + module );
}
});
}
},
/**
* Adds the specified module to the excluded or included list, depending on the flag
* @param {String} flag A module path relative to the src directory starting with + or - to indicate whether it should included or excluded
*/
excluder = function( flag ) {
var m = /^(\+|\-|)([\w\/-]+)$/.exec( flag ),
exclude = m[1] === "-",
module = m[2];
if ( exclude ) {
// Can't exclude certain modules
if ( minimum.indexOf( module ) === -1 ) {
// Add to excluded
if ( excluded.indexOf( module ) === -1 ) {
grunt.log.writeln( flag );
excluded.push( module );
// Exclude all files in the folder of the same name
// These are the removable dependencies
// It's fine if the directory is not there
try {
excludeList( fs.readdirSync( srcFolder + module ), module );
} catch( e ) {
grunt.verbose.writeln( e );
}
}
// Check removeWith list
excludeList( removeWith[ module ] );
} else {
grunt.log.error( "Module \"" + module + "\" is a mimimum requirement.");
}
} else {
grunt.log.writeln( flag );
included.push( module );
}
};
// append commit id to version
if ( process.env.COMMIT ) {
version += " " + process.env.COMMIT;
}
// figure out which files to exclude based on these rules in this order:
// dependency explicit exclude
// > explicit exclude
// > explicit include
// > dependency implicit exclude
// > implicit exclude
// examples:
// * none (implicit exclude)
// *:* all (implicit include)
// *:*:-css all except css and dependents (explicit > implicit)
// *:*:-css:+effects same (excludes effects because explicit include is trumped by explicit exclude of dependency)
// *:+effects none except effects and its dependencies (explicit include trumps implicit exclude of dependency)
for ( flag in flags ) {
if ( flag !== "*" ) {
excluder( flag );
}
}
grunt.verbose.writeflags( excluded, "Excluded" );
grunt.verbose.writeflags( included, "Included" );
// append excluded modules to version
if ( excluded.length ) {
version += " -" + excluded.join( ",-" );
// set pkg.version to version with excludes, so minified file picks it up
grunt.config.set( "pkg.version", version );
grunt.verbose.writeln( "Version changed to " + version );
// Have to use shallow or core will get excluded since it is a dependency
config.excludeShallow = excluded;
}
config.include = included;
/**
* Handle Final output from the optimizer
* @param {String} compiled
*/
config.out = function( compiled ) {
compiled = compiled
// Embed Version
.replace( /@VERSION/g, version )
// Embed Date
// yyyy-mm-ddThh:mmZ
.replace( /@DATE/g, ( new Date() ).toISOString().replace( /:\d+\.\d+Z$/, "Z" ) );
// Write concatenated source to file
grunt.file.write( name, compiled );
};
// Trace dependencies and concatenate files
requirejs.optimize( config, function( response ) {
grunt.verbose.writeln( response );
grunt.log.ok( "File '" + name + "' created." );
done();
}, function( err ) {
done( err );
});
});
// Special "alias" task to make custom build creation less grawlix-y
// Translation example
//
// grunt custom:+ajax,-dimensions,-effects,-offset
//
// Becomes:
//
// grunt build:*:*:+ajax:-dimensions:-effects:-offset
grunt.registerTask( "custom", function() {
var args = [].slice.call(arguments),
modules = args.length ? args[0].replace(/,/g, ":") : "";
grunt.log.writeln( "Creating custom build...\n" );
grunt.task.run([ "build:*:*:" + modules, "pre-uglify", "uglify", "dist" ]);
});
};

25762
build/r.js Normal file

File diff suppressed because one or more lines are too long

View File

@ -12,6 +12,11 @@
"type": "git",
"url": "https://github.com/jquery/jquery.git"
},
"keywords": [
"jquery",
"javascript",
"library"
],
"bugs": {
"url": "http://bugs.jquery.com"
},
@ -32,12 +37,10 @@
"gzip-js": "0.3.2",
"testswarm": "~1.1.0",
"archiver": "~0.4.6",
"grunt-jsonlint": "~1.0.0"
"grunt-jsonlint": "~1.0.0",
"requirejs": "~2.1.8"
},
"scripts": {
"install": "bower install"
},
"keywords": []
}
}

View File

@ -1,10 +1,16 @@
define([
"./core",
"./var/rnotwhite",
"./ajax/var/nonce",
"./ajax/var/rquery",
"./deferred"
], function( jQuery, rnotwhite, nonce, rquery ) {
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
@ -14,9 +20,6 @@ var
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:
@ -66,7 +69,7 @@ function addToPrefiltersOrTransports( structure ) {
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
@ -129,62 +132,6 @@ function ajaxExtend( target, src ) {
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( 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 ){
@ -419,7 +366,7 @@ jQuery.extend({
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
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 ) {
@ -467,7 +414,7 @@ jQuery.extend({
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + 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;
}
@ -477,10 +424,10 @@ jQuery.extend({
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
@ -853,3 +800,6 @@ function ajaxConvert( s, response, jqXHR, isSuccess ) {
return { state: "success", data: response };
}
return jQuery;
});

View File

@ -1,3 +1,10 @@
define([
"../core",
"./var/nonce",
"./var/rquery",
"../ajax"
], function( jQuery, nonce, rquery ) {
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
@ -5,7 +12,7 @@ var oldCallbacks = [],
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
@ -32,7 +39,7 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
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;
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
@ -78,3 +85,5 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
return "script";
}
});
});

71
src/ajax/load.js Normal file
View File

@ -0,0 +1,71 @@
define([
"../core",
"../ajax",
"../traversing",
"../selector"
], function( jQuery ) {
// 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, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( 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;
};
});

View File

@ -1,3 +1,8 @@
define([
"../core",
"../ajax"
], function( jQuery ) {
// Install script dataType
jQuery.ajaxSetup({
accepts: {
@ -84,3 +89,5 @@ jQuery.ajaxTransport( "script", function(s) {
};
}
});
});

5
src/ajax/var/nonce.js Normal file
View File

@ -0,0 +1,5 @@
define([
"../../core"
], function( jQuery ) {
return jQuery.now();
});

3
src/ajax/var/rquery.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return /\?/;
});

View File

@ -1,3 +1,8 @@
define([
"../core",
"../ajax"
], function( jQuery ) {
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
@ -205,3 +210,5 @@ if ( xhrSupported ) {
}
});
}
});

View File

@ -1,659 +1,6 @@
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
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( core_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 === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
define([
"./attributes/attr",
"./attributes/prop",
"./attributes/classes",
"./attributes/val"
]);

266
src/attributes/attr.js Normal file
View File

@ -0,0 +1,266 @@
define([
"../core",
"../var/rnotwhite",
"../var/strundefined",
"../selector"
], function( jQuery, rnotwhite, strundefined ) {
var nodeHook, boolHook,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
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
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// Some attributes are constructed with empty-string values when not defined
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
});

147
src/attributes/classes.js Normal file
View File

@ -0,0 +1,147 @@
define([
"../core",
"../var/rnotwhite",
"../var/strundefined"
], function( jQuery, rnotwhite, strundefined ) {
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
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( 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( 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;
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
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
});

132
src/attributes/prop.js Normal file
View File

@ -0,0 +1,132 @@
define([
"../core"
], function( jQuery ) {
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
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 ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
});

158
src/attributes/val.js Normal file
View File

@ -0,0 +1,158 @@
define([
"../core"
], function( jQuery ) {
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: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// 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;
};
}
});
});

View File

@ -1,10 +1,15 @@
define([
"./core",
"./var/rnotwhite"
], function( jQuery, rnotwhite ) {
// 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 ) {
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
@ -195,3 +200,5 @@ jQuery.Callbacks = function( options ) {
return self;
};
});

View File

@ -1,18 +1,24 @@
var
// The deferred used on DOM ready
readyList,
define([
"./var/strundefined",
"./var/deletedIds",
"./var/slice",
"./var/concat",
"./var/push",
"./var/indexOf",
// [[Class]] -> type pairs
"./var/class2type",
"./var/toString",
"./var/hasOwn",
"./var/trim"
], function( strundefined, deletedIds, slice, concat, push, indexOf,
class2type, toString, hasOwn, trim ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
@ -20,22 +26,7 @@ var
// 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 = "@VERSION",
// 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,
version = "@VERSION",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
@ -43,12 +34,6 @@ var
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
@ -73,34 +58,14 @@ var
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
jquery: version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
@ -191,7 +156,10 @@ jQuery.fn = jQuery.prototype = {
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
@ -209,7 +177,7 @@ jQuery.fn = jQuery.prototype = {
length: 0,
toArray: function() {
return core_slice.call( this );
return slice.call( this );
},
// Get the Nth element in the matched element set OR
@ -246,15 +214,8 @@ jQuery.fn = jQuery.prototype = {
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 ) );
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
@ -283,9 +244,9 @@ jQuery.fn = jQuery.prototype = {
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
// Give the init function the jQuery prototype for later instantiation
@ -357,8 +318,10 @@ jQuery.extend = jQuery.fn.extend = function() {
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
@ -372,52 +335,6 @@ jQuery.extend({
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
@ -443,7 +360,7 @@ jQuery.extend({
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
@ -460,8 +377,8 @@ jQuery.extend({
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
@ -473,7 +390,7 @@ jQuery.extend({
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
return hasOwn.call( obj, key );
}
}
@ -481,7 +398,7 @@ jQuery.extend({
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
@ -499,6 +416,7 @@ jQuery.extend({
// 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
// TODO: Circular reference core -> manipulation -> core
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
@ -656,11 +574,11 @@ jQuery.extend({
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
trim: trim && !trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
trim.call( text );
} :
// Otherwise use our own trimming functionality
@ -681,7 +599,7 @@ jQuery.extend({
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
push.call( ret, arr );
}
}
@ -692,8 +610,8 @@ jQuery.extend({
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
@ -779,7 +697,7 @@ jQuery.extend({
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
return concat.apply( [], ret );
},
// A global GUID counter for objects
@ -803,9 +721,9 @@ jQuery.extend({
}
// Simulated bind
args = core_slice.call( arguments, 2 );
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
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
@ -869,93 +787,9 @@ jQuery.extend({
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
@ -979,4 +813,7 @@ function isArraylike( obj ) {
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
rootjQuery = jQuery( document );
return jQuery;
});

151
src/core/ready.js Normal file
View File

@ -0,0 +1,151 @@
define([
"../core",
"../deferred"
], function( jQuery ) {
// 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;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
});

29
src/core/swap.js Normal file
View File

@ -0,0 +1,29 @@
define([
"../core"
], function( jQuery ) {
// 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.
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;
};
return jQuery.swap;
});

View File

@ -1,4 +1,14 @@
var iframe, getStyles, curCSS,
define([
"./core",
"./var/pnum",
"./css/var/cssExpand",
"./css/var/isHidden",
"./css/defaultDisplay",
"./core/swap",
"./selector" // contains
], function( jQuery, pnum, cssExpand, isHidden, defaultDisplay ) {
var getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
@ -6,10 +16,9 @@ var iframe, getStyles, curCSS,
// 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" },
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
@ -17,7 +26,6 @@ var iframe, getStyles, curCSS,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
@ -43,13 +51,6 @@ function vendorPropName( style, name ) {
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
@ -75,7 +76,7 @@ function showHide( elements, show ) {
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
@ -469,46 +470,6 @@ function getWidthOrHeight( elem, name, extra ) {
) + "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 ) {
@ -601,6 +562,7 @@ jQuery(function() {
// 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
// TODO: Optional dependency on offset
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
@ -616,21 +578,8 @@ jQuery(function() {
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
@ -659,3 +608,5 @@ jQuery.each({
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
});

57
src/css/defaultDisplay.js Normal file
View File

@ -0,0 +1,57 @@
define([
"../core",
"../manipulation" // appendTo
], function( jQuery ) {
var iframe,
elemdisplay = { BODY: "block" };
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
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'/>")
.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;
}
return defaultDisplay;
});

View File

@ -0,0 +1,18 @@
define([
"../core",
"../selector",
"../css"
], function( jQuery ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
});

3
src/css/var/cssExpand.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return [ "Top", "Right", "Bottom", "Left" ];
});

13
src/css/var/isHidden.js Normal file
View File

@ -0,0 +1,13 @@
define([
"../../core",
"../../selector"
// css is assumed
], function( jQuery ) {
return 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 );
};
});

View File

@ -1,6 +1,61 @@
define([
"./core",
"./var/deletedIds",
"./data/accepts"
], function( jQuery, deletedIds ) {
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
@ -31,7 +86,7 @@ function internalData( elem, name, data, pvt /* Internal Use Only */ ){
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
@ -212,19 +267,6 @@ jQuery.extend({
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
@ -287,50 +329,4 @@ jQuery.fn.extend({
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
});

21
src/data/accepts.js Normal file
View File

@ -0,0 +1,21 @@
define([
"../core"
], function( jQuery ) {
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
};
return jQuery.acceptData;
});

View File

@ -1,3 +1,9 @@
define([
"./core",
"./var/slice",
"./callbacks"
], function( jQuery, slice ) {
jQuery.extend({
Deferred: function( func ) {
@ -89,7 +95,7 @@ jQuery.extend({
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
@ -102,7 +108,7 @@ jQuery.extend({
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
@ -138,3 +144,4 @@ jQuery.extend({
return deferred.promise();
}
});
});

View File

@ -1,11 +1,11 @@
// Limit scope pollution from any deprecated API
// (function() {
define([
"./core",
"./traversing"
], function( jQuery ) {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
});

View File

@ -1,3 +1,7 @@
define([
"./core",
"./css"
], function( jQuery ) {
// 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 ) {
@ -39,3 +43,4 @@ jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
};
});
});
});

130
src/effects.js vendored
View File

@ -1,6 +1,18 @@
define([
"./core",
"./var/pnum",
"./css/var/cssExpand",
"./css/var/isHidden",
"./effects/Tween",
"./queue",
"./css",
"./deferred",
"./traversing"
], function( jQuery, pnum, cssExpand, isHidden, Tween ) {
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
@ -297,7 +309,7 @@ function defaultPrefilter( elem, props, opts ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
@ -372,100 +384,6 @@ function defaultPrefilter( elem, props, opts ) {
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
@ -662,17 +580,7 @@ jQuery.speed = function( speed, easing, fn ) {
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
@ -720,13 +628,5 @@ jQuery.fx.speeds = {
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
});

114
src/effects/Tween.js Normal file
View File

@ -0,0 +1,114 @@
define([
"../core",
"../css"
], function( jQuery ) {
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
});

View File

@ -0,0 +1,11 @@
define([
"../core",
"../selector",
"../effects",
], function( jQuery ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
});

View File

@ -1,3 +1,14 @@
define([
"./core",
"./var/strundefined",
"./var/rnotwhite",
"./var/hasOwn",
"./var/slice",
"./data/accepts",
"./selector",
"./support"
], function( jQuery, strundefined, rnotwhite, hasOwn, slice ) {
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
@ -57,7 +68,7 @@ jQuery.event = {
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) ?
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
@ -66,7 +77,7 @@ jQuery.event = {
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
types = ( types || "" ).match( rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
@ -152,7 +163,7 @@ jQuery.event = {
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
types = ( types || "" ).match( rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
@ -217,8 +228,8 @@ jQuery.event = {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
@ -355,7 +366,7 @@ jQuery.event = {
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
@ -645,7 +656,7 @@ jQuery.removeEvent = document.removeEventListener ?
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
@ -993,3 +1004,5 @@ jQuery.fn.extend({
}
}
});
});

View File

@ -1,3 +1,8 @@
define([
"../core",
"../event"
], function( jQuery ) {
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 ) {
@ -30,3 +35,5 @@ jQuery.fn.extend({
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
});

12
src/exports/amd.js Normal file
View File

@ -0,0 +1,12 @@
// 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;
});
}

View File

@ -27,21 +27,7 @@
return factory( w );
};
} else {
// Execute the factory to produce jQuery
var jQuery = factory( window );
// 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;
});
}
factory( window );
}
// Pass this, window may not be defined yet

38
src/jquery.js vendored Normal file
View File

@ -0,0 +1,38 @@
define([
"./core",
"./selector",
"./callbacks",
"./deferred",
"./core/ready",
"./traversing",
"./data",
"./queue",
"./queue/delay",
"./attributes",
"./event",
"./event/alias",
"./manipulation",
"./manipulation/_evalUrl",
"./wrap",
"./css",
"./css/hidden-visible-selectors",
"./serialize",
"./ajax",
"./ajax/xhr",
"./ajax/script",
"./ajax/jsonp",
"./ajax/load",
"./effects",
"./effects/animated-selector",
"./offset",
"./dimensions",
"./support",
"./deprecated"
], function( jQuery ) {
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
return (window.jQuery = window.$ = jQuery);
});

View File

@ -1,3 +1,15 @@
define([
"./core",
"./var/concat",
"./var/push",
"./var/deletedIds",
"./manipulation/var/rcheckableType",
"./data/accepts",
"./selector",
"./traversing",
"./event"
], function( jQuery, concat, push, deletedIds, rcheckableType ){
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
@ -22,7 +34,6 @@ var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figca
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
@ -94,8 +105,7 @@ jQuery.fn.extend({
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
@ -228,7 +238,7 @@ jQuery.fn.extend({
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
@ -292,8 +302,10 @@ jQuery.fn.extend({
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
@ -415,7 +427,7 @@ function fixCloneNodeIssues( src, dest ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
@ -459,7 +471,7 @@ jQuery.each({
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
@ -469,8 +481,8 @@ jQuery.each({
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
@ -490,7 +502,7 @@ function getAll( context, tag ) {
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
@ -687,7 +699,6 @@ jQuery.extend({
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
@ -717,28 +728,20 @@ jQuery.extend({
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
});

View File

@ -0,0 +1,16 @@
define([
"../ajax"
], function( jQuery ) {
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
return jQuery._evalUrl;
});

View File

@ -0,0 +1,3 @@
define(function() {
return /^(?:checkbox|radio)$/i;
});

View File

@ -1,3 +1,12 @@
define([
"./core",
"./var/strundefined",
"./css",
"./selector"
], function( jQuery, strundefined ) {
var docElem = window.document.documentElement;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
@ -25,7 +34,7 @@ jQuery.fn.offset = function( options ) {
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
@ -132,6 +141,16 @@ jQuery.fn.extend({
}
});
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
@ -160,10 +179,4 @@ jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( me
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
});

View File

@ -1,6 +1 @@
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
return (window.jQuery = window.$ = jQuery);
}));
}));

View File

@ -1,3 +1,9 @@
define([
"./core",
"./deferred",
"./callbacks"
], function( jQuery ) {
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
@ -97,19 +103,6 @@ jQuery.fn.extend({
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", [] );
},
@ -144,3 +137,5 @@ jQuery.fn.extend({
return defer.promise( obj );
}
});
});

22
src/queue/delay.js Normal file
View File

@ -0,0 +1,22 @@
define([
"../core",
"../queue",
"../effects" // Delay is optional because of this dependency
], function( jQuery ) {
// 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 );
};
});
};
return jQuery.fn.delay;
});

View File

@ -1,3 +1,8 @@
define([
"./core",
"../bower_components/sizzle/dist/sizzle"
], function ( jQuery, Sizzle ) {
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
@ -5,3 +10,5 @@ jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
});

1
src/selector.js Normal file
View File

@ -0,0 +1 @@
define([ "./selector-sizzle" ]);

View File

@ -1,3 +1,10 @@
define([
"./core",
"./manipulation/var/rcheckableType",
"./traversing", // filter
"./attributes/prop"
], function( jQuery, rcheckableType ) {
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
@ -19,7 +26,7 @@ jQuery.fn.extend({
// 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 ) );
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
@ -35,8 +42,8 @@ jQuery.fn.extend({
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
@ -97,3 +104,4 @@ function buildParams( prefix, obj, traditional, add ) {
add( prefix, obj );
}
}
});

View File

@ -1,3 +1,9 @@
define([
"./core",
"./var/strundefined",
"./core/swap"
], function( jQuery, strundefined ) {
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
@ -208,7 +214,7 @@ jQuery.support = (function( support ) {
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
@ -244,3 +250,4 @@ jQuery.support = (function( support ) {
return support;
})({});
});

View File

@ -1,3 +1,8 @@
define([
"./core",
"./var/indexOf",
"./selector"
], function( jQuery, indexOf ) {
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
@ -281,3 +286,4 @@ function winnow( elements, qualifier, not ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
});

3
src/var/class2type.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return {};
});

5
src/var/concat.js Normal file
View File

@ -0,0 +1,5 @@
define([
"./deletedIds"
], function( deletedIds ) {
return deletedIds.concat;
});

3
src/var/deletedIds.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return [];
});

5
src/var/hasOwn.js Normal file
View File

@ -0,0 +1,5 @@
define([
"./class2type"
], function( class2type ) {
return class2type.hasOwnProperty;
});

5
src/var/indexOf.js Normal file
View File

@ -0,0 +1,5 @@
define([
"./deletedIds"
], function( deletedIds ) {
return deletedIds.indexOf;
});

3
src/var/pnum.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;
});

5
src/var/push.js Normal file
View File

@ -0,0 +1,5 @@
define([
"./deletedIds"
], function( deletedIds ) {
return deletedIds.push;
});

3
src/var/rnotwhite.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return /\S+/g;
});

5
src/var/slice.js Normal file
View File

@ -0,0 +1,5 @@
define([
"./deletedIds"
], function( deletedIds ) {
return deletedIds.slice;
});

3
src/var/strundefined.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return typeof undefined;
});

5
src/var/toString.js Normal file
View File

@ -0,0 +1,5 @@
define([
"./class2type"
], function( class2type ) {
return class2type.toString;
});

3
src/var/trim.js Normal file
View File

@ -0,0 +1,3 @@
define(function() {
return "".trim;
});

View File

@ -1,3 +1,7 @@
define([
"./core",
"./traversing" // parent, contents
], function( jQuery ) {
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
@ -64,3 +68,4 @@ jQuery.fn.extend({
}).end();
}
});
});

View File

@ -1,6 +1,6 @@
/*jshint multistr:true, quotmark:false */
var amdDefined, fireNative,
var fireNative,
originaljQuery = this.jQuery || "jQuery",
original$ = this.$ || "$",
// see RFC 2606
@ -13,15 +13,6 @@ this.isLocal = window.location.protocol === "file:";
this.jQuery = originaljQuery;
this.$ = original$;
/**
* Set up a mock AMD define function for testing AMD registration.
*/
function define( name, dependencies, callback ) {
amdDefined = callback();
}
define.amd = {};
/**
* Returns an array of elements with the given IDs
* @example q("main", "foo", "bar")

View File

@ -242,11 +242,11 @@ this.Globals = (function() {
}
}
};
QUnit.config.urlConfig.push( {
QUnit.config.urlConfig.push({
id: "jqdata",
label: "Always check jQuery.data",
tooltip: "Trigger QUnit.expectJqData detection for all tests instead of just the ones that call it"
} );
});
/**
* Ensures that tests have cleaned up properly after themselves. Should be passed as the

View File

@ -14,63 +14,33 @@
<script src="data/testinit.js"></script>
<script src="../bower_components/qunit/qunit/qunit.js"></script>
<script>
(function() {
var src = "../dist/jquery.min.js";
// Config parameter to use minified jQuery
QUnit.config.urlConfig.push({
id: "dev",
label: "Load unminified",
tooltip: "Load the development (unminified) jQuery file"
});
if ( QUnit.urlParams.dev ) {
src = "../dist/jquery.js";
}
// Config parameter to force basic code paths
QUnit.config.urlConfig.push({
id: "basic",
label: "Bypass optimizations",
tooltip: "Force use of the most basic code by disabling native querySelectorAll; contains; compareDocumentPosition"
});
if ( QUnit.urlParams.basic ) {
document.querySelectorAll = null;
document.documentElement.contains = null;
document.documentElement.compareDocumentPosition = null;
}
// Load jQuery
document.write( "<script id='jquery-js' src='" + src + "'><\x2Fscript>" );
})();
</script>
<script src="data/testrunner.js"></script>
<script src="unit/core.js"></script>
<script src="unit/callbacks.js"></script>
<script src="unit/deferred.js"></script>
<script src="unit/support.js"></script>
<script src="unit/data.js"></script>
<script src="unit/queue.js"></script>
<script src="unit/attributes.js"></script>
<script src="unit/event.js"></script>
<script src="unit/selector.js"></script>
<script src="unit/traversing.js"></script>
<script src="unit/manipulation.js"></script>
<script src="unit/wrap.js"></script>
<script src="unit/css.js"></script>
<script src="unit/serialize.js"></script>
<script src="unit/ajax.js"></script>
<script src="unit/effects.js"></script>
<script src="unit/offset.js"></script>
<script src="unit/dimensions.js"></script>
<script src="unit/deprecated.js"></script>
<script src="unit/exports.js"></script>
<!-- Subproject tests must be last because they replace our test fixture -->
<script>
testSubproject( "Sizzle", "../bower_components/sizzle/test/", /^unit\/.*\.js$/ );
</script>
<script src="../bower_components/requirejs/require.js"></script>
<script>loadTests = [
"data/testrunner.js",
"unit/core.js",
"unit/callbacks.js",
"unit/deferred.js",
"unit/support.js",
"unit/data.js",
"unit/queue.js",
"unit/attributes.js",
"unit/event.js",
"unit/selector.js",
"unit/traversing.js",
"unit/manipulation.js",
"unit/wrap.js",
"unit/css.js",
"unit/serialize.js",
"unit/ajax.js",
"unit/effects.js",
"unit/offset.js",
"unit/dimensions.js"
];</script>
<!-- A script that includes jQuery min, dev, or AMD -->
<!-- Adds "basic" URL option, even to iframes -->
<!-- iframes will not load AMD as loading needs to be synchronous for some tests -->
<!-- Also loads the tests above synchronously with min or dev and async with AMD -->
<script src="jquery.js"></script>
<script>
// html5shiv, enabling HTML5 elements to be used with jQuery

82
test/jquery.js vendored
View File

@ -1,5 +1,77 @@
// Use the right jQuery source in iframe tests
document.write( "<script id='jquery-js' src='" +
parent.document.getElementById("jquery-js").src.replace( /^(?![^\/?#]+:)/,
parent.location.pathname.replace( /[^\/]$/, "$0/" ) ) +
"'><\x2Fscript>" );
// Use the right jQuery source on the test page (and iframes)
(function() {
/* global loadTests: true, testSubproject: false */
/* jshint eqeqeq: false */
var i, len,
// Parent is the current window if not an iframe, which is fine
src = /^(.*)test\//.exec( parent.location.pathname )[1],
QUnit = QUnit || parent.QUnit,
require = require || parent.require;
// Config parameter to force basic code paths
QUnit.config.urlConfig.push({
id: "basic",
label: "Bypass optimizations",
tooltip: "Force use of the most basic code by disabling native querySelectorAll; contains; compareDocumentPosition"
});
if ( QUnit.urlParams.basic ) {
document.querySelectorAll = null;
document.documentElement.contains = null;
document.documentElement.compareDocumentPosition = null;
}
// iFrames won't load AMD (the iframe tests synchronously expect jQuery to be there)
QUnit.config.urlConfig.push({
id: "amd",
label: "Load with AMD",
tooltip: "Load the AMD jQuery file (and its dependencies)"
});
if ( QUnit.urlParams.amd && parent == window ) {
require.config({ baseUrl: src });
src = "src/jquery";
// Include tests if specified
if ( typeof loadTests !== "undefined" ) {
QUnit.config.autostart = false;
require( [ src ], function() {
// Ensure load order (to preserve test numbers)
(function loadDep() {
var dep = loadTests.shift();
if ( dep ) {
require( [ dep ], loadDep );
} else {
// Subproject tests must be last because they replace our test fixture
testSubproject( "Sizzle", "../bower_components/sizzle/test/", /^unit\/.*\.js$/ );
QUnit.start();
}
})();
});
} else {
require( [ src ] );
}
return;
}
// Config parameter to use minified jQuery
QUnit.config.urlConfig.push({
id: "dev",
label: "Load unminified",
tooltip: "Load the development (unminified) jQuery file"
});
if ( QUnit.urlParams.dev ) {
src += "dist/jquery.js";
} else {
src += "dist/jquery.min.js";
}
// Load jQuery
document.write( "<script id='jquery-js' src='" + src + "'><\x2Fscript>" );
// Load tests synchronously if available
if ( typeof loadTests !== "undefined" ) {
for ( i = 0, len = loadTests.length; i < len; i++ ) {
document.write( "<script src='" + loadTests.shift() + "'><\x2Fscript>" );
}
}
})();

View File

@ -17,13 +17,6 @@ test("Basic requirements", function() {
ok( $, "$" );
});
testIframeWithCallback( "Conditional compilation compatibility (#13274)", "core/cc_on.html", function( cc_on, errors, $ ) {
expect( 3 );
ok( true, "JScript conditional compilation " + ( cc_on ? "supported" : "not supported" ) );
deepEqual( errors, [], "No errors" );
ok( $(), "jQuery executes" );
});
test("jQuery()", function() {
var elem, i,
@ -1358,3 +1351,10 @@ test("jQuery.camelCase()", function() {
equal( jQuery.camelCase( key ), val, "Converts: " + key + " => " + val );
});
});
testIframeWithCallback( "Conditional compilation compatibility (#13274)", "core/cc_on.html", function( cc_on, errors, $ ) {
expect( 3 );
ok( true, "JScript conditional compilation " + ( cc_on ? "supported" : "not supported" ) );
deepEqual( errors, [], "No errors" );
ok( $(), "jQuery executes" );
});

View File

@ -6,7 +6,7 @@ test("expando", function(){
equal(jQuery.expando !== undefined, true, "jQuery is exposing the expando");
});
function dataTests (elem) {
function dataTests( elem ) {
var dataObj, internalDataObj;
equal( jQuery.data(elem, "foo"), undefined, "No data exists initially" );
@ -73,30 +73,30 @@ function dataTests (elem) {
test("jQuery.data(div)", 25, function() {
var div = document.createElement("div");
dataTests(div);
dataTests( div );
// We stored one key in the private data
// assert that nothing else was put in there, and that that
// one stayed there.
QUnit.expectJqData(div, "foo");
QUnit.expectJqData( div, "foo" );
});
test("jQuery.data({})", 25, function() {
dataTests({});
dataTests( {} );
});
test("jQuery.data(window)", 25, function() {
// remove bound handlers from window object to stop potential false positives caused by fix for #5280 in
// transports/xhr.js
jQuery(window).off("unload");
jQuery( window ).off( "unload" );
dataTests(window);
dataTests( window );
});
test("jQuery.data(document)", 25, function() {
dataTests(document);
dataTests( document );
QUnit.expectJqData(document, "foo");
QUnit.expectJqData( document, "foo" );
});
test("Expando cleanup", 4, function() {

View File

@ -12,13 +12,18 @@ test( "zoom of doom (#13089)", function() {
if ( jQuery.css ) {
testIframeWithCallback( "body background is not lost if set prior to loading jQuery (#9239)", "support/bodyBackground.html", function( color, support ) {
expect( 2 );
var okValue = {
"#000000": true,
"rgb(0, 0, 0)": true
};
var okValue = {
"#000000": true,
"rgb(0, 0, 0)": true
};
ok( okValue[ color ], "color was not reset (" + color + ")" );
deepEqual( jQuery.extend( {}, support ), jQuery.support, "Same support properties" );
stop();
// Run doc ready tests as well
jQuery(function() {
deepEqual( jQuery.extend( {}, support ), jQuery.support, "Same support properties" );
start();
});
});
}