Repository: hauleth/vanilla-ujs
Branch: master
Commit: aed5e97ad9e7
Files: 31
Total size: 34.1 KB
Directory structure:
gitextract_r25h7kkx/
├── .gitignore
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── Gemfile
├── Gruntfile.js
├── LICENSE.txt
├── MAINTAINERS
├── README.md
├── lib/
│ ├── assets/
│ │ └── javascripts/
│ │ ├── vanilla-ujs/
│ │ │ ├── confirm.js
│ │ │ ├── csrf.js
│ │ │ ├── disable.js
│ │ │ ├── form.js
│ │ │ ├── liteajax.js
│ │ │ ├── method.js
│ │ │ └── polyfills.js
│ │ └── vanilla-ujs.js
│ ├── vanilla/
│ │ ├── ujs/
│ │ │ ├── rails.rb
│ │ │ └── version.rb
│ │ └── ujs.rb
│ └── vanilla-ujs.rb
├── package.json
├── test/
│ ├── config/
│ │ └── globals.js
│ ├── confirm.spec.js
│ ├── csrf.spec.js
│ ├── disable.spec.js
│ ├── form.spec.js
│ ├── helpers/
│ │ └── serv.js
│ ├── index.html
│ ├── liteajax.spec.js
│ └── method.spec.js
└── vanilla-ujs.gemspec
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
/.bundle/
/.yardoc
/Gemfile.lock
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
/node_modules
/vendor/bundle
/*.gem
================================================
FILE: .travis.yml
================================================
language: node_js
node_js: node
before_script:
- npm install grunt-cli
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of
fostering an open and welcoming community, we pledge to respect all people who
contribute through reporting issues, posting feature requests, updating
documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free
experience for everyone, regardless of level of experience, gender, gender
identity and expression, sexual orientation, disability, personal appearance,
body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic
addresses, without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to
fairly and consistently applying these principles to every aspect of managing
this project. Project maintainers who do not follow or enforce the Code of
Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting a project maintainer at lukasz@niemier.pl. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. Maintainers are
obligated to maintain confidentiality with regard to the reporter of an
incident.
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.3.0, available at
[http://contributor-covenant.org/version/1/3/0/][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/3/0/
================================================
FILE: Gemfile
================================================
source 'https://rubygems.org'
# Specify your gem's dependencies in vanilla-ujs.gemspec
gemspec
================================================
FILE: Gruntfile.js
================================================
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
mocha: {
all: {
options: {
reporter: 'Spec'
}
},
ci: {
options: {
}
},
options: {
run: true,
urls: ['http://localhost:8000/index.html'],
}
},
concat: {
options: {
stripBanners: true,
banner: "(function (window, document) {\n'use strict';\n",
footer: '}).call(void(0), window, document);'
},
dist: {
src: [
'lib/assets/javascripts/vanilla-ujs/polyfills.js',
'lib/assets/javascripts/vanilla-ujs/liteajax.js',
'lib/assets/javascripts/vanilla-ujs/confirm.js',
'lib/assets/javascripts/vanilla-ujs/method.js',
'lib/assets/javascripts/vanilla-ujs/disable.js',
'lib/assets/javascripts/vanilla-ujs/csrf.js',
'lib/assets/javascripts/vanilla-ujs/form.js',
],
dest: 'lib/assets/javascripts/vanilla-ujs.js'
}
},
express: {
test: {
options: {
port: 8000,
hostname: 'localhost',
server: 'test/helpers/serv.js',
bases: ['./lib/', './test/']
}
}
},
watch: {
tests: {
files: ["lib/**/*.js", "test/**/*.spec.js"],
tasks: ["test"],
},
}
});
grunt.registerTask('test', ['express:test', 'mocha:all']);
grunt.registerTask('webtest', ['express:test', 'express-keepalive']);
grunt.registerTask('ci', ['express:test', 'mocha:ci']);
grunt.registerTask('dist', ['concat']);
grunt.registerTask('default', ['test']);
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-express');
grunt.loadNpmTasks('grunt-mocha');
};
================================================
FILE: LICENSE.txt
================================================
Copyright (c) 2013 Łukasz Niemier
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: MAINTAINERS
================================================
Łukasz Jan Niemier <lukasz@niemier.pl> (@hauleth)
Alex Tsokurov <me@ximik.net> (@Ximik)
================================================
FILE: README.md
================================================
# Vanilla UJS
[![Build Status][travis-img]][travis-link][](https://gemnasium.com/hauleth/vanilla-ujs)
It is implementation of Rails [jQuery UJS][jq-ujs] in pure JavaScript.
No extra dependencies.
## Installation using the vanilla-ujs gem
For automated installation in Rails, use the `vanilla-ujs` gem.
Place this in your Gemfile:
```ruby
gem 'vanilla-ujs'
```
And run:
```shell
$ bundle install
```
Require `vanilla-ujs` into your application.js manifest.
```javascript
//= require vanilla-ujs
```
## Does it mean that I shouldn't use jQuery
No. You should if you want. This library is created to make your Rails code
independent from front-end library.
## Contribute
1. Clone repo
$ git clone git://github.com/hauleth/vanilla-ujs.git
$ cd vanilla-js/
2. Install dependencies
$ npm install
3. Run tests
$ grunt test
## Thanks
- Alex Tsokurov ([@ximik](https://github.com/ximik))
- Matt Huggins ([@mhuggins](https://github.com/mhuggins))
- Tasveer Singh ([@tazsingh](https://github.com/tazsingh))
- Tim O'Sulg ([@timgluz](https://github.com/timgluz))
- Walter Lee Davis ([@walterdavis](https://github.com/walterdavis))
# License
See [`LICENSE`](LICENSE.txt) file.
[travis-img]: https://travis-ci.org/hauleth/vanilla-ujs.svg?branch=master
[travis-link]: https://travis-ci.org/hauleth/vanilla-ujs
[jq-ujs]: https://github.com/rails/jquery-ujs
================================================
FILE: lib/assets/javascripts/vanilla-ujs/confirm.js
================================================
document.addEventListener('click', function (event) {
var message, element;
if (element = matchesSelfOrParent(event.target, 'a[data-confirm], button[data-confirm], input[data-confirm]')) {
message = element.getAttribute('data-confirm');
if (!confirm(message)) {
event.stopPropagation();
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
return;
}
}, false);
================================================
FILE: lib/assets/javascripts/vanilla-ujs/csrf.js
================================================
var CSRF = {
token: function () {
var token = document.querySelector('meta[name="csrf-token"]');
return token && token.getAttribute('content');
},
param: function () {
var param = document.querySelector('meta[name="csrf-param"]');
return param && param.getAttribute('content');
}
};
var sameOrigin = function (url) {
var a = document.createElement('a'), origin;
a.href = url;
origin = a.href.split('/', 3).join('/');
return window.location.href.indexOf(origin) === 0;
};
window.CSRF = CSRF;
document.addEventListener('ajax:before', function (e) {
var token = CSRF.token(), xhr = e.detail;
if (token)
xhr.setRequestHeader('X-CSRF-Token', token);
});
document.addEventListener('submit', function (e) {
var token = CSRF.token(),
param = CSRF.param(),
form = e.target;
if (matches.call(form, 'form')) {
if (matches.call(form, 'form[data-remote]'))
return true;
if (!form.method || form.method.toUpperCase() == 'GET')
return true;
if (!sameOrigin(form.action))
return true;
if (param && token && !form.querySelector('input[name='+param+']')) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', param);
input.setAttribute('value', token);
form.appendChild(input);
}
return true;
}
});
================================================
FILE: lib/assets/javascripts/vanilla-ujs/disable.js
================================================
document.addEventListener('click', function (event) {
var message, element;
// do not disable on right click. Work on left and middle click
if (event.which == 3) {
return;
}
if (element = matchesSelfOrParent(event.target, 'a[data-disable-with], button[data-disable-with], input[data-disable-with]')) {
// do not disable if the element is a submit button and its form has invalid input elements.
// since failed validations prevent the form from being submitted, we would lock the form permanently
// by disabling the submit button even though the form was never submitted
if (element.getAttribute("type") === "submit" && element.form.querySelector(":invalid") !== null) {
return;
}
message = element.getAttribute('data-disable-with');
if (!!element.value) {
element.value = message;
} else {
element.innerHTML = message;
}
// timeout is needed because Safari stops the submit if the button is immediately disabled
setTimeout(function() {
element.setAttribute('disabled', 'disabled');
}, 0);
return;
}
if (element = matchesSelfOrParent(event.target, 'a[data-disable], button[data-disable], input[data-disable]')) {
if (element.getAttribute("type") === "submit" && element.form.querySelector(":invalid") !== null) {
return;
}
setTimeout(function() {
element.setAttribute('disabled', 'disabled');
}, 0);
}
}, false);
================================================
FILE: lib/assets/javascripts/vanilla-ujs/form.js
================================================
var VanillaUJS = {
formHasNoInputs: function (form) {
var element,
fieldType;
for (var i = 0, elements = form.elements, count = elements.length; i < count; i++) {
element = elements[i];
fieldType = element.nodeName.toUpperCase();
if (!element.hasAttribute('name') || element.disabled) {
continue;
}
if ((fieldType == 'RADIO' || fieldType == 'CHECKBOX') && !element.checked) {
continue;
}
return false;
}
return true;
}
};
document.addEventListener('submit', function(event) {
var form = event.target;
if (matches.call(form, 'form[data-remote]')) {
var url = form.action;
var method = (form.method || form.getAttribute('data-method') || 'POST').toUpperCase();
var data = new FormData(form);
var formHasNoInputs = VanillaUJS.formHasNoInputs(form);
if (CSRF.param() && CSRF.token()) {
data[CSRF.param()] = CSRF.token();
} else if (formHasNoInputs) {
data = null;
}
if (LiteAjax.ajax({ url: url, method: method, data: data, target: form })){
event.preventDefault();
} else {
return true;
}
}
});
================================================
FILE: lib/assets/javascripts/vanilla-ujs/liteajax.js
================================================
var LiteAjax = (function () {
var LiteAjax = {};
LiteAjax.options = {
method: 'GET',
url: window.location.href
};
LiteAjax.ajax = function (url, options) {
if (typeof url == 'object') {
options = url;
url = undefined;
}
options = options || {};
if(!options.accepts) {
options.accepts = 'text/javascript, application/javascript, ' +
'application/ecmascript, application/x-ecmascript';
}
url = url || options.url || location.href || '';
var data = options.data;
var target = options.target || document;
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', function () {
var responseType = xhr.getResponseHeader('content-type');
if(responseType === 'text/javascript; charset=utf-8') {
eval(xhr.response);
}
var event = new CustomEvent('ajax:complete', {detail: xhr, bubbles: true});
target.dispatchEvent(event);
});
if (typeof options.success == 'function')
xhr.addEventListener('load', function (event) {
if (xhr.status >= 200 && xhr.status < 300)
options.success(xhr);
});
if (typeof options.error == 'function') {
xhr.addEventListener('load', function (event) {
if (xhr.status < 200 || xhr.status >= 300)
options.error(xhr);
});
xhr.addEventListener('error', function (event) {
options.error(xhr);
});
}
xhr.open(options.method || 'GET', url);
xhr.setRequestHeader('X-Requested-With', 'XmlHttpRequest');
xhr.setRequestHeader('Accept', '*/*;q=0.5, ' + options.accepts);
if(options.json) {
xhr.setRequestHeader('Content-type', 'application/json');
data = JSON.stringify(data);
}
var beforeSend = new CustomEvent('ajax:before', {detail: xhr, bubbles: true});
target.dispatchEvent(beforeSend);
xhr.send(data);
return xhr;
};
return LiteAjax;
})();
================================================
FILE: lib/assets/javascripts/vanilla-ujs/method.js
================================================
document.addEventListener('click', function(event) {
var element, url, method, data, handler;
// Only left click allowed. Firefox triggers click event on right click/contextmenu.
if (event.button !== 0) {
return;
}
if (element = matchesSelfOrParent(event.target, 'a[data-method]')) {
url = element.getAttribute('href');
method = element.getAttribute('data-method').toUpperCase();
data = {};
if (CSRF.param() && CSRF.token()) {
data[CSRF.param()] = CSRF.token();
}
if (matches.call(element, 'a[data-remote]')) {
handler = xhr;
} else {
handler = submit;
}
if (handler({ url: url, method: method, data: data, target: element })) {
event.preventDefault();
} else {
return true;
}
}
function submit(options) {
var form, input, param;
if (options.method == 'GET') {
return false;
}
form = document.createElement('form');
form.method = 'POST';
form.action = options.url;
form.style.display = 'none';
for (param in options.data) {
if (Object.prototype.hasOwnProperty.call(options.data, param)) {
input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', param);
input.setAttribute('value', options.data[param]);
form.appendChild(input);
}
}
if (options.method != 'POST') {
input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', '_method');
input.setAttribute('value', options.method);
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
return true;
}
function xhr(options) {
LiteAjax.ajax(options);
return true;
}
}, false);
================================================
FILE: lib/assets/javascripts/vanilla-ujs/polyfills.js
================================================
var matches = (function(doc) {
return doc.matchesSelector ||
doc.webkitMatchesSelector ||
doc.mozMatchesSelector ||
doc.oMatchesSelector ||
doc.msMatchesSelector;
})(document.documentElement);
var matchesSelfOrParent = function (element, selector) {
while (!matches.call(element, selector)) {
element = element.parentNode;
if (element instanceof HTMLDocument) {
return null;
}
}
return element;
};
var CustomEvent = function (event, params) {
params = params || {bubbles: false, cancelable: false, detail: undefined};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.CustomEvent.prototype;
window.CustomEvent = CustomEvent;
================================================
FILE: lib/assets/javascripts/vanilla-ujs.js
================================================
//= require_tree ./vanilla-ujs
================================================
FILE: lib/vanilla/ujs/rails.rb
================================================
module Vanilla
module Rails
class Engine < ::Rails::Engine
end
end
end
================================================
FILE: lib/vanilla/ujs/version.rb
================================================
module Vanilla
module Ujs
VERSION = '1.3.0'.freeze
end
end
================================================
FILE: lib/vanilla/ujs.rb
================================================
require 'vanilla/ujs/version'
require 'vanilla/ujs/rails'
module Vanilla
module Rails
# Your code goes here...
end
end
================================================
FILE: lib/vanilla-ujs.rb
================================================
require 'vanilla/ujs'
================================================
FILE: package.json
================================================
{
"name": "vanilla-ujs",
"version": "1.3.0",
"description": "Rails UJS in VanillaJS",
"main": "lib/assets/javascripts/vanilla-ujs.js",
"scripts": {
"build": "npm install && grunt dist",
"test": "grunt test",
"webtest": "grunt webtest"
},
"devDependencies": {
"body-parser": "~1.18.2",
"chai": "^4.1.2",
"express": "~4.16.2",
"grunt": "^1.0.1",
"grunt-contrib-concat": "*",
"grunt-contrib-jshint": "*",
"grunt-contrib-uglify": "~3.2.1",
"grunt-contrib-watch": "~1.0.0",
"grunt-express": "*",
"grunt-mocha": "~1.0",
"grunt-parallel": "^0.5.1",
"sinon": "^4.1.2"
},
"repository": {
"type": "git",
"url": "git://github.com/hauleth/vanilla-ujs.git"
},
"keywords": [
"ujs",
"rails",
"vanilla"
],
"author": "Łukasz Niemier",
"license": "MIT",
"bugs": {
"url": "https://github.com/hauleth/vanilla-ujs/issues"
},
"homepage": "https://github.com/hauleth/vanilla-ujs"
}
================================================
FILE: test/config/globals.js
================================================
(function () {
var global = typeof global !== 'undefined' ?
global :
typeof self !== 'undefined' ?
self :
typeof window !== 'undefined' ?
window :
{};
global.expect = chai.expect;
global.click = function (element) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 80, 20, false, false, false, false, 0, null);
element.dispatchEvent(evt);
};
mocha.suite.beforeEach(function(done) {
global.iframe = document.createElement('iframe');
global.iframe.src = '/fixture';
global.iframe.onload = function () {
global.iframe.onload = function () {};
global.win = function () {
return global.iframe.contentWindow;
};
global.doc = function () {
return global.iframe.contentDocument;
};
done();
};
var fixture = document.getElementById('fixture');
fixture.appendChild(global.iframe);
});
mocha.suite.afterEach(function() {
global.iframe.parentNode.removeChild(global.iframe);
});
}).call(this);
================================================
FILE: test/confirm.spec.js
================================================
describe('Link confirmation', function () {
describe('<a> link', function () {
var a, confirm, clickLink;
beforeEach(function () {
win().confirm = confirm = sinon.stub();
win().clickLink = clickLink = sinon.spy();
a = document.createElement('a');
a.setAttribute('data-confirm', 'Lolcontent');
a.href = '#clicked';
doc().body.appendChild(a);
});
it('call confirm', function () {
click(a);
expect(confirm.called).to.be.true;
});
it('fire default action if confirm() returns true', function () {
win.confirm = confirm = confirm.returns(true);
click(a);
expect(win().location.hash).to.equal('#clicked');
});
it('do not fire default action if confirm() returns false', function () {
win.confirm = confirm = confirm.returns(false);
click(a);
expect(win().location.hash).to.not.equal('#clicked');
});
it('call confirm woth elements inside link', function () {
var i = document.createElement('i');
a.appendChild(i);
click(i);
expect(confirm.called).to.be.true;
});
});
// TODO: Write tests for <button>
});
================================================
FILE: test/csrf.spec.js
================================================
describe('CSRF', function () {
beforeEach(function () {
var token, param;
token = doc().createElement('meta');
token.setAttribute('name', 'csrf-token');
token.setAttribute('content', 'CSRFToken');
doc().head.appendChild(token);
param = doc().createElement('meta');
param.setAttribute('name', 'csrf-param');
param.setAttribute('content', 'CSRFParam');
doc().head.appendChild(param);
});
describe('getters', function () {
it('return token value', function () {
expect(win().CSRF.token()).to.equal('CSRFToken');
});
it('return param value', function () {
expect(win().CSRF.param()).to.equal('CSRFParam');
});
});
describe('LiteAjax request', function () {
it('send valid CSRF header value', function (done) {
var xhr = win().LiteAjax.ajax('/xhr', {
success: function (req) {
expect(JSON.parse(req.response).csrf).to.equal('CSRFToken');
done();
}
});
});
});
});
================================================
FILE: test/disable.spec.js
================================================
describe('Should disable links and buttons with [data-disable-with]', function () {
describe('<a> link', function () {
var a;
beforeEach(function () {
a = document.createElement('a');
a.setAttribute('data-disable-with', 'Lolcontent');
a.href = '#clicked';
doc().body.appendChild(a);
});
it('when click a link', function (done) {
click(a);
expect(win().location.hash).to.equal('#clicked');
expect(a.innerText).to.equal('Lolcontent');
setTimeout(function () {
expect(win().location.hash).to.equal('#clicked');
expect(a.getAttribute('disabled')).to.equal('disabled');
done();
}, 5); // because original code has timeout too
});
it('when click element inside link', function (done) {
var i = document.createElement('i');
a.appendChild(i);
click(i);
expect(win().location.hash).to.equal('#clicked');
expect(a.innerText).to.equal('Lolcontent');
setTimeout(function () {
expect(a.getAttribute('disabled')).to.equal('disabled');
done();
}, 5); // because original code has timeout too
});
});
// TODO: Write tests for <button>
});
describe('Should disable links and buttons with [data-disable]', function () {
var a;
beforeEach(function () {
a = document.createElement('a');
a.innerText = 'Original'
a.setAttribute('data-disable', '');
a.href = '#clicked';
doc().body.appendChild(a);
});
it('when click a link', function (done) {
click(a);
expect(win().location.hash).to.equal('#clicked');
expect(a.innerText).to.equal('Original');
setTimeout(function () {
expect(a.getAttribute('disabled')).to.equal('disabled');
done();
}, 5); // because original code has timeout too
});
it('when click element inside link', function (done) {
var i = document.createElement('i');
a.appendChild(i);
click(i);
expect(win().location.hash).to.equal('#clicked');
expect(a.innerText).to.equal('Original');
setTimeout(function () {
expect(a.getAttribute('disabled')).to.equal('disabled');
done();
}, 5); // because original code has timeout too
});
})
================================================
FILE: test/form.spec.js
================================================
describe('Form methods', function () {
var form, submit, submitForm;
beforeEach(function () {
form = document.createElement('form');
submit = document.createElement('input')
doc().body.appendChild(form);
submit.setAttribute('type', 'submit');
submit.setAttribute('name', 'submit');
submit.setAttribute('value', 'submit');
form.appendChild(submit)
win().submitForm = submitForm = sinon.spy();
});
describe('[method=post]', function () {
beforeEach(function () {
form.onsubmit = submitForm;
form.setAttribute('method', 'post');
});
describe('no [data-remote]', function () {
beforeEach(function () {
form.setAttribute('action', '/echo?callback=parse');
});
it('is submitted as a form', function (done) {
var url = win().location.href;
window.parse = function (json) {
expect(url).to.not.equal(win().location.href);
expect(json).to.deep.equal({
method: 'post',
path: '/echo'
});
done();
};
click(submit);
expect(submitForm.called).to.be.true;
});
});
describe('[data-remote]', function () {
beforeEach(function () {
form.setAttribute('action', '/xhr');
form.setAttribute('data-remote', 'true');
});
it('calls ajax:before event on form with bubbling enabled', function (done) {
var handler = function (event) {
expect(event.target).to.equal(form);
expect(event.bubbles).to.equal(true);
doc().removeEventListener('ajax:before', handler);
done();
};
doc().addEventListener('ajax:before', handler);
click(submit);
expect(submitForm.called).to.be.true;
});
it('calls ajax:complete event on form with bubbling enabled', function (done) {
var handler = function (event) {
expect(event.target).to.equal(form);
expect(event.bubbles).to.equal(true);
doc().removeEventListener('ajax:complete', handler);
done();
};
doc().addEventListener('ajax:complete', handler);
click(submit);
expect(submitForm.called).to.be.true;
});
it('is sent as XHR request', function (done) {
var url = win().location.href;
var handler = function (event) {
expect(url).to.equal(win().location.href);
expect(JSON.parse(event.detail.response)).to.deep.equal({
method: 'post',
path: '/xhr'
});
doc().removeEventListener('ajax:complete', handler);
done();
};
doc().addEventListener('ajax:complete', handler);
click(submit);
expect(submitForm.called).to.be.true;
});
it('does not pass formdata when there are no form inputs', function (done) {
// Inputs without name are usually not included in a form POST, we use that to simulate
// a request without inputs
submit.removeAttribute('name');
win().LiteAjax.ajax = sinon.spy();
click(submit);
var options = win().LiteAjax.ajax.getCall(0).args[0];
expect(options.data).to.equal(null);
expect(submitForm.called).to.be.true;
done();
});
});
});
});
================================================
FILE: test/helpers/serv.js
================================================
var express = require('express'),
bodyParser = require('body-parser'),
fs = require('fs'),
path = require('path'),
app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var scripts = [
'polyfills',
'confirm',
'method',
'disable',
'liteajax',
'csrf',
'form'
].map(function (s) { return ['<script src="/assets/javascripts/vanilla-ujs/', s, '.js"></script>'].join(''); });
var template = function(body) {
return [
'<html><head><title>Testing…</title></head><body>',
body,
'</body></html>'
].join("\n");
};
app.get('/fixture', function (req, res) {
res.send(template(scripts.join('')));
});
app.all('/echo', function (req, res) {
res.send(template([
'<script>window.top.',
req.query.callback,
'(',
JSON.stringify({
method: (req.body._method || req.method).toLowerCase(),
csrf: req.get('X-CSRF-Token'),
path: req.path
}),
');</script>'
].join('')));
});
app.all('/xhr', function (req, res) {
res.send({
method: (req.body._method || req.method).toLowerCase(),
csrf: req.get('X-CSRF-Token') || req.body[req.params['param']],
path: req.path
});
});
app.all('/assets/mocha.js', function (req, res) {
res.sendFile(path.resolve(__dirname, "../../node_modules/mocha/mocha.js"));
});
app.all('/assets/mocha.css', function (req, res) {
res.sendFile(path.resolve(__dirname, "../../node_modules/mocha/mocha.css"));
});
app.all('/assets/sinon.js', function (req, res) {
res.sendFile(path.resolve(__dirname, "../../node_modules/sinon/pkg/sinon.js"));
});
app.all('/assets/chai.js', function (req, res) {
res.sendFile(path.resolve(__dirname, "../../node_modules/chai/chai.js"));
});
module.exports = app;
================================================
FILE: test/index.html
================================================
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta charset="UTF-8">
<script src="assets/mocha.js"></script>
<script src="assets/chai.js"></script>
<script src="assets/sinon.js"></script>
<script src="config/globals.js"></script>
<script>mocha.setup('bdd')</script>
<link rel="stylesheet" href="assets/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<div id="fixture"></div>
<script src="liteajax.spec.js"></script>
<script src="method.spec.js"></script>
<script src="confirm.spec.js"></script>
<script src="csrf.spec.js"></script>
<script src="form.spec.js"></script>
<script src="disable.spec.js"></script>
<script>
window.onload = function () {
if (navigator.userAgent.indexOf('PhantomJS') < 0) {
mocha.run();
}
};
</script>
</body>
</html>
================================================
FILE: test/liteajax.spec.js
================================================
describe('LiteAjax', function () {
describe('success callback', function () {
var xhr, callbackSpy;
beforeEach(function (done) {
callbackSpy = sinon.spy();
xhr = win().LiteAjax.ajax('/echo', {
success: function () {
callbackSpy();
done();
}
});
});
it('is called on valid request', function () {
expect(callbackSpy.called).to.be.true;
});
});
describe('error callback', function () {
var xhr, callbackSpy;
beforeEach(function (done) {
callbackSpy = sinon.spy();
xhr = win().LiteAjax.ajax('/404', {
success: function () { done(); },
error: function () {
callbackSpy();
done();
}
});
});
it('is called on invalid request', function () {
expect(callbackSpy.called).to.be.true;
});
});
});
================================================
FILE: test/method.spec.js
================================================
describe('Link methods', function () {
var a, clickLink;
beforeEach(function () {
a = document.createElement('a');
doc().body.appendChild(a);
win().clickLink = clickLink = sinon.spy();
});
describe('no [data-method]', function () {
beforeEach(function () {
a.onclick = clickLink;
});
it('is sent normally', function () {
click(a);
expect(clickLink.called).to.be.true;
});
});
describe('[data-method=get]', function () {
beforeEach(function () {
a.onclick = clickLink;
a.setAttribute('data-method', 'get');
});
it('is sent normally', function () {
click(a);
expect(clickLink.called).to.be.true;
});
});
describe('[data-method=post]', function () {
beforeEach(function () {
a.setAttribute('data-method', 'post');
});
describe('no [data-remote]', function () {
beforeEach(function () {
a.setAttribute('href', '/echo?callback=parse');
});
it('is sent as POST form', function (done) {
var url = win().location.href;
window.parse = function (json) {
expect(url).to.not.equal(win().location.href);
expect(json).to.deep.equal({
method: 'post',
path: '/echo'
});
done();
};
click(a);
});
it('is sent when clicking child element inside link', function (done) {
var url = win().location.href;
var i = document.createElement('i');
a.appendChild(i);
window.parse = function (json) {
expect(url).to.not.equal(win().location.href);
expect(json).to.deep.equal({
method: 'post',
path: '/echo'
});
done();
};
click(i);
});
});
describe('[data-remote]', function () {
beforeEach(function () {
a.setAttribute('href', '/xhr');
a.setAttribute('data-remote', 'true');
});
it('calls ajax:before event on a element with bubbling enabled', function (done) {
var handler = function (event) {
expect(event.target).to.equal(a);
expect(event.bubbles).to.equal(true);
doc().removeEventListener('ajax:before', handler);
done();
};
doc().addEventListener('ajax:before', handler);
click(a);
});
it('calls ajax:complete event on a element with bubbling enabled', function (done) {
var handler = function (event) {
expect(event.target).to.equal(a);
expect(event.bubbles).to.equal(true);
doc().removeEventListener('ajax:complete', handler);
done();
};
doc().addEventListener('ajax:complete', handler);
click(a);
});
it('is sent as XHR request', function (done) {
var url = win().location.href;
var handler = function (event) {
expect(url).to.equal(win().location.href);
expect(JSON.parse(event.detail.response)).to.deep.equal({
method: 'post',
path: '/xhr'
});
doc().removeEventListener('ajax:complete', handler);
done();
};
doc().addEventListener('ajax:complete', handler);
click(a);
});
});
});
describe('[data-method=delete]', function () {
beforeEach(function () {
a.setAttribute('href', '/echo?callback=parse');
a.setAttribute('data-method', 'delete');
});
it('is sent with DELETE method', function (done) {
window.parse = function (json) {
expect(json).to.deep.equal({
method: 'delete',
path: '/echo'
});
done();
};
click(a);
});
});
describe('[data-method=put]', function () {
beforeEach(function () {
a.setAttribute('href', '/echo?callback=parse');
a.setAttribute('data-method', 'put');
});
it('is sent with PUT method', function (done) {
window.parse = function (json) {
expect(json).to.deep.equal({
method: 'put',
path: '/echo'
});
done();
};
click(a);
});
});
});
================================================
FILE: vanilla-ujs.gemspec
================================================
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'vanilla/ujs/version'
Gem::Specification.new do |spec|
spec.name = 'vanilla-ujs'
spec.version = Vanilla::Ujs::VERSION
spec.authors = ['Łukasz Jan Niemier', 'Alex Tsukurov', 'Kirill Pimenov']
spec.email = ['lukasz@niemier.pl', 'me@ximik.net']
spec.summary = 'UJS without jQuery dependency'
spec.description = 'This gem provides Rails UJS features without jQuery library.'
spec.homepage = 'https://github.com/hauleth/vanilla-ujs'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test)/}) }
spec.require_paths = ['lib']
spec.required_rubygems_version = '>= 1.3.6'
spec.add_dependency 'railties', '>= 4.2.0'
spec.add_development_dependency 'bundler', '~> 1.11'
end
gitextract_r25h7kkx/ ├── .gitignore ├── .travis.yml ├── CODE_OF_CONDUCT.md ├── Gemfile ├── Gruntfile.js ├── LICENSE.txt ├── MAINTAINERS ├── README.md ├── lib/ │ ├── assets/ │ │ └── javascripts/ │ │ ├── vanilla-ujs/ │ │ │ ├── confirm.js │ │ │ ├── csrf.js │ │ │ ├── disable.js │ │ │ ├── form.js │ │ │ ├── liteajax.js │ │ │ ├── method.js │ │ │ └── polyfills.js │ │ └── vanilla-ujs.js │ ├── vanilla/ │ │ ├── ujs/ │ │ │ ├── rails.rb │ │ │ └── version.rb │ │ └── ujs.rb │ └── vanilla-ujs.rb ├── package.json ├── test/ │ ├── config/ │ │ └── globals.js │ ├── confirm.spec.js │ ├── csrf.spec.js │ ├── disable.spec.js │ ├── form.spec.js │ ├── helpers/ │ │ └── serv.js │ ├── index.html │ ├── liteajax.spec.js │ └── method.spec.js └── vanilla-ujs.gemspec
SYMBOL INDEX (9 symbols across 4 files)
FILE: lib/assets/javascripts/vanilla-ujs/method.js
function submit (line 31) | function submit(options) {
function xhr (line 66) | function xhr(options) {
FILE: lib/vanilla/ujs.rb
type Vanilla (line 4) | module Vanilla
type Rails (line 5) | module Rails
FILE: lib/vanilla/ujs/rails.rb
type Vanilla (line 1) | module Vanilla
type Rails (line 2) | module Rails
class Engine (line 3) | class Engine < ::Rails::Engine
FILE: lib/vanilla/ujs/version.rb
type Vanilla (line 1) | module Vanilla
type Ujs (line 2) | module Ujs
Condensed preview — 31 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (38K chars).
[
{
"path": ".gitignore",
"chars": 123,
"preview": "/.bundle/\n/.yardoc\n/Gemfile.lock\n/_yardoc/\n/coverage/\n/doc/\n/pkg/\n/spec/reports/\n/tmp/\n/node_modules\n/vendor/bundle\n/*.g"
},
{
"path": ".travis.yml",
"chars": 74,
"preview": "language: node_js\nnode_js: node\n\nbefore_script:\n - npm install grunt-cli\n"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 2385,
"preview": "# Contributor Code of Conduct\n\nAs contributors and maintainers of this project, and in the interest of\nfostering an open"
},
{
"path": "Gemfile",
"chars": 96,
"preview": "source 'https://rubygems.org'\n\n# Specify your gem's dependencies in vanilla-ujs.gemspec\ngemspec\n"
},
{
"path": "Gruntfile.js",
"chars": 1885,
"preview": "module.exports = function (grunt) {\n grunt.initConfig({\n pkg: grunt.file.readJSON('package.json'),\n mocha: {\n "
},
{
"path": "LICENSE.txt",
"chars": 1072,
"preview": "Copyright (c) 2013 Łukasz Niemier\n\n\nMIT License\n\nPermission is hereby granted, free of charge, to any person obtaining\na"
},
{
"path": "MAINTAINERS",
"chars": 88,
"preview": "Łukasz Jan Niemier <lukasz@niemier.pl> (@hauleth)\nAlex Tsokurov <me@ximik.net> (@Ximik)\n"
},
{
"path": "README.md",
"chars": 1467,
"preview": "# Vanilla UJS\n[![Build Status][travis-img]][travis-link][ {\n var message, element;\n\n if (element = matchesSelfOrParent(event"
},
{
"path": "lib/assets/javascripts/vanilla-ujs/csrf.js",
"chars": 1379,
"preview": "var CSRF = {\n token: function () {\n var token = document.querySelector('meta[name=\"csrf-token\"]');\n return token "
},
{
"path": "lib/assets/javascripts/vanilla-ujs/disable.js",
"chars": 1444,
"preview": "document.addEventListener('click', function (event) {\n var message, element;\n\n // do not disable on right click. Work "
},
{
"path": "lib/assets/javascripts/vanilla-ujs/form.js",
"chars": 1158,
"preview": "var VanillaUJS = {\n formHasNoInputs: function (form) {\n var element,\n fieldType;\n\n for (var i = 0, element"
},
{
"path": "lib/assets/javascripts/vanilla-ujs/liteajax.js",
"chars": 1950,
"preview": "var LiteAjax = (function () {\n var LiteAjax = {};\n\n LiteAjax.options = {\n method: 'GET',\n url: window.location.h"
},
{
"path": "lib/assets/javascripts/vanilla-ujs/method.js",
"chars": 1803,
"preview": "document.addEventListener('click', function(event) {\n var element, url, method, data, handler;\n\n // Only left click al"
},
{
"path": "lib/assets/javascripts/vanilla-ujs/polyfills.js",
"chars": 800,
"preview": "var matches = (function(doc) {\n return doc.matchesSelector ||\n doc.webkitMatchesSelector ||\n doc.mozMatchesSelect"
},
{
"path": "lib/assets/javascripts/vanilla-ujs.js",
"chars": 31,
"preview": "//= require_tree ./vanilla-ujs\n"
},
{
"path": "lib/vanilla/ujs/rails.rb",
"chars": 83,
"preview": "module Vanilla\n module Rails\n class Engine < ::Rails::Engine\n end\n end\nend\n"
},
{
"path": "lib/vanilla/ujs/version.rb",
"chars": 67,
"preview": "module Vanilla\n module Ujs\n VERSION = '1.3.0'.freeze\n end\nend\n"
},
{
"path": "lib/vanilla/ujs.rb",
"chars": 128,
"preview": "require 'vanilla/ujs/version'\nrequire 'vanilla/ujs/rails'\n\nmodule Vanilla\n module Rails\n # Your code goes here...\n "
},
{
"path": "lib/vanilla-ujs.rb",
"chars": 22,
"preview": "require 'vanilla/ujs'\n"
},
{
"path": "package.json",
"chars": 977,
"preview": "{\n \"name\": \"vanilla-ujs\",\n \"version\": \"1.3.0\",\n \"description\": \"Rails UJS in VanillaJS\",\n \"main\": \"lib/assets/javasc"
},
{
"path": "test/config/globals.js",
"chars": 1156,
"preview": "(function () {\n var global = typeof global !== 'undefined' ?\n global :\n typeof self !== 'un"
},
{
"path": "test/confirm.spec.js",
"chars": 1175,
"preview": "describe('Link confirmation', function () {\n describe('<a> link', function () {\n var a, confirm, clickLink;\n\n bef"
},
{
"path": "test/csrf.spec.js",
"chars": 997,
"preview": "describe('CSRF', function () {\n beforeEach(function () {\n var token, param;\n\n token = doc().createElement('meta')"
},
{
"path": "test/disable.spec.js",
"chars": 2216,
"preview": "describe('Should disable links and buttons with [data-disable-with]', function () {\n describe('<a> link', function () {"
},
{
"path": "test/form.spec.js",
"chars": 3326,
"preview": "describe('Form methods', function () {\n var form, submit, submitForm;\n\n beforeEach(function () {\n form = document.c"
},
{
"path": "test/helpers/serv.js",
"chars": 1730,
"preview": "var express = require('express'),\n bodyParser = require('body-parser'),\n fs = require('fs'),\n path = require('p"
},
{
"path": "test/index.html",
"chars": 871,
"preview": "<!DOCTYPE html>\n<html>\n <head>\n <title>Mocha</title>\n <meta charset=\"UTF-8\">\n <script src=\"assets/mocha.js\"></"
},
{
"path": "test/liteajax.spec.js",
"chars": 867,
"preview": "describe('LiteAjax', function () {\n describe('success callback', function () {\n var xhr, callbackSpy;\n\n beforeEac"
},
{
"path": "test/method.spec.js",
"chars": 4168,
"preview": "describe('Link methods', function () {\n var a, clickLink;\n\n beforeEach(function () {\n a = document.createElement('a"
},
{
"path": "vanilla-ujs.gemspec",
"chars": 914,
"preview": "# coding: utf-8\nlib = File.expand_path('../lib', __FILE__)\n$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)\nrequi"
}
]
About this extraction
This page contains the full source code of the hauleth/vanilla-ujs GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 31 files (34.1 KB), approximately 9.3k tokens, and a symbol index with 9 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.