Wrap existing JS modules in AMD module style

This commit is contained in:
Tautvidas Sipavičius
2015-08-12 16:33:15 +03:00
parent c1f9fb915b
commit 91f839dc49
9 changed files with 2183 additions and 999 deletions

View File

@@ -1,6 +1,14 @@
jQuery(function($) { define('admin', [
// dom ready './ajax',
$(function() { 'notice.js',
'modal.js',
'lib/handlebars.min.js',
'handlebars_helpers.js'
], function() {
jQuery(function($) {
// dom ready
$(function() {
});
}); });
}); });

View File

@@ -1,67 +1,67 @@
/** define('ajax', ['./mailpoet', 'jquery'], function(MailPoet, jQuery) {
* MailPoet Ajax "use strict";
**/ /**
(function() { * MailPoet Ajax
"use strict"; **/
MailPoet.Ajax = { MailPoet.Ajax = {
version: 0.1, version: 0.1,
options: {}, options: {},
defaults: { defaults: {
url: null, url: null,
controller: 'dummy', controller: 'dummy',
action: 'test', action: 'test',
data: {}, data: {},
onSuccess: function(data, textStatus, xhr) {}, onSuccess: function(data, textStatus, xhr) {},
onError: function(xhr, textStatus, errorThrown) {} onError: function(xhr, textStatus, errorThrown) {}
}, },
get: function(options) { get: function(options) {
this.request('get', options); this.request('get', options);
}, },
post: function(options) { post: function(options) {
this.request('post', options); this.request('post', options);
}, },
delete: function(options) { delete: function(options) {
this.request('delete', options); this.request('delete', options);
}, },
init: function(options) { init: function(options) {
// merge options // merge options
this.options = jQuery.extend({}, this.defaults, options); this.options = jQuery.extend({}, this.defaults, options);
if(this.options.url === null) { if(this.options.url === null) {
this.options.url = ajaxurl+'?action=mailpoet_ajax'; this.options.url = ajaxurl+'?action=mailpoet_ajax';
}
// routing
this.options.url += '&mailpoet_controller='+this.options.controller;
this.options.url += '&mailpoet_action='+this.options.action;
},
request: function(method, options) {
// set options
this.init(options);
// make ajax request depending on method
if(method === 'get') {
jQuery.get(
this.options.url,
this.options.data,
this.options.onSuccess,
'json'
);
} else {
jQuery.ajax(
this.options.url,
{
data: JSON.stringify(this.options.data),
processData: false,
contentType: "application/json; charset=utf-8",
type : method,
dataType: 'json',
success : this.options.onSuccess,
error : this.options.onError
}
);
}
} }
};
})(window.MailPoet = window.MailPoet || {}, jQuery); // routing
this.options.url += '&mailpoet_controller='+this.options.controller;
this.options.url += '&mailpoet_action='+this.options.action;
},
request: function(method, options) {
// set options
this.init(options);
// make ajax request depending on method
if(method === 'get') {
jQuery.get(
this.options.url,
this.options.data,
this.options.onSuccess,
'json'
);
} else {
jQuery.ajax(
this.options.url,
{
data: JSON.stringify(this.options.data),
processData: false,
contentType: "application/json; charset=utf-8",
type : method,
dataType: 'json',
success : this.options.onSuccess,
error : this.options.onError
}
);
}
}
};
});

View File

@@ -1,140 +1,142 @@
// Handlebars helpers define('handlebars_helpers', ['lib/handlebars.min.js'], function(Handlebars) {
Handlebars.registerHelper('concat', function() { // Handlebars helpers
var size = (arguments.length - 1), Handlebars.registerHelper('concat', function() {
output = ''; var size = (arguments.length - 1),
for(var i = 0; i < size; i++) { output = '';
output += arguments[i]; for(var i = 0; i < size; i++) {
output += arguments[i];
};
return output;
});
Handlebars.registerHelper('number_format', function(value, block) {
return Number(value).toLocaleString();
});
Handlebars.registerHelper('date_format', function(timestamp, block) {
if(window.moment) {
if(timestamp === undefined || isNaN(timestamp) || timestamp <= 0) {
return;
}
// set date format
var f = block.hash.format || "MMM Do, YYYY";
// check if we passed a timestamp
if(parseInt(timestamp, 10) == timestamp) {
return moment.unix(timestamp).format(f);
} else {
return moment.utc(timestamp).format(f);
}
} else {
return timestamp;
}; };
return output; });
});
Handlebars.registerHelper('cycle', function(value, block) {
Handlebars.registerHelper('number_format', function(value, block) { var values = value.split(' ');
return Number(value).toLocaleString(); return values[block.data.index % (values.length + 1)];
}); });
Handlebars.registerHelper('date_format', function(timestamp, block) {
if(window.moment) { Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
if(timestamp === undefined || isNaN(timestamp) || timestamp <= 0) { switch (operator) {
return; case '==':
} return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
// set date format return (v1 === v2) ? options.fn(this) : options.inverse(this);
var f = block.hash.format || "MMM Do, YYYY"; case '!=':
// check if we passed a timestamp return (v1 != v2) ? options.fn(this) : options.inverse(this);
if(parseInt(timestamp, 10) == timestamp) { case '!==':
return moment.unix(timestamp).format(f); return (v1 !== v2) ? options.fn(this) : options.inverse(this);
} else { case '<':
return moment.utc(timestamp).format(f); return (v1 < v2) ? options.fn(this) : options.inverse(this);
} case '<=':
} else { return (v1 <= v2) ? options.fn(this) : options.inverse(this);
return timestamp; case '>':
}; return (v1 > v2) ? options.fn(this) : options.inverse(this);
}); case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
Handlebars.registerHelper('cycle', function(value, block) { case '&&':
var values = value.split(' '); return (v1 && v2) ? options.fn(this) : options.inverse(this);
return values[block.data.index % (values.length + 1)]; case '||':
}); return (v1 || v2) ? options.fn(this) : options.inverse(this);
case 'in':
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) { var values = v2.split(',');
switch (operator) { return (v2.indexOf(v1) !== -1) ? options.fn(this) : options.inverse(this);
case '==': default:
return (v1 == v2) ? options.fn(this) : options.inverse(this); return options.inverse(this);
case '===': }
return (v1 === v2) ? options.fn(this) : options.inverse(this); });
case '!=':
return (v1 != v2) ? options.fn(this) : options.inverse(this); Handlebars.registerHelper('nl2br', function(value, block) {
case '!==': return value.gsub("\n", "<br />");
return (v1 !== v2) ? options.fn(this) : options.inverse(this); });
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this); Handlebars.registerHelper('json_encode', function(value, block) {
case '<=': return JSON.stringify(value);
return (v1 <= v2) ? options.fn(this) : options.inverse(this); });
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this); Handlebars.registerHelper('json_decode', function(value, block) {
case '>=': return JSON.parse(value);
return (v1 >= v2) ? options.fn(this) : options.inverse(this); });
case '&&': Handlebars.registerHelper('url', function(value, block) {
return (v1 && v2) ? options.fn(this) : options.inverse(this); var url = window.location.protocol + "//" + window.location.host + window.location.pathname;
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this); return url + value;
case 'in': });
var values = v2.split(','); Handlebars.registerHelper('emailFromMailto', function(value) {
return (v2.indexOf(v1) !== -1) ? options.fn(this) : options.inverse(this); var mailtoMatchingRegex = /^mailto\:/i;
default: if (typeof value === 'string' && value.match(mailtoMatchingRegex)) {
return options.inverse(this); return value.replace(mailtoMatchingRegex, '');
} } else {
}); return value;
}
Handlebars.registerHelper('nl2br', function(value, block) { });
return value.gsub("\n", "<br />"); Handlebars.registerHelper('lookup', function(obj, field, options) {
}); return obj && obj[field];
});
Handlebars.registerHelper('json_encode', function(value, block) {
return JSON.stringify(value);
}); Handlebars.registerHelper('rsa_key', function(value, block) {
// extract all lines into an array
Handlebars.registerHelper('json_decode', function(value, block) { if(value === undefined) return '';
return JSON.parse(value);
}); var lines = value.trim().split("\n");
Handlebars.registerHelper('url', function(value, block) {
var url = window.location.protocol + "//" + window.location.host + window.location.pathname; // remove header & footer
lines.shift();
return url + value; lines.pop();
});
Handlebars.registerHelper('emailFromMailto', function(value) { // return concatenated lines
var mailtoMatchingRegex = /^mailto\:/i; return lines.join('');
if (typeof value === 'string' && value.match(mailtoMatchingRegex)) { });
return value.replace(mailtoMatchingRegex, '');
} else { Handlebars.registerHelper('trim', function(value, block) {
return value; if(value === null || value === undefined) return '';
} return value.trim();
}); });
Handlebars.registerHelper('lookup', function(obj, field, options) {
return obj && obj[field]; /**
}); * {{ellipsis}}
* From: https://github.com/assemble/handlebars-helpers
* @author: Jon Schlinkert <http://github.com/jonschlinkert>
Handlebars.registerHelper('rsa_key', function(value, block) { * Truncate the input string and removes all HTML tags
// extract all lines into an array * @param {String} str The input string.
if(value === undefined) return ''; * @param {Number} limit The number of characters to limit the string.
* @param {String} append The string to append if charaters are omitted.
var lines = value.trim().split("\n"); * @return {String} The truncated string.
*/
// remove header & footer Handlebars.registerHelper('ellipsis', function (str, limit, append) {
lines.shift(); if (append === undefined) {
lines.pop(); append = '';
}
// return concatenated lines var sanitized = str.replace(/(<([^>]+)>)/g, '');
return lines.join(''); if (sanitized.length > limit) {
}); return sanitized.substr(0, limit - append.length) + append;
} else {
Handlebars.registerHelper('trim', function(value, block) { return sanitized;
if(value === null || value === undefined) return ''; }
return value.trim(); });
});
Handlebars.registerHelper('getNumber', function (string) {
/** return parseInt(string, 10);
* {{ellipsis}} });
* From: https://github.com/assemble/handlebars-helpers
* @author: Jon Schlinkert <http://github.com/jonschlinkert>
* Truncate the input string and removes all HTML tags
* @param {String} str The input string.
* @param {Number} limit The number of characters to limit the string.
* @param {String} append The string to append if charaters are omitted.
* @return {String} The truncated string.
*/
Handlebars.registerHelper('ellipsis', function (str, limit, append) {
if (append === undefined) {
append = '';
}
var sanitized = str.replace(/(<([^>]+)>)/g, '');
if (sanitized.length > limit) {
return sanitized.substr(0, limit - append.length) + append;
} else {
return sanitized;
}
});
Handlebars.registerHelper('getNumber', function (string) {
return parseInt(string, 10);
}); });

9
assets/js/mailpoet.js Normal file
View File

@@ -0,0 +1,9 @@
define('mailpoet', [], function() {
// A placeholder for MailPoet object
var MailPoet = {};
// Expose MailPoet globally
window.MailPoet = MailPoet;
return MailPoet;
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,175 +1,175 @@
/*================================================================================================== define('notice', ['./mailpoet', 'jquery'], function(MailPoet, jQuery) {
MailPoet Notice:
description: Handles notices
version: 0.2
author: Jonathan Labreuille
company: Wysija
dependencies: jQuery
Usage:
// success message (static: false)
MailPoet.Notice.success('Yatta!');
// error message (static: false)
MailPoet.Notice.error('Boo!');
// system message (static: true)
MailPoet.Notice.system('You need to updated ASAP!');
Examples:
MailPoet.Notice.success('- success #1 -');
setTimeout(function() {
MailPoet.Notice.success('- success #2 -');
setTimeout(function() {
MailPoet.Notice.error('- error -');
setTimeout(function() {
MailPoet.Notice.system('- system -');
setTimeout(function() {
MailPoet.Notice.hide();
}, 2500);
}, 300);
}, 400);
}, 500);
==================================================================================================*/
(function(){
"use strict"; "use strict";
/*==================================================================================================
MailPoet.Notice = { MailPoet Notice:
version: 0.2,
// default options
defaults: {
type: 'success',
message: '',
static: false,
scroll: false,
timeout: 2000,
onOpen: null,
onClose: null
},
options: {},
init: function(options) {
// set options
this.options = jQuery.extend({}, this.defaults, options);
// clone element description: Handles notices
this.element = jQuery('#mailpoet_notice_'+this.options.type).clone(); version: 0.2
author: Jonathan Labreuille
company: Wysija
dependencies: jQuery
// remove id from clone Usage:
this.element.removeAttr('id');
// insert notice after its parent // success message (static: false)
jQuery('#mailpoet_notice_'+this.options.type).after(this.element); MailPoet.Notice.success('Yatta!');
// setup onClose callback // error message (static: false)
var onClose = null; MailPoet.Notice.error('Boo!');
if(this.options.onClose !== null) {
onClose = this.options.onClose;
}
// listen to remove event // system message (static: true)
var element = this.element; MailPoet.Notice.system('You need to updated ASAP!');
jQuery(this.element).on('close', function() {
jQuery(this).fadeOut(200, function() {
// on close callback
if(onClose !== null) {
onClose();
}
// remove notice
jQuery(this).remove();
});
}.bind(this.element));
// listen to message event Examples:
jQuery(this.element).on('message', function(e, message) {
MailPoet.Notice.setMessage(message);
}.bind(this.element));
return this; MailPoet.Notice.success('- success #1 -');
}, setTimeout(function() {
isHTML: function(str) { MailPoet.Notice.success('- success #2 -');
var a = document.createElement('div'); setTimeout(function() {
a.innerHTML = str; MailPoet.Notice.error('- error -');
for(var c = a.childNodes, i = c.length; i--;) { setTimeout(function() {
if(c[i].nodeType == 1) return true; MailPoet.Notice.system('- system -');
}
return false;
},
setMessage: function(message) {
// if it's not an html message, let's sugar coat the message with a fancy <p>
if(this.isHTML(message) === false) {
message = '<p>'+message+'</p>';
}
// set message
return this.element.html(message);
},
show: function(options) {
// initialize
this.init(options);
// show notice setTimeout(function() {
this.showNotice(); MailPoet.Notice.hide();
}, 2500);
}, 300);
}, 400);
}, 500);
// return this; ==================================================================================================*/
},
showNotice: function() {
// set message
this.setMessage(this.options.message);
// make the notice appear MailPoet.Notice = {
this.element.fadeIn(200); version: 0.2,
// default options
defaults: {
type: 'success',
message: '',
static: false,
scroll: false,
timeout: 2000,
onOpen: null,
onClose: null
},
options: {},
init: function(options) {
// set options
this.options = jQuery.extend({}, this.defaults, options);
// if scroll option is enabled, scroll to the notice // clone element
if(this.options.scroll === true) { this.element = jQuery('#mailpoet_notice_'+this.options.type).clone();
this.element.get(0).scrollIntoView(false);
}
// if the notice is not static, it has to disappear after a timeout // remove id from clone
if(this.options.static === false) { this.element.removeAttr('id');
this.element.delay(this.options.timeout).trigger('close');
} else {
this.element.append('<a href="javascript:;" class="mailpoet_notice_close"><span class="dashicons dashicons-dismiss"></span></a>');
this.element.find('.mailpoet_notice_close').on('click', function() {
jQuery(this).trigger('close');
});
}
// call onOpen callback // insert notice after its parent
if(this.options.onOpen !== null) { jQuery('#mailpoet_notice_'+this.options.type).after(this.element);
this.options.onOpen(this.element);
} // setup onClose callback
}, var onClose = null;
hide: function(all) { if(this.options.onClose !== null) {
if(all !== undefined && all === true) { onClose = this.options.onClose;
jQuery('.mailpoet_notice:not([id])').trigger('close'); }
} else {
jQuery('.mailpoet_notice.updated:not([id]), .mailpoet_notice.error:not([id])') // listen to remove event
.trigger('close'); var element = this.element;
} jQuery(this.element).on('close', function() {
}, jQuery(this).fadeOut(200, function() {
error: function(message, options) { // on close callback
this.show(jQuery.extend({}, { if(onClose !== null) {
type: 'error', onClose();
message: '<p>'+message+'</p>' }
}, options)); // remove notice
}, jQuery(this).remove();
success: function(message, options) { });
this.show(jQuery.extend({}, { }.bind(this.element));
type: 'success',
message: '<p>'+message+'</p>' // listen to message event
}, options)); jQuery(this.element).on('message', function(e, message) {
}, MailPoet.Notice.setMessage(message);
system: function(message, options) { }.bind(this.element));
this.show(jQuery.extend({}, {
type: 'system', return this;
static: true, },
message: message isHTML: function(str) {
}, options)); var a = document.createElement('div');
} a.innerHTML = str;
}; for(var c = a.childNodes, i = c.length; i--;) {
})(window.MailPoet = window.MailPoet || {}, jQuery); if(c[i].nodeType == 1) return true;
}
return false;
},
setMessage: function(message) {
// if it's not an html message, let's sugar coat the message with a fancy <p>
if(this.isHTML(message) === false) {
message = '<p>'+message+'</p>';
}
// set message
return this.element.html(message);
},
show: function(options) {
// initialize
this.init(options);
// show notice
this.showNotice();
// return this;
},
showNotice: function() {
// set message
this.setMessage(this.options.message);
// make the notice appear
this.element.fadeIn(200);
// if scroll option is enabled, scroll to the notice
if(this.options.scroll === true) {
this.element.get(0).scrollIntoView(false);
}
// if the notice is not static, it has to disappear after a timeout
if(this.options.static === false) {
this.element.delay(this.options.timeout).trigger('close');
} else {
this.element.append('<a href="javascript:;" class="mailpoet_notice_close"><span class="dashicons dashicons-dismiss"></span></a>');
this.element.find('.mailpoet_notice_close').on('click', function() {
jQuery(this).trigger('close');
});
}
// call onOpen callback
if(this.options.onOpen !== null) {
this.options.onOpen(this.element);
}
},
hide: function(all) {
if(all !== undefined && all === true) {
jQuery('.mailpoet_notice:not([id])').trigger('close');
} else {
jQuery('.mailpoet_notice.updated:not([id]), .mailpoet_notice.error:not([id])')
.trigger('close');
}
},
error: function(message, options) {
this.show(jQuery.extend({}, {
type: 'error',
message: '<p>'+message+'</p>'
}, options));
},
success: function(message, options) {
this.show(jQuery.extend({}, {
type: 'success',
message: '<p>'+message+'</p>'
}, options));
},
system: function(message, options) {
this.show(jQuery.extend({}, {
type: 'system',
static: true,
message: message
}, options));
}
};
});

1166
assets/js/src/admin.js Normal file

File diff suppressed because one or more lines are too long

View File

@@ -23,11 +23,7 @@
<!-- javascripts --> <!-- javascripts -->
<%= javascript( <%= javascript(
'ajax.js', 'src/admin.js'
'notice.js',
'modal.js',
'lib/handlebars.min.js',
'handlebars_helpers.js'
)%> )%>
<!-- handlebars templates --> <!-- handlebars templates -->

View File

@@ -5,7 +5,7 @@ var path = require('path'),
module.exports = { module.exports = {
context: __dirname , context: __dirname ,
entry: { entry: {
mailpoet: './assets/js/mailpoet', admin: './assets/js/admin.js',
}, },
output: { output: {
path: './assets/js/src', path: './assets/js/src',
@@ -41,5 +41,8 @@ module.exports = {
alias: { alias: {
'hbs': 'handlebars-loader' 'hbs': 'handlebars-loader'
} }
},
externals: {
'jquery': 'jQuery',
} }
}; };