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 (@hauleth) Alex Tsokurov (@Ximik) ================================================ FILE: README.md ================================================ # Vanilla UJS [![Build Status][travis-img]][travis-link][![Dependency Status](https://gemnasium.com/hauleth/vanilla-ujs.svg)](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(' 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