ES5 one-var

This commit is contained in:
Amine Ben hammou
2017-09-25 09:39:00 +00:00
parent a11d6d7868
commit c3ea088fca
27 changed files with 584 additions and 593 deletions

View File

@ -43,7 +43,6 @@
"brace-style": 0, "brace-style": 0,
"no-else-return": 0, "no-else-return": 0,
"no-use-before-define": 0, "no-use-before-define": 0,
"one-var": 0,
"camelcase": 0, "camelcase": 0,
"padded-blocks": 0, "padded-blocks": 0,
"strict": 0, "strict": 0,

View File

@ -38,8 +38,8 @@ Object.extend(document, (function () {
} }
function createWrapper(selector, eventName, handler, context) { function createWrapper(selector, eventName, handler, context) {
var wrapper, var wrapper;
c = getWrappersForSelector(selector, eventName); var c = getWrappersForSelector(selector, eventName);
if(c.pluck('handler').include(handler)) return false; if(c.pluck('handler').include(handler)) return false;
wrapper = function(event) { wrapper = function(event) {
var element = event.findElement(selector); var element = event.findElement(selector);
@ -90,10 +90,10 @@ var Observable = (function () {
} }
function getHandlers(klass) { function getHandlers(klass) {
var proto = klass.prototype, var proto = klass.prototype;
namespace = proto.namespace; var namespace = proto.namespace;
return Object.keys(proto).grep(/^on/).inject(window.$H(), function (handlers, name) { return Object.keys(proto).grep(/^on/).inject(window.$H(), function(handlers, name) {
if (name === 'onDomLoaded') return handlers; if(name === 'onDomLoaded') return handlers;
handlers.set(getEventName(name, namespace), getWrapper(proto[name], klass)); handlers.set(getEventName(name, namespace), getWrapper(proto[name], klass));
return handlers; return handlers;
}); });
@ -148,8 +148,8 @@ Object.extend(window.Droppables, {
}), }),
show: function(point, element) { show: function(point, element) {
if(!this.drops.length) return; if(!this.drops.length) return;
var drop, var drop;
affected = []; var affected = [];
this.drops.each(function(drop) { this.drops.each(function(drop) {
if(window.Droppables.isAffected(point, element, drop)) affected.push(drop); if(window.Droppables.isAffected(point, element, drop)) affected.push(drop);
}); });
@ -325,14 +325,14 @@ var WysijaForm = {
}); });
} }
}, },
save: function () { save: function() {
var position = 1, var position = 1;
data = { var data = {
name: window.$F('mailpoet_form_name'), name: window.$F('mailpoet_form_name'),
settings: window.$('mailpoet_form_settings').serialize(true), settings: window.$('mailpoet_form_settings').serialize(true),
body: [], body: [],
styles: (window.MailPoet.CodeEditor !== undefined) ? window.MailPoet.CodeEditor.getValue() : null styles: (window.MailPoet.CodeEditor !== undefined) ? window.MailPoet.CodeEditor.getValue() : null
}; };
// body // body
WysijaForm.getBlocks().each(function (b) { WysijaForm.getBlocks().each(function (b) {
var block_data = (typeof (b.block['save']) === 'function') ? b.block.save() : null; var block_data = (typeof (b.block['save']) === 'function') ? b.block.save() : null;
@ -455,8 +455,8 @@ var WysijaForm = {
if (target !== undefined) { if (target !== undefined) {
// get placeholders (previous placeholder matches the placeholder linked to the next block) // get placeholders (previous placeholder matches the placeholder linked to the next block)
var block_placeholder = window.$(target.element.readAttribute('wysija_placeholder')), var block_placeholder = window.$(target.element.readAttribute('wysija_placeholder'));
previous_placeholder = target.element.previous('.block_placeholder'); var previous_placeholder = target.element.previous('.block_placeholder');
if (block_placeholder !== null) { if (block_placeholder !== null) {
// put block placeholder before the current block // put block placeholder before the current block
@ -481,22 +481,22 @@ var WysijaForm = {
}, },
setSettingsPosition: function () { setSettingsPosition: function () {
// get viewport offsets and dimensions // get viewport offsets and dimensions
var viewportHeight = document.viewport.getHeight(), var viewportHeight = document.viewport.getHeight();
blockPadding = 5; var blockPadding = 5;
window.$(WysijaForm.options.container).select('.wysija_settings').each(function (element) { window.$(WysijaForm.options.container).select('.wysija_settings').each(function (element) {
// get parent dimensions and position // get parent dimensions and position
var parentDim = element.up('.mailpoet_form_block').getDimensions(), var parentDim = element.up('.mailpoet_form_block').getDimensions();
parentPos = element.up('.mailpoet_form_block').cumulativeOffset(), var parentPos = element.up('.mailpoet_form_block').cumulativeOffset();
is_visible = (parentPos.top <= (WysijaForm.scroll.top + viewportHeight)), var is_visible = (parentPos.top <= (WysijaForm.scroll.top + viewportHeight));
buttonMargin = 5, var buttonMargin = 5;
relativeTop = buttonMargin; var relativeTop = buttonMargin;
if (is_visible) { if (is_visible) {
// desired position is set to center of viewport // desired position is set to center of viewport
var absoluteTop = parseInt(WysijaForm.scroll.top + ((viewportHeight / 2) - (element.getHeight() / 2)), 10), var absoluteTop = parseInt(WysijaForm.scroll.top + ((viewportHeight / 2) - (element.getHeight() / 2)), 10);
parentTop = parseInt(parentPos.top - blockPadding, 10), var parentTop = parseInt(parentPos.top - blockPadding, 10);
parentBottom = parseInt(parentPos.top + parentDim.height - blockPadding, 10); var parentBottom = parseInt(parentPos.top + parentDim.height - blockPadding, 10);
// always center // always center
relativeTop = parseInt((parentDim.height / 2) - (element.getHeight() / 2), 10); relativeTop = parseInt((parentDim.height / 2) - (element.getHeight() / 2), 10);
@ -638,8 +638,8 @@ var WysijaForm = {
}, },
encodeURIComponent: function (str) { encodeURIComponent: function (str) {
// check if it's a url and if so, prevent encoding of protocol // check if it's a url and if so, prevent encoding of protocol
var regexp = new RegExp(/^http[s]?:\/\//), var regexp = new RegExp(/^http[s]?:\/\//);
protocol = regexp.exec(str); var protocol = regexp.exec(str);
if (protocol === null) { if (protocol === null) {
// this is not a url so encode the whole thing // this is not a url so encode the whole thing
@ -681,14 +681,14 @@ WysijaForm.DraggableItem = window.Class.create({
this.insert(); this.insert();
}, },
STYLES: new window.Template('position: absolute; top: #{top}px; left: #{left}px;'), STYLES: new window.Template('position: absolute; top: #{top}px; left: #{left}px;'),
cloneElement: function () { cloneElement: function() {
var clone = this.element.clone(), var clone = this.element.clone();
offset = this.element.cumulativeOffset(), var offset = this.element.cumulativeOffset();
list = this.getList(), var list = this.getList();
styles = this.STYLES.evaluate({ var styles = this.STYLES.evaluate({
top: offset.top - list.scrollTop, top: offset.top - list.scrollTop,
left: offset.left - list.scrollLeft left: offset.left - list.scrollLeft
}); });
clone.setStyle(styles); clone.setStyle(styles);
clone.addClassName('mailpoet_form_widget'); clone.addClassName('mailpoet_form_widget');
@ -911,10 +911,10 @@ WysijaForm.Block.create = function (createBlock, target) {
return false; return false;
} }
var body = window.$(WysijaForm.options.body), var body = window.$(WysijaForm.options.body);
block_template = window.Handlebars.compile(window.$('form_template_block').innerHTML), var block_template = window.Handlebars.compile(window.$('form_template_block').innerHTML);
template = window.Handlebars.compile(window.$('form_template_' + block.type).innerHTML), var template = window.Handlebars.compile(window.$('form_template_' + block.type).innerHTML);
output = ''; var output = '';
if (block.type === 'segment') { if (block.type === 'segment') {
if (block.params.values === undefined) { if (block.params.values === undefined) {
@ -995,9 +995,9 @@ WysijaForm.Widget = window.Class.create(WysijaForm.Block, {
return data; return data;
}, },
setData: function (data) { setData: function(data) {
var current_data = this.getData(), var current_data = this.getData();
params = window.$H(current_data.params).merge(data.params).toObject(); var params = window.$H(current_data.params).merge(data.params).toObject();
// update type if it changed // update type if it changed
if (data.type !== undefined && data.type !== current_data.type) { if (data.type !== undefined && data.type !== current_data.type) {
@ -1026,11 +1026,11 @@ WysijaForm.Widget = window.Class.create(WysijaForm.Block, {
this.setData(data); this.setData(data);
var options = this.getData(); var options = this.getData();
// redraw block // redraw block
var block_template = window.Handlebars.compile(window.$('form_template_block').innerHTML), var block_template = window.Handlebars.compile(window.$('form_template_block').innerHTML);
template = window.Handlebars.compile(window.$('form_template_' + options.type).innerHTML), var template = window.Handlebars.compile(window.$('form_template_' + options.type).innerHTML);
data = window.$H(options).merge({ var data = window.$H(options).merge({
template: template(options) template: template(options)
}).toObject(); }).toObject();
this.element.replace(block_template(data)); this.element.replace(block_template(data));
WysijaForm.init(); WysijaForm.init();

View File

@ -1,9 +1,9 @@
define('handlebars_helpers', ['handlebars'], function (Handlebars) { define('handlebars_helpers', ['handlebars'], function (Handlebars) {
// Handlebars helpers // Handlebars helpers
Handlebars.registerHelper('concat', function () { Handlebars.registerHelper('concat', function() {
var size = (arguments.length - 1), var size = (arguments.length - 1);
output = ''; var output = '';
for (var i = 0; i < size; i++) { for(var i = 0; i < size; i++) {
output += arguments[i]; output += arguments[i];
} }
return output; return output;

View File

@ -23,21 +23,21 @@ define(
* Dual licensed under the MIT and GPL licenses. * Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/ * http://benalman.com/about/license/
*/ */
$.fn.serializeObject = function (coerce) { $.fn.serializeObject = function(coerce) {
var obj = {}, var obj = {};
coerce_types = { true: !0, false: !1, null: null }; var coerce_types = { true: !0, false: !1, null: null };
// Iterate over all name=value pairs. // Iterate over all name=value pairs.
$.each(this.serializeArray(), function (j, v) { $.each( this.serializeArray(), function(j, v){
var key = v.name, var key = v.name;
val = v.value, var val = v.value;
cur = obj, var cur = obj;
i = 0, var i = 0;
// If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it
// into its component parts. // into its component parts.
keys = key.split(']['), var keys = key.split( '][' );
keys_last = keys.length - 1; var keys_last = keys.length - 1;
// If the first keys part contains [ and the last ends with ], then [] // If the first keys part contains [ and the last ends with ], then []
// are correctly balanced. // are correctly balanced.

View File

@ -345,13 +345,13 @@ define('modal', ['mailpoet', 'jquery'],
setPosition: function () { setPosition: function () {
switch (this.options.type) { switch (this.options.type) {
case 'popup': case 'popup':
var screenWidth = jQuery(window).width(), var screenWidth = jQuery(window).width();
screenHeight = jQuery(window).height(), var screenHeight = jQuery(window).height();
modalWidth = jQuery('.mailpoet_' + this.options.type + '_wrapper').width(), var modalWidth = jQuery('.mailpoet_'+ this.options.type +'_wrapper').width();
modalHeight = jQuery('.mailpoet_' + this.options.type + '_wrapper').height(); var modalHeight = jQuery('.mailpoet_'+ this.options.type +'_wrapper').height();
var top = Math.max(48, parseInt((screenHeight / 2) - (modalHeight / 2))), var top = Math.max(48, parseInt((screenHeight / 2) - (modalHeight / 2)));
left = Math.max(0, parseInt((screenWidth / 2) - (modalWidth / 2))); var left = Math.max(0, parseInt((screenWidth / 2) - (modalWidth / 2)));
// set position of popup depending on screen dimensions. // set position of popup depending on screen dimensions.
jQuery('#mailpoet_popup').css({ jQuery('#mailpoet_popup').css({

View File

@ -12,9 +12,9 @@ define([
var BL = BehaviorsLookup; var BL = BehaviorsLookup;
BL.ColorPickerBehavior = Marionette.Behavior.extend({ BL.ColorPickerBehavior = Marionette.Behavior.extend({
onRender: function () { onRender: function() {
var that = this, var that = this;
preferredFormat = 'hex6'; var preferredFormat = 'hex6';
this.view.$('.mailpoet_color').each(function () { this.view.$('.mailpoet_color').each(function () {
var $input = that.view.$(this); var $input = that.view.$(this);
var updateColorInput = function (color) { var updateColorInput = function (color) {

View File

@ -25,11 +25,11 @@ define([
this.addDropZone(); this.addDropZone();
} }
}, },
addDropZone: function (_event) { addDropZone: function(_event) {
var that = this, var that = this;
view = this.view, var view = this.view;
domElement = that.$el.get(0), var domElement = that.$el.get(0);
acceptableElementSelector; var acceptableElementSelector;
// TODO: Extract this limitation code to be controlled from containers // TODO: Extract this limitation code to be controlled from containers
if (this.view.renderOptions.depth === 0) { if (this.view.renderOptions.depth === 0) {
@ -63,26 +63,26 @@ define([
// 3b. If insertion is special, compute position (which side) and which cell the insertion belongs to // 3b. If insertion is special, compute position (which side) and which cell the insertion belongs to
// 4. If insertion at that position is not visualized, display position visualization there, remove other visualizations from this container // 4. If insertion at that position is not visualized, display position visualization there, remove other visualizations from this container
var dropPosition = that.getDropPosition( var dropPosition = that.getDropPosition(
event.dragmove.pageX, event.dragmove.pageX,
event.dragmove.pageY, event.dragmove.pageY,
view.$el, view.$el,
view.model.get('orientation'), view.model.get('orientation'),
view.model.get('blocks').length view.model.get('blocks').length
), );
element = view.$el, var element = view.$el;
markerWidth = '', var markerWidth = '';
markerHeight = '', var markerHeight = '';
containerOffset = element.offset(), var containerOffset = element.offset();
viewCollection = that.getCollection(), var viewCollection = that.getCollection();
marker, var marker;
targetModel, var targetModel;
targetView, var targetView;
targetElement, var targetElement;
topOffset, var topOffset;
leftOffset, var leftOffset;
isLastBlockInsertion, var isLastBlockInsertion;
$targetBlock, var $targetBlock;
margin; var margin;
if (dropPosition === undefined) return; if (dropPosition === undefined) return;
@ -184,19 +184,19 @@ define([
// 4. Perform cleanup actions // 4. Perform cleanup actions
var dropPosition = that.getDropPosition( var dropPosition = that.getDropPosition(
event.dragEvent.pageX, event.dragEvent.pageX,
event.dragEvent.pageY, event.dragEvent.pageY,
view.$el, view.$el,
view.model.get('orientation'), view.model.get('orientation'),
view.model.get('blocks').length view.model.get('blocks').length
), );
droppableModel = event.draggable.getDropModel(), var droppableModel = event.draggable.getDropModel();
viewCollection = that.getCollection(), var viewCollection = that.getCollection();
droppedView, var droppedView;
droppedModel, var droppedModel;
index, var index;
tempCollection, var tempCollection;
tempCollection2; var tempCollection2;
if (dropPosition === undefined) return; if (dropPosition === undefined) return;
@ -281,31 +281,31 @@ define([
// 2. Remove visual markings of drop position visualization // 2. Remove visual markings of drop position visualization
this.view.$('.mailpoet_drop_marker').remove(); this.view.$('.mailpoet_drop_marker').remove();
}, },
getDropPosition: function (eventX, eventY, is_unsafe) { getDropPosition: function(eventX, eventY, is_unsafe) {
var SPECIAL_AREA_INSERTION_WIDTH = 0.00, // Disable special insertion. Default: 0.3 var SPECIAL_AREA_INSERTION_WIDTH = 0.00; // Disable special insertion. Default: 0.3
element = this.view.$el, var element = this.view.$el;
orientation = this.view.model.get('orientation'), var orientation = this.view.model.get('orientation');
elementOffset = element.offset(), var elementOffset = element.offset();
elementPageX = elementOffset.left, var elementPageX = elementOffset.left;
elementPageY = elementOffset.top, var elementPageY = elementOffset.top;
elementWidth = element.outerWidth(true), var elementWidth = element.outerWidth(true);
elementHeight = element.outerHeight(true), var elementHeight = element.outerHeight(true);
relativeX = eventX - elementPageX, var relativeX = eventX - elementPageX;
relativeY = eventY - elementPageY, var relativeY = eventY - elementPageY;
relativeOffset, var relativeOffset;
elementLength, var elementLength;
canAcceptNormalInsertion = this._canAcceptNormalInsertion(), var canAcceptNormalInsertion = this._canAcceptNormalInsertion();
canAcceptSpecialInsertion = this._canAcceptSpecialInsertion(), var canAcceptSpecialInsertion = this._canAcceptSpecialInsertion();
insertionType, var insertionType;
index, var index;
position, var position;
indexAndPosition; var indexAndPosition;
var unsafe = !!is_unsafe; var unsafe = !!is_unsafe;
@ -373,14 +373,14 @@ define([
// target element if event happens on the second half of the element. // target element if event happens on the second half of the element.
// Halves depend on orientation. // Halves depend on orientation.
var index = this._computeCellIndex(eventX, eventY), var index = this._computeCellIndex(eventX, eventY);
// TODO: Handle case when there are no children, container is empty // TODO: Handle case when there are no children, container is empty
targetView = this.getChildren().findByModel(this.getCollection().at(index)), var targetView = this.getChildren().findByModel(this.getCollection().at(index));
orientation = this.view.model.get('orientation'), var orientation = this.view.model.get('orientation');
element = targetView.$el, var element = targetView.$el;
eventOffset, var eventOffset;
closeOffset, var closeOffset;
elementDimension; var elementDimension;
if (orientation === 'vertical') { if (orientation === 'vertical') {
eventOffset = eventY; eventOffset = eventY;
@ -409,41 +409,41 @@ define([
_computeSpecialIndex: function (eventX, eventY) { _computeSpecialIndex: function (eventX, eventY) {
return this._computeCellIndex(eventX, eventY); return this._computeCellIndex(eventX, eventY);
}, },
_computeCellIndex: function (eventX, eventY) { _computeCellIndex: function(eventX, eventY) {
var orientation = this.view.model.get('orientation'), var orientation = this.view.model.get('orientation');
eventOffset = (orientation === 'vertical') ? eventY : eventX, var eventOffset = (orientation === 'vertical') ? eventY : eventX;
resultView = this.getChildren().find(function (view) { var resultView = this.getChildren().find(function(view) {
var element = view.$el, var element = view.$el;
closeOffset, var closeOffset;
farOffset; var farOffset;
if (orientation === 'vertical') { if (orientation === 'vertical') {
closeOffset = element.offset().top; closeOffset = element.offset().top;
farOffset = element.outerHeight(true); farOffset = element.outerHeight(true);
} else { } else {
closeOffset = element.offset().left; closeOffset = element.offset().left;
farOffset = element.outerWidth(true); farOffset = element.outerWidth(true);
} }
farOffset += closeOffset; farOffset += closeOffset;
return closeOffset <= eventOffset && eventOffset <= farOffset; return closeOffset <= eventOffset && eventOffset <= farOffset;
}); });
var index = (typeof resultView === 'object') ? resultView._index : 0; var index = (typeof resultView === 'object') ? resultView._index : 0;
return index; return index;
}, },
_canAcceptNormalInsertion: function () { _canAcceptNormalInsertion: function() {
var orientation = this.view.model.get('orientation'), var orientation = this.view.model.get('orientation');
depth = this.view.renderOptions.depth, var depth = this.view.renderOptions.depth;
childCount = this.getChildren().length; var childCount = this.getChildren().length;
// Note that depth is zero indexed. Root container has depth=0 // Note that depth is zero indexed. Root container has depth=0
return orientation === 'vertical' || (orientation === 'horizontal' && depth === 1 && childCount < this.options.columnLimit); return orientation === 'vertical' || (orientation === 'horizontal' && depth === 1 && childCount < this.options.columnLimit);
}, },
_canAcceptSpecialInsertion: function () { _canAcceptSpecialInsertion: function() {
var orientation = this.view.model.get('orientation'), var orientation = this.view.model.get('orientation');
depth = this.view.renderOptions.depth, var depth = this.view.renderOptions.depth;
childCount = this.getChildren().length; var childCount = this.getChildren().length;
return depth === 0 || (depth === 1 && orientation === 'horizontal' && childCount <= this.options.columnLimit); return depth === 0 || (depth === 1 && orientation === 'horizontal' && childCount <= this.options.columnLimit);
}, },
getCollectionView: function () { getCollectionView: function () {

View File

@ -31,9 +31,9 @@ define([
onDrop: function (model, view) {}, onDrop: function (model, view) {},
testAttachToInstance: function (model, view) { return true; } testAttachToInstance: function (model, view) { return true; }
}, },
onRender: function () { onRender: function() {
var that = this, var that = this;
interactable; var interactable;
// Give instances more control over whether Draggable should be applied // Give instances more control over whether Draggable should be applied
if (!this.options.testAttachToInstance(this.view.model, this.view)) return; if (!this.options.testAttachToInstance(this.view.model, this.view)) return;
@ -52,15 +52,15 @@ define([
if (that.options.cloneOriginal === true) { if (that.options.cloneOriginal === true) {
// Use substitution instead of a clone // Use substitution instead of a clone
var tempClone = (_.isFunction(that.options.onDragSubstituteBy)) ? that.options.onDragSubstituteBy(that) : undefined, var tempClone = (_.isFunction(that.options.onDragSubstituteBy)) ? that.options.onDragSubstituteBy(that) : undefined;
// Or use a clone // Or use a clone
clone = tempClone || event.target.cloneNode(true), var clone = tempClone || event.target.cloneNode(true);
$original = jQuery(event.target), var $original = jQuery(event.target);
$clone = jQuery(clone), var $clone = jQuery(clone);
centerXOffset, var centerXOffset;
centerYOffset, var centerYOffset;
parentOffset; var parentOffset;
$clone.addClass('mailpoet_droppable_active'); $clone.addClass('mailpoet_droppable_active');
$clone.css('position', 'absolute'); $clone.css('position', 'absolute');
@ -87,10 +87,10 @@ define([
}, },
// call this function on every dragmove event // call this function on every dragmove event
onmove: function (event) { onmove: function (event) {
var target = event.target, var target = event.target;
// keep the dragged position in the data-x/data-y attributes // keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx, var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy; var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element // translate the element
target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'; target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';

View File

@ -36,9 +36,9 @@ define([
this.hideResizeHandle(); this.hideResizeHandle();
} }
}, },
attachResize: function () { attachResize: function() {
var domElement = (this.options.elementSelector === null) ? this.view.$el.get(0) : this.view.$(this.options.elementSelector).get(0), var domElement = (this.options.elementSelector === null) ? this.view.$el.get(0) : this.view.$(this.options.elementSelector).get(0);
that = this; var that = this;
interact(domElement).resizable({ interact(domElement).resizable({
// axis: 'y', // axis: 'y',
edges: { edges: {
@ -51,6 +51,13 @@ define([
.on('resizestart', function (event) { .on('resizestart', function (event) {
that.isBeingResized = true; that.isBeingResized = true;
that.$el.addClass('mailpoet_resize_active'); that.$el.addClass('mailpoet_resize_active');
}).on('resizemove', function(event) {
var currentLength = parseFloat(that.view.model.get(that.options.modelField));
var newLength = currentLength + that.options.transformationFunction(event.dy);
if (newLength < that.options.minLength) newLength = that.options.minLength;
that.view.model.set(that.options.modelField, newLength + 'px');
}) })
.on('resizemove', function (event) { .on('resizemove', function (event) {
var onResize = that.options.onResize.bind(that); var onResize = that.options.onResize.bind(that);

View File

@ -23,10 +23,10 @@ define([
end: function (event, ui) { end: function (event, ui) {
ui.item.removeData('previousIndex'); ui.item.removeData('previousIndex');
}, },
update: function (event, ui) { update: function(event, ui) {
var previousIndex = ui.item.data('previousIndex'), var previousIndex = ui.item.data('previousIndex');
newIndex = ui.item.index(), var newIndex = ui.item.index();
model = collection.at(previousIndex); var model = collection.at(previousIndex);
// Replicate DOM changes. Move target model to a new position // Replicate DOM changes. Move target model to a new position
// within the collection // within the collection

View File

@ -30,8 +30,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.ALCSupervisor = SuperModel.extend({ Module.ALCSupervisor = SuperModel.extend({
initialize: function () { initialize: function () {
@ -59,9 +59,9 @@ define([
refreshBlocks: function (models, renderedBlocks) { refreshBlocks: function (models, renderedBlocks) {
_.each( _.each(
_.zip(models, renderedBlocks), _.zip(models, renderedBlocks),
function (args) { function(args) {
var model = args[0], var model = args[0];
contents = args[1]; var contents = args[1];
model.trigger('refreshPosts', contents); model.trigger('refreshPosts', contents);
} }
); );
@ -148,14 +148,14 @@ define([
events: _.extend(base.BlockView.prototype.events, { events: _.extend(base.BlockView.prototype.events, {
'click .mailpoet_automated_latest_content_block_overlay': 'showSettings' 'click .mailpoet_automated_latest_content_block_overlay': 'showSettings'
}), }),
onDragSubstituteBy: function () { return Module.AutomatedLatestContentWidgetView; }, onDragSubstituteBy: function() { return Module.AutomatedLatestContentWidgetView; },
onRender: function () { onRender: function() {
var ContainerView = App.getBlockTypeView('container'), var ContainerView = App.getBlockTypeView('container');
renderOptions = { var renderOptions = {
disableTextEditor: true, disableTextEditor: true,
disableDragAndDrop: true, disableDragAndDrop: true,
emptyContainerMessage: MailPoet.I18n.t('noPostsToDisplay') emptyContainerMessage: MailPoet.I18n.t('noPostsToDisplay')
}; };
this.toolsView = new Module.AutomatedLatestContentBlockToolsView({ model: this.model }); this.toolsView = new Module.AutomatedLatestContentBlockToolsView({ model: this.model });
this.showChildView('toolsRegion', this.toolsView); this.showChildView('toolsRegion', this.toolsView);
this.showChildView('postsRegion', new ContainerView({ model: this.model.get('_container'), renderOptions: renderOptions })); this.showChildView('postsRegion', new ContainerView({ model: this.model.get('_container'), renderOptions: renderOptions }));
@ -264,9 +264,9 @@ define([
} }
}).trigger('change'); }).trigger('change');
}, },
toggleDisplayOptions: function (event) { toggleDisplayOptions: function(event) {
var el = this.$('.mailpoet_automated_latest_content_display_options'), var el = this.$('.mailpoet_automated_latest_content_display_options');
showControl = this.$('.mailpoet_automated_latest_content_show_display_options'); var showControl = this.$('.mailpoet_automated_latest_content_show_display_options');
if (el.hasClass('mailpoet_closed')) { if (el.hasClass('mailpoet_closed')) {
el.removeClass('mailpoet_closed'); el.removeClass('mailpoet_closed');
showControl.addClass('mailpoet_hidden'); showControl.addClass('mailpoet_hidden');
@ -348,9 +348,9 @@ define([
} }
this.changeField('titleFormat', event); this.changeField('titleFormat', event);
}, },
_updateContentTypes: function (postTypes) { _updateContentTypes: function(postTypes) {
var select = this.$('.mailpoet_automated_latest_content_content_type'), var select = this.$('.mailpoet_automated_latest_content_content_type');
selectedValue = this.model.get('contentType'); var selectedValue = this.model.get('contentType');
select.find('option').remove(); select.find('option').remove();
_.each(postTypes, function (type) { _.each(postTypes, function (type) {

View File

@ -16,8 +16,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
AugmentedView = Marionette.View.extend({}); var AugmentedView = Marionette.View.extend({});
Module.BlockModel = SuperModel.extend({ Module.BlockModel = SuperModel.extend({
stale: [], // Attributes to be removed upon saving stale: [], // Attributes to be removed upon saving
@ -68,8 +68,8 @@ define([
options.dragBehavior.view.model.destroy(); options.dragBehavior.view.model.destroy();
}, },
onDragSubstituteBy: function(behavior) { onDragSubstituteBy: function(behavior) {
var WidgetView, var WidgetView;
node; var node;
// When block is being dragged, display the widget icon instead. // When block is being dragged, display the widget icon instead.
// This will create an instance of block's widget view and // This will create an instance of block's widget view and
// use it's rendered DOM element instead of the content block // use it's rendered DOM element instead of the content block

View File

@ -11,8 +11,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.ButtonBlockModel = base.BlockModel.extend({ Module.ButtonBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {

View File

@ -14,9 +14,9 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock, var base = BaseBlock;
BlockCollection; var BlockCollection;
BlockCollection = Backbone.Collection.extend({ BlockCollection = Backbone.Collection.extend({
model: base.BlockModel, model: base.BlockModel,
@ -121,8 +121,8 @@ define([
options.dragBehavior.view.model.destroy(); options.dragBehavior.view.model.destroy();
}, },
onDragSubstituteBy: function(behavior) { onDragSubstituteBy: function(behavior) {
var WidgetView, var WidgetView;
node; var node;
// When block is being dragged, display the widget icon instead. // When block is being dragged, display the widget icon instead.
// This will create an instance of block's widget view and // This will create an instance of block's widget view and
// use it's rendered DOM element instead of the content block // use it's rendered DOM element instead of the content block
@ -190,25 +190,25 @@ define([
this.toolsView.triggerMethod('hideTools'); this.toolsView.triggerMethod('hideTools');
} }
}, },
toggleEditingLayer: function (event) { toggleEditingLayer: function(event) {
var that = this, var that = this;
$toggleButton = this.$('> .mailpoet_tools .mailpoet_newsletter_layer_selector'), var $toggleButton = this.$('> .mailpoet_tools .mailpoet_newsletter_layer_selector');
$overlay = jQuery('.mailpoet_layer_overlay'), var $overlay = jQuery('.mailpoet_layer_overlay');
$container = this.$('> .mailpoet_container'), var $container = this.$('> .mailpoet_container');
enableContainerLayer = function () { var enableContainerLayer = function() {
that.$el.addClass('mailpoet_container_layer_active'); that.$el.addClass('mailpoet_container_layer_active');
$toggleButton.addClass('mailpoet_container_layer_active'); $toggleButton.addClass('mailpoet_container_layer_active');
$container.addClass('mailpoet_layer_highlight'); $container.addClass('mailpoet_layer_highlight');
$overlay.click(disableContainerLayer); $overlay.click(disableContainerLayer);
$overlay.show(); $overlay.show();
}, };
disableContainerLayer = function () { var disableContainerLayer = function() {
that.$el.removeClass('mailpoet_container_layer_active'); that.$el.removeClass('mailpoet_container_layer_active');
$toggleButton.removeClass('mailpoet_container_layer_active'); $toggleButton.removeClass('mailpoet_container_layer_active');
$container.removeClass('mailpoet_layer_highlight'); $container.removeClass('mailpoet_layer_highlight');
$overlay.hide(); $overlay.hide();
$overlay.off('click'); $overlay.off('click');
}; };
if ($toggleButton.hasClass('mailpoet_container_layer_active')) { if ($toggleButton.hasClass('mailpoet_container_layer_active')) {
disableContainerLayer(); disableContainerLayer();
} else { } else {

View File

@ -11,8 +11,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.DividerBlockModel = base.BlockModel.extend({ Module.DividerBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {

View File

@ -10,8 +10,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.FooterBlockModel = base.BlockModel.extend({ Module.FooterBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {

View File

@ -10,8 +10,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.HeaderBlockModel = base.BlockModel.extend({ Module.HeaderBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {

View File

@ -11,9 +11,9 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock, var base = BaseBlock;
ImageWidgetView; var ImageWidgetView;
Module.ImageBlockModel = base.BlockModel.extend({ Module.ImageBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {
@ -243,10 +243,10 @@ define([
view.url.focus(); view.url.focus();
}, },
editSelectionContent: function () { editSelectionContent: function() {
var state = this.state(), var state = this.state();
selection = state.get('selection'), var selection = state.get('selection');
view; var view;
view = new window.wp.media.view.AttachmentsBrowser({ view = new window.wp.media.view.AttachmentsBrowser({
controller: this, controller: this,
@ -301,9 +301,9 @@ define([
text: 'Select Image', text: 'Select Image',
requires: { selection: true }, requires: { selection: true },
click: function () { click: function() {
var state = controller.state(), var state = controller.state();
selection = state.get('selection'); var selection = state.get('selection');
controller.close(); controller.close();
state.trigger('insert', selection).reset(); state.trigger('insert', selection).reset();
@ -322,45 +322,45 @@ define([
}); });
var theFrame = new MediaManager({ var theFrame = new MediaManager({
id: 'mailpoet-media-manager', id: 'mailpoet-media-manager',
frame: 'select', frame: 'select',
title: 'Select image', title: 'Select image',
editing: false, editing: false,
multiple: false, multiple: false,
library: { library: {
type: 'image' type: 'image'
}, },
displaySettings: false, displaySettings: false,
button: { button: {
text: 'Select' text: 'Select'
} }
}), });
that = this; var that = this;
this._mediaManager = theFrame; this._mediaManager = theFrame;
this._mediaManager.on('insert', function () { this._mediaManager.on('insert', function () {
// Append media manager image selections to Images tab // Append media manager image selections to Images tab
var selection = theFrame.state().get('selection'); var selection = theFrame.state().get('selection');
selection.each(function (attachment) { selection.each(function(attachment) {
var sizes = attachment.get('sizes'), var sizes = attachment.get('sizes');
// Following advice from Becs, the target width should // Following advice from Becs, the target width should
// be a double of one column width to render well on // be a double of one column width to render well on
// retina screen devices // retina screen devices
targetImageWidth = 1320, var targetImageWidth = 1320;
// For main image use the size, that's closest to being 660px in width // For main image use the size, that's closest to being 660px in width
sizeKeys = _.keys(sizes), var sizeKeys = _.keys(sizes);
// Pick the width that is closest to target width // Pick the width that is closest to target width
increasingByWidthDifference = _.sortBy( var increasingByWidthDifference = _.sortBy(
_.keys(sizes), _.keys(sizes),
function (size) { return Math.abs(targetImageWidth - sizes[size].width); } function(size) { return Math.abs(targetImageWidth - sizes[size].width); }
), );
bestWidth = sizes[_.first(increasingByWidthDifference)].width, var bestWidth = sizes[_.first(increasingByWidthDifference)].width;
imagesOfBestWidth = _.filter(_.values(sizes), function (size) { return size.width === bestWidth; }), var imagesOfBestWidth = _.filter(_.values(sizes), function(size) { return size.width === bestWidth; });
// Maximize the height if there are multiple images with same width // Maximize the height if there are multiple images with same width
mainSize = _.max(imagesOfBestWidth, function (size) { return size.height; }); var mainSize = _.max(imagesOfBestWidth, function(size) { return size.height; });
that.model.set({ that.model.set({
height: mainSize.height + 'px', height: mainSize.height + 'px',

View File

@ -39,8 +39,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.PostsBlockModel = base.BlockModel.extend({ Module.PostsBlockModel = base.BlockModel.extend({
stale: ['_selectedPosts', '_availablePosts', '_transformedPosts'], stale: ['_selectedPosts', '_availablePosts', '_transformedPosts'],
@ -88,11 +88,11 @@ define([
_transformedPosts: App.getBlockTypeModel('container') _transformedPosts: App.getBlockTypeModel('container')
}; };
}, },
initialize: function () { initialize: function() {
var that = this, var that = this;
POST_REFRESH_DELAY_MS = 500, var POST_REFRESH_DELAY_MS = 500;
refreshAvailablePosts = _.debounce(this.fetchAvailablePosts.bind(this), POST_REFRESH_DELAY_MS), var refreshAvailablePosts = _.debounce(this.fetchAvailablePosts.bind(this), POST_REFRESH_DELAY_MS);
refreshTransformedPosts = _.debounce(this._refreshTransformedPosts.bind(this), POST_REFRESH_DELAY_MS); var refreshTransformedPosts = _.debounce(this._refreshTransformedPosts.bind(this), POST_REFRESH_DELAY_MS);
// Attach Radio.Requests API primarily for highlighting // Attach Radio.Requests API primarily for highlighting
_.extend(this, Radio.Requests); _.extend(this, Radio.Requests);
@ -119,10 +119,10 @@ define([
MailPoet.Notice.error(MailPoet.I18n.t('failedToFetchAvailablePosts')); MailPoet.Notice.error(MailPoet.I18n.t('failedToFetchAvailablePosts'));
}); });
}, },
_loadMorePosts: function () { _loadMorePosts: function() {
var that = this, var that = this;
postCount = this.get('_availablePosts').length, var postCount = this.get('_availablePosts').length;
nextOffset = this.get('offset') + Number(this.get('amount')); var nextOffset = this.get('offset') + Number(this.get('amount'));
if (postCount === 0 || postCount < nextOffset) { if (postCount === 0 || postCount < nextOffset) {
// No more posts to load // No more posts to load
@ -140,9 +140,9 @@ define([
that.trigger('morePostsLoaded'); that.trigger('morePostsLoaded');
}); });
}, },
_refreshTransformedPosts: function () { _refreshTransformedPosts: function() {
var that = this, var that = this;
data = this.toJSON(); var data = this.toJSON();
data.posts = this.get('_selectedPosts').pluck('ID'); data.posts = this.get('_selectedPosts').pluck('ID');
@ -157,11 +157,11 @@ define([
MailPoet.Notice.error(MailPoet.I18n.t('failedToFetchRenderedPosts')); MailPoet.Notice.error(MailPoet.I18n.t('failedToFetchRenderedPosts'));
}); });
}, },
_insertSelectedPosts: function () { _insertSelectedPosts: function() {
var that = this, var that = this;
data = this.toJSON(), var data = this.toJSON();
index = this.collection.indexOf(this), var index = this.collection.indexOf(this);
collection = this.collection; var collection = this.collection;
data.posts = this.get('_selectedPosts').pluck('ID'); data.posts = this.get('_selectedPosts').pluck('ID');
@ -195,12 +195,12 @@ define([
} }
this.trigger('showSettings'); this.trigger('showSettings');
var ContainerView = App.getBlockTypeView('container'), var ContainerView = App.getBlockTypeView('container');
renderOptions = { var renderOptions = {
disableTextEditor: true, disableTextEditor: true,
disableDragAndDrop: true, disableDragAndDrop: true,
emptyContainerMessage: MailPoet.I18n.t('noPostsToDisplay') emptyContainerMessage: MailPoet.I18n.t('noPostsToDisplay')
}; };
this.showChildView('postsRegion', new ContainerView({ model: this.model.get('_transformedPosts'), renderOptions: renderOptions })); this.showChildView('postsRegion', new ContainerView({ model: this.model.get('_transformedPosts'), renderOptions: renderOptions }));
}, },
notifyAboutSelf: function () { notifyAboutSelf: function () {
@ -236,9 +236,9 @@ define([
this.selectionView = new PostSelectionSettingsView({ model: this.model }); this.selectionView = new PostSelectionSettingsView({ model: this.model });
this.displayOptionsView = new PostsDisplayOptionsSettingsView({ model: this.model }); this.displayOptionsView = new PostsDisplayOptionsSettingsView({ model: this.model });
}, },
onRender: function () { onRender: function() {
var that = this, var that = this;
blockView = this.model.request('blockView'); var blockView = this.model.request('blockView');
this.showChildView('selectionRegion', this.selectionView); this.showChildView('selectionRegion', this.selectionView);
this.showChildView('displayOptionsRegion', this.displayOptionsView); this.showChildView('displayOptionsRegion', this.displayOptionsView);
@ -412,9 +412,9 @@ define([
changeField: function (field, event) { changeField: function (field, event) {
this.model.set(field, jQuery(event.target).val()); this.model.set(field, jQuery(event.target).val());
}, },
_updateContentTypes: function (postTypes) { _updateContentTypes: function(postTypes) {
var select = this.$('.mailpoet_settings_posts_content_type'), var select = this.$('.mailpoet_settings_posts_content_type');
selectedValue = this.model.get('contentType'); var selectedValue = this.model.get('contentType');
select.find('option').remove(); select.find('option').remove();
_.each(postTypes, function (type) { _.each(postTypes, function (type) {
@ -447,9 +447,9 @@ define([
initialize: function (options) { initialize: function (options) {
this.blockModel = options.blockModel; this.blockModel = options.blockModel;
}, },
postSelectionChange: function (event) { postSelectionChange: function(event) {
var checkBox = jQuery(event.target), var checkBox = jQuery(event.target);
selectedPostsCollection = this.blockModel.get('_selectedPosts'); var selectedPostsCollection = this.blockModel.get('_selectedPosts');
if (checkBox.prop('checked')) { if (checkBox.prop('checked')) {
selectedPostsCollection.add(this.model); selectedPostsCollection.add(this.model);
} else { } else {

View File

@ -13,12 +13,12 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock, var base = BaseBlock;
SocialBlockSettingsIconSelectorView, var SocialBlockSettingsIconSelectorView;
SocialBlockSettingsIconView, var SocialBlockSettingsIconView;
SocialBlockSettingsIconCollectionView, var SocialBlockSettingsIconCollectionView;
SocialBlockSettingsStylesView; var SocialBlockSettingsStylesView;
Module.SocialIconModel = SuperModel.extend({ Module.SocialIconModel = SuperModel.extend({
defaults: function () { defaults: function () {
@ -36,9 +36,9 @@ define([
initialize: function (options) { initialize: function (options) {
var that = this; var that = this;
// Make model swap to default values for that type when iconType changes // Make model swap to default values for that type when iconType changes
this.on('change:iconType', function () { this.on('change:iconType', function() {
var defaultValues = App.getConfig().get('socialIcons').get(that.get('iconType')), var defaultValues = App.getConfig().get('socialIcons').get(that.get('iconType'));
iconSet = that.collection.iconBlockModel.getIconSet(); var iconSet = that.collection.iconBlockModel.getIconSet();
this.set({ this.set({
link: defaultValues.get('defaultLink'), link: defaultValues.get('defaultLink'),
image: iconSet.get(that.get('iconType')), image: iconSet.get(that.get('iconType')),
@ -174,11 +174,11 @@ define([
this.$('.mailpoet_social_icon_image').attr('alt', this.model.get('text')); this.$('.mailpoet_social_icon_image').attr('alt', this.model.get('text'));
} }
}, },
templateContext: function () { templateContext: function() {
var icons = App.getConfig().get('socialIcons'), var icons = App.getConfig().get('socialIcons');
// Construct icon type list of format [{iconType: 'type', title: 'Title'}, ...] // Construct icon type list of format [{iconType: 'type', title: 'Title'}, ...]
availableIconTypes = _.map(_.keys(icons.attributes), function (key) { return { iconType: key, title: icons.get(key).get('title') }; }), var availableIconTypes = _.map(_.keys(icons.attributes), function(key) { return { iconType: key, title: icons.get(key).get('title') }; });
allIconSets = App.getAvailableStyles().get('socialIconSets'); var allIconSets = App.getAvailableStyles().get('socialIconSets');
return _.extend({}, base.BlockView.prototype.templateContext.apply(this, arguments), { return _.extend({}, base.BlockView.prototype.templateContext.apply(this, arguments), {
iconTypes: availableIconTypes, iconTypes: availableIconTypes,
currentType: icons.get(this.model.get('iconType')).toJSON(), currentType: icons.get(this.model.get('iconType')).toJSON(),

View File

@ -9,8 +9,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.SpacerBlockModel = base.BlockModel.extend({ Module.SpacerBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {

View File

@ -10,8 +10,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
base = BaseBlock; var base = BaseBlock;
Module.TextBlockModel = base.BlockModel.extend({ Module.TextBlockModel = base.BlockModel.extend({
defaults: function () { defaults: function () {

View File

@ -28,8 +28,8 @@ define([
'use strict'; 'use strict';
var Module = {}, var Module = {};
saveTimeout; var saveTimeout;
// Save editor contents to server // Save editor contents to server
Module.save = function () { Module.save = function () {
@ -76,10 +76,10 @@ define([
// Temporary workaround for html2canvas-alpha2. // Temporary workaround for html2canvas-alpha2.
// Removes 1px left transparent border from resulting canvas. // Removes 1px left transparent border from resulting canvas.
var oldContext = oldCanvas.getContext('2d'), var oldContext = oldCanvas.getContext('2d');
newCanvas = document.createElement('canvas'), var newCanvas = document.createElement('canvas');
newContext = newCanvas.getContext('2d'), var newContext = newCanvas.getContext('2d');
leftBorderWidth = 1; var leftBorderWidth = 1;
newCanvas.width = oldCanvas.width; newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height; newCanvas.height = oldCanvas.height;
@ -94,9 +94,9 @@ define([
}); });
}; };
Module.saveTemplate = function (options) { Module.saveTemplate = function(options) {
var that = this, var that = this;
promise = jQuery.Deferred(); var promise = jQuery.Deferred();
promise.then(function (thumbnail) { promise.then(function (thumbnail) {
var data = _.extend(options || {}, { var data = _.extend(options || {}, {
@ -191,10 +191,10 @@ define([
hideSaveAsTemplate: function () { hideSaveAsTemplate: function () {
this.$('.mailpoet_save_as_template_container').addClass('mailpoet_hidden'); this.$('.mailpoet_save_as_template_container').addClass('mailpoet_hidden');
}, },
saveAsTemplate: function () { saveAsTemplate: function() {
var templateName = this.$('.mailpoet_save_as_template_name').val(), var templateName = this.$('.mailpoet_save_as_template_name').val();
templateDescription = this.$('.mailpoet_save_as_template_description').val(), var templateDescription = this.$('.mailpoet_save_as_template_description').val();
that = this; var that = this;
if (templateName === '') { if (templateName === '') {
MailPoet.Notice.error( MailPoet.Notice.error(
@ -247,10 +247,10 @@ define([
hideExportTemplate: function () { hideExportTemplate: function () {
this.$('.mailpoet_export_template_container').addClass('mailpoet_hidden'); this.$('.mailpoet_export_template_container').addClass('mailpoet_hidden');
}, },
exportTemplate: function () { exportTemplate: function() {
var templateName = this.$('.mailpoet_export_template_name').val(), var templateName = this.$('.mailpoet_export_template_name').val();
templateDescription = this.$('.mailpoet_export_template_description').val(), var templateDescription = this.$('.mailpoet_export_template_description').val();
that = this; var that = this;
if (templateName === '') { if (templateName === '') {
MailPoet.Notice.error( MailPoet.Notice.error(

View File

@ -61,9 +61,9 @@ define([
previewRegion: '.mailpoet_preview_region' previewRegion: '.mailpoet_preview_region'
}, },
events: { events: {
'click .mailpoet_sidebar_region h3, .mailpoet_sidebar_region .handlediv': function (event) { 'click .mailpoet_sidebar_region h3, .mailpoet_sidebar_region .handlediv': function(event) {
var $openRegion = this.$el.find('.mailpoet_sidebar_region:not(.closed)'), var $openRegion = this.$el.find('.mailpoet_sidebar_region:not(.closed)');
$targetRegion = this.$el.find(event.target).closest('.mailpoet_sidebar_region'); var $targetRegion = this.$el.find(event.target).closest('.mailpoet_sidebar_region');
$openRegion.find('.mailpoet_region_content').velocity( $openRegion.find('.mailpoet_region_content').velocity(
'slideUp', 'slideUp',
@ -113,10 +113,8 @@ define([
// position of the sidebar would be scrollable and not fixed // position of the sidebar would be scrollable and not fixed
// partially out of visible screen // partially out of visible screen
this.$el.parent().each(function () { this.$el.parent().each(function () {
var calculated_left, var calculated_left;
self; var self = jQuery(this);
self = jQuery(this);
if (self.css('position') === 'fixed') { if (self.css('position') === 'fixed') {
calculated_left = self.parent().offset().left - jQuery(window).scrollLeft(); calculated_left = self.parent().offset().left - jQuery(window).scrollLeft();
@ -372,9 +370,9 @@ define([
Application.getLayoutWidgets = Module.getLayoutWidgets; Application.getLayoutWidgets = Module.getLayoutWidgets;
}); });
App.on('start', function (App, options) { App.on('start', function(App, options) {
var stylesModel = App.getGlobalStyles(), var stylesModel = App.getGlobalStyles();
sidebarView = new SidebarView(); var sidebarView = new SidebarView();
App._appView.showChildView('sidebarRegion', sidebarView); App._appView.showChildView('sidebarRegion', sidebarView);

View File

@ -8,24 +8,24 @@
* its placeholder into editor text. * its placeholder into editor text.
*/ */
/* jshint unused:false */ /*jshint unused:false */
/* global tinymce:true */ /*global tinymce:true */
tinymce.PluginManager.add('mailpoet_shortcodes', function (editor, url) { tinymce.PluginManager.add('mailpoet_shortcodes', function(editor, url) {
var appendLabelAndClose = function (shortcode) { var appendLabelAndClose = function(shortcode) {
editor.insertContent(shortcode); editor.insertContent(shortcode);
editor.windowManager.close(); editor.windowManager.close();
}, };
generateOnClickFunc = function (shortcode) { var generateOnClickFunc = function(shortcode) {
return function () { return function() {
appendLabelAndClose(shortcode); appendLabelAndClose(shortcode);
};
}; };
};
editor.addButton('mailpoet_shortcodes', { editor.addButton('mailpoet_shortcodes', {
icon: 'mailpoet_shortcodes', icon: 'mailpoet_shortcodes',
onclick: function () { onclick: function() {
var shortcodes = [], var shortcodes = [];
configShortcodes = editor.settings.mailpoet_shortcodes; var configShortcodes = editor.settings.mailpoet_shortcodes;
for (var segment in configShortcodes) { for (var segment in configShortcodes) {
if (configShortcodes.hasOwnProperty(segment)) { if (configShortcodes.hasOwnProperty(segment)) {

View File

@ -27,74 +27,74 @@ define(
jQuery('#mailpoet_subscribers_export > div.inside').html(subscribers_export_template(window.exportData)); jQuery('#mailpoet_subscribers_export > div.inside').html(subscribers_export_template(window.exportData));
// define reusable variables // define reusable variables
var segmentsContainerElement = jQuery('#export_lists'), var segmentsContainerElement = jQuery('#export_lists');
subscriberFieldsContainerElement = jQuery('#export_columns'), var subscriberFieldsContainerElement = jQuery('#export_columns');
exportConfirmedOptionElement = jQuery(':radio[name="option_confirmed"]'), var exportConfirmedOptionElement = jQuery(':radio[name="option_confirmed"]');
groupBySegmentOptionElement = jQuery(':checkbox[name="option_group_by_list"]'), var groupBySegmentOptionElement = jQuery(':checkbox[name="option_group_by_list"]');
nextStepButton = jQuery('a.mailpoet_export_process'), var nextStepButton = jQuery('a.mailpoet_export_process');
renderSegmentsAndFields = function (container, data) { var renderSegmentsAndFields = function (container, data) {
if (container.data('select2')) { if (container.data('select2')) {
container
.html('')
.select2('destroy');
}
container container
.select2({ .html('')
data: data, .select2('destroy');
width: '20em', }
templateResult: function (item) { container
return (item.subscriberCount > 0) .select2({
? item.name + ' (' + parseInt(item.subscriberCount).toLocaleString() + ')' data: data,
: item.name; width: '20em',
}, templateResult: function (item) {
templateSelection: function (item) { return (item.subscriberCount > 0)
return (item.subscriberCount > 0) ? item.name + ' (' + parseInt(item.subscriberCount).toLocaleString() + ')'
? item.name + ' (' + parseInt(item.subscriberCount).toLocaleString() + ')' : item.name;
: item.name; },
} templateSelection: function (item) {
}) return (item.subscriberCount > 0)
.on('select2:selecting', function (selectEvent) { ? item.name + ' (' + parseInt(item.subscriberCount).toLocaleString() + ')'
var selectElement = this, : item.name;
selectedOptionId = selectEvent.params.args.data.id, }
fieldsToExclude = [ })
'select', .on('select2:selecting', function (selectEvent) {
'deselect' var selectElement = this;
]; var selectedOptionId = selectEvent.params.args.data.id;
if (_.contains(fieldsToExclude, selectedOptionId)) { var fieldsToExclude = [
selectEvent.preventDefault(); 'select',
if (selectedOptionId === 'deselect') { 'deselect'
jQuery(selectElement).val('').trigger('change'); ];
} else { if (_.contains(fieldsToExclude, selectedOptionId)) {
var allOptions = []; selectEvent.preventDefault();
_.each(container.find('option'), function (field) { if (selectedOptionId === 'deselect') {
if (!_.contains(fieldsToExclude, field.value)) { jQuery(selectElement).val('').trigger('change');
allOptions.push(field.value); } else {
} var allOptions = [];
}); _.each(container.find('option'), function (field) {
jQuery(selectElement).val(allOptions).trigger('change'); if (!_.contains(fieldsToExclude, field.value)) {
} allOptions.push(field.value);
jQuery(selectElement).select2('close'); }
} });
}) jQuery(selectElement).val(allOptions).trigger('change');
.on('change', function () {
if ((window.exportData.segments && segmentsContainerElement.select2('data').length && subscriberFieldsContainerElement.select2('data').length)
||
(!window.exportData.segments && subscriberFieldsContainerElement.select2('data').length)
) {
toggleNextStepButton('on');
}
else {
toggleNextStepButton('off');
} }
jQuery(selectElement).select2('close');
}
})
.on('change', function () {
if ((window.exportData.segments && segmentsContainerElement.select2('data').length && subscriberFieldsContainerElement.select2('data').length)
||
(!window.exportData.segments && subscriberFieldsContainerElement.select2('data').length)
) {
toggleNextStepButton('on');
}
else {
toggleNextStepButton('off');
}
if (segmentsContainerElement.select2('data').length > 1 && window.exportData.groupBySegmentOption) { if (segmentsContainerElement.select2('data').length > 1 && window.exportData.groupBySegmentOption) {
jQuery('.mailpoet_group_by_list').show(); jQuery('.mailpoet_group_by_list').show();
} }
else if (window.exportData.groupBySegmentOption) { else if (window.exportData.groupBySegmentOption) {
jQuery('.mailpoet_group_by_list').hide(); jQuery('.mailpoet_group_by_list').hide();
} }
}); });
}; };
// set confirmed subscribers export option to false // set confirmed subscribers export option to false
window.exportData.exportConfirmedOption = false; window.exportData.exportConfirmedOption = false;

View File

@ -68,31 +68,29 @@ define(
jQuery('.mailpoet_method_process').html(methodProcessContainerTemplate()); jQuery('.mailpoet_method_process').html(methodProcessContainerTemplate());
// define reusable variables // define reusable variables
var currentStepE = jQuery(location.hash), var currentStepE = jQuery(location.hash);
methodSelectionElement = jQuery('#select_method'), var methodSelectionElement = jQuery('#select_method');
pasteInputElement = jQuery('#paste_input'), var pasteInputElement = jQuery('#paste_input');
pasteInputPlaceholderElement = var pasteInputPlaceholderElement =
pasteInputElement.data('placeholder').replace(/\\n/g, '\n'), pasteInputElement.data('placeholder').replace(/\\n/g, '\n');
pasteProcessButtonElement = var pasteProcessButtonElement =
jQuery('#method_paste > div.mailpoet_method_process') jQuery('#method_paste > div.mailpoet_method_process')
.find('a.mailpoet_process'), .find('a.mailpoet_process');
mailChimpKeyInputElement = jQuery('#mailchimp_key'), var mailChimpKeyInputElement = jQuery('#mailchimp_key');
mailChimpKeyVerifyButtonElement = jQuery('#mailchimp_key_verify'), var mailChimpKeyVerifyButtonElement = jQuery('#mailchimp_key_verify');
mailChimpListsContainerElement = jQuery('#mailchimp_lists'), var mailChimpListsContainerElement = jQuery('#mailchimp_lists');
mailChimpProcessButtonElement = var mailChimpProcessButtonElement = jQuery('#method_mailchimp > div.mailpoet_method_process')
jQuery('#method_mailchimp > div.mailpoet_method_process') .find('a.mailpoet_process');
.find('a.mailpoet_process'), var uploadElement = jQuery('#file_local');
uploadElement = jQuery('#file_local'), var uploadProcessButtonElement =
uploadProcessButtonElement = jQuery('#method_file > div.mailpoet_method_process')
jQuery('#method_file > div.mailpoet_method_process') .find('a.mailpoet_process');
.find('a.mailpoet_process');
// define method change behavior // define method change behavior
methodSelectionElement.change(function () { methodSelectionElement.change(function () {
MailPoet.Notice.hide(); MailPoet.Notice.hide();
var available_methods = jQuery(':radio[name="select_method"]'), var available_methods = jQuery(':radio[name="select_method"]');
selected_method = var selected_method = available_methods.index(available_methods.filter(':checked'));
available_methods.index(available_methods.filter(':checked'));
// hide all methods // hide all methods
currentStepE.find('.inside') currentStepE.find('.inside')
.children('div[id^="method_"]') .children('div[id^="method_"]')
@ -294,48 +292,48 @@ define(
} }
function parseCSV(isFile) { function parseCSV(isFile) {
var processedSubscribers = [], var processedSubscribers = [];
parsedEmails = [], var parsedEmails = [];
duplicateEmails = [], var duplicateEmails = [];
invalidEmails = [], var invalidEmails = [];
emailColumnPosition = null, var emailColumnPosition = null;
columnCount = null, var columnCount = null;
isHeaderFound = false, var isHeaderFound = false;
advancedOptionHeader = true, var advancedOptionHeader = true;
advancedOptionDelimiter = '', var advancedOptionDelimiter = '';
advancedOptionNewline = '', var advancedOptionNewline = '';
advancedOptionComments = false, var advancedOptionComments = false;
// trim spaces, commas, periods, // trim spaces, commas, periods,
// single/double quotes and convert to lowercase // single/double quotes and convert to lowercase
detectAndCleanupEmail = function (emailString) { var detectAndCleanupEmail = function (emailString) {
var test; var test;
// decode HTML entities // decode HTML entities
var email = jQuery('<div />').html(emailString).text(); var email = jQuery('<div />').html(emailString).text();
email = email email = email
.toLowerCase() .toLowerCase()
// left/right trim spaces, punctuation (e.g., " 'email@email.com'; ") // left/right trim spaces, punctuation (e.g., " 'email@email.com'; ")
// right trim non-printable characters (e.g., "email@email.com<6F>") // right trim non-printable characters (e.g., "email@email.com<6F>")
.replace(/^["';.,\s]+|[^\x20-\x7E]+$|["';.,_\s]+$/g, '') .replace(/^["';.,\s]+|[^\x20-\x7E]+$|["';.,_\s]+$/g, '')
// remove spaces (e.g., "email @ email . com") // remove spaces (e.g., "email @ email . com")
// remove urlencoded characters // remove urlencoded characters
.replace(/\s+|%\d+|,+/g, ''); .replace(/\s+|%\d+|,+/g, '');
// detect e-mails that will be otherwise rejected by email regex // detect e-mails that will be otherwise rejected by email regex
test = /<(.*?)>/.exec(email); test = /<(.*?)>/.exec(email);
if (test) { if (test) {
// is the email inside angle brackets (e.g., 'some@email.com <some@email.com>')? // is the email inside angle brackets (e.g., 'some@email.com <some@email.com>')?
email = test[1].trim(); email = test[1].trim();
} }
test = /mailto:(?:\s+)?(.*)/.exec(email); test = /mailto:(?:\s+)?(.*)/.exec(email);
if (test) { if (test) {
// is the email in 'mailto:email' format? // is the email in 'mailto:email' format?
email = test[1].trim(); email = test[1].trim();
} }
// test for valid characters using WP's rule (https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/formatting.php#L2902) // test for valid characters using WP's rule (https://core.trac.wordpress.org/browser/tags/4.7.3/src/wp-includes/formatting.php#L2902)
if (!/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.\-@]+$/.test(email)) { if (!/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.\-@]+$/.test(email) ) {
return false; return false;
} }
return email; return email;
}; };
return { return {
skipEmptyLines: true, skipEmptyLines: true,
@ -443,32 +441,23 @@ define(
return; return;
} }
// define reusable variables // define reusable variables
var nextStepButton = jQuery('#step2_process'), var nextStepButton = jQuery('#step2_process');
previousStepButton = jQuery('#return_to_step1'), var previousStepButton = jQuery('#return_to_step1');
// create a copy of subscribers object for further manipulation // create a copy of subscribers object for further manipulation
subscribers = jQuery.extend(true, {}, window.importData.step1), var subscribers = jQuery.extend(true, {}, window.importData.step1);
subscribersDataTemplate = var subscribersDataTemplate = Handlebars.compile(jQuery('#subscribers_data_template').html());
Handlebars var subscribersDataTemplatePartial = Handlebars.compile(jQuery('#subscribers_data_template_partial').html());
.compile(jQuery('#subscribers_data_template') var subscribersDataParseResultsTemplate = Handlebars.compile(jQuery('#subscribers_data_parse_results_template').html());
.html()), var segmentSelectElement = jQuery('#mailpoet_segments_select');
subscribersDataTemplatePartial = var maxRowsToShow = 10;
Handlebars var filler = '. . .';
.compile(jQuery('#subscribers_data_template_partial')
.html()),
subscribersDataParseResultsTemplate =
Handlebars
.compile(jQuery('#subscribers_data_parse_results_template')
.html()),
segmentSelectElement = jQuery('#mailpoet_segments_select'),
maxRowsToShow = 10,
filler = '. . .',
// create an array of filler data with the same number of // create an array of filler data with the same number of
// elements as in the subscribers' data row // elements as in the subscribers' data row
fillerArray = Array.apply( var fillerArray = Array.apply(
null, null,
new Array(subscribers.subscribers[0].length) new Array(subscribers.subscribers[0].length)
).map(String.prototype.valueOf, filler), ).map(String.prototype.valueOf, filler);
fillerPosition; var fillerPosition;
showCurrentStep(); showCurrentStep();
@ -642,20 +631,20 @@ define(
Handlebars.registerHelper( Handlebars.registerHelper(
'show_and_match_columns', 'show_and_match_columns',
function (subscribers, options) { function (subscribers, options) {
var displayedColumns = [], var displayedColumns = [];
displayedColumnsIds = []; var displayedColumnsIds = [];
// go through all elements of the first row in subscribers data // go through all elements of the first row in subscribers data
for (var i in subscribers.subscribers[0]) { for (var i in subscribers.subscribers[0]) {
var columnData = subscribers.subscribers[0][i], var columnData = subscribers.subscribers[0][i];
columnId = 'ignore'; // set default column type var columnId = 'ignore'; // set default column type
// if the column is not undefined and has a valid e-mail, set type as email // if the column is not undefined and has a valid e-mail, set type as email
if (columnData % 1 !== 0 && window.emailRegex.test(columnData)) { if (columnData % 1 !== 0 && window.emailRegex.test(columnData)) {
columnId = 'email'; columnId = 'email';
} else if (subscribers.header) { } else if (subscribers.header) {
var headerName = subscribers.header[i], var headerName = subscribers.header[i];
headerNameMatch = window.mailpoetColumns.map(function (el) { var headerNameMatch = window.mailpoetColumns.map(function (el) {
return el.name; return el.name;
}).indexOf(headerName); }).indexOf(headerName);
// set column type using header // set column type using header
if (headerNameMatch !== -1) { if (headerNameMatch !== -1) {
columnId = window.mailpoetColumns[headerNameMatch].id; columnId = window.mailpoetColumns[headerNameMatch].id;
@ -733,8 +722,8 @@ define(
} }
}) })
.on('select2:selecting', function (selectEvent) { .on('select2:selecting', function (selectEvent) {
var selectElement = this, var selectElement = this;
selectedOptionId = selectEvent.params.args.data.id; var selectedOptionId = selectEvent.params.args.data.id;
// CREATE CUSTOM FIELD // CREATE CUSTOM FIELD
if (selectedOptionId === 'create') { if (selectedOptionId === 'create') {
selectEvent.preventDefault(); selectEvent.preventDefault();
@ -807,8 +796,8 @@ define(
// check for duplicate values in all select options // check for duplicate values in all select options
jQuery('select.mailpoet_subscribers_column_data_match') jQuery('select.mailpoet_subscribers_column_data_match')
.each(function () { .each(function () {
var element = this, var element = this;
elementId = jQuery(element).val(); var elementId = jQuery(element).val();
// if another column has the same value and it's not an 'ignore', prompt user // if another column has the same value and it's not an 'ignore', prompt user
if (elementId === selectedOptionId if (elementId === selectedOptionId
&& elementId !== 'ignore') { && elementId !== 'ignore') {
@ -824,8 +813,8 @@ define(
} }
}) })
.on('select2:select', function (selectEvent) { .on('select2:select', function (selectEvent) {
var selectElement = this, var selectElement = this;
selectedOptionId = selectEvent.params.data.id; var selectedOptionId = selectEvent.params.data.id;
jQuery(selectElement).data('column-id', selectedOptionId); jQuery(selectElement).data('column-id', selectedOptionId);
filterSubscribers(); filterSubscribers();
}); });
@ -835,15 +824,15 @@ define(
jQuery( jQuery(
'[data-id="notice_invalidEmail"], [data-id="notice_invalidDate"]') '[data-id="notice_invalidEmail"], [data-id="notice_invalidDate"]')
.remove(); .remove();
var subscribersClone = jQuery.extend(true, {}, subscribers), var subscribersClone = jQuery.extend(true, {}, subscribers);
preventNextStep = false, var preventNextStep = false;
displayedColumns = jQuery.map( var displayedColumns = jQuery.map(
jQuery('.mailpoet_subscribers_column_data_match'), function (element, elementIndex) { jQuery('.mailpoet_subscribers_column_data_match'), function (element, elementIndex) {
var columnId = jQuery(element).data('column-id'); var columnId = jQuery(element).data('column-id');
var validationRule = jQuery(element).data('validation-rule'); var validationRule = jQuery(element).data('validation-rule');
jQuery(element).val(columnId).trigger('change'); jQuery(element).val(columnId).trigger('change');
return { id: columnId, index: elementIndex, validationRule: validationRule, element: element }; return { id: columnId, index: elementIndex, validationRule: validationRule, element: element };
}); });
// iterate through the object of mailpoet columns // iterate through the object of mailpoet columns
jQuery.map(window.mailpoetColumns, function (column, columnIndex) { jQuery.map(window.mailpoetColumns, function (column, columnIndex) {
// check if the column id matches the selected id of one of the // check if the column id matches the selected id of one of the
@ -976,28 +965,28 @@ define(
} }
MailPoet.Modal.loading(true); MailPoet.Modal.loading(true);
var columns = {}, var columns = {};
queue = new jQuery.AsyncQueue(), var queue = new jQuery.AsyncQueue();
batchNumber = 0, var batchNumber = 0;
batchSize = 2000, var batchSize = 2000;
timestamp = Date.now() / 1000, var timestamp = Date.now() / 1000;
subscribers = [], var subscribers = [];
importResults = { var importResults = {
created: 0, created: 0,
updated: 0, updated: 0,
errors: [], errors: [],
segments: [] segments: []
}, };
splitSubscribers = function (subscribers, size) { var splitSubscribers = function (subscribers, size) {
return subscribers.reduce(function (res, item, index) { return subscribers.reduce(function (res, item, index) {
if (index % size === 0) { if (index % size === 0) {
res.push([]); res.push([]);
} }
res[res.length - 1].push(item); res[res.length - 1].push(item);
return res; return res;
}, []); }, []);
}, };
subscribers = splitSubscribers(window.importData.step1.subscribers, batchSize); var subscribers = splitSubscribers(window.importData.step1.subscribers, batchSize);
_.each(jQuery('select.mailpoet_subscribers_column_data_match'), _.each(jQuery('select.mailpoet_subscribers_column_data_match'),
function (column, columnIndex) { function (column, columnIndex) {
@ -1087,24 +1076,22 @@ define(
// display statistics // display statistics
var subscribersDataImportResultsTemplate = var subscribersDataImportResultsTemplate =
Handlebars Handlebars.compile(jQuery('#subscribers_data_import_results_template').html());
.compile(jQuery('#subscribers_data_import_results_template') var exportMenuElement = jQuery('span.mailpoet_export');
.html()), var importResults = {
exportMenuElement = jQuery('span.mailpoet_export'), created: (window.importData.step2.created)
importResults = { ? MailPoet.I18n.t('subscribersCreated')
created: (window.importData.step2.created) .replace('%1$s', '<strong>' + window.importData.step2.created.toLocaleString() + '</strong>')
? MailPoet.I18n.t('subscribersCreated') .replace('%2$s', '"' + window.importData.step2.segments.join('", "') + '"')
.replace('%1$s', '<strong>' + window.importData.step2.created.toLocaleString() + '</strong>') : false,
.replace('%2$s', '"' + window.importData.step2.segments.join('", "') + '"') updated: (window.importData.step2.updated)
: false, ? MailPoet.I18n.t('subscribersUpdated')
updated: (window.importData.step2.updated) .replace('%1$s', '<strong>' + window.importData.step2.updated.toLocaleString() + '</strong>')
? MailPoet.I18n.t('subscribersUpdated') .replace('%2$s', '"' + window.importData.step2.segments.join('", "') + '"')
.replace('%1$s', '<strong>' + window.importData.step2.updated.toLocaleString() + '</strong>') : false,
.replace('%2$s', '"' + window.importData.step2.segments.join('", "') + '"') no_action: (!window.importData.step2.created && !window.importData.step2.updated),
: false, added_to_segment_with_welcome_notification: window.importData.step2.added_to_segment_with_welcome_notification
no_action: (!window.importData.step2.created && !window.importData.step2.updated), };
added_to_segment_with_welcome_notification: window.importData.step2.added_to_segment_with_welcome_notification
};
jQuery('#subscribers_data_import_results') jQuery('#subscribers_data_import_results')
.html(subscribersDataImportResultsTemplate(importResults)) .html(subscribersDataImportResultsTemplate(importResults))