From cb7d4df9fe433477a8bf4797403518f7d3e6db66 Mon Sep 17 00:00:00 2001
From: Jason Moon
Date: Tue, 27 Aug 2013 22:09:56 -0500
Subject: [PATCH 001/100] Wait to do the form DOM scans until absolutely
necessary
---
src/rails.js | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 84f9e6bc..2b1e9b4b 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -331,17 +331,21 @@
$document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) {
var form = $(this),
remote = form.data('remote') !== undefined,
- blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector),
- nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
+ blankRequiredInputs,
+ nonBlankFileInputs;
if (!rails.allowAction(form)) return rails.stopEverything(e);
// skip other logic when required values are missing or file upload is present
- if (blankRequiredInputs && form.attr("novalidate") == undefined && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
- return rails.stopEverything(e);
+ if (form.attr('novalidate') == undefined) {
+ blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector);
+ if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
+ return rails.stopEverything(e);
+ }
}
if (remote) {
+ nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
if (nonBlankFileInputs) {
// slight timeout so that the submit button gets properly serialized
// (make it easy for event handler to serialize form without disabled values)
From fbddf674f7f54d8e021c8a813e864088614c4a53 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Mon, 27 Jan 2014 15:28:16 -0200
Subject: [PATCH 002/100] Reorganize test suite custom CSS
The versions and CDN links won't be totally mangled by the QUnit
header now.
---
test/views/layout.erb | 15 +++++++++++----
1 file changed, 11 insertions(+), 4 deletions(-)
diff --git a/test/views/layout.erb b/test/views/layout.erb
index fe2c5483..eb791b6a 100644
--- a/test/views/layout.erb
+++ b/test/views/layout.erb
@@ -5,11 +5,18 @@
<%= script_tag jquery_src %>
From 1c84b339d3da8157c4ba43def0923cefa592e341 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Fri, 1 Nov 2013 18:35:15 -0200
Subject: [PATCH 003/100] Add support for the `data-disable` attribute.
This gives the same behavior as the `data-disable-with` attribute,
but instead of using a replacement String from the `data-disable-with`
attribute the disabled state will use the origin text/value of the element.
---
src/rails.js | 23 ++-
test/public/test/data-disable-with.js | 248 ++++++++++++++++++++++++++
test/public/test/data-disable.js | 136 ++++++--------
test/public/test/settings.js | 18 ++
test/views/index.erb | 2 +-
5 files changed, 340 insertions(+), 87 deletions(-)
create mode 100644 test/public/test/data-disable-with.js
diff --git a/src/rails.js b/src/rails.js
index 309d74d6..0c4fa64e 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -22,7 +22,7 @@
$.rails = rails = {
// Link elements bound by jquery-ujs
- linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]',
+ linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with], a[data-disable]',
// Button elements bound by jquery-ujs
buttonClickSelector: 'button[data-remote]',
@@ -37,10 +37,10 @@
formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])',
// Form input elements disabled during form submission
- disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]',
+ disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with], input[data-disable], button[data-disable], textarea[data-disable]',
// Form input elements re-enabled after form submission
- enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled',
+ enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',
// Form required input elements
requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])',
@@ -49,7 +49,7 @@
fileInputSelector: 'input[type=file]',
// Link onClick disable selector with possible reenable after remote submission
- linkDisableSelector: 'a[data-disable-with]',
+ linkDisableSelector: 'a[data-disable-with], a[data-disable]',
// Make sure that every Ajax request sends the CSRF token
CSRFProtection: function(xhr) {
@@ -190,9 +190,13 @@
*/
disableFormElements: function(form) {
form.find(rails.disableSelector).each(function() {
- var element = $(this), method = element.is('button') ? 'html' : 'val';
- element.data('ujs:enable-with', element[method]());
- element[method](element.data('disable-with'));
+ var element, method, enabledState;
+ element = $(this);
+ method = element.is('button') ? 'html' : 'val';
+ enabledState = element[method]();
+
+ element.data('ujs:enable-with', enabledState);
+ element[method](element.data('disable-with') || enabledState);
element.prop('disabled', true);
});
},
@@ -269,8 +273,9 @@
// replace element's html with the 'data-disable-with' after storing original html
// and prevent clicking on it
disableElement: function(element) {
- element.data('ujs:enable-with', element.html()); // store enabled state
- element.html(element.data('disable-with')); // set to disabled state
+ var enabledState = element.html();
+ element.data('ujs:enable-with', enabledState); // store enabled state
+ element.html(element.data('disable-with') || enabledState); // set to disabled state
element.bind('click.railsDisable', function(e) { // prevent further clicking
return rails.stopEverything(e);
});
diff --git a/test/public/test/data-disable-with.js b/test/public/test/data-disable-with.js
new file mode 100644
index 00000000..80a183af
--- /dev/null
+++ b/test/public/test/data-disable-with.js
@@ -0,0 +1,248 @@
+module('data-disable-with', {
+ setup: function() {
+ $('#qunit-fixture').append($('', {
+ action: '/echo',
+ 'data-remote': 'true',
+ method: 'post'
+ }))
+ .find('form')
+ .append($(''));
+
+ $('#qunit-fixture').append($('', {
+ action: '/echo',
+ method: 'post'
+ }))
+ .find('form:last')
+ // WEEIRDD: the form won't submit to an iframe if the button is name="submit" (??!)
+ .append($(''));
+
+ $('#qunit-fixture').append($('', {
+ text: 'Click me',
+ href: '/echo',
+ 'data-disable-with': 'clicking...'
+ }));
+ },
+ teardown: function() {
+ $(document).unbind('iframe:loaded');
+ }
+});
+
+
+asyncTest('form input field with "data-disable-with" attribute', 7, function() {
+ var form = $('form[data-remote]'), input = form.find('input[type=text]');
+
+ App.checkEnabledState(input, 'john');
+
+ form.bind('ajax:success', function(e, data) {
+ setTimeout(function() {
+ App.checkEnabledState(input, 'john');
+ equal(data.params.user_name, 'john');
+ start();
+ }, 13)
+ })
+ form.trigger('submit');
+
+ App.checkDisabledState(input, 'processing ...');
+});
+
+asyncTest('form button with "data-disable-with" attribute', 6, function() {
+ var form = $('form[data-remote]'), button = $('');
+ form.append(button);
+
+ App.checkEnabledState(button, 'Submit');
+
+ form.bind('ajax:success', function(e, data) {
+ setTimeout(function() {
+ App.checkEnabledState(button, 'Submit');
+ start();
+ }, 13)
+ })
+ form.trigger('submit');
+
+ App.checkDisabledState(button, 'submitting ...');
+});
+
+asyncTest('form input[type=submit][data-disable-with] disables', 6, function(){
+ var form = $('form:not([data-remote])'), input = form.find('input[type=submit]');
+
+ App.checkEnabledState(input, 'Submit');
+
+ // WEEIRDD: attaching this handler makes the test work in IE7
+ $(document).bind('iframe:loading', function(e, form) {});
+
+ $(document).bind('iframe:loaded', function(e, data) {
+ setTimeout(function() {
+ App.checkDisabledState(input, 'submitting ...');
+ start();
+ }, 30);
+ });
+ form.trigger('submit');
+
+ setTimeout(function() {
+ App.checkDisabledState(input, 'submitting ...');
+ }, 30);
+});
+
+asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced in ajax callback', 2, function(){
+ var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html();
+
+ form.bind('ajax:success', function(){
+ form.html(origFormContents);
+
+ setTimeout(function(){
+ var input = form.find('input[type=submit]');
+ App.checkEnabledState(input, 'Submit');
+ start();
+ }, 30);
+ }).trigger('submit');
+});
+
+asyncTest('form[data-remote] input[data-disable-with] is replaced with disabled field in ajax callback', 2, function(){
+ var form = $('form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'),
+ newDisabledInput = input.clone().attr('disabled', 'disabled');
+
+ form.bind('ajax:success', function(){
+ input.replaceWith(newDisabledInput);
+
+ setTimeout(function(){
+ App.checkEnabledState(newDisabledInput, 'Submit');
+ start();
+ }, 30);
+ }).trigger('submit');
+});
+
+asyncTest('form[data-remote] textarea[data-disable-with] attribute', 3, function() {
+ var form = $('form[data-remote]'),
+ textarea = $('').appendTo(form);
+
+ form.bind('ajax:success', function(e, data) {
+ setTimeout(function() {
+ equal(data.params.user_bio, 'born, lived, died.');
+ start();
+ }, 13)
+ })
+ form.trigger('submit');
+
+ App.checkDisabledState(textarea, 'processing ...');
+});
+
+asyncTest('a[data-disable-with] disables', 4, function() {
+ var link = $('a[data-disable-with]');
+
+ App.checkEnabledState(link, 'Click me');
+
+ link.trigger('click');
+ App.checkDisabledState(link, 'clicking...');
+ start();
+});
+
+asyncTest('a[data-remote][data-disable-with] disables and re-enables', 6, function() {
+ var link = $('a[data-disable-with]').attr('data-remote', true);
+
+ App.checkEnabledState(link, 'Click me');
+
+ link
+ .bind('ajax:beforeSend', function() {
+ App.checkDisabledState(link, 'clicking...');
+ })
+ .bind('ajax:complete', function() {
+ setTimeout( function() {
+ App.checkEnabledState(link, 'Click me');
+ start();
+ }, 15);
+ })
+ .trigger('click');
+});
+
+asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:before` event is cancelled', 6, function() {
+ var link = $('a[data-disable-with]').attr('data-remote', true);
+
+ App.checkEnabledState(link, 'Click me');
+
+ link
+ .bind('ajax:before', function() {
+ App.checkDisabledState(link, 'clicking...');
+ return false;
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ App.checkEnabledState(link, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:beforeSend` event is cancelled', 6, function() {
+ var link = $('a[data-disable-with]').attr('data-remote', true);
+
+ App.checkEnabledState(link, 'Click me');
+
+ link
+ .bind('ajax:beforeSend', function() {
+ App.checkDisabledState(link, 'clicking...');
+ return false;
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ App.checkEnabledState(link, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:error` event is triggered', 6, function() {
+ var link = $('a[data-disable-with]').attr('data-remote', true).attr('href', '/error');
+
+ App.checkEnabledState(link, 'Click me');
+
+ link
+ .bind('ajax:beforeSend', function() {
+ App.checkDisabledState(link, 'clicking...');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ App.checkEnabledState(link, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('form[data-remote] input|button|textarea[data-disable-with] does not disable when `ajax:beforeSend` event is cancelled', 8, function() {
+ var form = $('form[data-remote]'),
+ input = form.find('input:text'),
+ button = $('').appendTo(form),
+ textarea = $('').appendTo(form),
+ submit = $('').appendTo(form);
+
+ form
+ .bind('ajax:beforeSend', function() {
+ return false;
+ })
+ .trigger('submit');
+
+ App.checkEnabledState(input, 'john');
+ App.checkEnabledState(button, 'Submit');
+ App.checkEnabledState(textarea, 'born, lived, died.');
+ App.checkEnabledState(submit, 'Submit');
+
+ start();
+
+});
+
+asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
+ var link = $('a[data-disable-with]'), e;
+ e = $.Event('click');
+ e.metaKey = true;
+
+ App.checkEnabledState(link, 'Click me');
+
+ link.trigger(e);
+ App.checkEnabledState(link, 'Click me');
+
+ e = $.Event('click');
+ e.ctrlKey = true;
+
+ link.trigger(e);
+ App.checkEnabledState(link, 'Click me');
+ start();
+});
diff --git a/test/public/test/data-disable.js b/test/public/test/data-disable.js
index ec858787..181e42a1 100644
--- a/test/public/test/data-disable.js
+++ b/test/public/test/data-disable.js
@@ -6,7 +6,7 @@ module('data-disable', {
method: 'post'
}))
.find('form')
- .append($(''));
+ .append($(''));
$('#qunit-fixture').append($('', {
action: '/echo',
@@ -14,12 +14,12 @@ module('data-disable', {
}))
.find('form:last')
// WEEIRDD: the form won't submit to an iframe if the button is name="submit" (??!)
- .append($(''));
+ .append($(''));
$('#qunit-fixture').append($('', {
text: 'Click me',
href: '/echo',
- 'data-disable-with': 'clicking...'
+ 'data-disable': 'true'
}));
},
teardown: function() {
@@ -27,80 +27,62 @@ module('data-disable', {
}
});
-function getVal(el) {
- return el.is('input,textarea,select') ? el.val() : el.text();
-}
-
-function disabled(el) {
- return el.is('input,textarea,select,button') ? el.is(':disabled') : el.data('ujs:enable-with');
-}
-
-function checkEnabledState(el, text) {
- ok(!disabled(el), el.get(0).tagName + ' should not be disabled');
- equal(getVal(el), text, el.get(0).tagName + ' text should be original value');
-}
-
-function checkDisabledState(el, text) {
- ok(disabled(el), el.get(0).tagName + ' should be disabled');
- equal(getVal(el), text, el.get(0).tagName + ' text should be disabled value');
-}
-
-asyncTest('form input field with "data-disable-with" attribute', 7, function() {
+asyncTest('form input field with "data-disable" attribute', 7, function() {
var form = $('form[data-remote]'), input = form.find('input[type=text]');
- checkEnabledState(input, 'john');
+ App.checkEnabledState(input, 'john');
form.bind('ajax:success', function(e, data) {
setTimeout(function() {
- checkEnabledState(input, 'john');
+ App.checkEnabledState(input, 'john');
equal(data.params.user_name, 'john');
start();
}, 13)
})
form.trigger('submit');
- checkDisabledState(input, 'processing ...');
+ App.checkDisabledState(input, 'john');
});
-asyncTest('form button with "data-disable-with" attribute', 6, function() {
- var form = $('form[data-remote]'), button = $('');
+asyncTest('form button with "data-disable" attribute', 6, function() {
+ var form = $('form[data-remote]'), button = $('');
form.append(button);
- checkEnabledState(button, 'Submit');
+ App.checkEnabledState(button, 'Submit');
form.bind('ajax:success', function(e, data) {
setTimeout(function() {
- checkEnabledState(button, 'Submit');
+ App.checkEnabledState(button, 'Submit');
start();
}, 13)
})
form.trigger('submit');
- checkDisabledState(button, 'submitting ...');
+ App.checkDisabledState(button, 'Submit');
});
-asyncTest('form input[type=submit][data-disable-with] disables', 6, function(){
+asyncTest('form input[type=submit][data-disable] disables', 6, function(){
var form = $('form:not([data-remote])'), input = form.find('input[type=submit]');
- checkEnabledState(input, 'Submit');
+ App.checkEnabledState(input, 'Submit');
// WEEIRDD: attaching this handler makes the test work in IE7
$(document).bind('iframe:loading', function(e, form) {});
$(document).bind('iframe:loaded', function(e, data) {
setTimeout(function() {
- checkDisabledState(input, 'submitting ...');
+ App.checkDisabledState(input, 'Submit');
start();
}, 30);
});
form.trigger('submit');
setTimeout(function() {
- checkDisabledState(input, 'submitting ...');
+ App.checkDisabledState(input, 'Submit');
}, 30);
});
-asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced in ajax callback', 2, function(){
+asyncTest('form[data-remote] input[type=submit][data-disable] is replaced in ajax callback', 2, function(){
var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html();
form.bind('ajax:success', function(){
@@ -108,13 +90,13 @@ asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced i
setTimeout(function(){
var input = form.find('input[type=submit]');
- checkEnabledState(input, 'Submit');
+ App.checkEnabledState(input, 'Submit');
start();
}, 30);
}).trigger('submit');
});
-asyncTest('form[data-remote] input[data-disable-with] is replaced with disabled field in ajax callback', 2, function(){
+asyncTest('form[data-remote] input[data-disable] is replaced with disabled field in ajax callback', 2, function(){
var form = $('form:not([data-remote])').attr('data-remote', 'true'), input = form.find('input[type=submit]'),
newDisabledInput = input.clone().attr('disabled', 'disabled');
@@ -122,15 +104,15 @@ asyncTest('form[data-remote] input[data-disable-with] is replaced with disabled
input.replaceWith(newDisabledInput);
setTimeout(function(){
- checkEnabledState(newDisabledInput, 'Submit');
+ App.checkEnabledState(newDisabledInput, 'Submit');
start();
}, 30);
}).trigger('submit');
});
-asyncTest('form[data-remote] textarea[data-disable-with] attribute', 3, function() {
+asyncTest('form[data-remote] textarea[data-disable] attribute', 3, function() {
var form = $('form[data-remote]'),
- textarea = $('').appendTo(form);
+ textarea = $('').appendTo(form);
form.bind('ajax:success', function(e, data) {
setTimeout(function() {
@@ -140,96 +122,96 @@ asyncTest('form[data-remote] textarea[data-disable-with] attribute', 3, function
})
form.trigger('submit');
- checkDisabledState(textarea, 'processing ...');
+ App.checkDisabledState(textarea, 'born, lived, died.');
});
-asyncTest('a[data-disable-with] disables', 4, function() {
- var link = $('a[data-disable-with]');
+asyncTest('a[data-disable] disables', 4, function() {
+ var link = $('a[data-disable]');
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
link.trigger('click');
- checkDisabledState(link, 'clicking...');
+ App.checkDisabledState(link, 'Click me');
start();
});
-asyncTest('a[data-remote][data-disable-with] disables and re-enables', 6, function() {
- var link = $('a[data-disable-with]').attr('data-remote', true);
+asyncTest('a[data-remote][data-disable] disables and re-enables', 6, function() {
+ var link = $('a[data-disable]').attr('data-remote', true);
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
link
.bind('ajax:beforeSend', function() {
- checkDisabledState(link, 'clicking...');
+ App.checkDisabledState(link, 'Click me');
})
.bind('ajax:complete', function() {
setTimeout( function() {
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
start();
}, 15);
})
.trigger('click');
});
-asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:before` event is cancelled', 6, function() {
- var link = $('a[data-disable-with]').attr('data-remote', true);
+asyncTest('a[data-remote][data-disable] re-enables when `ajax:before` event is cancelled', 6, function() {
+ var link = $('a[data-disable]').attr('data-remote', true);
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
link
.bind('ajax:before', function() {
- checkDisabledState(link, 'clicking...');
+ App.checkDisabledState(link, 'Click me');
return false;
})
.trigger('click');
setTimeout(function() {
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
start();
}, 30);
});
-asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:beforeSend` event is cancelled', 6, function() {
- var link = $('a[data-disable-with]').attr('data-remote', true);
+asyncTest('a[data-remote][data-disable] re-enables when `ajax:beforeSend` event is cancelled', 6, function() {
+ var link = $('a[data-disable]').attr('data-remote', true);
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
link
.bind('ajax:beforeSend', function() {
- checkDisabledState(link, 'clicking...');
+ App.checkDisabledState(link, 'Click me');
return false;
})
.trigger('click');
setTimeout(function() {
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
start();
}, 30);
});
-asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:error` event is triggered', 6, function() {
- var link = $('a[data-disable-with]').attr('data-remote', true).attr('href', '/error');
+asyncTest('a[data-remote][data-disable] re-enables when `ajax:error` event is triggered', 6, function() {
+ var link = $('a[data-disable]').attr('data-remote', true).attr('href', '/error');
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
link
.bind('ajax:beforeSend', function() {
- checkDisabledState(link, 'clicking...');
+ App.checkDisabledState(link, 'Click me');
})
.trigger('click');
setTimeout(function() {
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
start();
}, 30);
});
-asyncTest('form[data-remote] input|button|textarea[data-disable-with] does not disable when `ajax:beforeSend` event is cancelled', 8, function() {
+asyncTest('form[data-remote] input|button|textarea[data-disable] does not disable when `ajax:beforeSend` event is cancelled', 8, function() {
var form = $('form[data-remote]'),
input = form.find('input:text'),
- button = $('').appendTo(form),
- textarea = $('').appendTo(form),
- submit = $('').appendTo(form);
+ button = $('').appendTo(form),
+ textarea = $('').appendTo(form),
+ submit = $('').appendTo(form);
form
.bind('ajax:beforeSend', function() {
@@ -237,29 +219,29 @@ asyncTest('form[data-remote] input|button|textarea[data-disable-with] does not d
})
.trigger('submit');
- checkEnabledState(input, 'john');
- checkEnabledState(button, 'Submit');
- checkEnabledState(textarea, 'born, lived, died.');
- checkEnabledState(submit, 'Submit');
+ App.checkEnabledState(input, 'john');
+ App.checkEnabledState(button, 'Submit');
+ App.checkEnabledState(textarea, 'born, lived, died.');
+ App.checkEnabledState(submit, 'Submit');
start();
});
asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
- var link = $('a[data-disable-with]'), e;
+ var link = $('a[data-disable]'), e;
e = $.Event('click');
e.metaKey = true;
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
link.trigger(e);
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
e = $.Event('click');
e.ctrlKey = true;
link.trigger(e);
- checkEnabledState(link, 'Click me');
+ App.checkEnabledState(link, 'Click me');
start();
});
diff --git a/test/public/test/settings.js b/test/public/test/settings.js
index 1eddc251..606f2900 100644
--- a/test/public/test/settings.js
+++ b/test/public/test/settings.js
@@ -20,6 +20,24 @@ App.assertRequestPath = function(requestEnv, path) {
equal(requestEnv['PATH_INFO'], path, 'request should be sent to right url');
};
+App.getVal = function(el) {
+ return el.is('input,textarea,select') ? el.val() : el.text();
+};
+
+App.disabled = function(el) {
+ return el.is('input,textarea,select,button') ? el.is(':disabled') : el.data('ujs:enable-with');
+};
+
+App.checkEnabledState = function(el, text) {
+ ok(!App.disabled(el), el.get(0).tagName + ' should not be disabled');
+ equal(App.getVal(el), text, el.get(0).tagName + ' text should be original value');
+};
+
+App.checkDisabledState = function(el, text) {
+ ok(App.disabled(el), el.get(0).tagName + ' should be disabled');
+ equal(App.getVal(el), text, el.get(0).tagName + ' text should be disabled value');
+};
+
// hijacks normal form submit; lets it submit to an iframe to prevent
// navigating away from the test suite
$(document).bind('submit', function(e) {
diff --git a/test/views/index.erb b/test/views/index.erb
index 6caf6f03..f153cd12 100644
--- a/test/views/index.erb
+++ b/test/views/index.erb
@@ -1,6 +1,6 @@
<% @title = "jquery-ujs test" %>
-<%= test 'data-confirm', 'data-remote', 'data-disable', 'call-remote', 'call-remote-callbacks', 'data-method', 'override', 'csrf-refresh' %>
+<%= test 'data-confirm', 'data-remote', 'data-disable', 'data-disable-with', 'call-remote', 'call-remote-callbacks', 'data-method', 'override', 'csrf-refresh' %>
From d61894b7b17f89440b08cb0b742a2a589533124f Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Mon, 27 Jan 2014 16:53:02 -0200
Subject: [PATCH 004/100] Tidy up `data-disable-with` test source a bit.
---
test/public/test/data-disable-with.js | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/test/public/test/data-disable-with.js b/test/public/test/data-disable-with.js
index 80a183af..116f398b 100644
--- a/test/public/test/data-disable-with.js
+++ b/test/public/test/data-disable-with.js
@@ -27,7 +27,6 @@ module('data-disable-with', {
}
});
-
asyncTest('form input field with "data-disable-with" attribute', 7, function() {
var form = $('form[data-remote]'), input = form.find('input[type=text]');
@@ -38,8 +37,8 @@ asyncTest('form input field with "data-disable-with" attribute', 7, function() {
App.checkEnabledState(input, 'john');
equal(data.params.user_name, 'john');
start();
- }, 13)
- })
+ }, 13);
+ });
form.trigger('submit');
App.checkDisabledState(input, 'processing ...');
@@ -55,8 +54,8 @@ asyncTest('form button with "data-disable-with" attribute', 6, function() {
setTimeout(function() {
App.checkEnabledState(button, 'Submit');
start();
- }, 13)
- })
+ }, 13);
+ });
form.trigger('submit');
App.checkDisabledState(button, 'submitting ...');
@@ -119,8 +118,8 @@ asyncTest('form[data-remote] textarea[data-disable-with] attribute', 3, function
setTimeout(function() {
equal(data.params.user_bio, 'born, lived, died.');
start();
- }, 13)
- })
+ }, 13);
+ });
form.trigger('submit');
App.checkDisabledState(textarea, 'processing ...');
From f160fa2f4615f93e1a0d75e49de59d19c18c8728 Mon Sep 17 00:00:00 2001
From: Steve Schwartz
Date: Wed, 29 Jan 2014 01:01:45 -0500
Subject: [PATCH 005/100] Added jquery 1.11.0 support. Removed jquery 1.7.x
support.
---
test/server.rb | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/test/server.rb b/test/server.rb
index 270999a2..3e97a1a1 100644
--- a/test/server.rb
+++ b/test/server.rb
@@ -1,7 +1,7 @@
require 'sinatra'
require 'json'
-JQUERY_VERSIONS = %w[ 1.7 1.7.1 1.7.2 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 ].freeze
+JQUERY_VERSIONS = %w[ 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 1.11.0 ].freeze
use Rack::Static, :urls => ["/src"], :root => File.expand_path('..', settings.root)
@@ -48,7 +48,7 @@ def jquery_versions
end
get '/' do
- params[:version] ||= '1.10.1'
+ params[:version] ||= '1.11.0'
params[:cdn] ||= 'jquery'
erb :index
end
From 737273923b67a1895a74abcaaa94d4289b0340e3 Mon Sep 17 00:00:00 2001
From: Steve Schwartz
Date: Wed, 29 Jan 2014 01:27:11 -0500
Subject: [PATCH 006/100] Added older jquery 1.10.2 support.
---
test/server.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/test/server.rb b/test/server.rb
index 3e97a1a1..f15a91bf 100644
--- a/test/server.rb
+++ b/test/server.rb
@@ -1,7 +1,7 @@
require 'sinatra'
require 'json'
-JQUERY_VERSIONS = %w[ 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 1.11.0 ].freeze
+JQUERY_VERSIONS = %w[ 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 1.10.2 1.11.0 ].freeze
use Rack::Static, :urls => ["/src"], :root => File.expand_path('..', settings.root)
From 980e1c5b4ba566d463a7f97bd3ac9a8bcab40ae5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?=
Date: Sun, 16 Feb 2014 15:15:04 -0300
Subject: [PATCH 007/100] Update the jQuery supported versions
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index bc488b72..d2442a5e 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ Full [documentation is on the wiki][wiki], including the [list of published Ajax
Requirements
------------
-- [jQuery 1.7.x or higher][jquery];
+- [jQuery 1.8.x or higher and less than 2.0][jquery];
- HTML5 doctype (optional).
If you don't use HTML5, adding "data" attributes to your HTML4 or XHTML pages might make them fail [W3C markup validation][validator]. However, this shouldn't create any issues for web browsers or other user agents.
From 21e128661f848d0351196218e044b1466ff25720 Mon Sep 17 00:00:00 2001
From: Christian Pekeler
Date: Sun, 2 Mar 2014 16:14:27 -0700
Subject: [PATCH 008/100] added rake to Gemfile so we can actually use the
tasks from Rakefile
---
Gemfile | 1 +
Gemfile.lock | 2 ++
2 files changed, 3 insertions(+)
diff --git a/Gemfile b/Gemfile
index 8d6aa8d1..aca39a6b 100644
--- a/Gemfile
+++ b/Gemfile
@@ -3,3 +3,4 @@ source 'https://rubygems.org'
gem 'sinatra', '~> 1.0'
gem 'shotgun', :group => :reloadable
gem 'thin', :group => :reloadable
+gem 'rake'
diff --git a/Gemfile.lock b/Gemfile.lock
index f4f2623d..aa541a84 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -4,6 +4,7 @@ GEM
daemons (1.1.0)
eventmachine (0.12.10)
rack (1.2.1)
+ rake (10.1.1)
shotgun (0.8)
rack (>= 1.0)
sinatra (1.1.2)
@@ -19,6 +20,7 @@ PLATFORMS
ruby
DEPENDENCIES
+ rake
shotgun
sinatra (~> 1.0)
thin
From 432191b799d9e7eaf8b98e77ca08dbed24651cee Mon Sep 17 00:00:00 2001
From: Matthew O'Riordan
Date: Tue, 4 Mar 2014 14:13:17 +0000
Subject: [PATCH 009/100] Include instructions for installation via Bower
---
README.md | 25 ++++++++++++++++++++++++-
1 file changed, 24 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index d2442a5e..31b2905c 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@ Requirements
If you don't use HTML5, adding "data" attributes to your HTML4 or XHTML pages might make them fail [W3C markup validation][validator]. However, this shouldn't create any issues for web browsers or other user agents.
-Installation
+Installation using the jQuery-Rails Gem
------------
For automated installation in Rails, use the "jquery-rails" gem. Place this in your Gemfile:
@@ -52,6 +52,29 @@ Choose to overwrite jquery_ujs.js if prompted.*
c. For Rails 2.x and for manual installation follow [this wiki](https://github.com/rails/jquery-ujs/wiki/Manual-installing-and-Rails-2) .
+Installation using Bower
+------------
+
+Modify your bower.json file and add jQuery-UJS as a dependency as follows:
+
+```javascript
+{
+ "dependencies": {
+ /* include jQuery-UJS as below */
+ "jquery-ujs": "git@github.com:rails/jquery-ujs.git"
+ }
+}
+```
+
+Then run `bower install jquery-ujs` to install the jQuery-UJS package.
+
+For Rails 3.1 and above, add these lines to the top of your app/assets/javascripts/application.js file:
+
+```javascript
+//= require jquery
+//= require jquery-ujs/src/rails
+```
+
How to run tests
------------
From abfd48517a080bc8ed146bce8cc480cea53f9ff9 Mon Sep 17 00:00:00 2001
From: Jason Moon
Date: Tue, 4 Mar 2014 15:50:44 -0600
Subject: [PATCH 010/100] Don't fire ajax:send if ajax:beforeSend was
cancelled. Don't disable form elements until ajax:send.
---
src/rails.js | 12 +++++++-----
test/public/test/call-remote-callbacks.js | 20 +++++++++++++++++---
test/public/test/data-disable.js | 4 ++--
3 files changed, 26 insertions(+), 10 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 309d74d6..79ef1a94 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -129,7 +129,11 @@
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
- return rails.fire(element, 'ajax:beforeSend', [xhr, settings]);
+ if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) {
+ element.trigger('ajax:send', xhr);
+ } else {
+ return false;
+ }
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
@@ -154,9 +158,7 @@
// Only pass url to `ajax` options if not blank
if (url) { options.url = url; }
- var jqxhr = rails.ajax(options);
- element.trigger('ajax:send', jqxhr);
- return jqxhr;
+ return rails.ajax(options);
} else {
return false;
}
@@ -382,7 +384,7 @@
button.closest('form').data('ujs:submit-button', data);
});
- $document.delegate(rails.formSubmitSelector, 'ajax:beforeSend.rails', function(event) {
+ $document.delegate(rails.formSubmitSelector, 'ajax:send.rails', function(event) {
if (this == event.target) rails.disableFormElements($(this));
});
diff --git a/test/public/test/call-remote-callbacks.js b/test/public/test/call-remote-callbacks.js
index b4c4c7c7..fa785be9 100644
--- a/test/public/test/call-remote-callbacks.js
+++ b/test/public/test/call-remote-callbacks.js
@@ -9,6 +9,7 @@ module('call-remote-callbacks', {
teardown: function() {
$(document).undelegate('form[data-remote]', 'ajax:beforeSend');
$(document).undelegate('form[data-remote]', 'ajax:before');
+ $(document).undelegate('form[data-remote]', 'ajax:send');
$(document).undelegate('form[data-remote]', 'ajax:complete');
$(document).undelegate('form[data-remote]', 'ajax:success');
$(document).unbind('ajaxStop');
@@ -97,6 +98,9 @@ asyncTest('stopping the "ajax:beforeSend" event aborts the request', 1, function
ok(true, 'aborting request in ajax:beforeSend');
return false;
});
+ form.unbind('ajax:send').bind('ajax:send', function() {
+ ok(false, 'ajax:send should not run');
+ });
form.unbind('ajax:complete').bind('ajax:complete', function() {
ok(false, 'ajax:complete should not run');
});
@@ -315,6 +319,9 @@ asyncTest('"ajax:beforeSend" can be observed and stopped with event delegation',
});
submit(function(form) {
+ form.unbind('ajax:send').bind('ajax:send', function() {
+ ok(false, 'ajax:send should not run');
+ });
form.unbind('ajax:complete').bind('ajax:complete', function() {
ok(false, 'ajax:complete should not run');
});
@@ -324,12 +331,15 @@ asyncTest('"ajax:beforeSend" can be observed and stopped with event delegation',
});
});
-asyncTest('"ajax:beforeSend", "ajax:success" and "ajax:complete" are triggered', 8, function() {
+asyncTest('"ajax:beforeSend", "ajax:send", "ajax:success" and "ajax:complete" are triggered', 9, function() {
submit(function(form) {
form.bind('ajax:beforeSend', function(e, xhr, settings) {
ok(xhr.setRequestHeader, 'first argument to "ajax:beforeSend" should be an XHR object');
equal(settings.url, '/echo', 'second argument to "ajax:beforeSend" should be a settings object');
});
+ form.bind('ajax:send', function(e, xhr) {
+ ok(xhr.abort, 'first argument to "ajax:send" should be an XHR object');
+ });
form.bind('ajax:success', function(e, data, status, xhr) {
ok(data.REQUEST_METHOD, 'first argument to ajax:success should be a data object');
equal(status, 'success', 'second argument to ajax:success should be a status string');
@@ -342,10 +352,11 @@ asyncTest('"ajax:beforeSend", "ajax:success" and "ajax:complete" are triggered',
});
});
-asyncTest('"ajax:beforeSend", "ajax:error" and "ajax:complete" are triggered on error', 6, function() {
+asyncTest('"ajax:beforeSend", "ajax:send", "ajax:error" and "ajax:complete" are triggered on error', 7, function() {
submit(function(form) {
form.attr('action', '/error');
form.bind('ajax:beforeSend', function(arg) { ok(true, 'ajax:beforeSend') });
+ form.bind('ajax:send', function(arg) { ok(true, 'ajax:send') });
form.bind('ajax:error', function(e, xhr, status, error) {
ok(xhr.getResponseHeader, 'first argument to "ajax:error" should be an XHR object');
equal(status, 'error', 'second argument to ajax:error should be a status string');
@@ -358,11 +369,14 @@ asyncTest('"ajax:beforeSend", "ajax:error" and "ajax:complete" are triggered on
});
// IF THIS TEST IS FAILING, TRY INCREASING THE TIMEOUT AT THE BOTTOM TO > 100
-asyncTest('binding to ajax callbacks via .delegate() triggers handlers properly', 3, function() {
+asyncTest('binding to ajax callbacks via .delegate() triggers handlers properly', 4, function() {
$(document)
.delegate('form[data-remote]', 'ajax:beforeSend', function() {
ok(true, 'ajax:beforeSend handler is triggered');
})
+ .delegate('form[data-remote]', 'ajax:send', function() {
+ ok(true, 'ajax:send handler is triggered');
+ })
.delegate('form[data-remote]', 'ajax:complete', function() {
ok(true, 'ajax:complete handler is triggered');
})
diff --git a/test/public/test/data-disable.js b/test/public/test/data-disable.js
index ec858787..b73b3035 100644
--- a/test/public/test/data-disable.js
+++ b/test/public/test/data-disable.js
@@ -159,7 +159,7 @@ asyncTest('a[data-remote][data-disable-with] disables and re-enables', 6, functi
checkEnabledState(link, 'Click me');
link
- .bind('ajax:beforeSend', function() {
+ .bind('ajax:send', function() {
checkDisabledState(link, 'clicking...');
})
.bind('ajax:complete', function() {
@@ -213,7 +213,7 @@ asyncTest('a[data-remote][data-disable-with] re-enables when `ajax:error` event
checkEnabledState(link, 'Click me');
link
- .bind('ajax:beforeSend', function() {
+ .bind('ajax:send', function() {
checkDisabledState(link, 'clicking...');
})
.trigger('click');
From 7886f4f494937b0baad126b36cb9a217cb672593 Mon Sep 17 00:00:00 2001
From: Paulo Pereira
Date: Wed, 5 Mar 2014 19:12:16 +0100
Subject: [PATCH 011/100] Add :enabled to disableSelector
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Ensures elements aren’t disabled twice.
---
src/rails.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/rails.js b/src/rails.js
index 309d74d6..f6f1e2af 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -37,7 +37,7 @@
formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])',
// Form input elements disabled during form submission
- disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]',
+ disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled',
// Form input elements re-enabled after form submission
enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled',
From 18769f566103dbe867108a24c5adab911d7624ea Mon Sep 17 00:00:00 2001
From: Thomas Walpole
Date: Wed, 5 Mar 2014 12:32:43 -0800
Subject: [PATCH 012/100] support use of disable-with on elements using the
"form" attribute
---
src/rails.js | 7 +++++--
test/public/test/data-disable.js | 32 +++++++++++++++++++++++++++++++-
2 files changed, 36 insertions(+), 3 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 309d74d6..60de2d2d 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -189,7 +189,8 @@
- Sets disabled property to true
*/
disableFormElements: function(form) {
- form.find(rails.disableSelector).each(function() {
+ var elements = form.is('form') ? $(form[0].elements).filter(rails.disableSelector) : form.find(rails.disableSelector);
+ elements.each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
element.data('ujs:enable-with', element[method]());
element[method](element.data('disable-with'));
@@ -202,7 +203,9 @@
- Sets disabled property to false
*/
enableFormElements: function(form) {
- form.find(rails.enableSelector).each(function() {
+ var elements = form.is('form') ? $(form[0].elements).filter(rails.enableSelector) : form.find(rails.enableSelector);
+ elements.each(function() {
+ // form.find(rails.enableSelector).each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
element.prop('disabled', false);
diff --git a/test/public/test/data-disable.js b/test/public/test/data-disable.js
index ec858787..0f579506 100644
--- a/test/public/test/data-disable.js
+++ b/test/public/test/data-disable.js
@@ -10,7 +10,8 @@ module('data-disable', {
$('#qunit-fixture').append($('', {
action: '/echo',
- method: 'post'
+ method: 'post',
+ id: 'not_remote'
}))
.find('form:last')
// WEEIRDD: the form won't submit to an iframe if the button is name="submit" (??!)
@@ -21,6 +22,14 @@ module('data-disable', {
href: '/echo',
'data-disable-with': 'clicking...'
}));
+
+ $('#qunit-fixture').append($('', {
+ type: 'submit',
+ form: 'not_remote',
+ 'data-disable-with': 'form attr submitting',
+ name: 'submit3',
+ value: 'Form Attr Submit'
+ }));
},
teardown: function() {
$(document).unbind('iframe:loaded');
@@ -100,6 +109,27 @@ asyncTest('form input[type=submit][data-disable-with] disables', 6, function(){
}, 30);
});
+asyncTest('form input[type=submit][data-disable-with] using "form" attribute disables', 6, function() {
+ var form = $('#not_remote'), input = $('input[form=not_remote]');
+ checkEnabledState(input, 'Form Attr Submit');
+
+ // WEEIRDD: attaching this handler makes the test work in IE7
+ $(document).bind('iframe:loading', function(e, form) {});
+
+ $(document).bind('iframe:loaded', function(e, data) {
+ setTimeout(function() {
+ checkDisabledState(input, 'form attr submitting');
+ start();
+ }, 30);
+ });
+ form.trigger('submit');
+
+ setTimeout(function() {
+ checkDisabledState(input, 'form attr submitting');
+ }, 30);
+
+});
+
asyncTest('form[data-remote] input[type=submit][data-disable-with] is replaced in ajax callback', 2, function(){
var form = $('form:not([data-remote])').attr('data-remote', 'true'), origFormContents = form.html();
From d3b65a4c38d8e9f1ecf509c93b622c7b7df56ee0 Mon Sep 17 00:00:00 2001
From: Thomas Walpole
Date: Wed, 5 Mar 2014 13:22:07 -0800
Subject: [PATCH 013/100] extraneous commented line
---
src/rails.js | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/rails.js b/src/rails.js
index 60de2d2d..08919b95 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -205,7 +205,6 @@
enableFormElements: function(form) {
var elements = form.is('form') ? $(form[0].elements).filter(rails.enableSelector) : form.find(rails.enableSelector);
elements.each(function() {
- // form.find(rails.enableSelector).each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
element.prop('disabled', false);
From ed1fb395e98055e948071b18c360a0843c7d1b06 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Tue, 11 Mar 2014 22:52:43 -0300
Subject: [PATCH 014/100] Trim empty newlines
---
test/public/test/data-disable-with.js | 1 -
test/public/test/data-disable.js | 1 -
2 files changed, 2 deletions(-)
diff --git a/test/public/test/data-disable-with.js b/test/public/test/data-disable-with.js
index 116f398b..39a30172 100644
--- a/test/public/test/data-disable-with.js
+++ b/test/public/test/data-disable-with.js
@@ -225,7 +225,6 @@ asyncTest('form[data-remote] input|button|textarea[data-disable-with] does not d
App.checkEnabledState(submit, 'Submit');
start();
-
});
asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
diff --git a/test/public/test/data-disable.js b/test/public/test/data-disable.js
index 8d070352..60b8fd42 100644
--- a/test/public/test/data-disable.js
+++ b/test/public/test/data-disable.js
@@ -225,7 +225,6 @@ asyncTest('form[data-remote] input|button|textarea[data-disable] does not disabl
App.checkEnabledState(submit, 'Submit');
start();
-
});
asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
From be6f905231b5c8163fcae2d8ff39590351d0be14 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Tue, 11 Mar 2014 23:13:34 -0300
Subject: [PATCH 015/100] Add support for `data-confirm` attribute on `button`
elements.
This should be supported as the `button_to` rails helper produces
the expected `data-*` attributes.
Closes #352.
---
src/rails.js | 2 +-
test/public/test/data-confirm.js | 96 +++++++++++++++++++++++++++++++-
2 files changed, 95 insertions(+), 3 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 79ef1a94..8919aa4d 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -25,7 +25,7 @@
linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]',
// Button elements bound by jquery-ujs
- buttonClickSelector: 'button[data-remote]',
+ buttonClickSelector: 'button[data-remote], button[data-confirm]',
// Select elements bound by jquery-ujs
inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',
diff --git a/test/public/test/data-confirm.js b/test/public/test/data-confirm.js
index 50735e17..cf95b20b 100644
--- a/test/public/test/data-confirm.js
+++ b/test/public/test/data-confirm.js
@@ -7,6 +7,13 @@ module('data-confirm', {
text: 'my social security number'
}));
+ $('#qunit-fixture').append($('', {
+ 'data-url': '/echo',
+ 'data-remote': 'true',
+ 'data-confirm': 'Are you absolutely sure?',
+ text: 'Click me'
+ }));
+
this.windowConfirm = window.confirm;
},
teardown: function() {
@@ -35,6 +42,28 @@ asyncTest('clicking on a link with data-confirm attribute. Confirm yes.', 6, fun
.trigger('click');
});
+asyncTest('clicking on a button with data-confirm attribute. Confirm yes.', 6, function() {
+ var message;
+ // auto-confirm:
+ window.confirm = function(msg) { message = msg; return true };
+
+ $('button[data-confirm]')
+ .bind('confirm:complete', function(e, data) {
+ App.assertCallbackInvoked('confirm:complete');
+ ok(data == true, 'confirm:complete passes in confirm answer (true)');
+ })
+ .bind('ajax:success', function(e, data, status, xhr) {
+ console.log(xhr);
+ App.assertCallbackInvoked('ajax:success');
+ App.assertRequestPath(data, '/echo');
+ App.assertGetRequest(data);
+
+ equal(message, 'Are you absolutely sure?');
+ start();
+ })
+ .trigger('click');
+});
+
asyncTest('clicking on a link with data-confirm attribute. Confirm No.', 3, function() {
var message;
// auto-decline:
@@ -56,8 +85,28 @@ asyncTest('clicking on a link with data-confirm attribute. Confirm No.', 3, func
}, 50);
});
+asyncTest('clicking on a button with data-confirm attribute. Confirm No.', 3, function() {
+ var message;
+ // auto-decline:
+ window.confirm = function(msg) { message = msg; return false };
+
+ $('button[data-confirm]')
+ .bind('confirm:complete', function(e, data) {
+ App.assertCallbackInvoked('confirm:complete');
+ ok(data == false, 'confirm:complete passes in confirm answer (false)');
+ })
+ .bind('ajax:beforeSend', function(e, data, status, xhr) {
+ App.assertCallbackNotInvoked('ajax:beforeSend');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ equal(message, 'Are you absolutely sure?');
+ start();
+ }, 50);
+});
-asyncTest('binding to confirm event and returning false', 1, function() {
+asyncTest('binding to confirm event of a link and returning false', 1, function() {
// redefine confirm function so we can make sure it's not called
window.confirm = function(msg) {
ok(false, 'confirm dialog should not be called');
@@ -78,7 +127,28 @@ asyncTest('binding to confirm event and returning false', 1, function() {
}, 50);
});
-asyncTest('binding to confirm:complete event and returning false', 2, function() {
+asyncTest('binding to confirm event of a button and returning false', 1, function() {
+ // redefine confirm function so we can make sure it's not called
+ window.confirm = function(msg) {
+ ok(false, 'confirm dialog should not be called');
+ };
+
+ $('button[data-confirm]')
+ .bind('confirm', function() {
+ App.assertCallbackInvoked('confirm');
+ return false;
+ })
+ .bind('confirm:complete', function() {
+ App.assertCallbackNotInvoked('confirm:complete');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ start();
+ }, 50);
+});
+
+asyncTest('binding to confirm:complete event of a link and returning false', 2, function() {
// auto-confirm:
window.confirm = function(msg) {
ok(true, 'confirm dialog should be called');
@@ -99,3 +169,25 @@ asyncTest('binding to confirm:complete event and returning false', 2, function()
start();
}, 50);
});
+
+asyncTest('binding to confirm:complete event of a button and returning false', 2, function() {
+ // auto-confirm:
+ window.confirm = function(msg) {
+ ok(true, 'confirm dialog should be called');
+ return true;
+ };
+
+ $('button[data-confirm]')
+ .bind('confirm:complete', function() {
+ App.assertCallbackInvoked('confirm:complete');
+ return false;
+ })
+ .bind('ajax:beforeSend', function() {
+ App.assertCallbackNotInvoked('ajax:beforeSend');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ start();
+ }, 50);
+});
From c1330f3dc5a96fe6bf00f20678e45b2a7e69f266 Mon Sep 17 00:00:00 2001
From: Thomas Walpole
Date: Thu, 27 Mar 2014 16:43:06 -0700
Subject: [PATCH 016/100] refactor form element selection into helper function
---
src/rails.js | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 08919b95..fd9c28af 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -15,7 +15,7 @@
if ( $.rails !== undefined ) {
$.error('jquery-ujs has already been loaded!');
}
-
+
// Shorthand to make it a little easier to call public rails functions from within rails.js
var rails;
var $document = $(document);
@@ -182,15 +182,21 @@
form.hide().append(metadataInput).appendTo('body');
form.submit();
},
-
+
+ // Helper function that returns form elements that match the specified CSS selector
+ // If form is actually a "form" element this will return associated elements outside the from that have
+ // the html form attribute set
+ formElements: function(form, selector) {
+ return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector)
+ },
+
/* Disables form elements:
- Caches element value in 'ujs:enable-with' data store
- Replaces element text with value of 'data-disable-with' attribute
- Sets disabled property to true
*/
disableFormElements: function(form) {
- var elements = form.is('form') ? $(form[0].elements).filter(rails.disableSelector) : form.find(rails.disableSelector);
- elements.each(function() {
+ rails.formElements(form, rails.disableSelector).each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
element.data('ujs:enable-with', element[method]());
element[method](element.data('disable-with'));
@@ -203,8 +209,7 @@
- Sets disabled property to false
*/
enableFormElements: function(form) {
- var elements = form.is('form') ? $(form[0].elements).filter(rails.enableSelector) : form.find(rails.enableSelector);
- elements.each(function() {
+ rails.formElements(form, rails.enableSelector).each(function() {
var element = $(this), method = element.is('button') ? 'html' : 'val';
if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
element.prop('disabled', false);
From 693ccdf750fa715dbdc252f0d7215d5fdd490cce Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Fri, 4 Apr 2014 19:03:15 -0300
Subject: [PATCH 017/100] Update replacement logic to avoid DOM operations when
we won't change the HTML after all.
---
src/rails.js | 22 +++++++++++++++-------
1 file changed, 15 insertions(+), 7 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 70454201..953d9d30 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -192,13 +192,17 @@
*/
disableFormElements: function(form) {
form.find(rails.disableSelector).each(function() {
- var element, method, enabledState;
+ var element, method, replacement;
+
element = $(this);
method = element.is('button') ? 'html' : 'val';
- enabledState = element[method]();
+ replacement = element.data('disable-with');
+
+ element.data('ujs:enable-with', element[method]());
+ if (replacement !== undefined) {
+ element[method](replacement);
+ }
- element.data('ujs:enable-with', enabledState);
- element[method](element.data('disable-with') || enabledState);
element.prop('disabled', true);
});
},
@@ -275,9 +279,13 @@
// replace element's html with the 'data-disable-with' after storing original html
// and prevent clicking on it
disableElement: function(element) {
- var enabledState = element.html();
- element.data('ujs:enable-with', enabledState); // store enabled state
- element.html(element.data('disable-with') || enabledState); // set to disabled state
+ var replacement = element.data('disable-with');
+
+ element.data('ujs:enable-with', element.html()); // store enabled state
+ if (replacement !== undefined) {
+ element.html(replacement);
+ }
+
element.bind('click.railsDisable', function(e) { // prevent further clicking
return rails.stopEverything(e);
});
From 2c2192d08406d85ddc4211cc76d9db5f9dd59d2a Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Fri, 4 Apr 2014 19:27:27 -0300
Subject: [PATCH 018/100] Add jQuery 2.0 and 2.1 to the test suite.
---
test/server.rb | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/test/server.rb b/test/server.rb
index f15a91bf..bb42f593 100644
--- a/test/server.rb
+++ b/test/server.rb
@@ -1,7 +1,7 @@
require 'sinatra'
require 'json'
-JQUERY_VERSIONS = %w[ 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 1.10.2 1.11.0 ].freeze
+JQUERY_VERSIONS = %w[ 1.8.0 1.8.1 1.8.2 1.8.3 1.9.0 1.9.1 1.10.0 1.10.1 1.10.2 1.11.0 2.0.0 2.1.0].freeze
use Rack::Static, :urls => ["/src"], :root => File.expand_path('..', settings.root)
From a71b9014321fc0844749caebd7b0fa9da02c5ddd Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Fri, 4 Apr 2014 19:41:16 -0300
Subject: [PATCH 019/100] Update Qunit to 1.14.
---
test/public/vendor/qunit.css | 149 +-
test/public/vendor/qunit.js | 3104 ++++++++++++++++++++++------------
2 files changed, 2104 insertions(+), 1149 deletions(-)
diff --git a/test/public/vendor/qunit.css b/test/public/vendor/qunit.css
index 87a5f820..93026e3b 100644
--- a/test/public/vendor/qunit.css
+++ b/test/public/vendor/qunit.css
@@ -1,7 +1,18 @@
+/*!
+ * QUnit 1.14.0
+ * http://qunitjs.com/
+ *
+ * Copyright 2013 jQuery Foundation and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-01-31T16:40Z
+ */
+
/** Font Family and Sizes */
#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
- font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial;
+ font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
}
#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
@@ -10,7 +21,7 @@
/** Resets */
-#qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
+#qunit-tests, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult, #qunit-modulefilter {
margin: 0;
padding: 0;
}
@@ -21,27 +32,29 @@
#qunit-header {
padding: 0.5em 0 0.5em 1em;
- color: #8699a4;
- background-color: #0d3349;
+ color: #8699A4;
+ background-color: #0D3349;
font-size: 1.5em;
line-height: 1em;
- font-weight: normal;
-
- border-radius: 15px 15px 0 0;
- -moz-border-radius: 15px 15px 0 0;
- -webkit-border-top-right-radius: 15px;
- -webkit-border-top-left-radius: 15px;
+ font-weight: 400;
+
+ border-radius: 5px 5px 0 0;
}
#qunit-header a {
text-decoration: none;
- color: #c2ccd1;
+ color: #C2CCD1;
}
#qunit-header a:hover,
#qunit-header a:focus {
- color: #fff;
+ color: #FFF;
+}
+
+#qunit-testrunner-toolbar label {
+ display: inline-block;
+ padding: 0 0.5em 0 0.1em;
}
#qunit-banner {
@@ -49,16 +62,22 @@
}
#qunit-testrunner-toolbar {
- padding: 0em 0 0.5em 2em;
+ padding: 0.5em 0 0.5em 2em;
+ color: #5E740B;
+ background-color: #EEE;
+ overflow: hidden;
}
#qunit-userAgent {
padding: 0.5em 0 0.5em 2.5em;
- background-color: #2b81af;
- color: #fff;
+ background-color: #2B81AF;
+ color: #FFF;
text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
}
+#qunit-modulefilter-container {
+ float: right;
+}
/** Tests: Pass/Fail */
@@ -68,38 +87,55 @@
#qunit-tests li {
padding: 0.4em 0.5em 0.4em 2.5em;
- border-bottom: 1px solid #fff;
+ border-bottom: 1px solid #FFF;
list-style-position: inside;
}
+#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
+ display: none;
+}
+
#qunit-tests li strong {
cursor: pointer;
}
-#qunit-tests ol {
+#qunit-tests li a {
+ padding: 0.5em;
+ color: #C2CCD1;
+ text-decoration: none;
+}
+#qunit-tests li a:hover,
+#qunit-tests li a:focus {
+ color: #000;
+}
+
+#qunit-tests li .runtime {
+ float: right;
+ font-size: smaller;
+}
+
+.qunit-assert-list {
margin-top: 0.5em;
padding: 0.5em;
-
- background-color: #fff;
-
- border-radius: 15px;
- -moz-border-radius: 15px;
- -webkit-border-radius: 15px;
-
- box-shadow: inset 0px 2px 13px #999;
- -moz-box-shadow: inset 0px 2px 13px #999;
- -webkit-box-shadow: inset 0px 2px 13px #999;
+
+ background-color: #FFF;
+
+ border-radius: 5px;
+}
+
+.qunit-collapsed {
+ display: none;
}
#qunit-tests table {
border-collapse: collapse;
- margin-top: .2em;
+ margin-top: 0.2em;
}
#qunit-tests th {
text-align: right;
vertical-align: top;
- padding: 0 .5em 0 0;
+ padding: 0 0.5em 0 0;
}
#qunit-tests td {
@@ -113,27 +149,26 @@
}
#qunit-tests del {
- background-color: #e0f2be;
- color: #374e0c;
+ background-color: #E0F2BE;
+ color: #374E0C;
text-decoration: none;
}
#qunit-tests ins {
- background-color: #ffcaca;
+ background-color: #FFCACA;
color: #500;
text-decoration: none;
}
/*** Test Counts */
-#qunit-tests b.counts { color: black; }
+#qunit-tests b.counts { color: #000; }
#qunit-tests b.passed { color: #5E740B; }
#qunit-tests b.failed { color: #710909; }
#qunit-tests li li {
- margin: 0.5em;
- padding: 0.4em 0.5em 0.4em 0.5em;
- background-color: #fff;
+ padding: 5px;
+ background-color: #FFF;
border-bottom: none;
list-style-position: inside;
}
@@ -141,16 +176,16 @@
/*** Passing Styles */
#qunit-tests li li.pass {
- color: #5E740B;
- background-color: #fff;
- border-left: 26px solid #C6E746;
+ color: #3C510C;
+ background-color: #FFF;
+ border-left: 10px solid #C6E746;
}
#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
#qunit-tests .pass .test-name { color: #366097; }
-
+
#qunit-tests .pass .test-actual,
-#qunit-tests .pass .test-expected { color: #999999; }
+#qunit-tests .pass .test-expected { color: #999; }
#qunit-banner.qunit-pass { background-color: #C6E746; }
@@ -158,33 +193,37 @@
#qunit-tests li li.fail {
color: #710909;
- background-color: #fff;
- border-left: 26px solid #EE5757;
+ background-color: #FFF;
+ border-left: 10px solid #EE5757;
+ white-space: pre;
}
-#qunit-tests .fail { color: #000000; background-color: #EE5757; }
+#qunit-tests > li:last-child {
+ border-radius: 0 0 5px 5px;
+}
+
+#qunit-tests .fail { color: #000; background-color: #EE5757; }
#qunit-tests .fail .test-name,
-#qunit-tests .fail .module-name { color: #000000; }
+#qunit-tests .fail .module-name { color: #000; }
#qunit-tests .fail .test-actual { color: #EE5757; }
-#qunit-tests .fail .test-expected { color: green; }
+#qunit-tests .fail .test-expected { color: #008000; }
-#qunit-banner.qunit-fail,
-#qunit-testrunner-toolbar { background-color: #EE5757; }
+#qunit-banner.qunit-fail { background-color: #EE5757; }
-/** Footer */
+/** Result */
#qunit-testresult {
padding: 0.5em 0.5em 0.5em 2.5em;
- color: #2b81af;
+ color: #2B81AF;
background-color: #D2E0E6;
- border-radius: 0 0 15px 15px;
- -moz-border-radius: 0 0 15px 15px;
- -webkit-border-bottom-right-radius: 15px;
- -webkit-border-bottom-left-radius: 15px;
+ border-bottom: 1px solid #FFF;
+}
+#qunit-testresult .module-name {
+ font-weight: 700;
}
/** Fixture */
@@ -193,4 +232,6 @@
position: absolute;
top: -10000px;
left: -10000px;
+ width: 1000px;
+ height: 1000px;
}
diff --git a/test/public/vendor/qunit.js b/test/public/vendor/qunit.js
index f9db71c1..0e279fde 100644
--- a/test/public/vendor/qunit.js
+++ b/test/public/vendor/qunit.js
@@ -1,484 +1,358 @@
-/*
- * QUnit - A JavaScript Unit Testing Framework
- *
- * http://docs.jquery.com/QUnit
+/*!
+ * QUnit 1.14.0
+ * http://qunitjs.com/
+ *
+ * Copyright 2013 jQuery Foundation and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
*
- * Copyright (c) 2011 John Resig, Jörn Zaefferer
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * or GPL (GPL-LICENSE.txt) licenses.
+ * Date: 2014-01-31T16:40Z
*/
-(function(window) {
-
-var defined = {
- setTimeout: typeof window.setTimeout !== "undefined",
- sessionStorage: (function() {
- try {
- return !!sessionStorage.getItem;
- } catch(e){
- return false;
- }
- })()
-}
-
-var testId = 0;
-
-var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
- this.name = name;
- this.testName = testName;
- this.expected = expected;
- this.testEnvironmentArg = testEnvironmentArg;
- this.async = async;
- this.callback = callback;
- this.assertions = [];
-};
-Test.prototype = {
- init: function() {
- var tests = id("qunit-tests");
- if (tests) {
- var b = document.createElement("strong");
- b.innerHTML = "Running " + this.name;
- var li = document.createElement("li");
- li.appendChild( b );
- li.id = this.id = "test-output" + testId++;
- tests.appendChild( li );
- }
- },
- setup: function() {
- if (this.module != config.previousModule) {
- if ( config.previousModule ) {
- QUnit.moduleDone( config.previousModule, config.moduleStats.bad, config.moduleStats.all );
- }
- config.previousModule = this.module;
- config.moduleStats = { all: 0, bad: 0 };
- QUnit.moduleStart( this.module, this.moduleTestEnvironment );
- }
-
- config.current = this;
- this.testEnvironment = extend({
- setup: function() {},
- teardown: function() {}
- }, this.moduleTestEnvironment);
- if (this.testEnvironmentArg) {
- extend(this.testEnvironment, this.testEnvironmentArg);
- }
-
- QUnit.testStart( this.testName, this.testEnvironment );
-
- // allow utility functions to access the current test environment
- // TODO why??
- QUnit.current_testEnvironment = this.testEnvironment;
-
- try {
- if ( !config.pollution ) {
- saveGlobal();
+(function( window ) {
+
+var QUnit,
+ assert,
+ config,
+ onErrorFnPrev,
+ testId = 0,
+ fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""),
+ toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty,
+ // Keep a local reference to Date (GH-283)
+ Date = window.Date,
+ setTimeout = window.setTimeout,
+ clearTimeout = window.clearTimeout,
+ defined = {
+ document: typeof window.document !== "undefined",
+ setTimeout: typeof window.setTimeout !== "undefined",
+ sessionStorage: (function() {
+ var x = "qunit-test-string";
+ try {
+ sessionStorage.setItem( x, x );
+ sessionStorage.removeItem( x );
+ return true;
+ } catch( e ) {
+ return false;
}
-
- this.testEnvironment.setup.call(this.testEnvironment);
- } catch(e) {
- // TODO use testName instead of name for no-markup message?
- QUnit.ok( false, "Setup failed on " + this.name + ": " + e.message );
- }
+ }())
},
- run: function() {
- if ( this.async ) {
- QUnit.stop();
- }
-
- try {
- this.callback.call(this.testEnvironment);
- } catch(e) {
- // TODO use testName instead of name for no-markup message?
- fail("Test " + this.name + " died, exception and test follows", e, this.callback);
- QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
- // else next test will carry the responsibility
- saveGlobal();
-
- // Restart the tests if they're blocking
- if ( config.blocking ) {
- start();
+ /**
+ * Provides a normalized error string, correcting an issue
+ * with IE 7 (and prior) where Error.prototype.toString is
+ * not properly implemented
+ *
+ * Based on http://es5.github.com/#x15.11.4.4
+ *
+ * @param {String|Error} error
+ * @return {String} error message
+ */
+ errorString = function( error ) {
+ var name, message,
+ errorString = error.toString();
+ if ( errorString.substring( 0, 7 ) === "[object" ) {
+ name = error.name ? error.name.toString() : "Error";
+ message = error.message ? error.message.toString() : "";
+ if ( name && message ) {
+ return name + ": " + message;
+ } else if ( name ) {
+ return name;
+ } else if ( message ) {
+ return message;
+ } else {
+ return "Error";
}
+ } else {
+ return errorString;
}
},
- teardown: function() {
- try {
- checkPollution();
- this.testEnvironment.teardown.call(this.testEnvironment);
- } catch(e) {
- // TODO use testName instead of name for no-markup message?
- QUnit.ok( false, "Teardown failed on " + this.name + ": " + e.message );
- }
- },
- finish: function() {
- if ( this.expected && this.expected != this.assertions.length ) {
- QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
- }
-
- var good = 0, bad = 0,
- tests = id("qunit-tests");
-
- config.stats.all += this.assertions.length;
- config.moduleStats.all += this.assertions.length;
-
- if ( tests ) {
- var ol = document.createElement("ol");
-
- for ( var i = 0; i < this.assertions.length; i++ ) {
- var assertion = this.assertions[i];
-
- var li = document.createElement("li");
- li.className = assertion.result ? "pass" : "fail";
- li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
- ol.appendChild( li );
-
- if ( assertion.result ) {
- good++;
- } else {
- bad++;
- config.stats.bad++;
- config.moduleStats.bad++;
- }
- }
-
- // store result when possible
- defined.sessionStorage && sessionStorage.setItem("qunit-" + this.testName, bad);
-
- if (bad == 0) {
- ol.style.display = "none";
- }
-
- var b = document.createElement("strong");
- b.innerHTML = this.name + " (" + bad + ", " + good + ", " + this.assertions.length + ")";
-
- addEvent(b, "click", function() {
- var next = b.nextSibling, display = next.style.display;
- next.style.display = display === "none" ? "block" : "none";
- });
-
- addEvent(b, "dblclick", function(e) {
- var target = e && e.target ? e.target : window.event.srcElement;
- if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
- target = target.parentNode;
- }
- if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
- window.location.search = "?" + encodeURIComponent(getText([target]).replace(/\(.+\)$/, "").replace(/(^\s*|\s*$)/g, ""));
- }
- });
-
- var li = id(this.id);
- li.className = bad ? "fail" : "pass";
- li.style.display = resultDisplayStyle(!bad);
- li.removeChild( li.firstChild );
- li.appendChild( b );
- li.appendChild( ol );
-
- if ( bad ) {
- var toolbar = id("qunit-testrunner-toolbar");
- if ( toolbar ) {
- toolbar.style.display = "block";
- id("qunit-filter-pass").disabled = null;
- }
- }
-
- } else {
- for ( var i = 0; i < this.assertions.length; i++ ) {
- if ( !this.assertions[i].result ) {
- bad++;
- config.stats.bad++;
- config.moduleStats.bad++;
- }
+ /**
+ * Makes a clone of an object using only Array or Object as base,
+ * and copies over the own enumerable properties.
+ *
+ * @param {Object} obj
+ * @return {Object} New object with only the own properties (recursively).
+ */
+ objectValues = function( obj ) {
+ // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392.
+ /*jshint newcap: false */
+ var key, val,
+ vals = QUnit.is( "array", obj ) ? [] : {};
+ for ( key in obj ) {
+ if ( hasOwn.call( obj, key ) ) {
+ val = obj[key];
+ vals[key] = val === Object(val) ? objectValues(val) : val;
}
}
+ return vals;
+ };
- try {
- QUnit.reset();
- } catch(e) {
- // TODO use testName instead of name for no-markup message?
- fail("reset() failed, following Test " + this.name + ", exception and reset fn follows", e, QUnit.reset);
- }
-
- QUnit.testDone( this.testName, bad, this.assertions.length );
- },
-
- queue: function() {
- var test = this;
- synchronize(function() {
- test.init();
- });
- function run() {
- // each of these can by async
- synchronize(function() {
- test.setup();
- });
- synchronize(function() {
- test.run();
- });
- synchronize(function() {
- test.teardown();
- });
- synchronize(function() {
- test.finish();
- });
- }
- // defer when previous test run passed, if storage is available
- var bad = defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.testName);
- if (bad) {
- run();
- } else {
- synchronize(run);
- };
- }
-
-}
-var QUnit = {
+// Root QUnit object.
+// `QUnit` initialized at top of scope
+QUnit = {
// call on start of module test to prepend name to all tests
- module: function(name, testEnvironment) {
+ module: function( name, testEnvironment ) {
config.currentModule = name;
- config.currentModuleTestEnviroment = testEnvironment;
+ config.currentModuleTestEnvironment = testEnvironment;
+ config.modules[name] = true;
},
- asyncTest: function(testName, expected, callback) {
+ asyncTest: function( testName, expected, callback ) {
if ( arguments.length === 2 ) {
callback = expected;
- expected = 0;
+ expected = null;
}
- QUnit.test(testName, expected, callback, true);
+ QUnit.test( testName, expected, callback, true );
},
-
- test: function(testName, expected, callback, async) {
- var name = '' + testName + '', testEnvironmentArg;
+
+ test: function( testName, expected, callback, async ) {
+ var test,
+ nameHtml = "" + escapeText( testName ) + "";
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
- // is 2nd argument a testEnvironment?
- if ( expected && typeof expected === 'object') {
- testEnvironmentArg = expected;
- expected = null;
- }
if ( config.currentModule ) {
- name = '' + config.currentModule + ": " + name;
- }
-
- if ( !validTest(config.currentModule + ": " + testName) ) {
- return;
+ nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml;
}
-
- var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
- test.module = config.currentModule;
- test.moduleTestEnvironment = config.currentModuleTestEnviroment;
- test.queue();
- },
-
- /**
- * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
- */
- expect: function(asserts) {
- config.current.expected = asserts;
- },
- /**
- * Asserts true.
- * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
- */
- ok: function(a, msg) {
- a = !!a;
- var details = {
- result: a,
- message: msg
- };
- msg = escapeHtml(msg);
- QUnit.log(a, msg, details);
- config.current.assertions.push({
- result: a,
- message: msg
+ test = new Test({
+ nameHtml: nameHtml,
+ testName: testName,
+ expected: expected,
+ async: async,
+ callback: callback,
+ module: config.currentModule,
+ moduleTestEnvironment: config.currentModuleTestEnvironment,
+ stack: sourceFromStacktrace( 2 )
});
- },
-
- /**
- * Checks that the first two arguments are equal, with an optional message.
- * Prints out both actual and expected values.
- *
- * Prefered to ok( actual == expected, message )
- *
- * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
- *
- * @param Object actual
- * @param Object expected
- * @param String message (optional)
- */
- equal: function(actual, expected, message) {
- QUnit.push(expected == actual, actual, expected, message);
- },
-
- notEqual: function(actual, expected, message) {
- QUnit.push(expected != actual, actual, expected, message);
- },
-
- deepEqual: function(actual, expected, message) {
- QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
- },
- notDeepEqual: function(actual, expected, message) {
- QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
- },
+ if ( !validTest( test ) ) {
+ return;
+ }
- strictEqual: function(actual, expected, message) {
- QUnit.push(expected === actual, actual, expected, message);
+ test.queue();
},
- notStrictEqual: function(actual, expected, message) {
- QUnit.push(expected !== actual, actual, expected, message);
+ // Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through.
+ expect: function( asserts ) {
+ if (arguments.length === 1) {
+ config.current.expected = asserts;
+ } else {
+ return config.current.expected;
+ }
},
- raises: function(block, expected, message) {
- var actual, ok = false;
-
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
-
- try {
- block();
- } catch (e) {
- actual = e;
- }
-
- if (actual) {
- // we don't want to validate thrown error
- if (!expected) {
- ok = true;
- // expected is a regexp
- } else if (QUnit.objectType(expected) === "regexp") {
- ok = expected.test(actual);
- // expected is a constructor
- } else if (actual instanceof expected) {
- ok = true;
- // expected is a validation function which returns true is validation passed
- } else if (expected.call({}, actual) === true) {
- ok = true;
- }
+ start: function( count ) {
+ // QUnit hasn't been initialized yet.
+ // Note: RequireJS (et al) may delay onLoad
+ if ( config.semaphore === undefined ) {
+ QUnit.begin(function() {
+ // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first
+ setTimeout(function() {
+ QUnit.start( count );
+ });
+ });
+ return;
}
-
- QUnit.ok(ok, message);
- },
- start: function() {
- config.semaphore--;
- if (config.semaphore > 0) {
- // don't start until equal number of stop-calls
+ config.semaphore -= count || 1;
+ // don't start until equal number of stop-calls
+ if ( config.semaphore > 0 ) {
return;
}
- if (config.semaphore < 0) {
- // ignore if start is called more often then stop
+ // ignore if start is called more often then stop
+ if ( config.semaphore < 0 ) {
config.semaphore = 0;
+ QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) );
+ return;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
- window.setTimeout(function() {
+ setTimeout(function() {
+ if ( config.semaphore > 0 ) {
+ return;
+ }
if ( config.timeout ) {
- clearTimeout(config.timeout);
+ clearTimeout( config.timeout );
}
config.blocking = false;
- process();
+ process( true );
}, 13);
} else {
config.blocking = false;
- process();
+ process( true );
}
},
-
- stop: function(timeout) {
- config.semaphore++;
+
+ stop: function( count ) {
+ config.semaphore += count || 1;
config.blocking = true;
- if ( timeout && defined.setTimeout ) {
- clearTimeout(config.timeout);
- config.timeout = window.setTimeout(function() {
+ if ( config.testTimeout && defined.setTimeout ) {
+ clearTimeout( config.timeout );
+ config.timeout = setTimeout(function() {
QUnit.ok( false, "Test timed out" );
+ config.semaphore = 1;
QUnit.start();
- }, timeout);
+ }, config.testTimeout );
}
}
-
};
-// Backwards compatibility, deprecated
-QUnit.equals = QUnit.equal;
-QUnit.same = QUnit.deepEqual;
+// We use the prototype to distinguish between properties that should
+// be exposed as globals (and in exports) and those that shouldn't
+(function() {
+ function F() {}
+ F.prototype = QUnit;
+ QUnit = new F();
+ // Make F QUnit's constructor so that we can add to the prototype later
+ QUnit.constructor = F;
+}());
-// Maintain internal state
-var config = {
+/**
+ * Config object: Maintain internal state
+ * Later exposed as QUnit.config
+ * `config` initialized at top of scope
+ */
+config = {
// The queue of tests to run
queue: [],
// block until document ready
- blocking: true
+ blocking: true,
+
+ // when enabled, show only failing tests
+ // gets persisted through sessionStorage and can be changed in UI via checkbox
+ hidepassed: false,
+
+ // by default, run previously failed tests first
+ // very useful in combination with "Hide passed tests" checked
+ reorder: true,
+
+ // by default, modify document.title when suite is done
+ altertitle: true,
+
+ // by default, scroll to top of the page when suite is done
+ scrolltop: true,
+
+ // when enabled, all tests must call expect()
+ requireExpects: false,
+
+ // add checkboxes that are persisted in the query-string
+ // when enabled, the id is set to `true` as a `QUnit.config` property
+ urlConfig: [
+ {
+ id: "noglobals",
+ label: "Check for Globals",
+ tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings."
+ },
+ {
+ id: "notrycatch",
+ label: "No try-catch",
+ tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings."
+ }
+ ],
+
+ // Set of all modules.
+ modules: {},
+
+ // logging callback queues
+ begin: [],
+ done: [],
+ log: [],
+ testStart: [],
+ testDone: [],
+ moduleStart: [],
+ moduleDone: []
};
-// Load paramaters
+// Initialize more QUnit.config and QUnit.urlParams
(function() {
- var location = window.location || { search: "", protocol: "file:" },
- GETParams = location.search.slice(1).split('&');
-
- for ( var i = 0; i < GETParams.length; i++ ) {
- GETParams[i] = decodeURIComponent( GETParams[i] );
- if ( GETParams[i] === "noglobals" ) {
- GETParams.splice( i, 1 );
- i--;
- config.noglobals = true;
- } else if ( GETParams[i].search('=') > -1 ) {
- GETParams.splice( i, 1 );
- i--;
+ var i, current,
+ location = window.location || { search: "", protocol: "file:" },
+ params = location.search.slice( 1 ).split( "&" ),
+ length = params.length,
+ urlParams = {};
+
+ if ( params[ 0 ] ) {
+ for ( i = 0; i < length; i++ ) {
+ current = params[ i ].split( "=" );
+ current[ 0 ] = decodeURIComponent( current[ 0 ] );
+
+ // allow just a key to turn on a flag, e.g., test.html?noglobals
+ current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
+ if ( urlParams[ current[ 0 ] ] ) {
+ urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
+ } else {
+ urlParams[ current[ 0 ] ] = current[ 1 ];
+ }
+ }
+ }
+
+ QUnit.urlParams = urlParams;
+
+ // String search anywhere in moduleName+testName
+ config.filter = urlParams.filter;
+
+ // Exact match of the module name
+ config.module = urlParams.module;
+
+ config.testNumber = [];
+ if ( urlParams.testNumber ) {
+
+ // Ensure that urlParams.testNumber is an array
+ urlParams.testNumber = [].concat( urlParams.testNumber );
+ for ( i = 0; i < urlParams.testNumber.length; i++ ) {
+ current = urlParams.testNumber[ i ];
+ config.testNumber.push( parseInt( current, 10 ) );
}
}
-
- // restrict modules/tests by get parameters
- config.filters = GETParams;
-
+
// Figure out if we're running the tests from a server or not
- QUnit.isLocal = !!(location.protocol === 'file:');
-})();
+ QUnit.isLocal = location.protocol === "file:";
+}());
-// Expose the API as global variables, unless an 'exports'
-// object exists, in that case we assume we're in CommonJS
-if ( typeof exports === "undefined" || typeof require === "undefined" ) {
- extend(window, QUnit);
- window.QUnit = QUnit;
-} else {
- extend(exports, QUnit);
- exports.QUnit = QUnit;
-}
+extend( QUnit, {
-// define these after exposing globals to keep them in these QUnit namespace only
-extend(QUnit, {
config: config,
// Initialize the configuration options
init: function() {
- extend(config, {
+ extend( config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
- started: +new Date,
+ started: +new Date(),
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
- filters: [],
+ filter: "",
queue: [],
- semaphore: 0
+ semaphore: 1
});
- var tests = id("qunit-tests"),
- banner = id("qunit-banner"),
- result = id("qunit-testresult");
+ var tests, banner, result,
+ qunit = id( "qunit" );
+
+ if ( qunit ) {
+ qunit.innerHTML =
+ "" +
+ "" +
+ "" +
+ "" +
+ "
";
+ }
+
+ tests = id( "qunit-tests" );
+ banner = id( "qunit-banner" );
+ result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
@@ -491,562 +365,1537 @@ extend(QUnit, {
if ( result ) {
result.parentNode.removeChild( result );
}
- },
-
- /**
- * Resets the test setup. Useful for tests that modify the DOM.
- *
- * If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
- */
- reset: function() {
- if ( window.jQuery ) {
- jQuery( "#main, #qunit-fixture" ).html( config.fixture );
- } else {
- var main = id( 'main' ) || id( 'qunit-fixture' );
- if ( main ) {
- main.innerHTML = config.fixture;
- }
+
+ if ( tests ) {
+ result = document.createElement( "p" );
+ result.id = "qunit-testresult";
+ result.className = "result";
+ tests.parentNode.insertBefore( result, tests );
+ result.innerHTML = "Running...
";
}
},
-
- /**
- * Trigger an event on an element.
- *
- * @example triggerEvent( document.body, "click" );
- *
- * @param DOMElement elem
- * @param String type
- */
- triggerEvent: function( elem, type, event ) {
- if ( document.createEvent ) {
- event = document.createEvent("MouseEvents");
- event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
- 0, 0, 0, 0, 0, false, false, false, false, 0, null);
- elem.dispatchEvent( event );
- } else if ( elem.fireEvent ) {
- elem.fireEvent("on"+type);
+ // Resets the test setup. Useful for tests that modify the DOM.
+ /*
+ DEPRECATED: Use multiple tests instead of resetting inside a test.
+ Use testStart or testDone for custom cleanup.
+ This method will throw an error in 2.0, and will be removed in 2.1
+ */
+ reset: function() {
+ var fixture = id( "qunit-fixture" );
+ if ( fixture ) {
+ fixture.innerHTML = config.fixture;
}
},
-
+
// Safe object type checking
is: function( type, obj ) {
- return QUnit.objectType( obj ) == type;
+ return QUnit.objectType( obj ) === type;
},
-
- objectType: function( obj ) {
- if (typeof obj === "undefined") {
- return "undefined";
- // consider: typeof null === object
+ objectType: function( obj ) {
+ if ( typeof obj === "undefined" ) {
+ return "undefined";
}
- if (obj === null) {
- return "null";
+
+ // Consider: typeof null === object
+ if ( obj === null ) {
+ return "null";
}
- var type = Object.prototype.toString.call( obj )
- .match(/^\[object\s(.*)\]$/)[1] || '';
+ var match = toString.call( obj ).match(/^\[object\s(.*)\]$/),
+ type = match && match[1] || "";
- switch (type) {
- case 'Number':
- if (isNaN(obj)) {
- return "nan";
- } else {
- return "number";
- }
- case 'String':
- case 'Boolean':
- case 'Array':
- case 'Date':
- case 'RegExp':
- case 'Function':
- return type.toLowerCase();
+ switch ( type ) {
+ case "Number":
+ if ( isNaN(obj) ) {
+ return "nan";
+ }
+ return "number";
+ case "String":
+ case "Boolean":
+ case "Array":
+ case "Date":
+ case "RegExp":
+ case "Function":
+ return type.toLowerCase();
}
- if (typeof obj === "object") {
- return "object";
+ if ( typeof obj === "object" ) {
+ return "object";
}
return undefined;
},
-
- push: function(result, actual, expected, message) {
- var details = {
- result: result,
- message: message,
- actual: actual,
- expected: expected
- };
-
- message = escapeHtml(message) || (result ? "okay" : "failed");
- message = '' + message + "";
- expected = escapeHtml(QUnit.jsDump.parse(expected));
- actual = escapeHtml(QUnit.jsDump.parse(actual));
- var output = message + '| Expected: | ' + expected + ' |
';
- if (actual != expected) {
- output += '| Result: | ' + actual + ' |
';
- output += '| Diff: | ' + QUnit.diff(expected, actual) +' |
';
- }
- if (!result) {
- var source = sourceFromStacktrace();
- if (source) {
+
+ push: function( result, actual, expected, message ) {
+ if ( !config.current ) {
+ throw new Error( "assertion outside test context, was " + sourceFromStacktrace() );
+ }
+
+ var output, source,
+ details = {
+ module: config.current.module,
+ name: config.current.testName,
+ result: result,
+ message: message,
+ actual: actual,
+ expected: expected
+ };
+
+ message = escapeText( message ) || ( result ? "okay" : "failed" );
+ message = "" + message + "";
+ output = message;
+
+ if ( !result ) {
+ expected = escapeText( QUnit.jsDump.parse(expected) );
+ actual = escapeText( QUnit.jsDump.parse(actual) );
+ output += "| Expected: | " + expected + " |
";
+
+ if ( actual !== expected ) {
+ output += "| Result: | " + actual + " |
";
+ output += "| Diff: | " + QUnit.diff( expected, actual ) + " |
";
+ }
+
+ source = sourceFromStacktrace();
+
+ if ( source ) {
details.source = source;
- output += '| Source: | ' + source +' |
';
+ output += "| Source: | " + escapeText( source ) + " |
";
}
+
+ output += "
";
}
- output += "
";
-
- QUnit.log(result, message, details);
-
+
+ runLoggingCallbacks( "log", QUnit, details );
+
config.current.assertions.push({
result: !!result,
message: output
});
},
-
- // Logging callbacks
- begin: function() {},
- done: function(failures, total) {},
- log: function(result, message) {},
- testStart: function(name, testEnvironment) {},
- testDone: function(name, failures, total) {},
- moduleStart: function(name, testEnvironment) {},
- moduleDone: function(name, failures, total) {}
-});
-if ( typeof document === "undefined" || document.readyState === "complete" ) {
- config.autorun = true;
+ pushFailure: function( message, source, actual ) {
+ if ( !config.current ) {
+ throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) );
+ }
+
+ var output,
+ details = {
+ module: config.current.module,
+ name: config.current.testName,
+ result: false,
+ message: message
+ };
+
+ message = escapeText( message ) || "error";
+ message = "" + message + "";
+ output = message;
+
+ output += "";
+
+ if ( actual ) {
+ output += "| Result: | " + escapeText( actual ) + " |
";
+ }
+
+ if ( source ) {
+ details.source = source;
+ output += "| Source: | " + escapeText( source ) + " |
";
+ }
+
+ output += "
";
+
+ runLoggingCallbacks( "log", QUnit, details );
+
+ config.current.assertions.push({
+ result: false,
+ message: output
+ });
+ },
+
+ url: function( params ) {
+ params = extend( extend( {}, QUnit.urlParams ), params );
+ var key,
+ querystring = "?";
+
+ for ( key in params ) {
+ if ( hasOwn.call( params, key ) ) {
+ querystring += encodeURIComponent( key ) + "=" +
+ encodeURIComponent( params[ key ] ) + "&";
+ }
+ }
+ return window.location.protocol + "//" + window.location.host +
+ window.location.pathname + querystring.slice( 0, -1 );
+ },
+
+ extend: extend,
+ id: id,
+ addEvent: addEvent,
+ addClass: addClass,
+ hasClass: hasClass,
+ removeClass: removeClass
+ // load, equiv, jsDump, diff: Attached later
+});
+
+/**
+ * @deprecated: Created for backwards compatibility with test runner that set the hook function
+ * into QUnit.{hook}, instead of invoking it and passing the hook function.
+ * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here.
+ * Doing this allows us to tell if the following methods have been overwritten on the actual
+ * QUnit object.
+ */
+extend( QUnit.constructor.prototype, {
+
+ // Logging callbacks; all receive a single argument with the listed properties
+ // run test/logs.html for any related changes
+ begin: registerLoggingCallback( "begin" ),
+
+ // done: { failed, passed, total, runtime }
+ done: registerLoggingCallback( "done" ),
+
+ // log: { result, actual, expected, message }
+ log: registerLoggingCallback( "log" ),
+
+ // testStart: { name }
+ testStart: registerLoggingCallback( "testStart" ),
+
+ // testDone: { name, failed, passed, total, runtime }
+ testDone: registerLoggingCallback( "testDone" ),
+
+ // moduleStart: { name }
+ moduleStart: registerLoggingCallback( "moduleStart" ),
+
+ // moduleDone: { name, failed, passed, total }
+ moduleDone: registerLoggingCallback( "moduleDone" )
+});
+
+if ( !defined.document || document.readyState === "complete" ) {
+ config.autorun = true;
}
-addEvent(window, "load", function() {
- QUnit.begin();
-
+QUnit.load = function() {
+ runLoggingCallbacks( "begin", QUnit, {} );
+
// Initialize the config, saving the execution queue
- var oldconfig = extend({}, config);
+ var banner, filter, i, j, label, len, main, ol, toolbar, val, selection,
+ urlConfigContainer, moduleFilter, userAgent,
+ numModules = 0,
+ moduleNames = [],
+ moduleFilterHtml = "",
+ urlConfigHtml = "",
+ oldconfig = extend( {}, config );
+
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
- var userAgent = id("qunit-userAgent");
+ len = config.urlConfig.length;
+
+ for ( i = 0; i < len; i++ ) {
+ val = config.urlConfig[i];
+ if ( typeof val === "string" ) {
+ val = {
+ id: val,
+ label: val
+ };
+ }
+ config[ val.id ] = QUnit.urlParams[ val.id ];
+ if ( !val.value || typeof val.value === "string" ) {
+ urlConfigHtml += "";
+ } else {
+ urlConfigHtml += "";
+ }
+ }
+ for ( i in config.modules ) {
+ if ( config.modules.hasOwnProperty( i ) ) {
+ moduleNames.push(i);
+ }
+ }
+ numModules = moduleNames.length;
+ moduleNames.sort( function( a, b ) {
+ return a.localeCompare( b );
+ });
+ moduleFilterHtml += "";
+
+ // `userAgent` initialized at top of scope
+ userAgent = id( "qunit-userAgent" );
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
- var banner = id("qunit-header");
+
+ // `banner` initialized at top of scope
+ banner = id( "qunit-header" );
if ( banner ) {
- var paramsIndex = location.href.lastIndexOf(location.search);
- if ( paramsIndex > -1 ) {
- var mainPageLocation = location.href.slice(0, paramsIndex);
- if ( mainPageLocation == location.href ) {
- banner.innerHTML = ' ' + banner.innerHTML + ' ';
- } else {
- var testName = decodeURIComponent(location.search.slice(1));
- banner.innerHTML = '' + banner.innerHTML + ' › ' + testName + '';
- }
- }
+ banner.innerHTML = "" + banner.innerHTML + " ";
}
-
- var toolbar = id("qunit-testrunner-toolbar");
+
+ // `toolbar` initialized at top of scope
+ toolbar = id( "qunit-testrunner-toolbar" );
if ( toolbar ) {
- toolbar.style.display = "none";
-
- var filter = document.createElement("input");
+ // `filter` initialized at top of scope
+ filter = document.createElement( "input" );
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
- filter.disabled = true;
+
addEvent( filter, "click", function() {
- var li = document.getElementsByTagName("li");
- for ( var i = 0; i < li.length; i++ ) {
- if ( li[i].className.indexOf("pass") > -1 ) {
- li[i].style.display = filter.checked ? "none" : "";
+ var tmp,
+ ol = id( "qunit-tests" );
+
+ if ( filter.checked ) {
+ ol.className = ol.className + " hidepass";
+ } else {
+ tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
+ ol.className = tmp.replace( / hidepass /, " " );
+ }
+ if ( defined.sessionStorage ) {
+ if (filter.checked) {
+ sessionStorage.setItem( "qunit-filter-passed-tests", "true" );
+ } else {
+ sessionStorage.removeItem( "qunit-filter-passed-tests" );
}
}
});
+
+ if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) {
+ filter.checked = true;
+ // `ol` initialized at top of scope
+ ol = id( "qunit-tests" );
+ ol.className = ol.className + " hidepass";
+ }
toolbar.appendChild( filter );
- var label = document.createElement("label");
- label.setAttribute("for", "qunit-filter-pass");
- label.innerHTML = "Hide passed tests";
- toolbar.appendChild( label );
- }
+ // `label` initialized at top of scope
+ label = document.createElement( "label" );
+ label.setAttribute( "for", "qunit-filter-pass" );
+ label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." );
+ label.innerHTML = "Hide passed tests";
+ toolbar.appendChild( label );
+
+ urlConfigContainer = document.createElement("span");
+ urlConfigContainer.innerHTML = urlConfigHtml;
+ // For oldIE support:
+ // * Add handlers to the individual elements instead of the container
+ // * Use "click" instead of "change" for checkboxes
+ // * Fallback from event.target to event.srcElement
+ addEvents( urlConfigContainer.getElementsByTagName("input"), "click", function( event ) {
+ var params = {},
+ target = event.target || event.srcElement;
+ params[ target.name ] = target.checked ?
+ target.defaultValue || true :
+ undefined;
+ window.location = QUnit.url( params );
+ });
+ addEvents( urlConfigContainer.getElementsByTagName("select"), "change", function( event ) {
+ var params = {},
+ target = event.target || event.srcElement;
+ params[ target.name ] = target.options[ target.selectedIndex ].value || undefined;
+ window.location = QUnit.url( params );
+ });
+ toolbar.appendChild( urlConfigContainer );
+
+ if (numModules > 1) {
+ moduleFilter = document.createElement( "span" );
+ moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
+ moduleFilter.innerHTML = moduleFilterHtml;
+ addEvent( moduleFilter.lastChild, "change", function() {
+ var selectBox = moduleFilter.getElementsByTagName("select")[0],
+ selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value);
+
+ window.location = QUnit.url({
+ module: ( selectedModule === "" ) ? undefined : selectedModule,
+ // Remove any existing filters
+ filter: undefined,
+ testNumber: undefined
+ });
+ });
+ toolbar.appendChild(moduleFilter);
+ }
+ }
+
+ // `main` initialized at top of scope
+ main = id( "qunit-fixture" );
+ if ( main ) {
+ config.fixture = main.innerHTML;
+ }
+
+ if ( config.autostart ) {
+ QUnit.start();
+ }
+};
+
+if ( defined.document ) {
+ addEvent( window, "load", QUnit.load );
+}
+
+// `onErrorFnPrev` initialized at top of scope
+// Preserve other handlers
+onErrorFnPrev = window.onerror;
+
+// Cover uncaught exceptions
+// Returning true will suppress the default browser handler,
+// returning false will let it run.
+window.onerror = function ( error, filePath, linerNr ) {
+ var ret = false;
+ if ( onErrorFnPrev ) {
+ ret = onErrorFnPrev( error, filePath, linerNr );
+ }
+
+ // Treat return value as window.onerror itself does,
+ // Only do our handling if not suppressed.
+ if ( ret !== true ) {
+ if ( QUnit.config.current ) {
+ if ( QUnit.config.current.ignoreGlobalErrors ) {
+ return true;
+ }
+ QUnit.pushFailure( error, filePath + ":" + linerNr );
+ } else {
+ QUnit.test( "global failure", extend( function() {
+ QUnit.pushFailure( error, filePath + ":" + linerNr );
+ }, { validTest: validTest } ) );
+ }
+ return false;
+ }
+
+ return ret;
+};
+
+function done() {
+ config.autorun = true;
+
+ // Log the last module results
+ if ( config.previousModule ) {
+ runLoggingCallbacks( "moduleDone", QUnit, {
+ name: config.previousModule,
+ failed: config.moduleStats.bad,
+ passed: config.moduleStats.all - config.moduleStats.bad,
+ total: config.moduleStats.all
+ });
+ }
+ delete config.previousModule;
+
+ var i, key,
+ banner = id( "qunit-banner" ),
+ tests = id( "qunit-tests" ),
+ runtime = +new Date() - config.started,
+ passed = config.stats.all - config.stats.bad,
+ html = [
+ "Tests completed in ",
+ runtime,
+ " milliseconds.
",
+ "",
+ passed,
+ " assertions of ",
+ config.stats.all,
+ " passed, ",
+ config.stats.bad,
+ " failed."
+ ].join( "" );
+
+ if ( banner ) {
+ banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" );
+ }
+
+ if ( tests ) {
+ id( "qunit-testresult" ).innerHTML = html;
+ }
+
+ if ( config.altertitle && defined.document && document.title ) {
+ // show âś– for good, âś” for bad suite result in title
+ // use escape sequences in case file gets loaded with non-utf-8-charset
+ document.title = [
+ ( config.stats.bad ? "\u2716" : "\u2714" ),
+ document.title.replace( /^[\u2714\u2716] /i, "" )
+ ].join( " " );
+ }
+
+ // clear own sessionStorage items if all tests passed
+ if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
+ // `key` & `i` initialized at top of scope
+ for ( i = 0; i < sessionStorage.length; i++ ) {
+ key = sessionStorage.key( i++ );
+ if ( key.indexOf( "qunit-test-" ) === 0 ) {
+ sessionStorage.removeItem( key );
+ }
+ }
+ }
+
+ // scroll back to top to show results
+ if ( config.scrolltop && window.scrollTo ) {
+ window.scrollTo(0, 0);
+ }
+
+ runLoggingCallbacks( "done", QUnit, {
+ failed: config.stats.bad,
+ passed: passed,
+ total: config.stats.all,
+ runtime: runtime
+ });
+}
+
+/** @return Boolean: true if this test should be ran */
+function validTest( test ) {
+ var include,
+ filter = config.filter && config.filter.toLowerCase(),
+ module = config.module && config.module.toLowerCase(),
+ fullName = ( test.module + ": " + test.testName ).toLowerCase();
+
+ // Internally-generated tests are always valid
+ if ( test.callback && test.callback.validTest === validTest ) {
+ delete test.callback.validTest;
+ return true;
+ }
+
+ if ( config.testNumber.length > 0 ) {
+ if ( inArray( test.testNumber, config.testNumber ) < 0 ) {
+ return false;
+ }
+ }
+
+ if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) {
+ return false;
+ }
+
+ if ( !filter ) {
+ return true;
+ }
+
+ include = filter.charAt( 0 ) !== "!";
+ if ( !include ) {
+ filter = filter.slice( 1 );
+ }
+
+ // If the filter matches, we need to honour include
+ if ( fullName.indexOf( filter ) !== -1 ) {
+ return include;
+ }
+
+ // Otherwise, do the opposite
+ return !include;
+}
+
+// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions)
+// Later Safari and IE10 are supposed to support error.stack as well
+// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
+function extractStacktrace( e, offset ) {
+ offset = offset === undefined ? 3 : offset;
+
+ var stack, include, i;
+
+ if ( e.stacktrace ) {
+ // Opera
+ return e.stacktrace.split( "\n" )[ offset + 3 ];
+ } else if ( e.stack ) {
+ // Firefox, Chrome
+ stack = e.stack.split( "\n" );
+ if (/^error$/i.test( stack[0] ) ) {
+ stack.shift();
+ }
+ if ( fileName ) {
+ include = [];
+ for ( i = offset; i < stack.length; i++ ) {
+ if ( stack[ i ].indexOf( fileName ) !== -1 ) {
+ break;
+ }
+ include.push( stack[ i ] );
+ }
+ if ( include.length ) {
+ return include.join( "\n" );
+ }
+ }
+ return stack[ offset ];
+ } else if ( e.sourceURL ) {
+ // Safari, PhantomJS
+ // hopefully one day Safari provides actual stacktraces
+ // exclude useless self-reference for generated Error objects
+ if ( /qunit.js$/.test( e.sourceURL ) ) {
+ return;
+ }
+ // for actual exceptions, this is useful
+ return e.sourceURL + ":" + e.line;
+ }
+}
+function sourceFromStacktrace( offset ) {
+ try {
+ throw new Error();
+ } catch ( e ) {
+ return extractStacktrace( e, offset );
+ }
+}
+
+/**
+ * Escape text for attribute or text content.
+ */
+function escapeText( s ) {
+ if ( !s ) {
+ return "";
+ }
+ s = s + "";
+ // Both single quotes and double quotes (for attributes)
+ return s.replace( /['"<>&]/g, function( s ) {
+ switch( s ) {
+ case "'":
+ return "'";
+ case "\"":
+ return """;
+ case "<":
+ return "<";
+ case ">":
+ return ">";
+ case "&":
+ return "&";
+ }
+ });
+}
+
+function synchronize( callback, last ) {
+ config.queue.push( callback );
+
+ if ( config.autorun && !config.blocking ) {
+ process( last );
+ }
+}
+
+function process( last ) {
+ function next() {
+ process( last );
+ }
+ var start = new Date().getTime();
+ config.depth = config.depth ? config.depth + 1 : 1;
+
+ while ( config.queue.length && !config.blocking ) {
+ if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
+ config.queue.shift()();
+ } else {
+ setTimeout( next, 13 );
+ break;
+ }
+ }
+ config.depth--;
+ if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
+ done();
+ }
+}
+
+function saveGlobal() {
+ config.pollution = [];
+
+ if ( config.noglobals ) {
+ for ( var key in window ) {
+ if ( hasOwn.call( window, key ) ) {
+ // in Opera sometimes DOM element ids show up here, ignore them
+ if ( /^qunit-test-output/.test( key ) ) {
+ continue;
+ }
+ config.pollution.push( key );
+ }
+ }
+ }
+}
+
+function checkPollution() {
+ var newGlobals,
+ deletedGlobals,
+ old = config.pollution;
+
+ saveGlobal();
+
+ newGlobals = diff( config.pollution, old );
+ if ( newGlobals.length > 0 ) {
+ QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
+ }
+
+ deletedGlobals = diff( old, config.pollution );
+ if ( deletedGlobals.length > 0 ) {
+ QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
+ }
+}
+
+// returns a new Array with the elements that are in a but not in b
+function diff( a, b ) {
+ var i, j,
+ result = a.slice();
+
+ for ( i = 0; i < result.length; i++ ) {
+ for ( j = 0; j < b.length; j++ ) {
+ if ( result[i] === b[j] ) {
+ result.splice( i, 1 );
+ i--;
+ break;
+ }
+ }
+ }
+ return result;
+}
+
+function extend( a, b ) {
+ for ( var prop in b ) {
+ if ( hasOwn.call( b, prop ) ) {
+ // Avoid "Member not found" error in IE8 caused by messing with window.constructor
+ if ( !( prop === "constructor" && a === window ) ) {
+ if ( b[ prop ] === undefined ) {
+ delete a[ prop ];
+ } else {
+ a[ prop ] = b[ prop ];
+ }
+ }
+ }
+ }
+
+ return a;
+}
+
+/**
+ * @param {HTMLElement} elem
+ * @param {string} type
+ * @param {Function} fn
+ */
+function addEvent( elem, type, fn ) {
+ if ( elem.addEventListener ) {
+
+ // Standards-based browsers
+ elem.addEventListener( type, fn, false );
+ } else if ( elem.attachEvent ) {
+
+ // support: IE <9
+ elem.attachEvent( "on" + type, fn );
+ } else {
+
+ // Caller must ensure support for event listeners is present
+ throw new Error( "addEvent() was called in a context without event listener support" );
+ }
+}
+
+/**
+ * @param {Array|NodeList} elems
+ * @param {string} type
+ * @param {Function} fn
+ */
+function addEvents( elems, type, fn ) {
+ var i = elems.length;
+ while ( i-- ) {
+ addEvent( elems[i], type, fn );
+ }
+}
+
+function hasClass( elem, name ) {
+ return (" " + elem.className + " ").indexOf(" " + name + " ") > -1;
+}
+
+function addClass( elem, name ) {
+ if ( !hasClass( elem, name ) ) {
+ elem.className += (elem.className ? " " : "") + name;
+ }
+}
+
+function removeClass( elem, name ) {
+ var set = " " + elem.className + " ";
+ // Class name may appear multiple times
+ while ( set.indexOf(" " + name + " ") > -1 ) {
+ set = set.replace(" " + name + " " , " ");
+ }
+ // If possible, trim it for prettiness, but not necessarily
+ elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
+}
+
+function id( name ) {
+ return defined.document && document.getElementById && document.getElementById( name );
+}
+
+function registerLoggingCallback( key ) {
+ return function( callback ) {
+ config[key].push( callback );
+ };
+}
+
+// Supports deprecated method of completely overwriting logging callbacks
+function runLoggingCallbacks( key, scope, args ) {
+ var i, callbacks;
+ if ( QUnit.hasOwnProperty( key ) ) {
+ QUnit[ key ].call(scope, args );
+ } else {
+ callbacks = config[ key ];
+ for ( i = 0; i < callbacks.length; i++ ) {
+ callbacks[ i ].call( scope, args );
+ }
+ }
+}
+
+// from jquery.js
+function inArray( elem, array ) {
+ if ( array.indexOf ) {
+ return array.indexOf( elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+function Test( settings ) {
+ extend( this, settings );
+ this.assertions = [];
+ this.testNumber = ++Test.count;
+}
+
+Test.count = 0;
+
+Test.prototype = {
+ init: function() {
+ var a, b, li,
+ tests = id( "qunit-tests" );
+
+ if ( tests ) {
+ b = document.createElement( "strong" );
+ b.innerHTML = this.nameHtml;
+
+ // `a` initialized at top of scope
+ a = document.createElement( "a" );
+ a.innerHTML = "Rerun";
+ a.href = QUnit.url({ testNumber: this.testNumber });
+
+ li = document.createElement( "li" );
+ li.appendChild( b );
+ li.appendChild( a );
+ li.className = "running";
+ li.id = this.id = "qunit-test-output" + testId++;
+
+ tests.appendChild( li );
+ }
+ },
+ setup: function() {
+ if (
+ // Emit moduleStart when we're switching from one module to another
+ this.module !== config.previousModule ||
+ // They could be equal (both undefined) but if the previousModule property doesn't
+ // yet exist it means this is the first test in a suite that isn't wrapped in a
+ // module, in which case we'll just emit a moduleStart event for 'undefined'.
+ // Without this, reporters can get testStart before moduleStart which is a problem.
+ !hasOwn.call( config, "previousModule" )
+ ) {
+ if ( hasOwn.call( config, "previousModule" ) ) {
+ runLoggingCallbacks( "moduleDone", QUnit, {
+ name: config.previousModule,
+ failed: config.moduleStats.bad,
+ passed: config.moduleStats.all - config.moduleStats.bad,
+ total: config.moduleStats.all
+ });
+ }
+ config.previousModule = this.module;
+ config.moduleStats = { all: 0, bad: 0 };
+ runLoggingCallbacks( "moduleStart", QUnit, {
+ name: this.module
+ });
+ }
+
+ config.current = this;
+
+ this.testEnvironment = extend({
+ setup: function() {},
+ teardown: function() {}
+ }, this.moduleTestEnvironment );
+
+ this.started = +new Date();
+ runLoggingCallbacks( "testStart", QUnit, {
+ name: this.testName,
+ module: this.module
+ });
+
+ /*jshint camelcase:false */
+
+
+ /**
+ * Expose the current test environment.
+ *
+ * @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead.
+ */
+ QUnit.current_testEnvironment = this.testEnvironment;
+
+ /*jshint camelcase:true */
+
+ if ( !config.pollution ) {
+ saveGlobal();
+ }
+ if ( config.notrycatch ) {
+ this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert );
+ return;
+ }
+ try {
+ this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert );
+ } catch( e ) {
+ QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) );
+ }
+ },
+ run: function() {
+ config.current = this;
+
+ var running = id( "qunit-testresult" );
+
+ if ( running ) {
+ running.innerHTML = "Running:
" + this.nameHtml;
+ }
+
+ if ( this.async ) {
+ QUnit.stop();
+ }
+
+ this.callbackStarted = +new Date();
+
+ if ( config.notrycatch ) {
+ this.callback.call( this.testEnvironment, QUnit.assert );
+ this.callbackRuntime = +new Date() - this.callbackStarted;
+ return;
+ }
+
+ try {
+ this.callback.call( this.testEnvironment, QUnit.assert );
+ this.callbackRuntime = +new Date() - this.callbackStarted;
+ } catch( e ) {
+ this.callbackRuntime = +new Date() - this.callbackStarted;
+
+ QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
+ // else next test will carry the responsibility
+ saveGlobal();
+
+ // Restart the tests if they're blocking
+ if ( config.blocking ) {
+ QUnit.start();
+ }
+ }
+ },
+ teardown: function() {
+ config.current = this;
+ if ( config.notrycatch ) {
+ if ( typeof this.callbackRuntime === "undefined" ) {
+ this.callbackRuntime = +new Date() - this.callbackStarted;
+ }
+ this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert );
+ return;
+ } else {
+ try {
+ this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert );
+ } catch( e ) {
+ QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) );
+ }
+ }
+ checkPollution();
+ },
+ finish: function() {
+ config.current = this;
+ if ( config.requireExpects && this.expected === null ) {
+ QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack );
+ } else if ( this.expected !== null && this.expected !== this.assertions.length ) {
+ QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack );
+ } else if ( this.expected === null && !this.assertions.length ) {
+ QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack );
+ }
+
+ var i, assertion, a, b, time, li, ol,
+ test = this,
+ good = 0,
+ bad = 0,
+ tests = id( "qunit-tests" );
+
+ this.runtime = +new Date() - this.started;
+ config.stats.all += this.assertions.length;
+ config.moduleStats.all += this.assertions.length;
+
+ if ( tests ) {
+ ol = document.createElement( "ol" );
+ ol.className = "qunit-assert-list";
+
+ for ( i = 0; i < this.assertions.length; i++ ) {
+ assertion = this.assertions[i];
+
+ li = document.createElement( "li" );
+ li.className = assertion.result ? "pass" : "fail";
+ li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" );
+ ol.appendChild( li );
+
+ if ( assertion.result ) {
+ good++;
+ } else {
+ bad++;
+ config.stats.bad++;
+ config.moduleStats.bad++;
+ }
+ }
+
+ // store result when possible
+ if ( QUnit.config.reorder && defined.sessionStorage ) {
+ if ( bad ) {
+ sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad );
+ } else {
+ sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName );
+ }
+ }
+
+ if ( bad === 0 ) {
+ addClass( ol, "qunit-collapsed" );
+ }
+
+ // `b` initialized at top of scope
+ b = document.createElement( "strong" );
+ b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")";
+
+ addEvent(b, "click", function() {
+ var next = b.parentNode.lastChild,
+ collapsed = hasClass( next, "qunit-collapsed" );
+ ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" );
+ });
+
+ addEvent(b, "dblclick", function( e ) {
+ var target = e && e.target ? e.target : window.event.srcElement;
+ if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) {
+ target = target.parentNode;
+ }
+ if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
+ window.location = QUnit.url({ testNumber: test.testNumber });
+ }
+ });
+
+ // `time` initialized at top of scope
+ time = document.createElement( "span" );
+ time.className = "runtime";
+ time.innerHTML = this.runtime + " ms";
+
+ // `li` initialized at top of scope
+ li = id( this.id );
+ li.className = bad ? "fail" : "pass";
+ li.removeChild( li.firstChild );
+ a = li.firstChild;
+ li.appendChild( b );
+ li.appendChild( a );
+ li.appendChild( time );
+ li.appendChild( ol );
+
+ } else {
+ for ( i = 0; i < this.assertions.length; i++ ) {
+ if ( !this.assertions[i].result ) {
+ bad++;
+ config.stats.bad++;
+ config.moduleStats.bad++;
+ }
+ }
+ }
+
+ runLoggingCallbacks( "testDone", QUnit, {
+ name: this.testName,
+ module: this.module,
+ failed: bad,
+ passed: this.assertions.length - bad,
+ total: this.assertions.length,
+ runtime: this.runtime,
+ // DEPRECATED: this property will be removed in 2.0.0, use runtime instead
+ duration: this.runtime
+ });
+
+ QUnit.reset();
+
+ config.current = undefined;
+ },
+
+ queue: function() {
+ var bad,
+ test = this;
+
+ synchronize(function() {
+ test.init();
+ });
+ function run() {
+ // each of these can by async
+ synchronize(function() {
+ test.setup();
+ });
+ synchronize(function() {
+ test.run();
+ });
+ synchronize(function() {
+ test.teardown();
+ });
+ synchronize(function() {
+ test.finish();
+ });
+ }
+
+ // `bad` initialized at top of scope
+ // defer when previous test run passed, if storage is available
+ bad = QUnit.config.reorder && defined.sessionStorage &&
+ +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName );
- var main = id('main') || id('qunit-fixture');
- if ( main ) {
- config.fixture = main.innerHTML;
+ if ( bad ) {
+ run();
+ } else {
+ synchronize( run, true );
+ }
}
+};
- if (config.autostart) {
- QUnit.start();
- }
-});
+// `assert` initialized at top of scope
+// Assert helpers
+// All of these must either call QUnit.push() or manually do:
+// - runLoggingCallbacks( "log", .. );
+// - config.current.assertions.push({ .. });
+assert = QUnit.assert = {
+ /**
+ * Asserts rough true-ish result.
+ * @name ok
+ * @function
+ * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
+ */
+ ok: function( result, msg ) {
+ if ( !config.current ) {
+ throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
+ }
+ result = !!result;
+ msg = msg || ( result ? "okay" : "failed" );
-function done() {
- config.autorun = true;
+ var source,
+ details = {
+ module: config.current.module,
+ name: config.current.testName,
+ result: result,
+ message: msg
+ };
- // Log the last module results
- if ( config.currentModule ) {
- QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
- }
+ msg = "" + escapeText( msg ) + "";
- var banner = id("qunit-banner"),
- tests = id("qunit-tests"),
- html = ['Tests completed in ',
- +new Date - config.started, ' milliseconds.
',
- '', config.stats.all - config.stats.bad, ' tests of ', config.stats.all, ' passed, ', config.stats.bad,' failed.'].join('');
+ if ( !result ) {
+ source = sourceFromStacktrace( 2 );
+ if ( source ) {
+ details.source = source;
+ msg += "| Source: | " +
+ escapeText( source ) +
+ " |
|---|
";
+ }
+ }
+ runLoggingCallbacks( "log", QUnit, details );
+ config.current.assertions.push({
+ result: result,
+ message: msg
+ });
+ },
- if ( banner ) {
- banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
- }
+ /**
+ * Assert that the first two arguments are equal, with an optional message.
+ * Prints out both actual and expected values.
+ * @name equal
+ * @function
+ * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
+ */
+ equal: function( actual, expected, message ) {
+ /*jshint eqeqeq:false */
+ QUnit.push( expected == actual, actual, expected, message );
+ },
- if ( tests ) {
- var result = id("qunit-testresult");
+ /**
+ * @name notEqual
+ * @function
+ */
+ notEqual: function( actual, expected, message ) {
+ /*jshint eqeqeq:false */
+ QUnit.push( expected != actual, actual, expected, message );
+ },
- if ( !result ) {
- result = document.createElement("p");
- result.id = "qunit-testresult";
- result.className = "result";
- tests.parentNode.insertBefore( result, tests.nextSibling );
- }
+ /**
+ * @name propEqual
+ * @function
+ */
+ propEqual: function( actual, expected, message ) {
+ actual = objectValues(actual);
+ expected = objectValues(expected);
+ QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
+ },
- result.innerHTML = html;
- }
+ /**
+ * @name notPropEqual
+ * @function
+ */
+ notPropEqual: function( actual, expected, message ) {
+ actual = objectValues(actual);
+ expected = objectValues(expected);
+ QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
+ },
- QUnit.done( config.stats.bad, config.stats.all );
-}
+ /**
+ * @name deepEqual
+ * @function
+ */
+ deepEqual: function( actual, expected, message ) {
+ QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
+ },
-function validTest( name ) {
- var i = config.filters.length,
- run = false;
+ /**
+ * @name notDeepEqual
+ * @function
+ */
+ notDeepEqual: function( actual, expected, message ) {
+ QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
+ },
- if ( !i ) {
- return true;
- }
-
- while ( i-- ) {
- var filter = config.filters[i],
- not = filter.charAt(0) == '!';
+ /**
+ * @name strictEqual
+ * @function
+ */
+ strictEqual: function( actual, expected, message ) {
+ QUnit.push( expected === actual, actual, expected, message );
+ },
- if ( not ) {
- filter = filter.slice(1);
- }
+ /**
+ * @name notStrictEqual
+ * @function
+ */
+ notStrictEqual: function( actual, expected, message ) {
+ QUnit.push( expected !== actual, actual, expected, message );
+ },
+
+ "throws": function( block, expected, message ) {
+ var actual,
+ expectedOutput = expected,
+ ok = false;
- if ( name.indexOf(filter) !== -1 ) {
- return !not;
+ // 'expected' is optional
+ if ( !message && typeof expected === "string" ) {
+ message = expected;
+ expected = null;
}
- if ( not ) {
- run = true;
+ config.current.ignoreGlobalErrors = true;
+ try {
+ block.call( config.current.testEnvironment );
+ } catch (e) {
+ actual = e;
}
- }
+ config.current.ignoreGlobalErrors = false;
- return run;
-}
+ if ( actual ) {
-// so far supports only Firefox, Chrome and Opera (buggy)
-// could be extended in the future to use something like https://github.com/csnover/TraceKit
-function sourceFromStacktrace() {
- try {
- throw new Error();
- } catch ( e ) {
- if (e.stacktrace) {
- // Opera
- return e.stacktrace.split("\n")[6];
- } else if (e.stack) {
- // Firefox, Chrome
- return e.stack.split("\n")[4];
- }
- }
-}
+ // we don't want to validate thrown error
+ if ( !expected ) {
+ ok = true;
+ expectedOutput = null;
-function resultDisplayStyle(passed) {
- return passed && id("qunit-filter-pass") && id("qunit-filter-pass").checked ? 'none' : '';
-}
+ // expected is an Error object
+ } else if ( expected instanceof Error ) {
+ ok = actual instanceof Error &&
+ actual.name === expected.name &&
+ actual.message === expected.message;
-function escapeHtml(s) {
- if (!s) {
- return "";
- }
- s = s + "";
- return s.replace(/[\&"<>\\]/g, function(s) {
- switch(s) {
- case "&": return "&";
- case "\\": return "\\\\";
- case '"': return '\"';
- case "<": return "<";
- case ">": return ">";
- default: return s;
- }
- });
-}
+ // expected is a regexp
+ } else if ( QUnit.objectType( expected ) === "regexp" ) {
+ ok = expected.test( errorString( actual ) );
-function synchronize( callback ) {
- config.queue.push( callback );
+ // expected is a string
+ } else if ( QUnit.objectType( expected ) === "string" ) {
+ ok = expected === errorString( actual );
- if ( config.autorun && !config.blocking ) {
- process();
- }
-}
+ // expected is a constructor
+ } else if ( actual instanceof expected ) {
+ ok = true;
-function process() {
- var start = (new Date()).getTime();
+ // expected is a validation function which returns true is validation passed
+ } else if ( expected.call( {}, actual ) === true ) {
+ expectedOutput = null;
+ ok = true;
+ }
- while ( config.queue.length && !config.blocking ) {
- if ( config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate) ) {
- config.queue.shift()();
+ QUnit.push( ok, actual, expectedOutput, message );
} else {
- window.setTimeout( process, 13 );
- break;
+ QUnit.pushFailure( message, null, "No exception was thrown." );
}
}
- if (!config.blocking && !config.queue.length) {
- done();
- }
-}
+};
-function saveGlobal() {
- config.pollution = [];
-
- if ( config.noglobals ) {
- for ( var key in window ) {
- config.pollution.push( key );
- }
- }
-}
+/**
+ * @deprecated since 1.8.0
+ * Kept assertion helpers in root for backwards compatibility.
+ */
+extend( QUnit.constructor.prototype, assert );
-function checkPollution( name ) {
- var old = config.pollution;
- saveGlobal();
-
- var newGlobals = diff( old, config.pollution );
- if ( newGlobals.length > 0 ) {
- ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
- config.current.expected++;
- }
+/**
+ * @deprecated since 1.9.0
+ * Kept to avoid TypeErrors for undefined methods.
+ */
+QUnit.constructor.prototype.raises = function() {
+ QUnit.push( false, false, false, "QUnit.raises has been deprecated since 2012 (fad3c1ea), use QUnit.throws instead" );
+};
- var deletedGlobals = diff( config.pollution, old );
- if ( deletedGlobals.length > 0 ) {
- ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
- config.current.expected++;
- }
-}
+/**
+ * @deprecated since 1.0.0, replaced with error pushes since 1.3.0
+ * Kept to avoid TypeErrors for undefined methods.
+ */
+QUnit.constructor.prototype.equals = function() {
+ QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
+};
+QUnit.constructor.prototype.same = function() {
+ QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
+};
-// returns a new Array with the elements that are in a but not in b
-function diff( a, b ) {
- var result = a.slice();
- for ( var i = 0; i < result.length; i++ ) {
- for ( var j = 0; j < b.length; j++ ) {
- if ( result[i] === b[j] ) {
- result.splice(i, 1);
- i--;
- break;
+// Test for equality any JavaScript type.
+// Author: Philippe Rathé
+QUnit.equiv = (function() {
+
+ // Call the o related callback with the given arguments.
+ function bindCallbacks( o, callbacks, args ) {
+ var prop = QUnit.objectType( o );
+ if ( prop ) {
+ if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
+ return callbacks[ prop ].apply( callbacks, args );
+ } else {
+ return callbacks[ prop ]; // or undefined
}
}
}
- return result;
-}
-function fail(message, exception, callback) {
- if ( typeof console !== "undefined" && console.error && console.warn ) {
- console.error(message);
- console.error(exception);
- console.warn(callback.toString());
+ // the real equiv function
+ var innerEquiv,
+ // stack to decide between skip/abort functions
+ callers = [],
+ // stack to avoiding loops from circular referencing
+ parents = [],
+ parentsB = [],
+
+ getProto = Object.getPrototypeOf || function ( obj ) {
+ /*jshint camelcase:false */
+ return obj.__proto__;
+ },
+ callbacks = (function () {
+
+ // for string, boolean, number and null
+ function useStrictEquality( b, a ) {
+ /*jshint eqeqeq:false */
+ if ( b instanceof a.constructor || a instanceof b.constructor ) {
+ // to catch short annotation VS 'new' annotation of a
+ // declaration
+ // e.g. var i = 1;
+ // var j = new Number(1);
+ return a == b;
+ } else {
+ return a === b;
+ }
+ }
- } else if ( window.opera && opera.postError ) {
- opera.postError(message, exception, callback.toString);
- }
-}
+ return {
+ "string": useStrictEquality,
+ "boolean": useStrictEquality,
+ "number": useStrictEquality,
+ "null": useStrictEquality,
+ "undefined": useStrictEquality,
+
+ "nan": function( b ) {
+ return isNaN( b );
+ },
+
+ "date": function( b, a ) {
+ return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
+ },
+
+ "regexp": function( b, a ) {
+ return QUnit.objectType( b ) === "regexp" &&
+ // the regex itself
+ a.source === b.source &&
+ // and its modifiers
+ a.global === b.global &&
+ // (gmi) ...
+ a.ignoreCase === b.ignoreCase &&
+ a.multiline === b.multiline &&
+ a.sticky === b.sticky;
+ },
+
+ // - skip when the property is a method of an instance (OOP)
+ // - abort otherwise,
+ // initial === would have catch identical references anyway
+ "function": function() {
+ var caller = callers[callers.length - 1];
+ return caller !== Object && typeof caller !== "undefined";
+ },
+
+ "array": function( b, a ) {
+ var i, j, len, loop, aCircular, bCircular;
+
+ // b could be an object literal here
+ if ( QUnit.objectType( b ) !== "array" ) {
+ return false;
+ }
-function extend(a, b) {
- for ( var prop in b ) {
- a[prop] = b[prop];
- }
+ len = a.length;
+ if ( len !== b.length ) {
+ // safe and faster
+ return false;
+ }
- return a;
-}
+ // track reference to avoid circular references
+ parents.push( a );
+ parentsB.push( b );
+ for ( i = 0; i < len; i++ ) {
+ loop = false;
+ for ( j = 0; j < parents.length; j++ ) {
+ aCircular = parents[j] === a[i];
+ bCircular = parentsB[j] === b[i];
+ if ( aCircular || bCircular ) {
+ if ( a[i] === b[i] || aCircular && bCircular ) {
+ loop = true;
+ } else {
+ parents.pop();
+ parentsB.pop();
+ return false;
+ }
+ }
+ }
+ if ( !loop && !innerEquiv(a[i], b[i]) ) {
+ parents.pop();
+ parentsB.pop();
+ return false;
+ }
+ }
+ parents.pop();
+ parentsB.pop();
+ return true;
+ },
+
+ "object": function( b, a ) {
+ /*jshint forin:false */
+ var i, j, loop, aCircular, bCircular,
+ // Default to true
+ eq = true,
+ aProperties = [],
+ bProperties = [];
+
+ // comparing constructors is more strict than using
+ // instanceof
+ if ( a.constructor !== b.constructor ) {
+ // Allow objects with no prototype to be equivalent to
+ // objects with Object as their constructor.
+ if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) ||
+ ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) {
+ return false;
+ }
+ }
-function addEvent(elem, type, fn) {
- if ( elem.addEventListener ) {
- elem.addEventListener( type, fn, false );
- } else if ( elem.attachEvent ) {
- elem.attachEvent( "on" + type, fn );
- } else {
- fn();
- }
-}
+ // stack constructor before traversing properties
+ callers.push( a.constructor );
+
+ // track reference to avoid circular references
+ parents.push( a );
+ parentsB.push( b );
+
+ // be strict: don't ensure hasOwnProperty and go deep
+ for ( i in a ) {
+ loop = false;
+ for ( j = 0; j < parents.length; j++ ) {
+ aCircular = parents[j] === a[i];
+ bCircular = parentsB[j] === b[i];
+ if ( aCircular || bCircular ) {
+ if ( a[i] === b[i] || aCircular && bCircular ) {
+ loop = true;
+ } else {
+ eq = false;
+ break;
+ }
+ }
+ }
+ aProperties.push(i);
+ if ( !loop && !innerEquiv(a[i], b[i]) ) {
+ eq = false;
+ break;
+ }
+ }
-function id(name) {
- return !!(typeof document !== "undefined" && document && document.getElementById) &&
- document.getElementById( name );
-}
+ parents.pop();
+ parentsB.pop();
+ callers.pop(); // unstack, we are done
-// Test for equality any JavaScript type.
-// Discussions and reference: http://philrathe.com/articles/equiv
-// Test suites: http://philrathe.com/tests/equiv
-// Author: Philippe Rathé
-QUnit.equiv = function () {
-
- var innerEquiv; // the real equiv function
- var callers = []; // stack to decide between skip/abort functions
- var parents = []; // stack to avoiding loops from circular referencing
-
- // Call the o related callback with the given arguments.
- function bindCallbacks(o, callbacks, args) {
- var prop = QUnit.objectType(o);
- if (prop) {
- if (QUnit.objectType(callbacks[prop]) === "function") {
- return callbacks[prop].apply(callbacks, args);
- } else {
- return callbacks[prop]; // or undefined
- }
- }
- }
-
- var callbacks = function () {
-
- // for string, boolean, number and null
- function useStrictEquality(b, a) {
- if (b instanceof a.constructor || a instanceof b.constructor) {
- // to catch short annotaion VS 'new' annotation of a declaration
- // e.g. var i = 1;
- // var j = new Number(1);
- return a == b;
- } else {
- return a === b;
- }
- }
-
- return {
- "string": useStrictEquality,
- "boolean": useStrictEquality,
- "number": useStrictEquality,
- "null": useStrictEquality,
- "undefined": useStrictEquality,
-
- "nan": function (b) {
- return isNaN(b);
- },
-
- "date": function (b, a) {
- return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf();
- },
-
- "regexp": function (b, a) {
- return QUnit.objectType(b) === "regexp" &&
- a.source === b.source && // the regex itself
- a.global === b.global && // and its modifers (gmi) ...
- a.ignoreCase === b.ignoreCase &&
- a.multiline === b.multiline;
- },
-
- // - skip when the property is a method of an instance (OOP)
- // - abort otherwise,
- // initial === would have catch identical references anyway
- "function": function () {
- var caller = callers[callers.length - 1];
- return caller !== Object &&
- typeof caller !== "undefined";
- },
-
- "array": function (b, a) {
- var i, j, loop;
- var len;
-
- // b could be an object literal here
- if ( ! (QUnit.objectType(b) === "array")) {
- return false;
- }
-
- len = a.length;
- if (len !== b.length) { // safe and faster
- return false;
- }
-
- //track reference to avoid circular references
- parents.push(a);
- for (i = 0; i < len; i++) {
- loop = false;
- for(j=0;j< 2) {
- return true; // end transition
- }
-
- return (function (a, b) {
- if (a === b) {
- return true; // catch the most you can
- } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) {
- return false; // don't lose time with error prone cases
- } else {
- return bindCallbacks(a, callbacks, [b, a]);
- }
-
- // apply transition with (1..n) arguments
- })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
- };
-
- return innerEquiv;
-
-}();
+ for ( i in b ) {
+ bProperties.push( i ); // collect b's properties
+ }
+
+ // Ensures identical properties name
+ return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
+ }
+ };
+ }());
+
+ innerEquiv = function() { // can take multiple arguments
+ var args = [].slice.apply( arguments );
+ if ( args.length < 2 ) {
+ return true; // end transition
+ }
+
+ return (function( a, b ) {
+ if ( a === b ) {
+ return true; // catch the most you can
+ } else if ( a === null || b === null || typeof a === "undefined" ||
+ typeof b === "undefined" ||
+ QUnit.objectType(a) !== QUnit.objectType(b) ) {
+ return false; // don't lose time with error prone cases
+ } else {
+ return bindCallbacks(a, callbacks, [ b, a ]);
+ }
+
+ // apply transition with (1..n) arguments
+ }( args[0], args[1] ) && innerEquiv.apply( this, args.splice(1, args.length - 1 )) );
+ };
+
+ return innerEquiv;
+}());
/**
- * jsDump
- * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
- * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
- * Date: 5/15/2008
+ * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
+ * http://flesler.blogspot.com Licensed under BSD
+ * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
+ *
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
@@ -1054,185 +1903,224 @@ QUnit.equiv = function () {
*/
QUnit.jsDump = (function() {
function quote( str ) {
- return '"' + str.toString().replace(/"/g, '\\"') + '"';
- };
+ return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\"";
+ }
function literal( o ) {
- return o + '';
- };
+ return o + "";
+ }
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
- if ( arr.join )
- arr = arr.join( ',' + s + inner );
- if ( !arr )
+ if ( arr.join ) {
+ arr = arr.join( "," + s + inner );
+ }
+ if ( !arr ) {
return pre + post;
+ }
return [ pre, inner + arr, base + post ].join(s);
- };
- function array( arr ) {
- var i = arr.length, ret = Array(i);
+ }
+ function array( arr, stack ) {
+ var i = arr.length, ret = new Array(i);
this.up();
- while ( i-- )
- ret[i] = this.parse( arr[i] );
+ while ( i-- ) {
+ ret[i] = this.parse( arr[i] , undefined , stack);
+ }
this.down();
- return join( '[', ret, ']' );
- };
-
- var reName = /^function (\w+)/;
-
- var jsDump = {
- parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
- var parser = this.parsers[ type || this.typeOf(obj) ];
- type = typeof parser;
-
- return type == 'function' ? parser.call( this, obj ) :
- type == 'string' ? parser :
- this.parsers.error;
- },
- typeOf:function( obj ) {
- var type;
- if ( obj === null ) {
- type = "null";
- } else if (typeof obj === "undefined") {
- type = "undefined";
- } else if (QUnit.is("RegExp", obj)) {
- type = "regexp";
- } else if (QUnit.is("Date", obj)) {
- type = "date";
- } else if (QUnit.is("Function", obj)) {
- type = "function";
- } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
- type = "window";
- } else if (obj.nodeType === 9) {
- type = "document";
- } else if (obj.nodeType) {
- type = "node";
- } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) {
- type = "array";
- } else {
- type = typeof obj;
- }
- return type;
- },
- separator:function() {
- return this.multiline ? this.HTML ? '
' : '\n' : this.HTML ? ' ' : ' ';
- },
- indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
- if ( !this.multiline )
- return '';
- var chr = this.indentChar;
- if ( this.HTML )
- chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
- return Array( this._depth_ + (extra||0) ).join(chr);
- },
- up:function( a ) {
- this._depth_ += a || 1;
- },
- down:function( a ) {
- this._depth_ -= a || 1;
- },
- setParser:function( name, parser ) {
- this.parsers[name] = parser;
- },
- // The next 3 are exposed so you can use them
- quote:quote,
- literal:literal,
- join:join,
- //
- _depth_: 1,
- // This is the list of parsers, to modify them, use jsDump.setParser
- parsers:{
- window: '[Window]',
- document: '[Document]',
- error:'[ERROR]', //when no parser is found, shouldn't happen
- unknown: '[Unknown]',
- 'null':'null',
- undefined:'undefined',
- 'function':function( fn ) {
- var ret = 'function',
- name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
- if ( name )
- ret += ' ' + name;
- ret += '(';
-
- ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
- return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
+ return join( "[", ret, "]" );
+ }
+
+ var reName = /^function (\w+)/,
+ jsDump = {
+ // type is used mostly internally, you can fix a (custom)type in advance
+ parse: function( obj, type, stack ) {
+ stack = stack || [ ];
+ var inStack, res,
+ parser = this.parsers[ type || this.typeOf(obj) ];
+
+ type = typeof parser;
+ inStack = inArray( obj, stack );
+
+ if ( inStack !== -1 ) {
+ return "recursion(" + (inStack - stack.length) + ")";
+ }
+ if ( type === "function" ) {
+ stack.push( obj );
+ res = parser.call( this, obj, stack );
+ stack.pop();
+ return res;
+ }
+ return ( type === "string" ) ? parser : this.parsers.error;
+ },
+ typeOf: function( obj ) {
+ var type;
+ if ( obj === null ) {
+ type = "null";
+ } else if ( typeof obj === "undefined" ) {
+ type = "undefined";
+ } else if ( QUnit.is( "regexp", obj) ) {
+ type = "regexp";
+ } else if ( QUnit.is( "date", obj) ) {
+ type = "date";
+ } else if ( QUnit.is( "function", obj) ) {
+ type = "function";
+ } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) {
+ type = "window";
+ } else if ( obj.nodeType === 9 ) {
+ type = "document";
+ } else if ( obj.nodeType ) {
+ type = "node";
+ } else if (
+ // native arrays
+ toString.call( obj ) === "[object Array]" ||
+ // NodeList objects
+ ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
+ ) {
+ type = "array";
+ } else if ( obj.constructor === Error.prototype.constructor ) {
+ type = "error";
+ } else {
+ type = typeof obj;
+ }
+ return type;
},
- array: array,
- nodelist: array,
- arguments: array,
- object:function( map ) {
- var ret = [ ];
- QUnit.jsDump.up();
- for ( var key in map )
- ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(map[key]) );
- QUnit.jsDump.down();
- return join( '{', ret, '}' );
+ separator: function() {
+ return this.multiline ? this.HTML ? "
" : "\n" : this.HTML ? " " : " ";
},
- node:function( node ) {
- var open = QUnit.jsDump.HTML ? '<' : '<',
- close = QUnit.jsDump.HTML ? '>' : '>';
-
- var tag = node.nodeName.toLowerCase(),
- ret = open + tag;
-
- for ( var a in QUnit.jsDump.DOMAttrs ) {
- var val = node[QUnit.jsDump.DOMAttrs[a]];
- if ( val )
- ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
+ // extra can be a number, shortcut for increasing-calling-decreasing
+ indent: function( extra ) {
+ if ( !this.multiline ) {
+ return "";
}
- return ret + close + open + '/' + tag + close;
+ var chr = this.indentChar;
+ if ( this.HTML ) {
+ chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
+ }
+ return new Array( this.depth + ( extra || 0 ) ).join(chr);
},
- functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
- var l = fn.length;
- if ( !l ) return '';
-
- var args = Array(l);
- while ( l-- )
- args[l] = String.fromCharCode(97+l);//97 is 'a'
- return ' ' + args.join(', ') + ' ';
+ up: function( a ) {
+ this.depth += a || 1;
},
- key:quote, //object calls it internally, the key part of an item in a map
- functionCode:'[code]', //function calls it internally, it's the content of the function
- attribute:quote, //node calls it internally, it's an html attribute value
- string:quote,
- date:quote,
- regexp:literal, //regex
- number:literal,
- 'boolean':literal
- },
- DOMAttrs:{//attributes to dump from nodes, name=>realName
- id:'id',
- name:'name',
- 'class':'className'
- },
- HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
- indentChar:' ',//indentation unit
- multiline:true //if true, items in a collection, are separated by a \n, else just a space.
- };
-
- return jsDump;
-})();
+ down: function( a ) {
+ this.depth -= a || 1;
+ },
+ setParser: function( name, parser ) {
+ this.parsers[name] = parser;
+ },
+ // The next 3 are exposed so you can use them
+ quote: quote,
+ literal: literal,
+ join: join,
+ //
+ depth: 1,
+ // This is the list of parsers, to modify them, use jsDump.setParser
+ parsers: {
+ window: "[Window]",
+ document: "[Document]",
+ error: function(error) {
+ return "Error(\"" + error.message + "\")";
+ },
+ unknown: "[Unknown]",
+ "null": "null",
+ "undefined": "undefined",
+ "function": function( fn ) {
+ var ret = "function",
+ // functions never have name in IE
+ name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
+
+ if ( name ) {
+ ret += " " + name;
+ }
+ ret += "( ";
+
+ ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" );
+ return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" );
+ },
+ array: array,
+ nodelist: array,
+ "arguments": array,
+ object: function( map, stack ) {
+ /*jshint forin:false */
+ var ret = [ ], keys, key, val, i;
+ QUnit.jsDump.up();
+ keys = [];
+ for ( key in map ) {
+ keys.push( key );
+ }
+ keys.sort();
+ for ( i = 0; i < keys.length; i++ ) {
+ key = keys[ i ];
+ val = map[ key ];
+ ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) );
+ }
+ QUnit.jsDump.down();
+ return join( "{", ret, "}" );
+ },
+ node: function( node ) {
+ var len, i, val,
+ open = QUnit.jsDump.HTML ? "<" : "<",
+ close = QUnit.jsDump.HTML ? ">" : ">",
+ tag = node.nodeName.toLowerCase(),
+ ret = open + tag,
+ attrs = node.attributes;
+
+ if ( attrs ) {
+ for ( i = 0, len = attrs.length; i < len; i++ ) {
+ val = attrs[i].nodeValue;
+ // IE6 includes all attributes in .attributes, even ones not explicitly set.
+ // Those have values like undefined, null, 0, false, "" or "inherit".
+ if ( val && val !== "inherit" ) {
+ ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" );
+ }
+ }
+ }
+ ret += close;
-// from Sizzle.js
-function getText( elems ) {
- var ret = "", elem;
+ // Show content of TextNode or CDATASection
+ if ( node.nodeType === 3 || node.nodeType === 4 ) {
+ ret += node.nodeValue;
+ }
- for ( var i = 0; elems[i]; i++ ) {
- elem = elems[i];
+ return ret + open + "/" + tag + close;
+ },
+ // function calls it internally, it's the arguments part of the function
+ functionArgs: function( fn ) {
+ var args,
+ l = fn.length;
- // Get the text from text nodes and CDATA nodes
- if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
- ret += elem.nodeValue;
+ if ( !l ) {
+ return "";
+ }
- // Traverse everything else, except comment nodes
- } else if ( elem.nodeType !== 8 ) {
- ret += getText( elem.childNodes );
- }
- }
+ args = new Array(l);
+ while ( l-- ) {
+ // 97 is 'a'
+ args[l] = String.fromCharCode(97+l);
+ }
+ return " " + args.join( ", " ) + " ";
+ },
+ // object calls it internally, the key part of an item in a map
+ key: quote,
+ // function calls it internally, it's the content of the function
+ functionCode: "[code]",
+ // node calls it internally, it's an html attribute value
+ attribute: quote,
+ string: quote,
+ date: quote,
+ regexp: literal,
+ number: literal,
+ "boolean": literal
+ },
+ // if true, entities are escaped ( <, >, \t, space and \n )
+ HTML: false,
+ // indentation unit
+ indentChar: " ",
+ // if true, items in a collection, are separated by a \n, else just a space.
+ multiline: true
+ };
- return ret;
-};
+ return jsDump;
+}());
/*
* Javascript Diff Algorithm
@@ -1243,132 +2131,158 @@ function getText( elems ) {
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
- *
+ *
* Usage: QUnit.diff(expected, actual)
- *
- * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick brown fox jumped jumps over"
+ *
+ * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over"
*/
QUnit.diff = (function() {
- function diff(o, n){
- var ns = new Object();
- var os = new Object();
-
- for (var i = 0; i < n.length; i++) {
- if (ns[n[i]] == null)
- ns[n[i]] = {
- rows: new Array(),
+ /*jshint eqeqeq:false, eqnull:true */
+ function diff( o, n ) {
+ var i,
+ ns = {},
+ os = {};
+
+ for ( i = 0; i < n.length; i++ ) {
+ if ( !hasOwn.call( ns, n[i] ) ) {
+ ns[ n[i] ] = {
+ rows: [],
o: null
};
- ns[n[i]].rows.push(i);
+ }
+ ns[ n[i] ].rows.push( i );
}
-
- for (var i = 0; i < o.length; i++) {
- if (os[o[i]] == null)
- os[o[i]] = {
- rows: new Array(),
+
+ for ( i = 0; i < o.length; i++ ) {
+ if ( !hasOwn.call( os, o[i] ) ) {
+ os[ o[i] ] = {
+ rows: [],
n: null
};
- os[o[i]].rows.push(i);
- }
-
- for (var i in ns) {
- if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
- n[ns[i].rows[0]] = {
- text: n[ns[i].rows[0]],
- row: os[i].rows[0]
- };
- o[os[i].rows[0]] = {
- text: o[os[i].rows[0]],
- row: ns[i].rows[0]
- };
+ }
+ os[ o[i] ].rows.push( i );
+ }
+
+ for ( i in ns ) {
+ if ( hasOwn.call( ns, i ) ) {
+ if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) {
+ n[ ns[i].rows[0] ] = {
+ text: n[ ns[i].rows[0] ],
+ row: os[i].rows[0]
+ };
+ o[ os[i].rows[0] ] = {
+ text: o[ os[i].rows[0] ],
+ row: ns[i].rows[0]
+ };
+ }
}
}
-
- for (var i = 0; i < n.length - 1; i++) {
- if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
- n[i + 1] == o[n[i].row + 1]) {
- n[i + 1] = {
- text: n[i + 1],
+
+ for ( i = 0; i < n.length - 1; i++ ) {
+ if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null &&
+ n[ i + 1 ] == o[ n[i].row + 1 ] ) {
+
+ n[ i + 1 ] = {
+ text: n[ i + 1 ],
row: n[i].row + 1
};
- o[n[i].row + 1] = {
- text: o[n[i].row + 1],
+ o[ n[i].row + 1 ] = {
+ text: o[ n[i].row + 1 ],
row: i + 1
};
}
}
-
- for (var i = n.length - 1; i > 0; i--) {
- if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
- n[i - 1] == o[n[i].row - 1]) {
- n[i - 1] = {
- text: n[i - 1],
+
+ for ( i = n.length - 1; i > 0; i-- ) {
+ if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null &&
+ n[ i - 1 ] == o[ n[i].row - 1 ]) {
+
+ n[ i - 1 ] = {
+ text: n[ i - 1 ],
row: n[i].row - 1
};
- o[n[i].row - 1] = {
- text: o[n[i].row - 1],
+ o[ n[i].row - 1 ] = {
+ text: o[ n[i].row - 1 ],
row: i - 1
};
}
}
-
+
return {
o: o,
n: n
};
}
-
- return function(o, n){
- o = o.replace(/\s+$/, '');
- n = n.replace(/\s+$/, '');
- var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
-
- var str = "";
-
- var oSpace = o.match(/\s+/g);
- if (oSpace == null) {
- oSpace = [" "];
+
+ return function( o, n ) {
+ o = o.replace( /\s+$/, "" );
+ n = n.replace( /\s+$/, "" );
+
+ var i, pre,
+ str = "",
+ out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ),
+ oSpace = o.match(/\s+/g),
+ nSpace = n.match(/\s+/g);
+
+ if ( oSpace == null ) {
+ oSpace = [ " " ];
}
else {
- oSpace.push(" ");
+ oSpace.push( " " );
}
- var nSpace = n.match(/\s+/g);
- if (nSpace == null) {
- nSpace = [" "];
+
+ if ( nSpace == null ) {
+ nSpace = [ " " ];
}
else {
- nSpace.push(" ");
+ nSpace.push( " " );
}
-
- if (out.n.length == 0) {
- for (var i = 0; i < out.o.length; i++) {
- str += '' + out.o[i] + oSpace[i] + "";
+
+ if ( out.n.length === 0 ) {
+ for ( i = 0; i < out.o.length; i++ ) {
+ str += "" + out.o[i] + oSpace[i] + "";
}
}
else {
- if (out.n[0].text == null) {
- for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
- str += '' + out.o[n] + oSpace[n] + "";
+ if ( out.n[0].text == null ) {
+ for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) {
+ str += "" + out.o[n] + oSpace[n] + "";
}
}
-
- for (var i = 0; i < out.n.length; i++) {
+
+ for ( i = 0; i < out.n.length; i++ ) {
if (out.n[i].text == null) {
- str += '' + out.n[i] + nSpace[i] + "";
+ str += "" + out.n[i] + nSpace[i] + "";
}
else {
- var pre = "";
-
- for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
- pre += '' + out.o[n] + oSpace[n] + "";
+ // `pre` initialized at top of scope
+ pre = "";
+
+ for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) {
+ pre += "" + out.o[n] + oSpace[n] + "";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
-
+
return str;
};
-})();
+}());
+
+// For browser, export only select globals
+if ( typeof window !== "undefined" ) {
+ extend( window, QUnit.constructor.prototype );
+ window.QUnit = QUnit;
+}
+
+// For CommonJS environments, export everything
+if ( typeof module !== "undefined" && module.exports ) {
+ module.exports = QUnit;
+}
+
-})(this);
+// Get a reference to the global object, like window in browsers
+}( (function() {
+ return this;
+})() ));
From 328892c9c6068834ab396ed9a0fc4bd23d36ea2f Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Fri, 4 Apr 2014 19:45:09 -0300
Subject: [PATCH 020/100] Document support for jQuery 2.0 and 2.1.
---
README.md | 2 +-
bower.json | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/README.md b/README.md
index d2442a5e..8df8340d 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@ Full [documentation is on the wiki][wiki], including the [list of published Ajax
Requirements
------------
-- [jQuery 1.8.x or higher and less than 2.0][jquery];
+- [jQuery 1.8.x or higher][jquery];
- HTML5 doctype (optional).
If you don't use HTML5, adding "data" attributes to your HTML4 or XHTML pages might make them fail [W3C markup validation][validator]. However, this shouldn't create any issues for web browsers or other user agents.
diff --git a/bower.json b/bower.json
index ecbb1382..19c1332a 100644
--- a/bower.json
+++ b/bower.json
@@ -6,7 +6,7 @@
"main": "src/rails.js",
"license": "MIT",
"dependencies": {
- "jquery": ">1.7.* <2.0.0"
+ "jquery": ">1.8.*"
},
"ignore": [
"**/.*",
From 162f6fbdcd9f58ebc9d11b2638eac7495daa8a7f Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Thu, 7 Nov 2013 15:35:47 -0200
Subject: [PATCH 021/100] Add a script to run the test suite through PhantomJS
on Travis.
---
.gitignore | 1 +
.travis.yml | 15 +++
script/cibuild | 40 ++++++
script/runner.js | 148 ++++++++++++++++++++++
test/public/test/call-remote-callbacks.js | 28 ++--
test/public/test/data-confirm.js | 1 -
test/server.rb | 2 +-
7 files changed, 220 insertions(+), 15 deletions(-)
create mode 100644 .travis.yml
create mode 100755 script/cibuild
create mode 100644 script/runner.js
diff --git a/.gitignore b/.gitignore
index 3330f6be..251f2cfc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
test/public/vendor/jquery.js
+node_modules
*.swp
*.swo
.#*
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 00000000..8b7d9259
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,15 @@
+language: ruby
+script: ./script/cibuild
+env:
+ - JQUERY_VERSION: 1.8.0
+ - JQUERY_VERSION: 1.8.1
+ - JQUERY_VERSION: 1.8.2
+ - JQUERY_VERSION: 1.8.3
+ - JQUERY_VERSION: 1.9.0
+ - JQUERY_VERSION: 1.9.1
+ - JQUERY_VERSION: 1.10.0
+ - JQUERY_VERSION: 1.10.1
+ - JQUERY_VERSION: 1.10.2
+ - JQUERY_VERSION: 1.11.0
+ - JQUERY_VERSION: 2.0.0
+ - JQUERY_VERSION: 2.1.0
diff --git a/script/cibuild b/script/cibuild
new file mode 100755
index 00000000..cc661ece
--- /dev/null
+++ b/script/cibuild
@@ -0,0 +1,40 @@
+#!/bin/bash
+
+port=4567
+
+start_server() {
+ mkdir -p log
+ bundle exec ruby test/server.rb > log/test.log 2>&1 &
+}
+
+run_tests() {
+ phantomjs script/runner.js http://localhost:$port/
+}
+
+server_started() {
+ lsof -i :${1?} >/dev/null
+}
+
+timestamp() {
+ date +%s
+}
+
+wait_for_server() {
+ timeout=$(( `timestamp` + $1 ))
+ while true; do
+ if server_started "$2"; then
+ break
+ elif [ `timestamp` -gt "$timeout" ]; then
+ echo "timed out after $1 seconds" >&2
+ exit 1
+ fi
+ done
+}
+
+start_server
+server_pid=$!
+wait_for_server 5 $port
+run_tests
+result=$?
+kill $server_pid
+exit $result
diff --git a/script/runner.js b/script/runner.js
new file mode 100644
index 00000000..5d9f96c5
--- /dev/null
+++ b/script/runner.js
@@ -0,0 +1,148 @@
+/*
+ * PhantomJS Runner QUnit Plugin 1.2.0
+ *
+ * PhantomJS binaries: http://phantomjs.org/download.html
+ * Requires PhantomJS 1.6+ (1.7+ recommended)
+ *
+ * Run with:
+ * phantomjs runner.js [url-of-your-qunit-testsuite]
+ *
+ * e.g.
+ * phantomjs runner.js http://localhost/qunit/test/index.html
+ */
+
+/*global phantom:false, require:false, console:false, window:false, QUnit:false */
+
+(function() {
+ 'use strict';
+
+ var url, page, timeout,
+ args = require('system').args;
+
+ // arg[0]: scriptName, args[1...]: arguments
+ if (args.length < 2 || args.length > 3) {
+ console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite] [timeout-in-seconds]');
+ phantom.exit(1);
+ }
+
+ url = args[1];
+ page = require('webpage').create();
+ if (args[2] !== undefined) {
+ timeout = parseInt(args[2], 10);
+ }
+
+ // Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`)
+ page.onConsoleMessage = function(msg) {
+ console.log(msg);
+ };
+
+ page.onInitialized = function() {
+ page.evaluate(addLogging);
+ };
+
+ page.onCallback = function(message) {
+ var result,
+ failed;
+
+ if (message) {
+ if (message.name === 'QUnit.done') {
+ result = message.data;
+ failed = !result || !result.total || result.failed;
+
+ if (!result.total) {
+ console.error('No tests were executed. Are you loading tests asynchronously?');
+ }
+
+ phantom.exit(failed ? 1 : 0);
+ }
+ }
+ };
+
+ page.open(url, function(status) {
+ if (status !== 'success') {
+ console.error('Unable to access network: ' + status);
+ phantom.exit(1);
+ } else {
+ // Cannot do this verification with the 'DOMContentLoaded' handler because it
+ // will be too late to attach it if a page does not have any script tags.
+ var qunitMissing = page.evaluate(function() { return (typeof QUnit === 'undefined' || !QUnit); });
+ if (qunitMissing) {
+ console.error('The `QUnit` object is not present on this page.');
+ phantom.exit(1);
+ }
+
+ // Set a timeout on the test running, otherwise tests with async problems will hang forever
+ if (typeof timeout === 'number') {
+ setTimeout(function() {
+ console.error('The specified timeout of ' + timeout + ' seconds has expired. Aborting...');
+ phantom.exit(1);
+ }, timeout * 1000);
+ }
+
+ // Do nothing... the callback mechanism will handle everything!
+ }
+ });
+
+ function addLogging() {
+ window.document.addEventListener('DOMContentLoaded', function() {
+ var currentTestAssertions = [];
+
+ QUnit.log(function(details) {
+ var response;
+
+ // Ignore passing assertions
+ if (details.result) {
+ return;
+ }
+
+ response = details.message || '';
+
+ if (typeof details.expected !== 'undefined') {
+ if (response) {
+ response += ', ';
+ }
+
+ response += 'expected: ' + details.expected + ', but was: ' + details.actual;
+ }
+
+ if (details.source) {
+ response += "\n" + details.source;
+ }
+
+ currentTestAssertions.push('Failed assertion: ' + response);
+ });
+
+ QUnit.testDone(function(result) {
+ var i,
+ len,
+ name = '';
+
+ if (result.module) {
+ name += result.module + ': ';
+ }
+ name += result.name;
+
+ if (result.failed) {
+ console.log('\n' + 'Test failed: ' + name);
+
+ for (i = 0, len = currentTestAssertions.length; i < len; i++) {
+ console.log(' ' + currentTestAssertions[i]);
+ }
+ }
+
+ currentTestAssertions.length = 0;
+ });
+
+ QUnit.done(function(result) {
+ console.log('\n' + 'Took ' + result.runtime + 'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.');
+
+ if (typeof window.callPhantom === 'function') {
+ window.callPhantom({
+ 'name': 'QUnit.done',
+ 'data': result
+ });
+ }
+ });
+ }, false);
+ }
+})();
diff --git a/test/public/test/call-remote-callbacks.js b/test/public/test/call-remote-callbacks.js
index fa785be9..c1791f6b 100644
--- a/test/public/test/call-remote-callbacks.js
+++ b/test/public/test/call-remote-callbacks.js
@@ -352,21 +352,23 @@ asyncTest('"ajax:beforeSend", "ajax:send", "ajax:success" and "ajax:complete" ar
});
});
-asyncTest('"ajax:beforeSend", "ajax:send", "ajax:error" and "ajax:complete" are triggered on error', 7, function() {
- submit(function(form) {
- form.attr('action', '/error');
- form.bind('ajax:beforeSend', function(arg) { ok(true, 'ajax:beforeSend') });
- form.bind('ajax:send', function(arg) { ok(true, 'ajax:send') });
- form.bind('ajax:error', function(e, xhr, status, error) {
- ok(xhr.getResponseHeader, 'first argument to "ajax:error" should be an XHR object');
- equal(status, 'error', 'second argument to ajax:error should be a status string');
- // Firefox 8 returns "Forbidden " with trailing space
- equal($.trim(error), 'Forbidden', 'third argument to ajax:error should be an HTTP status response');
- // Opera returns "0" for HTTP code
- equal(xhr.status, window.opera ? 0 : 403, 'status code should be 403');
+if(window.phantom !== undefined) {
+ asyncTest('"ajax:beforeSend", "ajax:send", "ajax:error" and "ajax:complete" are triggered on error', 7, function() {
+ submit(function(form) {
+ form.attr('action', '/error');
+ form.bind('ajax:beforeSend', function(arg) { ok(true, 'ajax:beforeSend') });
+ form.bind('ajax:send', function(arg) { ok(true, 'ajax:send') });
+ form.bind('ajax:error', function(e, xhr, status, error) {
+ ok(xhr.getResponseHeader, 'first argument to "ajax:error" should be an XHR object');
+ equal(status, 'error', 'second argument to ajax:error should be a status string');
+ // Firefox 8 returns "Forbidden " with trailing space
+ equal($.trim(error), 'Forbidden', 'third argument to ajax:error should be an HTTP status response');
+ // Opera returns "0" for HTTP code
+ equal(xhr.status, window.opera ? 0 : 403, 'status code should be 403');
+ });
});
});
-});
+}
// IF THIS TEST IS FAILING, TRY INCREASING THE TIMEOUT AT THE BOTTOM TO > 100
asyncTest('binding to ajax callbacks via .delegate() triggers handlers properly', 4, function() {
diff --git a/test/public/test/data-confirm.js b/test/public/test/data-confirm.js
index cf95b20b..b84dd280 100644
--- a/test/public/test/data-confirm.js
+++ b/test/public/test/data-confirm.js
@@ -53,7 +53,6 @@ asyncTest('clicking on a button with data-confirm attribute. Confirm yes.', 6, f
ok(data == true, 'confirm:complete passes in confirm answer (true)');
})
.bind('ajax:success', function(e, data, status, xhr) {
- console.log(xhr);
App.assertCallbackInvoked('ajax:success');
App.assertRequestPath(data, '/echo');
App.assertGetRequest(data);
diff --git a/test/server.rb b/test/server.rb
index bb42f593..85f11db2 100644
--- a/test/server.rb
+++ b/test/server.rb
@@ -48,7 +48,7 @@ def jquery_versions
end
get '/' do
- params[:version] ||= '1.11.0'
+ params[:version] ||= ENV['JQUERY_VERSION'] || '1.11.0'
params[:cdn] ||= 'jquery'
erb :index
end
From 24917cd930b5c4238c1a535a1f7e3fb4f628deef Mon Sep 17 00:00:00 2001
From: "Andrew S. Brown"
Date: Thu, 20 Mar 2014 16:16:43 -0700
Subject: [PATCH 022/100] add disable-with support for standalone remote
buttons
---
src/rails.js | 40 ++++++++++++----
test/public/test/data-disable.js | 80 +++++++++++++++++++++++++++++++-
2 files changed, 110 insertions(+), 10 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index 9ba2e0a2..3e1b5825 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -51,6 +51,9 @@
// Link onClick disable selector with possible reenable after remote submission
linkDisableSelector: 'a[data-disable-with]',
+ // Button onClick disable selector with possible reenable after remote submission
+ buttonDisableSelector: 'button[data-remote][data-disable-with]',
+
// Make sure that every Ajax request sends the CSRF token
CSRFProtection: function(xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
@@ -199,25 +202,33 @@
*/
disableFormElements: function(form) {
rails.formElements(form, rails.disableSelector).each(function() {
- var element = $(this), method = element.is('button') ? 'html' : 'val';
- element.data('ujs:enable-with', element[method]());
- element[method](element.data('disable-with'));
- element.prop('disabled', true);
+ rails.disableFormElement($(this));
});
},
+ disableFormElement: function(element) {
+ var method = element.is('button') ? 'html' : 'val';
+ element.data('ujs:enable-with', element[method]());
+ element[method](element.data('disable-with'));
+ element.prop('disabled', true);
+ },
+
/* Re-enables disabled form elements:
- Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
- Sets disabled property to false
*/
enableFormElements: function(form) {
rails.formElements(form, rails.enableSelector).each(function() {
- var element = $(this), method = element.is('button') ? 'html' : 'val';
- if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
- element.prop('disabled', false);
+ rails.enableFormElement($(this));
});
},
+ enableFormElement: function(element) {
+ var method = element.is('button') ? 'html' : 'val';
+ if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
+ element.prop('disabled', false);
+ },
+
/* For 'data-confirm' attribute:
- Fires `confirm` event
- Shows the confirmation dialog
@@ -293,7 +304,6 @@
}
element.unbind('click.railsDisable'); // enable element
}
-
};
if (rails.fire($document, 'rails:attachBindings')) {
@@ -304,6 +314,10 @@
rails.enableElement($(this));
});
+ $document.delegate(rails.buttonDisableSelector, 'ajax:complete', function() {
+ rails.enableFormElement($(this));
+ });
+
$document.delegate(rails.linkClickSelector, 'click.rails', function(e) {
var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey;
if (!rails.allowAction(link)) return rails.stopEverything(e);
@@ -332,7 +346,15 @@
var button = $(this);
if (!rails.allowAction(button)) return rails.stopEverything(e);
- rails.handleRemote(button);
+ if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button);
+
+ var handleRemote = rails.handleRemote(button);
+ // response from rails.handleRemote() will either be false or a deferred object promise.
+ if (handleRemote === false) {
+ rails.enableFormElement(button);
+ } else {
+ handleRemote.error( function() { rails.enableFormElement(button); } );
+ }
return false;
});
diff --git a/test/public/test/data-disable.js b/test/public/test/data-disable.js
index 07720939..ab8848ef 100644
--- a/test/public/test/data-disable.js
+++ b/test/public/test/data-disable.js
@@ -22,7 +22,7 @@ module('data-disable', {
href: '/echo',
'data-disable-with': 'clicking...'
}));
-
+
$('#qunit-fixture').append($('', {
type: 'submit',
form: 'not_remote',
@@ -30,6 +30,13 @@ module('data-disable', {
name: 'submit3',
value: 'Form Attr Submit'
}));
+
+ $('#qunit-fixture').append($('', {
+ text: 'Click me',
+ 'data-remote': true,
+ 'data-url': '/echo',
+ 'data-disable-with': 'clicking...'
+ }));
},
teardown: function() {
$(document).unbind('iframe:loaded');
@@ -293,3 +300,74 @@ asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
checkEnabledState(link, 'Click me');
start();
});
+
+asyncTest('button[data-remote][data-disable-with] disables and re-enables', 6, function() {
+ var button = $('button[data-remote][data-disable-with]');
+
+ checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:send', function() {
+ checkDisabledState(button, 'clicking...');
+ })
+ .bind('ajax:complete', function() {
+ setTimeout( function() {
+ checkEnabledState(button, 'Click me');
+ start();
+ }, 15);
+ })
+ .trigger('click');
+});
+
+asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:before` event is cancelled', 6, function() {
+ var button = $('button[data-remote][data-disable-with]');
+
+ checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:before', function() {
+ checkDisabledState(button, 'clicking...');
+ return false;
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ checkEnabledState(button, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:beforeSend` event is cancelled', 6, function() {
+ var button = $('button[data-remote][data-disable-with]');
+
+ checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:beforeSend', function() {
+ checkDisabledState(button, 'clicking...');
+ return false;
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ checkEnabledState(button, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:error` event is triggered', 6, function() {
+ var button = $('a[data-disable-with]').attr('data-remote', true).attr('href', '/error');
+
+ checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:send', function() {
+ checkDisabledState(button, 'clicking...');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ checkEnabledState(button, 'Click me');
+ start();
+ }, 30);
+});
From 861ea20897e3faa02d80008e2c6e537aa35011bf Mon Sep 17 00:00:00 2001
From: Brad Urani
Date: Fri, 18 Apr 2014 15:11:19 -0500
Subject: [PATCH 023/100] Update rails.js
---
src/rails.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/rails.js b/src/rails.js
index 3e1b5825..f56d071b 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -192,7 +192,7 @@
// If form is actually a "form" element this will return associated elements outside the from that have
// the html form attribute set
formElements: function(form, selector) {
- return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector)
+ return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector);
},
/* Disables form elements:
From f1a4b365e629376d5a097527d44a860a63b1a3be Mon Sep 17 00:00:00 2001
From: Steve Schwartz
Date: Sun, 27 Apr 2014 20:06:32 -0400
Subject: [PATCH 024/100] Fixed helpers to use App settings helpers.
---
test/public/test/data-disable-with.js | 24 ++++++++++++------------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/test/public/test/data-disable-with.js b/test/public/test/data-disable-with.js
index df8283a0..f0903b1f 100644
--- a/test/public/test/data-disable-with.js
+++ b/test/public/test/data-disable-with.js
@@ -286,15 +286,15 @@ asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
asyncTest('button[data-remote][data-disable-with] disables and re-enables', 6, function() {
var button = $('button[data-remote][data-disable-with]');
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
button
.bind('ajax:send', function() {
- checkDisabledState(button, 'clicking...');
+ App.checkDisabledState(button, 'clicking...');
})
.bind('ajax:complete', function() {
setTimeout( function() {
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
start();
}, 15);
})
@@ -304,17 +304,17 @@ asyncTest('button[data-remote][data-disable-with] disables and re-enables', 6, f
asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:before` event is cancelled', 6, function() {
var button = $('button[data-remote][data-disable-with]');
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
button
.bind('ajax:before', function() {
- checkDisabledState(button, 'clicking...');
+ App.checkDisabledState(button, 'clicking...');
return false;
})
.trigger('click');
setTimeout(function() {
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
start();
}, 30);
});
@@ -322,17 +322,17 @@ asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:before`
asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:beforeSend` event is cancelled', 6, function() {
var button = $('button[data-remote][data-disable-with]');
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
button
.bind('ajax:beforeSend', function() {
- checkDisabledState(button, 'clicking...');
+ App.checkDisabledState(button, 'clicking...');
return false;
})
.trigger('click');
setTimeout(function() {
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
start();
}, 30);
});
@@ -340,16 +340,16 @@ asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:beforeSe
asyncTest('button[data-remote][data-disable-with] re-enables when `ajax:error` event is triggered', 6, function() {
var button = $('a[data-disable-with]').attr('data-remote', true).attr('href', '/error');
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
button
.bind('ajax:send', function() {
- checkDisabledState(button, 'clicking...');
+ App.checkDisabledState(button, 'clicking...');
})
.trigger('click');
setTimeout(function() {
- checkEnabledState(button, 'Click me');
+ App.checkEnabledState(button, 'Click me');
start();
}, 30);
});
From becb82231b515f49c871560b25939a24167d8627 Mon Sep 17 00:00:00 2001
From: Steve Schwartz
Date: Sun, 27 Apr 2014 20:20:12 -0400
Subject: [PATCH 025/100] Added support for button[data-disable].
---
src/rails.js | 2 +-
test/public/test/data-disable.js | 73 +++++++++++++++++++++++++++++++-
2 files changed, 73 insertions(+), 2 deletions(-)
diff --git a/src/rails.js b/src/rails.js
index fec1fb6c..6705a6de 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -52,7 +52,7 @@
linkDisableSelector: 'a[data-disable-with], a[data-disable]',
// Button onClick disable selector with possible reenable after remote submission
- buttonDisableSelector: 'button[data-remote][data-disable-with]',
+ buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]',
// Make sure that every Ajax request sends the CSRF token
CSRFProtection: function(xhr) {
diff --git a/test/public/test/data-disable.js b/test/public/test/data-disable.js
index c8850f96..25e9dfc9 100644
--- a/test/public/test/data-disable.js
+++ b/test/public/test/data-disable.js
@@ -26,7 +26,7 @@ module('data-disable', {
text: 'Click me',
'data-remote': true,
'data-url': '/echo',
- 'data-disable-with': 'clicking...'
+ 'data-disable': 'true'
}));
},
teardown: function() {
@@ -251,3 +251,74 @@ asyncTest('ctrl-clicking on a link does not disables the link', 6, function() {
App.checkEnabledState(link, 'Click me');
start();
});
+
+asyncTest('button[data-remote][data-disable] disables and re-enables', 6, function() {
+ var button = $('button[data-remote][data-disable]');
+
+ App.checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:send', function() {
+ App.checkDisabledState(button, 'Click me');
+ })
+ .bind('ajax:complete', function() {
+ setTimeout( function() {
+ App.checkEnabledState(button, 'Click me');
+ start();
+ }, 15);
+ })
+ .trigger('click');
+});
+
+asyncTest('button[data-remote][data-disable] re-enables when `ajax:before` event is cancelled', 6, function() {
+ var button = $('button[data-remote][data-disable]');
+
+ App.checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:before', function() {
+ App.checkDisabledState(button, 'Click me');
+ return false;
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ App.checkEnabledState(button, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('button[data-remote][data-disable] re-enables when `ajax:beforeSend` event is cancelled', 6, function() {
+ var button = $('button[data-remote][data-disable]');
+
+ App.checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:beforeSend', function() {
+ App.checkDisabledState(button, 'Click me');
+ return false;
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ App.checkEnabledState(button, 'Click me');
+ start();
+ }, 30);
+});
+
+asyncTest('button[data-remote][data-disable] re-enables when `ajax:error` event is triggered', 6, function() {
+ var button = $('a[data-disable]').attr('data-remote', true).attr('href', '/error');
+
+ App.checkEnabledState(button, 'Click me');
+
+ button
+ .bind('ajax:send', function() {
+ App.checkDisabledState(button, 'Click me');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ App.checkEnabledState(button, 'Click me');
+ start();
+ }, 30);
+});
From c7a5b12a3b37c4a20f4e5fb22da843f24ef2d356 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Fri, 6 Jun 2014 16:04:24 -0300
Subject: [PATCH 026/100] Remove the script folder from the bower package
---
bower.json | 1 +
1 file changed, 1 insertion(+)
diff --git a/bower.json b/bower.json
index 19c1332a..02c4e9ed 100644
--- a/bower.json
+++ b/bower.json
@@ -13,6 +13,7 @@
"Gemfile*",
"Rakefile",
"bower_components",
+ "script",
"test"
]
}
From ca6526413e7e8534c0df70707c71148dfb395dfe Mon Sep 17 00:00:00 2001
From: Marnen Laibow-Koser
Date: Mon, 9 Jun 2014 11:33:10 -0400
Subject: [PATCH 027/100] Form inputs can use the form attribute too.
---
src/rails.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/rails.js b/src/rails.js
index 837f45a2..579d742c 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -34,7 +34,7 @@
formSubmitSelector: 'form',
// Form input elements bound by jquery-ujs
- formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])',
+ formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',
// Form input elements disabled during form submission
disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',
From eb0e88537cd23208591c0426e8b06c1f0cfad39d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?=
Date: Wed, 18 Jun 2014 11:18:31 -0300
Subject: [PATCH 028/100] Release v1.0.0
---
bower.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/bower.json b/bower.json
index 02c4e9ed..ea9b1ab4 100644
--- a/bower.json
+++ b/bower.json
@@ -1,10 +1,11 @@
{
"name": "jquery-ujs",
"homepage": "https://github.com/rails/jquery-ujs",
- "authors": [],
+ "authors": ["Stephen St. Martin", "Steve Schwartz"],
"description": "Ruby on Rails unobtrusive scripting adapter for jQuery",
"main": "src/rails.js",
"license": "MIT",
+ "version": "1.0.0",
"dependencies": {
"jquery": ">1.8.*"
},
From e2123e080f77e76748069a07ada04bdd7b4244b7 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Wed, 18 Jun 2014 11:21:32 -0300
Subject: [PATCH 029/100] Update jQuery requirement version inside rails.js.
---
src/rails.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/rails.js b/src/rails.js
index 837f45a2..18194eb7 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -4,7 +4,7 @@
* Unobtrusive scripting adapter for jQuery
* https://github.com/rails/jquery-ujs
*
- * Requires jQuery 1.7.0 or later.
+ * Requires jQuery 1.8.0 or later.
*
* Released under the MIT license
*
From 05c9fcab8e29c7c712f2661ccfd51fe73b3e9e60 Mon Sep 17 00:00:00 2001
From: Marnen Laibow-Koser
Date: Tue, 8 Jul 2014 12:34:52 -0400
Subject: [PATCH 030/100] Add test case for input with form ID.
---
test/public/test/data-confirm.js | 33 ++++++++++++++++++++++++++++++++
1 file changed, 33 insertions(+)
diff --git a/test/public/test/data-confirm.js b/test/public/test/data-confirm.js
index b84dd280..d29735fa 100644
--- a/test/public/test/data-confirm.js
+++ b/test/public/test/data-confirm.js
@@ -14,6 +14,18 @@ module('data-confirm', {
text: 'Click me'
}));
+ $('#qunit-fixture').append($('', {
+ id: 'confirm',
+ action: '/echo',
+ 'data-remote': 'true'
+ }));
+
+ $('#qunit-fixture').append($('', {
+ type: 'submit',
+ form: 'confirm',
+ 'data-confirm': 'Are you absolutely sure?'
+ }));
+
this.windowConfirm = window.confirm;
},
teardown: function() {
@@ -105,6 +117,27 @@ asyncTest('clicking on a button with data-confirm attribute. Confirm No.', 3, fu
}, 50);
});
+asyncTest('clicking on a submit button with form and data-confirm attributes. Confirm No.', 3, function() {
+ var message;
+ // auto-decline:
+ window.confirm = function(msg) { message = msg; return false };
+
+ $('input[type=submit][form]')
+ .bind('confirm:complete', function(e, data) {
+ App.assertCallbackInvoked('confirm:complete');
+ ok(data == false, 'confirm:complete passes in confirm answer (false)');
+ })
+ .bind('ajax:beforeSend', function(e, data, status, xhr) {
+ App.assertCallbackNotInvoked('ajax:beforeSend');
+ })
+ .trigger('click');
+
+ setTimeout(function() {
+ equal(message, 'Are you absolutely sure?');
+ start();
+ }, 50);
+});
+
asyncTest('binding to confirm event of a link and returning false', 1, function() {
// redefine confirm function so we can make sure it's not called
window.confirm = function(msg) {
From 358b19d6adf5a939505f84fd91ea492a254412e6 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Wed, 6 Aug 2014 22:46:28 -0300
Subject: [PATCH 031/100] Do not crash the test suite if the form does not have
an `action` attribute.
---
test/public/test/settings.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/test/public/test/settings.js b/test/public/test/settings.js
index 606f2900..85a33ac1 100644
--- a/test/public/test/settings.js
+++ b/test/public/test/settings.js
@@ -47,7 +47,7 @@ $(document).bind('submit', function(e) {
iframe = $('