Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bevacqua committed Jun 26, 2015
0 parents commit c31b64b
Show file tree
Hide file tree
Showing 11 changed files with 465 additions and 0 deletions.
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
npm-debug.log
.DS_Store
Thumbs.db
4 changes: 4 additions & 0 deletions .jshintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
bower_components
dist
example
23 changes: 23 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"curly": true,
"eqeqeq": true,
"newcap": true,
"noarg": true,
"noempty": true,
"nonew": true,
"sub": true,
"undef": true,
"unused": true,
"trailing": true,
"boss": true,
"eqnull": true,
"strict": true,
"immed": true,
"expr": true,
"latedef": "nofunc",
"quotmark": "single",
"validthis": true,
"indent": 2,
"node": true,
"browser": true
}
3 changes: 3 additions & 0 deletions changelog.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# 1.0.0 IPO

- Initial Public Release
151 changes: 151 additions & 0 deletions gradual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
'use strict';

// jshint scripturl:true

var $ = require('dominus');
var queso = require('queso');
var safeson = require('safeson');
var emitter = require('contra.emitter');
var formulario = require('formulario');
var formResponseHandler = require('./lib/formResponseHandler');
var state = require('./lib/state');
var transformers = [];
var gradual = emitter({
hijack: hijack,
transform: transform,
submit: submit,
configure: state.configure
});

function noop () {}

function hijack (e) {
var form = e.target;
submitForm(form);
e.preventDefault();
}

function transform (fn) {
transformers.push(fn);
}

/* AJAX form submissions use an intermediary <iframe> to help browsers remember
* autocompletion suggestions. We submit the form against the <iframe> and then
* grab the response as plain-text JSON that we need to parse into JSON.
* Afterwards we can hand that JSON to the response handler, business as usual.
* Since we've submitted the form "organically", the browser stores suggestions.
*/
function frame (form) {
var name = 'ff-' + new Date().valueOf();
$(form)
.attr('autocomplete', 'on')
.attr('target', name);
return $('<iframe>')
.css('display', 'none')
.attr('id', name)
.attr('name', name)
.attr('src', 'javascript:void 0')
.afterOf(form);
}

function submitForm (form, done) {
var textareaCloneValue = 'data-clone-value';
var iframe = frame(form);
var content = iframe[0].contentWindow;
var restore = transformers.map(run);
var textareas = $('textarea', form);
textareas.forEach(preserveValue);
var formClone = form.cloneNode(true);
var textareaClones = $('textarea', formClone);
disable(form);
$('button', form).forEach(disable);
$('[autofocus]', formClone).attr('autofocus', null);
textareaClones.forEach(updateValue);
textareas.forEach(restoreTextarea);
var formCloneId = 'f' + iframe[0].id;
formClone.id = formCloneId;
iframe.once('load', grabResponse);
content.document.body.appendChild(formClone);
var frameForm = content.document.getElementById(formCloneId);
var prefix = frameForm.action.indexOf('?') === -1 ? '?' : '&';
frameForm.action += prefix + 'json&as-text' + queso(state.qs, true);
frameForm.onsubmit = null;
frameForm.submit();
restore.forEach(run);
function preserveValue (textarea) {
var ta = $(textarea);
ta.attr(textareaCloneValue, ta.value());
}
function updateValue (textarea) {
var ta = $(textarea);
ta.value(ta.attr(textareaCloneValue)).attr(textareaCloneValue, null);
}
function restoreTextarea (textarea) {
$(textarea).attr(textareaCloneValue, null);
}
function grabResponse () {
var html = readResponse(content);
if (!html) {
gotResponse(new Error('Internal Server Error')); return;
}
var json = decodeResponse(html);
var err = json ? null : new Error('Malformed response');
gotResponse(err, json);
function gotResponse (err, data) {
$('button', form).forEach(enable);
enable(form);
iframe.remove();
raise(err, data, form, done);
}
}
function readResponse (content) {
try {
return content.document.body.innerHTML;
} catch (e) { // failure to read (most likely) means server crashed or response timed out
}
}
function decodeResponse (html) {
try {
return safeson.decode(html);
} catch (e) {
}
}
function run (fn) {
return (fn || noop)(form);
}
function disable (el) {
el.disabled = true;
}
function enable (el) {
el.disabled = false;
}
}

function submit (options, done) {
var form = options.form;
if (form) {
submitForm(form, done); return;
}
var formData = formulario(options.data);
var req = {
method: options.method,
headers: formData.headers,
body: formData.body
};
return state.taunus.xhr(options.action, req, handler);
function handler (err, data) {
raise(err, data, null, done);
}
}

function raise (err, data, context, done) {
if (err) {
gradual.emit.call(context, 'error', err);
} else {
gradual.emit.call(context, 'data', data);
}
gradual.emit.call(context, 'response', err, data);
formResponseHandler(err, data, context, done);
}

module.exports = gradual;
79 changes: 79 additions & 0 deletions lib/formResponseHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'use strict';

var $ = require('dominus');
var state = require('./state');

function noop () {}

function formResponseHandler (err, data, form, done) {
var end = done || noop;
if (err) {
end(err); return;
}
var host = getNotificationHost(data);
if (host) {
messages(form, host);
} else if (data.redirect) {
data.redirect.force = true;
state.taunus.redirect(data.redirect); return;
}
end(null, data);
}

function hasItems (host, prop) {
return Array.isArray(host[prop]) ? host[prop].length : host[prop];
}

function getNotificationHost (host) {
if (!host) {
return false;
}
if (hasItems(host, 'validation') || hasItems(host, 'messages')) {
return host;
}
return getNotificationHost(host.model) || getNotificationHost(host.flash);
}

function messages (form, model) {
var partial = 'partials/form-validation';
var dialog = $('<div>');
var dialogElement = dialog[0];
var show = form ? attachToForm : displayInDialog;

$('.fv-dialog').remove();

if (form) {
$('.ss-container,.fv-container', form).remove();
}

state.taunus.partial(dialogElement, partial, model).on('render', show);

function attachToForm () {
var contents = dialog.children();
$(form).addClass('ff-validated').prepend(contents);
dialog.remove();
}

function displayInDialog () {
var body = $(document.body);

$('<button>')
.appendTo(dialog.find('.fv-header'))
.addClass('fv-dialog-dismiss')
.attr('aria-label', 'Click here to dismiss this message')
.on('click', dialogClose);
dialog.appendTo(body).addClass('fv-dialog');
body.on('click', dialogClose);
}

function dialogClose (e) {
var body = $(document.body);
var target = $(e.target);
if (target.is('.fv-dialog-dismiss') || (target.is('.fv-dialog') === false && target.parents('.fv-dialog').length === 0)) {
body.off('click', dialogClose);
dialog.remove();
}
}
}

module.exports = formResponseHandler;
12 changes: 12 additions & 0 deletions lib/state.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict';

var state = {
configure: configure
};

function configure (options) {
state.taunus = options.taunus;
state.qs = options.qs;
}

module.exports = state;
20 changes: 20 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright © 2015 Nicolas Bevacqua

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.
25 changes: 25 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "gradual",
"version": "1.0.0",
"description": "Automated progressive enhancement for <form> elements when using Taunus",
"main": "gradual.js",
"repository": {
"type": "git",
"url": "https://github.com/taunus/gradual.git"
},
"author": "Nicolas Bevacqua <nicolasbevacqua@gmail.com> (http://bevacqua.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/taunus/gradual/issues"
},
"homepage": "https://github.com/taunus/gradual",
"dependencies": {
"contra.emitter": "1.1.1",
"dominus": "5.0.0",
"formulario": "1.0.0",
"queso": "1.0.0",
"safeson": "1.0.0"
},
"devDependencies": {
}
}
Loading

0 comments on commit c31b64b

Please sign in to comment.