From cb7d4df9fe433477a8bf4797403518f7d3e6db66 Mon Sep 17 00:00:00 2001
From: Jason Moon
Date: Tue, 27 Aug 2013 22:09:56 -0500
Subject: [PATCH 001/101] 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 c7dcc344eefcd9a646fe570f00fec73078ecb6c4 Mon Sep 17 00:00:00 2001
From: Derek Prior
Date: Fri, 8 Nov 2013 13:01:02 -0500
Subject: [PATCH 002/101] Expose CSRF Token refresh as a function
Refreshing CSRF tokens ensures that forms do not contain cached tokens.
This is currently done once, when jquery-ujs is loaded. If a cached form
is later loaded onto the page (say via a remote form for 'load more'),
the CSRF token is not udated.
This change exposes the CSRF token refreshing code at
`$.rails.refreshCSRFTokens` so it can be called at will without developers
having to re-implement the function.
---
src/rails.js | 12 ++++++++----
test/public/test/csrf-refresh.js | 24 ++++++++++++++++++++++++
test/views/index.erb | 2 +-
3 files changed, 33 insertions(+), 5 deletions(-)
create mode 100644 test/public/test/csrf-refresh.js
diff --git a/src/rails.js b/src/rails.js
index c841beaf..309d74d6 100644
--- a/src/rails.js
+++ b/src/rails.js
@@ -57,6 +57,13 @@
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
},
+ // making sure that all forms have actual up-to-date token(cached forms contain old one)
+ refreshCSRFTokens: function(){
+ var csrfToken = $('meta[name=csrf-token]').attr('content');
+ var csrfParam = $('meta[name=csrf-param]').attr('content');
+ $('form input[name="' + csrfParam + '"]').val(csrfToken);
+ },
+
// Triggers an event on an element and returns false if the event result is false
fire: function(obj, name, data) {
var event = $.Event(name);
@@ -384,10 +391,7 @@
});
$(function(){
- // making sure that all forms have actual up-to-date token(cached forms contain old one)
- var csrfToken = $('meta[name=csrf-token]').attr('content');
- var csrfParam = $('meta[name=csrf-param]').attr('content');
- $('form input[name="' + csrfParam + '"]').val(csrfToken);
+ rails.refreshCSRFTokens();
});
}
diff --git a/test/public/test/csrf-refresh.js b/test/public/test/csrf-refresh.js
new file mode 100644
index 00000000..65642433
--- /dev/null
+++ b/test/public/test/csrf-refresh.js
@@ -0,0 +1,24 @@
+(function(){
+
+module('csrf-refresh', {});
+
+asyncTest('refresh all csrf tokens', 1, function() {
+ var correctToken = "cf50faa3fe97702ca1ae";
+
+ var form = $('')
+ var input = $('').attr({ type: 'hidden', name: 'authenticity_token', id: 'authenticity_token', value: 'foo' })
+ input.appendTo(form)
+
+ $('#qunit-fixture')
+ .append('')
+ .append('')
+ .append(form);
+
+ $.rails.refreshCSRFTokens();
+ currentToken = $('#qunit-fixture #authenticity_token').val();
+
+ start();
+ equal(currentToken, correctToken);
+});
+
+})();
diff --git a/test/views/index.erb b/test/views/index.erb
index 2364f06f..6caf6f03 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' %>
+<%= test 'data-confirm', 'data-remote', 'data-disable', 'call-remote', 'call-remote-callbacks', 'data-method', 'override', 'csrf-refresh' %>
<%= @title %>
From fbddf674f7f54d8e021c8a813e864088614c4a53 Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Mon, 27 Jan 2014 15:28:16 -0200
Subject: [PATCH 003/101] 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 004/101] 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' %>
<%= @title %>
From d61894b7b17f89440b08cb0b742a2a589533124f Mon Sep 17 00:00:00 2001
From: Lucas Mazza
Date: Mon, 27 Jan 2014 16:53:02 -0200
Subject: [PATCH 005/101] 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 006/101] 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 007/101] 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 008/101] 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 009/101] 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 010/101] 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 011/101] 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 012/101] 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 013/101] 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 014/101] 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 015/101] 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 016/101] 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 017/101] 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 018/101] 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 019/101] 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 020/101] 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 =
+ "
" + escapeText( document.title ) + "
" +
+ "" +
+ "" +
+ "" +
+ "";
+ }
+
+ 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 + '