This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
+181
View File
@@ -0,0 +1,181 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global varienAccordion, varienLoader, Cookie */
/* eslint-disable strict */
define([
'prototype'
], function () {
window.varienAccordion = new Class.create(); //eslint-disable-line
varienAccordion.prototype = {
/**
* @param {*} containerId
* @param {*} activeOnlyOne
*/
initialize: function (containerId, activeOnlyOne) {
var links, i;
this.containerId = containerId;
this.activeOnlyOne = activeOnlyOne || false;
this.container = $(this.containerId);
this.items = $$('#' + this.containerId + ' dt');
this.loader = new varienLoader(true); //jscs:ignore requireCapitalizedConstructors
links = $$('#' + this.containerId + ' dt a');
for (i in links) {
if (links[i].href) {
Event.observe(links[i], 'click', this.clickItem.bind(this));
this.items[i].dd = this.items[i].next('dd');
this.items[i].link = links[i];
}
}
this.initFromCookie();
},
/**
* Init from cookie.
*/
initFromCookie: function () {
var activeItemId, visibility;
if (this.activeOnlyOne &&
(activeItemId = Cookie.read(this.cookiePrefix() + 'active-item')) !== null) {
this.hideAllItems();
this.showItem(this.getItemById(activeItemId));
} else if (!this.activeOnlyOne) {
this.items.each(function (item) {
if ((visibility = Cookie.read(this.cookiePrefix() + item.id)) !== null) {
if (visibility == 0) { //eslint-disable-line eqeqeq
this.hideItem(item);
} else {
this.showItem(item);
}
}
}.bind(this));
}
},
/**
* @return {String}
*/
cookiePrefix: function () {
return 'accordion-' + this.containerId + '-';
},
/**
* @param {*} itemId
* @return {*}
*/
getItemById: function (itemId) {
var result = null;
this.items.each(function (item) {
if (item.id == itemId) { //eslint-disable-line
result = item;
throw $break;
}
});
return result;
},
/**
* @param {*} event
*/
clickItem: function (event) {
var item = Event.findElement(event, 'dt');
if (this.activeOnlyOne) {
this.hideAllItems();
this.showItem(item);
Cookie.write(this.cookiePrefix() + 'active-item', item.id, 30 * 24 * 60 * 60);
} else {
if (this.isItemVisible(item)) { //eslint-disable-line no-lonely-if
this.hideItem(item);
Cookie.write(this.cookiePrefix() + item.id, 0, 30 * 24 * 60 * 60);
} else {
this.showItem(item);
Cookie.write(this.cookiePrefix() + item.id, 1, 30 * 24 * 60 * 60);
}
}
Event.stop(event);
},
/**
* @param {Object} item
*/
showItem: function (item) {
if (item && item.link) {
if (item.link.href) {
this.loadContent(item);
}
Element.addClassName(item, 'open');
Element.addClassName(item.dd, 'open');
}
},
/**
* @param {Object} item
*/
hideItem: function (item) {
Element.removeClassName(item, 'open');
Element.removeClassName(item.dd, 'open');
},
/**
* @param {*} item
* @return {*}
*/
isItemVisible: function (item) {
return Element.hasClassName(item, 'open');
},
/**
* @param {*} item
*/
loadContent: function (item) {
if (item.link.href.indexOf('#') == item.link.href.length - 1) { //eslint-disable-line eqeqeq
return;
}
if (Element.hasClassName(item.link, 'ajax')) {
this.loadingItem = item;
this.loader.load(item.link.href, {
updaterId: this.loadingItem.dd.id
}, this.setItemContent.bind(this));
return;
}
location.href = item.link.href;
},
/**
* @param {Object} content
*/
setItemContent: function (content) {
if (content.isJSON) {
return;
}
this.loadingItem.dd.innerHTML = content;
},
/**
* Hide all items
*/
hideAllItems: function () {
var i;
for (i in this.items) {
if (this.items[i].id) {
Element.removeClassName(this.items[i], 'open');
Element.removeClassName(this.items[i].dd, 'open');
}
}
}
};
});
+339
View File
@@ -0,0 +1,339 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* @deprecated since version 2.2.0
*/
/* global AdminBackup, setLocation */
/* eslint-disable strict */
define([
'jquery',
'Magento_Ui/js/modal/modal',
'mage/mage',
'prototype'
], function (jQuery) {
window.AdminBackup = new Class.create();
AdminBackup.prototype = {
/**
* Initialize.
*/
initialize: function () {
this.reset();
this.rollbackUrl = this.backupUrl = '';
},
/**
* reset.
*/
reset: function () {
this.time = 0;
this.type = '';
},
/**
* @param {*} type
* @return {Boolean}
*/
backup: function (type) {
this.reset();
this.type = type;
this.requestBackupOptions();
return false;
},
/**
* @param {*} type
* @param {*} time
* @return {Boolean}
*/
rollback: function (type, time) {
this.reset();
this.time = time;
this.type = type;
this.showRollbackWarning();
return false;
},
/**
* Show rollback warning.
*/
showRollbackWarning: function () {
this.showPopup('rollback-warning');
},
/**
* request backup options.
*/
requestBackupOptions: function () {
this.hidePopups();
this.showPopup('backup-options');
if (this.type === 'snapshot') {
jQuery('#exclude-media-checkbox-container').removeClass('no-display');
}
},
/**
* Request password.
*/
requestPassword: function () {
this.hidePopups();
this.showPopup('rollback-request-password');
this.type != 'db' ? //eslint-disable-line eqeqeq
$('use-ftp-checkbox-row').show() :
$('use-ftp-checkbox-row').hide();
},
/**
* Toggle Ftp Credentials Form.
*/
toggleFtpCredentialsForm: function () {
$('use_ftp').checked ? $('ftp-credentials-container').show()
: $('ftp-credentials-container').hide();
$$('#ftp-credentials-container input').each(function (item) {
if (item.name == 'ftp_path') { //eslint-disable-line eqeqeq
return;
}
$('use_ftp').checked ? item.addClassName('required-entry') : item.removeClassName('required-entry');
});
},
/**
* Submit backup.
*/
submitBackup: function () {
var data = {
'type': this.type,
'maintenance_mode': $('backup_maintenance_mode').checked ? 1 : 0,
'backup_name': $('backup_name').value,
'exclude_media': $('exclude_media').checked ? 1 : 0
};
new Ajax.Request(this.backupUrl, {
onSuccess: function (transport) {
this.processResponse(transport, 'backup-options');
}.bind(this),
method: 'post',
parameters: data
});
this.modal.modal('closeModal');
},
/**
* Submit rollback.
*/
submitRollback: function () {
var data = this.getPostData();
new Ajax.Request(this.rollbackUrl, {
onSuccess: function (transport) {
this.processResponse(transport, 'rollback-request-password');
}.bind(this),
method: 'post',
parameters: data
});
this.modal.modal('closeModal');
},
/**
* @param {Object} transport
* @param {*} popupId
*/
processResponse: function (transport, popupId) {
var json;
if (!transport.responseText.isJSON()) {
return;
}
json = transport.responseText.evalJSON();
if (json.error) {
this.showPopup(popupId);
this.displayError(popupId, json.error);
return;
}
if (json['redirect_url']) {
setLocation(json['redirect_url']);
}
},
/**
* @param {*} parentContainer
* @param {*} message
*/
displayError: function (parentContainer, message) {
var messageHtml = this.getErrorMessageHtml(message);
$$('#' + parentContainer + ' .backup-messages .messages').invoke('update', messageHtml);
$$('#' + parentContainer + ' .backup-messages').invoke('show');
},
/**
* @param {*} message
* @return {String}
*/
getErrorMessageHtml: function (message) {
return '<div class="message message-error error"><div>' + message + '</div></div>';
},
/**
* @return {*|jQuery}
*/
getPostData: function () {
var data = $('rollback-form').serialize(true);
data.time = this.time;
data.type = this.type;
return data;
},
backupConfig: {
'backup-options': {
title: jQuery.mage.__('Backup options'),
/**
* @return {String}
*/
content: function () {
return document.getElementById('backup-options-template').textContent;
},
/**
* Action Ok.
*/
actionOk: function () {
this.modal.find('#backup-form').validation({
submitHandler: jQuery.proxy(this.submitBackup, this)
});
this.modal.find('#backup-form').submit();
}
},
'rollback-warning': {
title: jQuery.mage.__('Warning'),
/**
* @return {String}
*/
content: function () {
return document.getElementById('rollback-warning-template').textContent;
},
/**
* Action Ok.
*/
actionOk: function () {
this.modal.modal('closeModal');
this.requestPassword();
}
},
'rollback-request-password': {
title: jQuery.mage.__('Backup options'),
/**
* @return {String}
*/
content: function () {
return document.getElementById('rollback-request-password-template').textContent;
},
/**
* Action Ok.
*/
actionOk: function () {
this.modal.find('#rollback-form').validation({
submitHandler: jQuery.proxy(this.submitRollback, this)
});
this.modal.find('#rollback-form').submit();
},
/**
* Opened.
*/
opened: function () {
this.toggleFtpCredentialsForm();
}
}
},
/**
* @param {*} divId
*/
showPopup: function (divId) {
var self = this;
this.modal = jQuery('<div></div>').attr({
id: divId
}).html(this.backupConfig[divId].content()).modal({
modalClass: 'magento',
title: this.backupConfig[divId].title,
type: 'slide',
/**
* @param {juery.Event} e
* @param {Object} modal
*/
closed: function (e, modal) {
modal.modal.remove();
},
/**
* Opened.
*/
opened: function () {
if (self.backupConfig[divId].opened) {
self.backupConfig[divId].opened.call(self);
}
},
buttons: [{
text: jQuery.mage.__('Cancel'),
'class': 'action cancel',
/**
* Click action.
*/
click: function () {
this.closeModal();
}
}, {
text: jQuery.mage.__('Ok'),
'class': 'action primary',
/**
* Click action.
*/
click: function () {
self.backupConfig[divId].actionOk.call(self);
}
}]
});
this.modal.modal('openModal');
},
/**
* Hide Popups.
*/
hidePopups: function () {
var mask;
$$('.backup-dialog').each(Element.hide);
mask = $('popup-window-mask');
if (mask) {
mask.hide();
}
}
};
});
+539
View File
@@ -0,0 +1,539 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global MediabrowserUtility, FORM_KEY, tinyMceEditors */
/* eslint-disable strict */
define([
'jquery',
'wysiwygAdapter',
'Magento_Ui/js/modal/prompt',
'Magento_Ui/js/modal/confirm',
'Magento_Ui/js/modal/alert',
'underscore',
'Magento_Ui/js/modal/modal',
'jquery/ui',
'jquery/jstree/jquery.jstree',
'mage/mage'
], function ($, wysiwyg, prompt, confirm, alert, _) {
window.MediabrowserUtility = {
windowId: 'modal_dialog_message',
modalLoaded: false,
targetElementId: false,
pathId: '',
/**
* @return {Number}
*/
getMaxZIndex: function () {
var max = 0,
cn = document.body.childNodes,
i, el, zIndex;
for (i = 0; i < cn.length; i++) {
el = cn[i];
zIndex = el.nodeType == 1 ? parseInt(el.style.zIndex, 10) || 0 : 0; //eslint-disable-line eqeqeq
if (zIndex < 10000) {
max = Math.max(max, zIndex);
}
}
return max + 10;
},
/**
* @param {*} url
* @param {*} width
* @param {*} height
* @param {*} title
* @param {Object} options
*/
openDialog: function (url, width, height, title, options) {
var windowId = this.windowId,
content = '<div class="popup-window" id="' + windowId + '"></div>';
if (this.modalLoaded) {
if (!_.isUndefined(options)) {
this.modal.modal('option', 'closed', options.closed);
}
this.modal.modal('openModal');
this.setTargetElementId(options, url);
this.setPathId(url);
$(window).trigger('reload.MediaGallery');
return;
}
this.modal = $(content).modal($.extend({
title: title || 'Insert File...',
modalClass: 'magento',
type: 'slide',
buttons: []
}, options));
this.modal.modal('openModal');
$.ajax({
url: url,
type: 'get',
context: $(this),
showLoader: true
}).done(function (data) {
this.modal.html(data).trigger('contentUpdated');
this.modalLoaded = true;
this.setTargetElementId(options, url);
this.setPathId(url);
}.bind(this));
},
/**
* Setter for endcoded path id
*/
setPathId: function (url) {
this.pathId = url.match(/(&|\/|%26)current_tree_path(=|\/)([\s\S].*?)(\/|$)/)[3];
},
/**
* Setter for targetElementId property
*
* @param {Object} options
* @param {String} url
*/
setTargetElementId: function (options, url) {
this.targetElementId = options && options.targetElementId ?
options.targetElementId
: url.match(/\/target_element_id\/([\s\S].*?)\//)[1];
},
/**
* Close dialog.
*/
closeDialog: function () {
this.modal.modal('closeModal');
}
};
$.widget('mage.mediabrowser', {
eventPrefix: 'mediabrowser',
options: {
contentsUrl: null,
onInsertUrl: null,
newFolderUrl: null,
deleteFolderUrl: null,
deleteFilesUrl: null,
headerText: null,
tree: null,
currentNode: null,
storeId: null,
showBreadcrumbs: null,
hidden: 'no-display'
},
/**
* Proxy creation
* @protected
*/
_create: function () {
this._on({
'click [data-row=file]': 'selectFile',
'dblclick [data-row=file]': 'insert',
'click #new_folder': 'newFolder',
'click #delete_folder': 'deleteFolder',
'click #delete_files': 'deleteFiles',
'click #insert_files': 'insertSelectedFiles',
'fileuploaddone': '_uploadDone',
'click [data-row=breadcrumb]': 'selectFolder'
});
$(window).on('reload.MediaGallery', $.proxy(this.reload, this));
this.activeNode = null;
//tree dont use event bubbling
this.tree = this.element.find('[data-role=tree]');
this.tree.on('select_node.jstree', $.proxy(this._selectNode, this));
},
/**
* @param {jQuery.Event} event
* @param {Object} data
* @private
*/
_selectNode: function (event, data) {
var node = data.node;
this.activeNode = node;
this.element.find('#delete_files, #insert_files').toggleClass(this.options.hidden, true);
this.element.find('#contents').toggleClass(this.options.hidden, false);
this.element.find('#delete_folder')
.toggleClass(this.options.hidden, node.id === 'root'); //eslint-disable-line eqeqeq
this.element.find('#content_header_text')
.html(node.id === 'root' ? this.headerText : node.text); //eslint-disable-line eqeqeq
this.drawBreadcrumbs(data);
this.loadFileList(node);
},
/**
* @return {*}
*/
reload: function (uploaded) {
return this.loadFileList(this.activeNode, uploaded);
},
/**
* @param {Object} element
* @param {*} value
*/
insertAtCursor: function (element, value) {
var sel, startPos, endPos, scrollTop;
if ('selection' in document) {
//For browsers like Internet Explorer
element.focus();
sel = document.selection.createRange();
sel.text = value;
element.focus();
} else if (element.selectionStart || element.selectionStart == '0') { //eslint-disable-line eqeqeq
//For browsers like Firefox and Webkit based
startPos = element.selectionStart;
endPos = element.selectionEnd;
scrollTop = element.scrollTop;
element.value = element.value.substring(0, startPos) + value +
element.value.substring(startPos, endPos) + element.value.substring(endPos, element.value.length);
element.focus();
element.selectionStart = startPos + value.length;
element.selectionEnd = startPos + value.length + element.value.substring(startPos, endPos).length;
element.scrollTop = scrollTop;
} else {
element.value += value;
element.focus();
}
},
/**
* @param {Object} node
*/
loadFileList: function (node, uploaded) {
var contentBlock = this.element.find('#contents');
return $.ajax({
url: this.options.contentsUrl,
type: 'GET',
dataType: 'html',
data: {
'form_key': FORM_KEY,
node: node ? node.id : null
},
context: contentBlock,
showLoader: true
}).done(function (data) {
contentBlock.html(data).trigger('contentUpdated');
if (uploaded) {
contentBlock.find('.filecnt:last').trigger('click');
}
});
},
/**
* @param {jQuery.Event} event
*/
selectFolder: function (event) {
this.element.find('[data-id="' + $(event.currentTarget).data('node').id + '"]>a').trigger('click');
},
/**
* Insert selected files.
*/
insertSelectedFiles: function () {
this.element.find('[data-row=file].selected').trigger('dblclick');
},
/**
* @param {jQuery.Event} event
*/
selectFile: function (event) {
var fileRow = $(event.currentTarget);
fileRow.toggleClass('selected');
this.element.find('[data-row=file]').not(fileRow).removeClass('selected');
this.element.find('#delete_files, #insert_files')
.toggleClass(this.options.hidden, !fileRow.is('.selected'));
fileRow.trigger('selectfile');
},
/**
* @private
*/
_uploadDone: function () {
this.element.find('.file-row').remove();
this.reload(true);
},
/**
* @param {jQuery.Event} event
* @return {Boolean}
*/
insert: function (event) {
var fileRow = $(event.currentTarget),
targetEl;
if (!fileRow.prop('id')) {
return false;
}
targetEl = this.getTargetElement();
if (!targetEl.length) {
MediabrowserUtility.closeDialog();
throw 'Target element not found for content update';
}
return $.ajax({
url: this.options.onInsertUrl,
data: {
filename: fileRow.attr('id'),
node: this.activeNode.id,
store: this.options.storeId,
'as_is': typeof targetEl !== 'function' && targetEl.is('textarea') ? 1 : 0,
'force_static_path': typeof targetEl !== 'function' && targetEl.data('force_static_path') ? 1 : 0,
'form_key': FORM_KEY
},
context: this,
showLoader: true
}).done($.proxy(function (data) {
if (typeof targetEl === 'function') {
targetEl(data, {text: fileRow.find('img').attr('alt')});
} else if (targetEl.is('textarea')) {
this.insertAtCursor(targetEl.get(0), data);
} else {
targetEl
.val(data)
.data('size', fileRow.data('size'))
.data('mime-type', fileRow.data('mime-type'));
}
MediabrowserUtility.closeDialog();
if (typeof targetEl !== 'function') {
targetEl.focus();
jQuery(targetEl).trigger('change');
}
}, this));
},
/**
* Find document target element in next order:
* in acive file browser opener:
* - input field with ID: "src" in opener window
* - input field with ID: "href" in opener window
* in document:
* - element with target ID
*
* return {HTMLElement|null}
*/
getTargetElement: function () {
var mediaBrowser = window.MediabrowserUtility;
if (!_.isUndefined(wysiwyg) && wysiwyg.get(mediaBrowser.targetElementId)) {
return this.getMediaBrowserOpener() || window;
}
return $('#' + mediaBrowser.targetElementId);
},
/**
* Return opener Window object if it exists, not closed and editor is active
*
* return {Object|null}
*/
getMediaBrowserOpener: function () {
var targetElementId = window.MediabrowserUtility.targetElementId;
if (!_.isUndefined(wysiwyg) && wysiwyg.get(targetElementId) && !_.isUndefined(tinyMceEditors)) {
return tinyMceEditors.get(targetElementId).getMediaBrowserOpener();
}
return null;
},
/**
* New folder.
*/
newFolder: function () {
var self = this;
prompt({
title: this.options.newFolderPrompt,
actions: {
/**
* @param {*} folderName
*/
confirm: function (folderName) {
$.ajax({
url: self.options.newFolderUrl,
dataType: 'json',
data: {
name: folderName,
node: self.activeNode.id,
store: self.options.storeId,
'form_key': FORM_KEY
},
context: self.element,
showLoader: true
}).done($.proxy(function (data) {
if (data.error) {
alert({
content: data.message
});
} else {
self.tree.jstree(
'refresh_node',
self.element.find('[data-id="' + self.activeNode.id + '"]')
);
}
}, this));
return true;
}
}
});
},
/**
* Delete folder.
*/
deleteFolder: function () {
var self = this;
confirm({
content: this.options.deleteFolderConfirmationMessage,
actions: {
/**
* Confirm.
*/
confirm: function () {
return $.ajax({
url: self.options.deleteFolderUrl,
dataType: 'json',
data: {
node: self.activeNode.id,
store: self.options.storeId,
'form_key': FORM_KEY
},
context: self.element,
showLoader: true
}).done($.proxy(function (data) {
if (data.error) {
alert({
content: data.message
});
} else {
self.tree.jstree('refresh', self.activeNode.id);
self.reload();
$(window).trigger('fileDeleted.mediabrowser', {
ids: self.activeNode.id
});
}
}, this));
},
/**
* @return {Boolean}
*/
cancel: function () {
return false;
}
}
});
},
/**
* Delete files.
*/
deleteFiles: function () {
var self = this;
confirm({
content: this.options.deleteFileConfirmationMessage,
actions: {
/**
* Confirm.
*/
confirm: function () {
var selectedFiles = self.element.find('[data-row=file].selected'),
ids = selectedFiles.map(function () {
return $(this).attr('id');
}).toArray();
return $.ajax({
url: self.options.deleteFilesUrl,
data: {
files: ids,
store: self.options.storeId,
'form_key': FORM_KEY
},
context: self.element,
showLoader: true
}).done($.proxy(function (data) {
if (data.error) {
alert({
content: data.message
});
} else {
self.reload();
self.element.find('#delete_files, #insert_files').toggleClass(
self.options.hidden, true
);
$(window).trigger('fileDeleted.mediabrowser', {
ids: ids
});
}
}, this));
},
/**
* @return {Boolean}
*/
cancel: function () {
return false;
}
}
});
},
/**
* @param {Object} data
*/
drawBreadcrumbs: function (data) {
var node, breadcrumbs;
if (this.element.find('#breadcrumbs').length) {
this.element.find('#breadcrumbs').remove();
}
node = data.node;
if (node.id === 'root') { //eslint-disable-line eqeqeq
return;
}
breadcrumbs = $('<ul class="breadcrumbs" id="breadcrumbs"></ul>');
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
data.instance.get_path(node).each(function (name, index) {
if (index > 0) {
breadcrumbs.append($('<li>\/</li>')); //eslint-disable-line
}
breadcrumbs.append($('<li />').attr('data-row', 'breadcrumb').text(name));
});
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
breadcrumbs.insertAfter(this.element.find('#content_header'));
}
});
return window.MediabrowserUtility;
});
+193
View File
@@ -0,0 +1,193 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global varienEvents */
/* eslint-disable strict */
define([
'Magento_Ui/js/modal/alert',
'prototype'
], function (alert) {
// from http://www.someelement.com/2007/03/eventpublisher-custom-events-la-pubsub.html
window.varienEvents = Class.create();
varienEvents.prototype = {
/**
* Initialize.
*/
initialize: function () {
this.arrEvents = {};
this.eventPrefix = '';
},
/**
* Attaches a {handler} function to the publisher's {eventName} event for execution upon the event firing
* @param {String} eventName
* @param {Function} handler
* @param {Boolean} [asynchFlag] - Defaults to false if omitted.
* Indicates whether to execute {handler} asynchronously (true) or not (false).
*/
attachEventHandler: function (eventName, handler) {
var asynchVar, handlerObj;
if (typeof handler == 'undefined' || handler == null) {
return;
}
eventName += this.eventPrefix;
// using an event cache array to track all handlers for proper cleanup
if (this.arrEvents[eventName] == null) {
this.arrEvents[eventName] = [];
}
//create a custom object containing the handler method and the asynch flag
asynchVar = arguments.length > 2 ? arguments[2] : false;
handlerObj = {
method: handler,
asynch: asynchVar
};
this.arrEvents[eventName].push(handlerObj);
},
/**
* Removes a single handler from a specific event
* @param {String} eventName - The event name to clear the handler from
* @param {Function} handler - A reference to the handler function to un-register from the event
*/
removeEventHandler: function (eventName, handler) {
eventName += this.eventPrefix;
if (this.arrEvents[eventName] != null) {
this.arrEvents[eventName] = this.arrEvents[eventName].reject(function (obj) {
return obj.method == handler; //eslint-disable-line eqeqeq
});
}
},
/**
* Removes all handlers from a single event
* @param {String} eventName - The event name to clear handlers from
*/
clearEventHandlers: function (eventName) {
eventName += this.eventPrefix;
this.arrEvents[eventName] = null;
},
/**
* Removes all handlers from ALL events
*/
clearAllEventHandlers: function () {
this.arrEvents = {};
},
/**
* Collect and modify value of arg synchronously in succession and return its new value.
* In order to use, call attachEventHandler and add function handlers with eventName.
* Then call fireEventReducer with eventName and any argument to have its value accumulatively modified.
* Event handlers will be applied to argument in order of first attached to last attached.
* @param {String} eventName
* @param {*} arg
*/
fireEventReducer: function (eventName, arg) {
var evtName = eventName + this.eventPrefix,
result = arg,
len,
i;
if (!this.arrEvents[evtName]) {
return result;
}
len = this.arrEvents[evtName].length; //optimization
for (i = 0; i < len; i++) {
/* eslint-disable max-depth */
try {
result = this.arrEvents[evtName][i].method(result);
} catch (e) {
if (this.id) {
alert({
content: 'error: error in ' + this.id + '.fireEventReducer():\n\nevent name: ' +
eventName + '\n\nerror message: ' + e.message
});
} else {
alert({
content: 'error: error in [unknown object].fireEventReducer():\n\nevent name: ' +
eventName + '\n\nerror message: ' + e.message
});
}
}
/* eslint-disable max-depth */
}
return result;
},
/**
* Fires the event {eventName}, resulting in all registered handlers to be executed.
* It also collects and returns results of all non-asynchronous handlers
* @param {String} eventName - The name of the event to fire
* @param {Object} [args] - Any object, will be passed into the handler function as the only argument
* @return {Array}
*/
fireEvent: function (eventName) {
var evtName = eventName + this.eventPrefix,
results = [],
result, len, i, eventArgs, method, eventHandler;
if (this.arrEvents[evtName] != null) {
len = this.arrEvents[evtName].length; //optimization
for (i = 0; i < len; i++) {
/* eslint-disable max-depth */
try {
if (arguments.length > 1) {
if (this.arrEvents[evtName][i].asynch) {
eventArgs = arguments[1];
method = this.arrEvents[evtName][i].method.bind(this);
setTimeout(function () { //eslint-disable-line no-loop-func
method(eventArgs);
}, 10);
} else {
result = this.arrEvents[evtName][i].method(arguments[1]);
}
} else {
if (this.arrEvents[evtName][i].asynch) { //eslint-disable-line no-lonely-if
eventHandler = this.arrEvents[evtName][i].method;
setTimeout(eventHandler, 1);
} else if (
this.arrEvents &&
this.arrEvents[evtName] &&
this.arrEvents[evtName][i] &&
this.arrEvents[evtName][i].method
) {
result = this.arrEvents[evtName][i].method();
}
}
results.push(result);
}
catch (e) {
if (this.id) {
alert({
content: 'error: error in ' + this.id + '.fireEvent():\n\nevent name: ' +
eventName + '\n\nerror message: ' + e.message
});
} else {
alert({
content: 'error: error in [unknown object].fireEvent():\n\nevent name: ' +
eventName + '\n\nerror message: ' + e.message
});
}
}
/* eslint-enable max-depth */
}
}
return results;
}
};
window.varienGlobalEvents = new varienEvents(); //jscs:ignore requireCapitalizedConstructors
return window.varienGlobalEvents;
});
+624
View File
@@ -0,0 +1,624 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global varienGlobalEvents, varienWindowOnloadCache, RegionUpdater, FormElementDependenceController */
/* eslint-disable strict */
define([
'jquery',
'prototype',
'mage/adminhtml/events'
], function (jQuery) {
var varienElementMethods;
/*
* @TODO Need to be removed after refactoring all dependent of the form the components
*/
(function ($) {
$(function () {
$(document).on('beforeSubmit', function (e) { //eslint-disable-line max-nested-callbacks
if (typeof varienGlobalEvents !== 'undefined') {
varienGlobalEvents.fireEvent('formSubmit', $(e.target).attr('id'));
}
});
});
})(jQuery);
/**
* Additional elements methods
*/
varienElementMethods = {
/**
* @param {HTMLElement} element
*/
setHasChanges: function (element) {
var elm;
if ($(element) && $(element).hasClassName('no-changes')) {
return;
}
elm = element;
while (elm && elm.tagName != 'BODY') { //eslint-disable-line eqeqeq
if (elm.statusBar) {
Element.addClassName($(elm.statusBar), 'changed');
}
elm = elm.parentNode;
}
},
/**
* @param {HTMLElement} element
* @param {*} flag
* @param {Object} form
*/
setHasError: function (element, flag, form) {
var elm = element;
while (elm && elm.tagName != 'BODY') { //eslint-disable-line eqeqeq
if (elm.statusBar) {
/* eslint-disable max-depth */
if (form.errorSections.keys().indexOf(elm.statusBar.id) < 0) {
form.errorSections.set(elm.statusBar.id, flag);
}
if (flag) {
Element.addClassName($(elm.statusBar), 'error');
if (form.canShowError && $(elm.statusBar).show) {
form.canShowError = false;
$(elm.statusBar).show();
}
form.errorSections.set(elm.statusBar.id, flag);
} else if (!form.errorSections.get(elm.statusBar.id)) {
Element.removeClassName($(elm.statusBar), 'error');
}
/* eslint-enable max-depth */
}
elm = elm.parentNode;
}
this.canShowElement = false;
}
};
Element.addMethods(varienElementMethods);
// Global bind changes
window.varienWindowOnloadCache = {};
/**
* @param {*} useCache
*/
function varienWindowOnload(useCache) {
var dataElements = $$('input', 'select', 'textarea'),
i;
for (i = 0; i < dataElements.length; i++) {
if (dataElements[i] && dataElements[i].id) {
/* eslint-disable max-depth */
if (!useCache || !varienWindowOnloadCache[dataElements[i].id]) {
Event.observe(dataElements[i], 'change', dataElements[i].setHasChanges.bind(dataElements[i]));
if (useCache) {
varienWindowOnloadCache[dataElements[i].id] = true;
}
}
/* eslint-disable max-depth */
}
}
}
Event.observe(window, 'load', varienWindowOnload);
window.RegionUpdater = Class.create();
RegionUpdater.prototype = {
/**
* @param {HTMLElement} countryEl
* @param {HTMLElement} regionTextEl
* @param {HTMLElement}regionSelectEl
* @param {Object} regions
* @param {*} disableAction
* @param {*} clearRegionValueOnDisable
*/
initialize: function (
countryEl, regionTextEl, regionSelectEl, regions, disableAction, clearRegionValueOnDisable
) {
this.isRegionRequired = true;
this.countryEl = $(countryEl);
this.regionTextEl = $(regionTextEl);
this.regionSelectEl = $(regionSelectEl);
this.config = regions.config;
delete regions.config;
this.regions = regions;
this.sortedRegions = this.getSortedRegions();
this.disableAction = typeof disableAction === 'undefined' ? 'hide' : disableAction;
this.clearRegionValueOnDisable = typeof clearRegionValueOnDisable === 'undefined' ?
false : clearRegionValueOnDisable;
if (this.regionSelectEl.options.length <= 1) {
this.update();
} else {
this.lastCountryId = this.countryEl.value;
}
this.countryEl.changeUpdater = this.update.bind(this);
Event.observe(this.countryEl, 'change', this.update.bind(this));
},
/**
* @private
*/
_checkRegionRequired: function () {
var label, wildCard, elements, that, regionRequired;
if (!this.isRegionRequired) {
return;
}
elements = [this.regionTextEl, this.regionSelectEl];
that = this;
if (typeof this.config == 'undefined') {
return;
}
regionRequired = this.config['regions_required'].indexOf(this.countryEl.value) >= 0;
elements.each(function (currentElement) {
var form, validationInstance, field, topElement;
if (!currentElement) {
return;
}
form = currentElement.form;
validationInstance = form ? jQuery(form).data('validation') : null;
field = currentElement.up('.field') || new Element('div');
if (validationInstance) {
validationInstance.clearError(currentElement);
}
label = $$('label[for="' + currentElement.id + '"]')[0];
if (label) {
wildCard = label.down('em') || label.down('span.required');
topElement = label.up('tr') || label.up('li');
if (!that.config['show_all_regions'] && topElement) {
if (regionRequired) {
topElement.show();
} else {
topElement.hide();
}
}
}
if (label && wildCard) {
if (!regionRequired) {
wildCard.hide();
} else {
wildCard.show();
}
}
//compute the need for the required fields
if (!regionRequired || !currentElement.visible()) {
if (field.hasClassName('required')) {
field.removeClassName('required');
}
if (currentElement.hasClassName('required-entry')) {
currentElement.removeClassName('required-entry');
}
if (currentElement.tagName.toLowerCase() == 'select' && //eslint-disable-line eqeqeq
currentElement.hasClassName('validate-select')
) {
currentElement.removeClassName('validate-select');
}
} else {
if (!field.hasClassName('required')) {
field.addClassName('required');
}
if (!currentElement.hasClassName('required-entry')) {
currentElement.addClassName('required-entry');
}
if (currentElement.tagName.toLowerCase() == 'select' && //eslint-disable-line eqeqeq
!currentElement.hasClassName('validate-select')
) {
currentElement.addClassName('validate-select');
}
}
});
},
/**
* Disable region validation.
*/
disableRegionValidation: function () {
this.isRegionRequired = false;
},
/**
* Update.
*/
update: function () {
var option, selectElement, def, regionId, region;
selectElement = this.regionSelectEl;
if (this.sortedRegions[this.countryEl.value]) {
if (this.lastCountryId != this.countryEl.value) { //eslint-disable-line eqeqeq
def = selectElement.getAttribute('defaultValue');
if (this.regionTextEl) {
if (!def) {
def = this.regionTextEl.value.toLowerCase();
}
this.regionTextEl.value = '';
}
selectElement.options.length = 1;
this.sortedRegions[this.countryEl.value].forEach(function (item) {
regionId = item[0];
region = item[1];
option = document.createElement('OPTION');
option.value = regionId;
option.text = region.name.stripTags();
option.title = region.name;
if (selectElement.options.add) {
selectElement.options.add(option);
} else {
selectElement.appendChild(option);
}
if (regionId == def || region.name.toLowerCase() == def || region.code.toLowerCase() == def) { //eslint-disable-line
selectElement.value = regionId;
}
});
}
if (this.disableAction == 'hide') { //eslint-disable-line eqeqeq
if (this.regionTextEl) {
this.regionTextEl.style.display = 'none';
this.regionTextEl.style.disabled = true;
}
this.regionSelectEl.style.display = '';
this.regionSelectEl.disabled = false;
} else if (this.disableAction == 'disable') { //eslint-disable-line eqeqeq
if (this.regionTextEl) {
this.regionTextEl.disabled = true;
}
this.regionSelectEl.disabled = false;
}
this.setMarkDisplay(this.regionSelectEl, true);
this.lastCountryId = this.countryEl.value;
} else {
if (this.disableAction == 'hide') { //eslint-disable-line eqeqeq
if (this.regionTextEl) {
this.regionTextEl.style.display = '';
this.regionTextEl.style.disabled = false;
}
this.regionSelectEl.style.display = 'none';
this.regionSelectEl.disabled = true;
} else if (this.disableAction == 'disable') { //eslint-disable-line eqeqeq
if (this.regionTextEl) {
this.regionTextEl.disabled = false;
}
this.regionSelectEl.disabled = true;
if (this.clearRegionValueOnDisable) {
this.regionSelectEl.value = '';
}
} else if (this.disableAction == 'nullify') { //eslint-disable-line eqeqeq
this.regionSelectEl.options.length = 1;
this.regionSelectEl.value = '';
this.regionSelectEl.selectedIndex = 0;
this.lastCountryId = '';
}
this.setMarkDisplay(this.regionSelectEl, false);
}
varienGlobalEvents.fireEvent('address_country_changed', this.countryEl);
this._checkRegionRequired();
},
/**
* @param {HTMLElement} elem
* @param {*} display
*/
setMarkDisplay: function (elem, display) {
var marks;
if (elem.parentNode.parentNode) {
marks = Element.select(elem.parentNode.parentNode, '.required');
if (marks[0]) {
display ? marks[0].show() : marks[0].hide();
}
}
},
/**
* Sort regions from JSON by name
*
* @returns {*[]}
*/
getSortedRegions: function () {
var country, regionsEntries, regionsByCountry;
regionsByCountry = [];
for (country in this.regions) { //eslint-disable-line guard-for-in
regionsEntries = Object.entries(this.regions[country]);
regionsEntries.sort(function (a, b) {
return a[1].name > b[1].name ? 1 : -1;
});
regionsByCountry[country] = regionsEntries;
}
return regionsByCountry;
}
};
window.regionUpdater = RegionUpdater;
/**
* Fix errorrs in IE
*/
Event.pointerX = function (event) {
try {
return event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)); //eslint-disable-line
}
catch (e) {}
};
/**
* @param {jQuery.Event} event
* @return {*}
*/
Event.pointerY = function (event) {
try {
return event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop)); //eslint-disable-line
}
catch (e) {}
};
/**
* Observer that watches for dependent form elements
* If an element depends on 1 or more of other elements,
* it should show up only when all of them gain specified values
*/
window.FormElementDependenceController = Class.create();
FormElementDependenceController.prototype = {
/**
* Structure of elements: {
* 'id_of_dependent_element' : {
* 'id_of_master_element_1' : 'reference_value',
* 'id_of_master_element_2' : 'reference_value'
* 'id_of_master_element_3' : ['reference_value1', 'reference_value2']
* ...
* }
* }
* @param {Object} elementsMap
* @param {Object} config
*/
initialize: function (elementsMap, config) {
var idTo, idFrom, values, fromId, radioFrom;
if (config) {
this._config = jQuery.extend(this._config, config);
}
for (idTo in elementsMap) { //eslint-disable-line guard-for-in
for (idFrom in elementsMap[idTo]) { //eslint-disable-line guard-for-in
if ($(idFrom)) {
Event.observe(
$(idFrom),
'change',
this.trackChange.bindAsEventListener(this, idTo, elementsMap[idTo])
);
} else {
// Check if radio button
values = elementsMap[idTo][idFrom].values;
fromId = $(idFrom + values[0]);
radioFrom = fromId ? $$('[name="' + fromId.name + '"]') : false;
if (radioFrom) {
radioFrom.invoke(
'on',
'change',
this.trackChange.bindAsEventListener(this, idTo, elementsMap[idTo])
);
}
}
this.trackChange(null, idTo, elementsMap[idTo]);
}
}
},
/**
* Misc. config options
* Keys are underscored intentionally
*/
_config: {
'levels_up': 1 // how many levels up to travel when toggling element
},
/**
* Define whether target element should be toggled and show/hide its row
*
* @param {Object} e - event
* @param {String} idTo - id of target element
* @param {Object} valuesFrom - ids of master elements and reference values
* @return
*/
trackChange: function (e, idTo, valuesFrom) {
// define whether the target should show up
var shouldShowUp = true,
idFrom, from, values, isInArray, isNegative, headElement, isInheritCheckboxChecked, target, inputs,
isAnInputOrSelect, currentConfig, rowElement, fromId, radioFrom, targetArray, isChooser;
for (idFrom in valuesFrom) { //eslint-disable-line guard-for-in
from = $(idFrom);
if (from) {
values = valuesFrom[idFrom].values;
isInArray = values.indexOf(from.value) != -1; //eslint-disable-line
isNegative = valuesFrom[idFrom].negative;
if (!from || isInArray && isNegative || !isInArray && !isNegative) {
shouldShowUp = false;
}
// Check if radio button
} else {
values = valuesFrom[idFrom].values;
fromId = $(idFrom + values[0]);
if (fromId) {
radioFrom = $$('[name="' + fromId.name + '"]:checked');
isInArray = radioFrom.length > 0 && values.indexOf(radioFrom[0].value) !== -1;
isNegative = valuesFrom[idFrom].negative;
if (!radioFrom || isInArray && isNegative || !isInArray && !isNegative) {
shouldShowUp = false;
}
}
}
}
// toggle target row
headElement = jQuery('#' + idTo + '-head');
isInheritCheckboxChecked = $(idTo + '_inherit') && $(idTo + '_inherit').checked;
target = $(idTo);
// Account for the chooser style parameters.
if (target === null && headElement.length === 0 && idTo.substring(0, 16) === 'options_fieldset') {
targetArray = $$('input[id*="' + idTo + '"]');
isChooser = true;
if (targetArray !== null && targetArray.length > 0) {
target = targetArray[0];
}
headElement = jQuery('.field-' + idTo).add('.field-chooser' + idTo);
}
// Target won't always exist (for example, if field type is "label")
if (target) {
inputs = target.up(this._config['levels_up']).select('input', 'select', 'td');
isAnInputOrSelect = ['input', 'select'].indexOf(target.tagName.toLowerCase()) != -1; //eslint-disable-line
if (target.type === 'fieldset') {
inputs = target.select('input', 'select', 'td');
}
} else {
inputs = false;
isAnInputOrSelect = false;
}
if (shouldShowUp) {
currentConfig = this._config;
if (inputs) {
inputs.each(function (item) {
// don't touch hidden inputs (and Use Default inputs too), bc they may have custom logic
if ((!item.type || item.type != 'hidden') && !($(item.id + '_inherit') && $(item.id + '_inherit').checked) && //eslint-disable-line
!(currentConfig['can_edit_price'] != undefined && !currentConfig['can_edit_price']) && //eslint-disable-line
!item.getAttribute('readonly') || isChooser //eslint-disable-line
) {
item.disabled = false;
jQuery(item).removeClass('ignore-validate');
}
});
}
if (headElement.length > 0) {
headElement.show();
if (headElement.hasClass('open') && target) {
target.show();
} else if (target) {
target.hide();
}
} else {
if (target) {
target.show();
headElement = jQuery('.field-' + idTo).add('.field-chooser' + idTo);
headElement.show();
}
if (isAnInputOrSelect && !isInheritCheckboxChecked) {
if (target) {
if (target.getAttribute('readonly')) {
target.disabled = true;
} else {
target.disabled = false;
}
}
jQuery('#' + idTo).removeClass('ignore-validate');
}
}
} else {
if (inputs) {
inputs.each(function (item) {
// don't touch hidden inputs (and Use Default inputs too), bc they may have custom logic
if ((!item.type || item.type != 'hidden') && //eslint-disable-line eqeqeq
!($(item.id + '_inherit') && $(item.id + '_inherit').checked)
) {
item.disabled = true;
jQuery(item).addClass('ignore-validate');
}
});
}
if (headElement.length > 0) {
headElement.hide();
} else {
headElement = jQuery('.field-' + idTo).add('.field-chooser' + idTo);
headElement.hide();
}
if (target) {
target.hide();
}
if (isAnInputOrSelect && !isInheritCheckboxChecked) {
if (target) {
target.disabled = true;
}
jQuery('#' + idTo).addClass('ignore-validate');
}
}
rowElement = $('row_' + idTo);
if (rowElement == undefined && target) { //eslint-disable-line eqeqeq
rowElement = target.up(this._config['levels_up']);
if (target.type === 'fieldset') {
rowElement = target;
}
}
if (rowElement) {
if (shouldShowUp) {
rowElement.show();
} else {
rowElement.hide();
}
}
}
};
window.varienWindowOnload = varienWindowOnload;
window.varienElementMethods = varienElementMethods;
});
+56
View File
@@ -0,0 +1,56 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global setLocation */
define([
'Magento_Ui/js/modal/confirm',
'mage/dataPost'
], function (confirm, dataPost) {
'use strict';
/**
* Set of a temporary methods used to provide
* backward compatibility with a legacy code.
*/
window.setLocation = function (url) {
window.location.href = url;
};
/**
* Helper for onclick action.
* @param {String} message
* @param {String} url
* @param {Object} postData
* @returns {Boolean}
*/
window.deleteConfirm = function (message, url, postData) {
confirm({
content: message,
actions: {
/**
* Confirm action.
*/
confirm: function () {
if (postData !== undefined) {
postData.action = url;
dataPost().postData(postData);
} else {
setLocation(url);
}
}
}
});
return false;
};
/**
* Helper for onclick action.
* @param {String} message
* @param {String} url
* @returns {Boolean}
*/
window.confirmSetLocation = window.deleteConfirm;
});
File diff suppressed because it is too large Load Diff
+519
View File
@@ -0,0 +1,519 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
function setLocation(url) {
window.location.href = url;
}
function setElementDisable(element, disable) {
if ($(element)) {
$(element).disabled = disable;
}
}
function toggleParentVis(obj) {
obj = $(obj).parentNode;
if (obj.style.display == 'none') {
obj.style.display = '';
} else {
obj.style.display = 'none';
}
}
// to fix new app/design/adminhtml/default/default/template/widget/form/renderer/fieldset.phtml
// with toggleParentVis
function toggleFieldsetVis(obj) {
id = obj;
obj = $(obj);
if (obj.style.display == 'none') {
obj.style.display = '';
} else {
obj.style.display = 'none';
}
obj = obj.parentNode.childElements();
for (var i = 0; i < obj.length; i++) {
if (obj[i].id != undefined &&
obj[i].id == id &&
obj[i - 1].classNames() == 'entry-edit-head') {
if (obj[i - 1].style.display == 'none') {
obj[i - 1].style.display = '';
} else {
obj[i - 1].style.display = 'none';
}
}
}
}
function toggleVis(obj) {
obj = $(obj);
if (obj.style.display == 'none') {
obj.style.display = '';
} else {
obj.style.display = 'none';
}
}
function imagePreview(element) {
if ($(element)) {
var win = window.open('', 'preview', 'width=400,height=400,resizable=1,scrollbars=1');
win.document.open();
win.document.write('<body style="padding:0;margin:0"><img src="' + $(element).src + '" id="image_preview"/></body>');
win.document.close();
Event.observe(win, 'load', function () {
var img = win.document.getElementById('image_preview');
win.resizeTo(img.width + 40, img.height + 80);
});
}
}
function checkByProductPriceType(elem) {
if (elem.id == 'price_type') {
this.productPriceType = elem.value;
return false;
}
if (elem.id == 'price' && this.productPriceType == 0) {
return false;
}
return true;
}
function toggleSeveralValueElements(checkbox, containers, excludedElements, checked) {
'use strict';
if (containers && checkbox) {
if (Object.prototype.toString.call(containers) != '[object Array]') {
containers = [containers];
}
containers.each(function (container) {
toggleValueElements(checkbox, container, excludedElements, checked);
});
}
}
function toggleValueElements(checkbox, container, excludedElements, checked) {
if (container && checkbox) {
var ignoredElements = [checkbox];
if (typeof excludedElements != 'undefined') {
if (Object.prototype.toString.call(excludedElements) != '[object Array]') {
excludedElements = [excludedElements];
}
for (var i = 0; i < excludedElements.length; i++) {
ignoredElements.push(excludedElements[i]);
}
}
//var elems = container.select('select', 'input');
var elems = Element.select(container, ['select', 'input', 'textarea', 'button', 'img']).filter(function (el) {
return el.readAttribute('type') != 'hidden';
});
var isDisabled = checked != undefined ? checked : checkbox.checked;
elems.each(function (elem) {
if (checkByProductPriceType(elem)) {
var i = ignoredElements.length;
while (i-- && elem != ignoredElements[i]);
if (i != -1) {
return;
}
elem.disabled = isDisabled;
if (isDisabled) {
elem.addClassName('disabled');
} else {
elem.removeClassName('disabled');
}
if (elem.nodeName.toLowerCase() == 'img') {
isDisabled ? elem.hide() : elem.show();
}
}
});
}
}
/**
* @todo add validation for fields
*/
function submitAndReloadArea(area, url) {
if ($(area)) {
var fields = $(area).select('input', 'select', 'textarea');
var data = Form.serializeElements(fields, true);
url += url.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true';
new Ajax.Request(url, {
parameters: $H(data),
loaderArea: area,
onSuccess: function (transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON();
if (response.error) {
alert(response.message);
}
if (response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(area).update(transport.responseText);
}
}
catch (e) {
$(area).update(transport.responseText);
}
}
});
}
}
/********** MESSAGES ***********/
function syncOnchangeValue(baseElem, distElem) {
var compare = {
baseElem: baseElem, distElem: distElem
};
Event.observe(baseElem, 'change', function () {
if ($(this.baseElem) && $(this.distElem)) {
$(this.distElem).value = $(this.baseElem).value;
}
}.bind(compare));
}
// Insert some content to the cursor position of input element
function updateElementAtCursor(el, value, win) {
if (win == undefined) {
win = window.self;
}
if (document.selection) {
el.focus();
sel = win.document.selection.createRange();
sel.text = value;
} else if (el.selectionStart || el.selectionStart == '0') {
var startPos = el.selectionStart;
var endPos = el.selectionEnd;
el.value = el.value.substring(0, startPos) + value + el.value.substring(endPos, el.value.length);
} else {
el.value += value;
}
}
// Firebug detection
function firebugEnabled() {
if (window.console && window.console.firebug) {
return true;
}
return false;
}
function disableElement(elem) {
elem.disabled = true;
elem.addClassName('disabled');
}
function enableElement(elem) {
elem.disabled = false;
elem.removeClassName('disabled');
}
function disableElements(search) {
$$('.' + search).each(disableElement);
}
function enableElements(search) {
$$('.' + search).each(enableElement);
}
/** Cookie Reading And Writing **/
var Cookie = {
all: function () {
var pairs = document.cookie.split(';');
var cookies = {};
pairs.each(function (item, index) {
var pair = item.strip().split('=');
cookies[unescape(pair[0])] = unescape(pair[1]);
});
return cookies;
},
read: function (cookieName) {
var cookies = this.all();
if (cookies[cookieName]) {
return cookies[cookieName];
}
return null;
},
write: function (cookieName, cookieValue, cookieLifeTime, samesite) {
var expires = '';
if (cookieLifeTime) {
var date = new Date();
date.setTime(date.getTime() + cookieLifeTime * 1000);
expires = '; expires=' + date.toUTCString();
}
var urlPath = '/' + BASE_URL.split('/').slice(3).join('/'); // Get relative path
samesite = '; samesite=' + (samesite ? samesite : 'lax');
document.cookie = escape(cookieName) + '=' + escape(cookieValue) + expires + '; path=' + urlPath + samesite;
},
clear: function (cookieName) {
this.write(cookieName, '', -1);
}
};
var Fieldset = {
cookiePrefix: 'fh-',
applyCollapse: function (containerId) {
if ($(containerId + '-state')) {
collapsed = $(containerId + '-state').value == 1 ? 0 : 1;
} else {
collapsed = $(containerId + '-head').collapsed;
}
if (collapsed == 1 || collapsed === undefined) {
$(containerId + '-head').removeClassName('open');
if ($(containerId + '-head').up('.section-config')) {
$(containerId + '-head').up('.section-config').removeClassName('active');
}
$(containerId).hide();
} else {
$(containerId + '-head').addClassName('open');
if ($(containerId + '-head').up('.section-config')) {
$(containerId + '-head').up('.section-config').addClassName('active');
}
$(containerId).show();
}
},
toggleCollapse: function (containerId, saveThroughAjax) {
if ($(containerId + '-state')) {
collapsed = $(containerId + '-state').value == 1 ? 0 : 1;
} else {
collapsed = $(containerId + '-head').collapsed;
}
//Cookie.read(this.cookiePrefix + containerId);
if (collapsed == 1 || collapsed === undefined) {
//Cookie.write(this.cookiePrefix + containerId, 0, 30*24*60*60);
if ($(containerId + '-state')) {
$(containerId + '-state').value = 1;
}
$(containerId + '-head').collapsed = 0;
} else {
//Cookie.clear(this.cookiePrefix + containerId);
if ($(containerId + '-state')) {
$(containerId + '-state').value = 0;
}
$(containerId + '-head').collapsed = 1;
}
this.applyCollapse(containerId);
if (typeof saveThroughAjax != 'undefined') {
this.saveState(saveThroughAjax, {
container: containerId, value: $(containerId + '-state').value
});
}
},
addToPrefix: function (value) {
this.cookiePrefix += value + '-';
},
saveState: function (url, parameters) {
new Ajax.Request(url, {
method: 'post',
parameters: Object.toQueryString(parameters),
loaderArea: false
});
}
};
var Base64 = {
// private property
_keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
//'+/=', '-_,'
// public method for encoding
encode: function (input) {
var output = '';
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
if (typeof window.btoa === 'function') {
return window.btoa(input);
}
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = (chr1 & 3) << 4 | chr2 >> 4;
enc3 = (chr2 & 15) << 2 | chr3 >> 6;
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode: function (input) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
if (typeof window.atob === 'function') {
return Base64._utf8_decode(window.atob(input));
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
output += String.fromCharCode(chr1);
if (enc3 != 64) {
output += String.fromCharCode(chr2);
}
if (enc4 != 64) {
output += String.fromCharCode(chr3);
}
}
return Base64._utf8_decode(output);
},
mageEncode: function (input) {
return this.encode(input).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ',');
},
mageDecode: function (output) {
output = output.replace(/\-/g, '+').replace(/_/g, '/').replace(/,/g, '=');
return this.decode(output);
},
idEncode: function (input) {
return this.encode(input).replace(/\+/g, ':').replace(/\//g, '_').replace(/=/g, '-');
},
idDecode: function (output) {
output = output.replace(/\-/g, '=').replace(/_/g, '/').replace(/\:/g, '\+');
return this.decode(output);
},
// private method for UTF-8 encoding
_utf8_encode: function (string) {
string = string.replace(/\r\n/g, '\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
utftext += String.fromCharCode(c >> 6 | 192);
utftext += String.fromCharCode(c & 63 | 128);
} else {
utftext += String.fromCharCode(c >> 12 | 224);
utftext += String.fromCharCode(c >> 6 & 63 | 128);
utftext += String.fromCharCode(c & 63 | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode: function (utftext) {
var string = '';
var i = 0;
var c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode((c & 31) << 6 | c2 & 63);
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode((c & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
i += 3;
}
}
return string;
}
};
/**
* Array functions
*/
/**
* Callback function for sort numeric values
*
* @param val1
* @param val2
*/
function sortNumeric(val1, val2) {
return val1 - val2;
}
+235
View File
@@ -0,0 +1,235 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
var SessionError = Class.create();
SessionError.prototype = {
initialize: function (errorText) {
this.errorText = errorText;
},
toString: function () {
return 'Session Error:' + this.errorText;
}
};
Ajax.Request.addMethods({
initialize: function ($super, url, options) {
$super(options);
this.transport = Ajax.getTransport();
if (!url.match(new RegExp('[?&]isAjax=true',''))) {
url = url.match(new RegExp('\\?','g')) ? url + '&isAjax=true' : url + '?isAjax=true';
}
if (Object.isString(this.options.parameters) &&
this.options.parameters.indexOf('form_key=') == -1
) {
this.options.parameters += '&' + Object.toQueryString({
form_key: FORM_KEY
});
} else {
if (!this.options.parameters) {
this.options.parameters = {
form_key: FORM_KEY
};
}
if (!this.options.parameters.form_key) {
this.options.parameters.form_key = FORM_KEY;
}
}
this.request(url);
},
respondToReadyState: function (readyState) {
var state = Ajax.Request.Events[readyState],
response = new Ajax.Response(this);
if (state == 'Complete') {
try {
this._complete = true;
if (response.responseText.isJSON()) {
var jsonObject = response.responseText.evalJSON();
if (jsonObject.ajaxExpired && jsonObject.ajaxRedirect) {
window.location.replace(jsonObject.ajaxRedirect);
throw new SessionError('session expired');
}
}
(this.options['on' + response.status] ||
this.options['on' + (this.success() ? 'Success' : 'Failure')] ||
Prototype.emptyFunction)(response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
if (e instanceof SessionError) {
return;
}
}
var contentType = response.getHeader('Content-type');
if (this.options.evalJS == 'force' ||
this.options.evalJS && this.isSameOrigin() && contentType &&
contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)) {
this.evalResponse();
}
}
try {
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
// avoid memory leak in MSIE: clean up
this.transport.onreadystatechange = Prototype.emptyFunction;
}
}
});
Ajax.Updater.respondToReadyState = Ajax.Request.respondToReadyState;
var varienLoader = new Class.create();
varienLoader.prototype = {
initialize: function (caching) {
this.callback = false;
this.cache = $H();
this.caching = caching || false;
this.url = false;
},
getCache: function (url) {
if (this.cache.get(url)) {
return this.cache.get(url);
}
return false;
},
load: function (url, params, callback) {
this.url = url;
this.callback = callback;
if (this.caching) {
var transport = this.getCache(url);
if (transport) {
this.processResult(transport);
return;
}
}
if (typeof params.updaterId != 'undefined') {
new varienUpdater(params.updaterId, url, {
evalScripts: true,
onComplete: this.processResult.bind(this),
onFailure: this._processFailure.bind(this)
});
} else {
new Ajax.Request(url,{
method: 'post',
parameters: params || {},
onComplete: this.processResult.bind(this),
onFailure: this._processFailure.bind(this)
});
}
},
_processFailure: function (transport) {
location.href = BASE_URL;
},
processResult: function (transport) {
if (this.caching) {
this.cache.set(this.url, transport);
}
if (this.callback) {
this.callback(transport.responseText);
}
}
};
if (!window.varienLoaderHandler)
var varienLoaderHandler = new Object();
varienLoaderHandler.handler = {
onCreate: function (request) {
if (request.options.loaderArea === false) {
return;
}
jQuery('body').trigger('processStart');
},
onException: function (transport) {
jQuery('body').trigger('processStop');
},
onComplete: function (transport) {
jQuery('body').trigger('processStop');
}
};
/**
* @todo need calculate middle of visible area and scroll bind
*/
function setLoaderPosition() {
var elem = $('loading_mask_loader');
if (elem && Prototype.Browser.IE) {
var elementDims = elem.getDimensions();
var viewPort = document.viewport.getDimensions();
var offsets = document.viewport.getScrollOffsets();
elem.style.left = Math.floor(viewPort.width / 2 + offsets.left - elementDims.width / 2) + 'px';
elem.style.top = Math.floor(viewPort.height / 2 + offsets.top - elementDims.height / 2) + 'px';
elem.style.position = 'absolute';
}
}
function toggleSelectsUnderBlock(block, flag) {
if (Prototype.Browser.IE) {
var selects = document.getElementsByTagName('select');
for (var i = 0; i < selects.length; i++) {
/**
* @todo: need check intersection
*/
if (flag) {
if (selects[i].needShowOnSuccess) {
selects[i].needShowOnSuccess = false;
// Element.show(selects[i])
selects[i].style.visibility = '';
}
} else if (Element.visible(selects[i])) {
// Element.hide(selects[i]);
selects[i].style.visibility = 'hidden';
selects[i].needShowOnSuccess = true;
}
}
}
}
Ajax.Responders.register(varienLoaderHandler.handler);
var varienUpdater = Class.create(Ajax.Updater, {
updateContent: function ($super, responseText) {
if (responseText.isJSON()) {
var responseJSON = responseText.evalJSON();
if (responseJSON.ajaxExpired && responseJSON.ajaxRedirect) {
window.location.replace(responseJSON.ajaxRedirect);
}
} else {
$super(responseText);
}
}
});
+22
View File
@@ -0,0 +1,22 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([], function () {
'use strict';
return {
afterInitialization: 'afterInitialization',
afterChangeContent: 'afterChangeContent',
afterUndo: 'afterUndo',
afterPaste: 'afterPaste',
beforeSetContent: 'beforeSetContent',
afterSetContent: 'afterSetContent',
afterSave: 'afterSave',
afterOpenFileBrowser: 'afterOpenFileBrowser',
afterFormSubmit: 'afterFormSubmit',
afterBlur: 'afterBlur',
afterFocus: 'afterFocus'
};
});
+212
View File
@@ -0,0 +1,212 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore'
], function (_) {
'use strict';
/* eslint-disable max-len */
var schema = {
blockContent: [
'address', 'article', 'aside', 'blockquote', 'details', 'dialog', 'div', 'dl', 'fieldset',
'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr',
'menu', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'ul'
],
phrasingContent: [
'#comment', '#text', 'a', 'abbr', 'audio', 'b', 'bdi', 'bdo', 'br', 'button', 'canvas',
'cite','code', 'command', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img',
'input', 'ins', 'kbd', 'keygen', 'label', 'map', 'mark', 'meter', 'noscript', 'object',
'output', 'picture', 'progress', 'q', 'ruby', 's', 'samp', 'script', 'select', 'small',
'span', 'strong', 'sub', 'sup', 'textarea', 'time', 'u', 'var', 'video', 'wbr'
],
blockElements: [
'address', 'article', 'aside', 'blockquote', 'caption', 'center', 'datalist', 'dd', 'dir', 'div',
'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'header', 'hgroup', 'hr', 'isindex', 'li', 'menu', 'nav', 'noscript', 'ol', 'optgroup', 'option',
'p', 'pre', 'section', 'select', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'
],
boolAttrs: [
'autoplay', 'checked', 'compact', 'controls', 'declare', 'defer', 'disabled', 'ismap', 'loop',
'multiple', 'nohref', 'noresize', 'noshade', 'nowrap', 'readonly', 'selected'
],
shortEnded: [
'area', 'base', 'basefont', 'br', 'col', 'embed', 'frame', 'hr', 'img', 'input', 'isindex',
'link', 'meta', 'param', 'source', 'track', 'wbr'
],
whiteSpace: [
'audio', 'iframe', 'noscript', 'object', 'pre', 'script', 'style', 'textarea', 'video'
],
selfClosing: [
'colgroup', 'dd', 'dt', 'li', 'option', 'p', 'td', 'tfoot', 'th', 'thead', 'tr'
]
};
schema.flowContent = schema.blockContent.concat(schema.phrasingContent, ['style']);
schema.nonEmpty = ['td', 'th', 'iframe', 'video', 'audio', 'object', 'script', 'i', 'em', 'span'].concat(schema.shortEnded);
_.extend(schema, (function (phrasingContent, flowContent) {
var validElements = [],
validChildren = [],
compiled = {},
globalAttrs,
rawData;
globalAttrs = [
'id', 'dir', 'lang', 'class', 'style', 'title', 'hidden', 'onclick', 'onkeyup',
'tabindex', 'dropzone', 'accesskey', 'draggable', 'translate', 'onmouseup',
'onkeydown', 'spellcheck', 'ondblclick', 'onmouseout', 'onkeypress', 'contextmenu',
'onmousedown', 'onmouseover', 'onmousemove', 'contenteditable'
];
rawData = [
['html', 'manifest', 'head body'],
['head', '', 'base command link meta noscript script style title'],
['title hr noscript br'],
['base', 'href target'],
['link', 'href rel media hreflang type sizes hreflang'],
['meta', 'name http-equiv content charset'],
['style', 'media type scoped'],
['script', 'src async defer type charset'],
['body', 'onafterprint onbeforeprint onbeforeunload onblur onerror onfocus ' +
'onhashchange onload onmessage onoffline ononline onpagehide onpageshow ' +
'onpopstate onresize onscroll onstorage onunload background bgcolor text link vlink alink', flowContent
],
['caption', '', _.without(flowContent, 'table')],
['address dt dd div', '', flowContent],
['h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn', '', phrasingContent],
['blockquote', 'cite', flowContent],
['ol', 'reversed start type', 'li'],
['ul', 'type compact', 'li'],
['li', 'value type', flowContent],
['dl', '', 'dt dd'],
['a', 'href target rel media hreflang type charset name rev shape coords download', phrasingContent],
['q', 'cite', phrasingContent],
['ins del', 'cite datetime', flowContent],
['img', 'src sizes srcset alt usemap ismap width height name longdesc align border hspace vspace'],
['iframe', 'src name width height longdesc frameborder marginwidth marginheight scrolling align sandbox seamless allowfullscreen', flowContent],
['embed', 'src type width height'],
['object', 'data type typemustmatch name usemap form width height declare classid code codebase codetype archive standby align border hspace vspace', flowContent.concat(['param'])],
['param', 'name value valuetype type'],
['map', 'name', flowContent.concat(['area'])],
['area', 'alt coords shape href target rel media hreflang type nohref'],
['table', 'border summary width frame rules cellspacing cellpadding align bgcolor', 'caption colgroup thead tfoot tbody tr col'],
['colgroup', 'span width align char charoff valign', 'col'],
['col', 'span'],
['tbody thead tfoot', 'align char charoff valign', 'tr'],
['tr', 'align char charoff valign bgcolor', 'td th'],
['td', 'colspan rowspan headers abbr axis scope align char charoff valign nowrap bgcolor width height', flowContent],
['th', 'colspan rowspan headers scope abbr axis align char charoff valign nowrap bgcolor width height accept', flowContent],
['form', 'accept-charset action autocomplete enctype method name novalidate target onsubmit onreset', flowContent],
['fieldset', 'disabled form name', flowContent.concat(['legend'])],
['label', 'form for', phrasingContent],
['input', 'accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate ' +
'formtarget height list max maxlength min multiple name pattern readonly required size src step type value width usemap align'
],
['button', 'disabled form formaction formenctype formmethod formnovalidate formtarget name type value', phrasingContent],
['select', 'disabled form multiple name required size onfocus onblur onchange', 'option optgroup'],
['optgroup', 'disabled label', 'option'],
['option', 'disabled label selected value'],
['textarea', 'cols dirname disabled form maxlength name readonly required rows wrap'],
['menu', 'type label', flowContent.concat(['li'])],
['noscript', '', flowContent],
['wbr'],
['ruby', '', phrasingContent.concat(['rt', 'rp'])],
['figcaption', '', flowContent],
['mark rt rp summary bdi', '', phrasingContent],
['canvas', 'width height', flowContent],
['video', 'src crossorigin poster preload autoplay mediagroup loop muted controls width height buffered', flowContent.concat(['track', 'source'])],
['audio', 'src crossorigin preload autoplay mediagroup loop muted controls buffered volume', flowContent.concat(['track', 'source'])],
['picture', '', 'img source'],
['source', 'src srcset type media sizes'],
['track', 'kind src srclang label default'],
['datalist', '', phrasingContent.concat(['option'])],
['article section nav aside header footer', '', flowContent],
['hgroup', '', 'h1 h2 h3 h4 h5 h6'],
['figure', '', flowContent.concat(['figcaption'])],
['time', 'datetime', phrasingContent],
['dialog', 'open', flowContent],
['command', 'type label icon disabled checked radiogroup command'],
['output', 'for form name', phrasingContent],
['progress', 'value max', phrasingContent],
['meter', 'value min max low high optimum', phrasingContent],
['details', 'open', flowContent.concat(['summary'])],
['keygen', 'autofocus challenge disabled form keytype name'],
['script', 'language xml:space'],
['style', 'xml:space'],
['embed', 'align name hspace vspace'],
['br', 'clear'],
['applet', 'codebase archive code object alt name width height align hspace vspace'],
['font basefont', 'size color face'],
['h1 h2 h3 h4 h5 h6 div p legend caption', 'align'],
['ol dl menu dir', 'compact'],
['pre', 'width xml:space'],
['hr', 'align noshade size width'],
['isindex', 'prompt'],
['col', 'width align char charoff valign'],
['input button select textarea', 'autofocus'],
['input textarea', 'placeholder onselect onchange onfocus onblur'],
['link script img', 'crossorigin']
];
rawData.forEach(function (data) {
var nodes = data[0].split(' '),
attributes = data[1] || [],
children = data[2] || [],
ni = nodes.length,
nodeName,
schemaData;
if (typeof attributes === 'string') {
attributes = attributes.split(' ');
}
if (typeof children === 'string') {
children = children.split(' ');
}
while (ni--) {
nodeName = nodes[ni];
schemaData = compiled[nodeName] || {};
compiled[nodeName] = {
attributes: _.union(schemaData.attributes, globalAttrs, attributes),
children: _.union(schemaData.children, children)
};
}
});
['a', 'dfn', 'form', 'meter', 'progress'].forEach(function (nodeName) {
var node = compiled[nodeName];
node.children = _.without(node.children, nodeName);
});
_.each(compiled, function (node, nodeName) {
var filteredAttributes = [];
_.each(node.attributes, function (attribute) { //eslint-disable-line max-nested-callbacks
// Disallowing usage of 'on*' attributes.
if (!/^on/.test(attribute)) {
filteredAttributes.push(attribute);
}
});
node.attributes = filteredAttributes;
validElements.push(nodeName + '[' + node.attributes.join('|') + ']');
validChildren.push(nodeName + '[' + node.children.join('|') + ']');
});
return {
nodes: compiled,
validElements: validElements,
validChildren: validChildren
};
})(schema.phrasingContent, schema.flowContent));
return schema;
});
@@ -0,0 +1,241 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global tinymce, MagentovariablePlugin, varienGlobalEvents, Base64 */
/* eslint-disable strict */
define([
'Magento_Variable/js/config-directive-generator',
'Magento_Variable/js/custom-directive-generator',
'wysiwygAdapter',
'jquery',
'mage/adminhtml/tools'
], function (configDirectiveGenerator, customDirectiveGenerator, wysiwyg, jQuery) {
return function (config) {
var self = null,
magentovariable = function (editor) {
this.widget = {
/**
* Encode variables in content
*
* @param {String} content
* @returns {*}
*/
encodeVariables: function (content) {
content = content.gsub(/\{\{config path="([^"]+)"}}/i, function (match) {
var path = match[1],
magentoVariables,
imageHtml;
magentoVariables = JSON.parse(config.placeholders);
if (magentoVariables[match[1]]
&& magentoVariables[match[1]]['variable_type'] === 'default') {
imageHtml = '<span id="%id" ' +
'class="magento-variable magento-placeholder mceNonEditable">' +
'%s</span>';
imageHtml = imageHtml.replace('%s', magentoVariables[match[1]]['variable_name']);
} else {
imageHtml = '<span id="%id" class="' +
'magento-variable magento-placeholder magento-placeholder-error ' +
'mceNonEditable' +
'">' +
'Not found' +
'</span>';
}
return imageHtml.replace('%id', Base64.idEncode(path));
});
content = content.gsub(/\{\{customVar code=([^}"]+)}}/i, function (match) {
var path = match[1],
magentoVariables,
imageHtml;
magentoVariables = JSON.parse(config.placeholders);
if (magentoVariables[match[1]]
&& magentoVariables[match[1]]['variable_type'] === 'custom') {
imageHtml = '<span id="%id" class="magento-variable magento-custom-var ' +
'magento-placeholder mceNonEditable">%s</span>';
imageHtml = imageHtml.replace('%s', magentoVariables[match[1]]['variable_name']);
} else {
imageHtml = '<span id="%id" class="' +
'magento-variable magento-custom-var magento-placeholder ' +
'magento-placeholder-error mceNonEditable' +
'">' +
match[1] +
'</span>';
}
return imageHtml.replace('%id', Base64.idEncode(path));
});
return content;
},
/**
* Decode variables in content.
*
* @param {String} content
* @returns {String}
*/
decodeVariables: function (content) {
var doc = new DOMParser().parseFromString(content.replace(/&quot;/g, '&amp;quot;'),
'text/html'),
returnval = '';
[].forEach.call(doc.querySelectorAll('span.magento-variable'), function (el) {
var $el = jQuery(el);
if ($el.hasClass('magento-custom-var')) {
$el.replaceWith(
customDirectiveGenerator.processConfig(
Base64.idDecode(
$el.attr('id')
)
)
);
} else {
$el.replaceWith(
configDirectiveGenerator.processConfig(
Base64.idDecode(
$el.attr('id')
)
)
);
}
});
returnval += doc.head ? doc.head.innerHTML.replace(/&amp;quot;/g, '&quot;') : '';
returnval += doc.body ? doc.body.innerHTML.replace(/&amp;quot;/g, '&quot;') : '';
return returnval ? returnval : content;
},
/**
* @return {Object}
*/
getInfo: function () {
return {
longname: 'Magento Variable Manager Plugin',
author: 'Magento Core Team',
authorurl: 'http://magentocommerce.com',
infourl: 'http://magentocommerce.com',
version: '1.0'
};
}
};
self = this.widget;
this.activePlaceholder = null;
/**
* Add new command to open variables selector slideout.
*/
editor.addCommand('openVariablesSlideout', function (commandConfig) {
var selectedElement;
if (commandConfig) {
selectedElement = commandConfig.selectedElement;
} else {
selectedElement = tinymce.activeEditor.selection.getNode();
}
MagentovariablePlugin.setEditor(editor);
MagentovariablePlugin.loadChooser(
config.url,
wysiwyg.getId(),
selectedElement
);
});
/**
* Add button to the editor toolbar.
*/
editor.ui.registry.addIcon(
'magentovariable',
'<svg width="24" height="24" viewBox="0 0 32.000000 32.000000" ' +
'preserveAspectRatio="xMidYMid meet"><g transform="translate(0.000000,32.000000) ' +
'scale(0.100000,-0.100000)" fill="#000000" stroke="none"><path d="M68 250 c-56 -44 -75 -136 -37 ' +
'-184 27 -34 42 -33 23 2 -26 50 -9 129 38 179 26 28 10 30 -24 3z"/><path d="M266 253 c5 -10 9 ' +
'-41 9 -70 0 -42 -6 -60 -32 -97 -36 -51 -35 -56 7 -26 54 39 78 139 44 188 -18 26 -40 30 -28 5z"/>' +
'<path d="M128 223 c-15 -4 -15 -6 0 -33 16 -28 16 -30 -11 -58 -30 -31 -34 -42 -13 -42 8 0 17 11 ' +
'20 25 4 14 11 25 16 25 5 0 12 -11 16 -25 6 -25 37 -35 49 -15 3 5 2 10 -3 10 -23 0 -20 44 5 76 ' +
'25 34 25 34 4 34 -12 0 -20 -4 -17 -8 2 -4 0 -14 -5 -22 -7 -10 -12 -11 -15 -4 -10 25 -30 40 ' +
'-46 37z"/></g>' +
'</svg>'
);
editor.ui.registry.addToggleButton('magentovariable', {
icon: 'magentovariable',
tooltip: jQuery.mage.__('Insert Variable'),
/**
* execute openVariablesSlideout for onAction callback
*/
onAction: function () {
editor.execCommand('openVariablesSlideout');
},
/**
* Highlight or dismiss Insert Variable button when variable is selected or deselected.
*/
onSetup: function (api) {
/**
* Toggle active state of Insert Variable button.
*
* @param {Object} e
*/
var toggleVariableButton = function (e) {
api.setActive(false);
if (jQuery(e.target).hasClass('magento-variable')) {
api.setActive(true);
}
};
editor.on('click', toggleVariableButton);
editor.on('change', toggleVariableButton);
}
});
/**
* Double click handler on the editor to handle dbl click on variable placeholder.
*/
editor.on('dblclick', function (evt) {
if (jQuery(evt.target).hasClass('magento-variable')) {
editor.selection.collapse(false);
editor.execCommand('openVariablesSlideout', {
ui: true,
selectedElement: evt.target
});
}
});
/**
* Attach event handler for when wysiwyg editor is about to encode its content
*/
varienGlobalEvents.attachEventHandler('wysiwygEncodeContent', function (content) {
content = self.encodeVariables(content);
return content;
});
/**
* Attach event handler for when wysiwyg editor is about to decode its content
*/
varienGlobalEvents.attachEventHandler('wysiwygDecodeContent', function (content) {
content = self.decodeVariables(content);
return content;
});
};
/**
* Register plugin
*/
tinymce.PluginManager.add('magentovariable', magentovariable);
};
});
@@ -0,0 +1,261 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global tinymce, widgetTools, Base64 */
/* eslint-disable strict */
define([
'wysiwygAdapter',
'mage/adminhtml/events',
'mage/adminhtml/wysiwyg/widget'
], function (wysiwyg, varienGlobalEvents) {
return function (config) {
var self = null,
magentowidget = function (editor) {
this.widget = {
/**
* @param {Object} placeholder - Contains the selected node
* @returns {Boolean}
*/
isWidgetPlaceholderSelected: function (placeholder) {
var isSelected = false;
if (placeholder.nodeName &&
(placeholder.nodeName === 'SPAN' || placeholder.nodeName === 'IMG') &&
placeholder.className && placeholder.className.indexOf('magento-widget') !== -1
) {
this.activePlaceholder = placeholder;
isSelected = true;
} else {
this.activePlaceholder = null;
}
return isSelected;
},
/**
* Convert {{widget}} style syntax to image placeholder HTML
* @param {String} content
* @return {*}
*/
encodeWidgets: function (content) {
return content.gsub(/\{\{widget([\S\s]*?)}}/i, function (match) {
var attributes = wysiwyg.parseAttributesString(match[1]),
imageSrc,
imageHtml = '';
if (attributes.type) {
attributes.type = attributes.type.replace(/\\\\/g, '\\');
imageSrc = config.placeholders[attributes.type];
if (imageSrc) {
imageHtml += '<span class="magento-placeholder magento-widget mceNonEditable" ' +
'contenteditable="false">';
} else {
imageSrc = config['error_image_url'];
imageHtml += '<span ' +
'class="magento-placeholder magento-placeholder-error magento-widget ' +
'mceNonEditable" ' +
'contenteditable="false">';
}
imageHtml += '<img';
imageHtml += ' id="' + Base64.idEncode(match[0]) + '"';
imageHtml += ' src="' + imageSrc + '"';
imageHtml += ' />';
if (config.types[attributes.type]) {
imageHtml += config.types[attributes.type];
}
imageHtml += '</span>';
return imageHtml;
}
});
},
/**
* Convert image placeholder HTML to {{widget}} style syntax
* @param {String} content
* @return {*}
*/
decodeWidgets: function (content) {
return content.gsub(
/(<span class="[^"]*magento-widget[^"]*"[^>]*>)?<img([^>]+id="[^>]+)>(([^>]*)<\/span>)?/i,
function (match) {
var attributes = wysiwyg.parseAttributesString(match[2]),
widgetCode,
result = match[0];
if (attributes.id) {
try {
widgetCode = Base64.idDecode(attributes.id);
} catch (e) {
// Ignore and continue.
}
if (widgetCode && widgetCode.indexOf('{{widget') !== -1) {
result = widgetCode;
}
}
return result;
}
);
},
/**
* Tinymce has strange behavior with html and this removes one of its side-effects
* @param {String} content
* @return {String}
*/
removeDuplicateAncestorWidgetSpanElement: function (content) {
var parser, doc, returnval = '';
if (!window.DOMParser) {
return content;
}
parser = new DOMParser();
doc = parser.parseFromString(content.replace(/&quot;/g, '&amp;quot;'), 'text/html');
[].forEach.call(doc.querySelectorAll('.magento-widget'), function (widgetEl) {
var widgetChildEl = widgetEl.querySelector('.magento-widget');
if (!widgetChildEl) {
return;
}
[].forEach.call(widgetEl.childNodes, function (el) {
widgetEl.parentNode.insertBefore(el, widgetEl);
});
widgetEl.parentNode.removeChild(widgetEl);
});
returnval += doc.head ? doc.head.innerHTML.replace(/&amp;quot;/g, '&quot;') : '';
returnval += doc.body ? doc.body.innerHTML.replace(/&amp;quot;/g, '&quot;') : '';
return returnval ? returnval : content;
},
/**
* @return {Object}
*/
getInfo: function () {
return {
longname: 'Magento Widget Manager Plugin',
author: 'Magento Core Team',
authorurl: 'http://magentocommerce.com',
infourl: 'http://magentocommerce.com',
version: '1.0'
};
}
};
self = this.widget;
this.activePlaceholder = null;
editor.addCommand('mceMagentowidget', function (img) {
if (self.activePlaceholder) {
img = self.activePlaceholder;
}
widgetTools.setActiveSelectedNode(img);
widgetTools.openDialog(
config['window_url'] + 'widget_target_id/' + editor.getElement().id + '/'
);
});
// Register Widget plugin button
editor.ui.registry.addIcon(
'magentowidget',
'<svg width="24" height="24" viewBox="0 0 32.000000 32.000000" ' +
'preserveAspectRatio="xMidYMid meet"> <g transform="translate(0.000000,32.000000) ' +
'scale(0.100000,-0.100000)" fill="#000000" stroke="none"> <path d="M130 290 c0 -5 13 -10 30 ' +
'-10 22 0 28 -4 24 -15 -5 -11 2 -15 26 -15 21 0 30 -4 28 -12 -7 -20 -40 -22 -50 -4 -5 9 -14 16 ' +
'-20 16 -6 0 -19 7 -28 15 -9 8 -25 12 -38 8 -33 -8 -27 -26 8 -21 34 5 40 -6 12 -21 -14 -7 -25 -6 ' +
'-40 5 -12 8 -23 10 -27 5 -5 -8 88 -71 105 -71 3 0 29 14 58 31 l53 30 -23 18 c-13 10 -31 20 -40 ' +
'24 -10 3 -18 11 -18 17 0 5 -13 10 -30 10 -16 0 -30 -4 -30 -10z m58 -82 c-3 -7 -15 -13 -28 -13 ' +
'-13 0 -25 6 -27 13 -3 8 6 12 27 12 21 0 30 -4 28 -12z"/> <path d="M30 151 l0 -60 61 -36 c33 ' +
'-19 64 -35 69 -35 5 0 36 16 69 35 l61 36 0 60 0 61 -65 -37 -65 -36 -65 36 -65 37 0 -61z"/> </g>' +
'</svg>'
);
editor.ui.registry.addToggleButton('magentowidget', {
icon: 'magentowidget',
tooltip: jQuery.mage.__('Insert Widget'),
/**
* execute openVariablesSlideout for onAction callback
*/
onAction: function () {
editor.execCommand('mceMagentowidget');
},
/**
* Add a node change handler, selects the button in the UI when a image is selected
* @param {ToolbarToggleButtonInstanceApi} api
*/
onSetup: function (api) {
/**
* NodeChange handler
*/
editor.on('NodeChange', function (e) {
var placeholder = e.element;
if (self.isWidgetPlaceholderSelected(placeholder)) {
widgetTools.setEditMode(true);
api.setActive(true);
} else {
widgetTools.setEditMode(false);
api.setActive(false);
}
});
}
});
// Add a widget placeholder image double click callback
editor.on('dblClick', function (e) {
var placeholder = e.target;
if (self.isWidgetPlaceholderSelected(placeholder)) {
widgetTools.setEditMode(true);
this.execCommand('mceMagentowidget', null);
}
});
/**
* Attach event handler for when wysiwyg editor is about to encode its content
*/
varienGlobalEvents.attachEventHandler('wysiwygEncodeContent', function (content) {
content = self.encodeWidgets(self.decodeWidgets(content));
content = self.removeDuplicateAncestorWidgetSpanElement(content);
return content;
});
/**
* Attach event handler for when wysiwyg editor is about to decode its content
*/
varienGlobalEvents.attachEventHandler('wysiwygDecodeContent', function (content) {
content = self.decodeWidgets(content);
return content;
});
/**
* Attach event handler for when popups associated with wysiwyg are about to be closed
*/
varienGlobalEvents.attachEventHandler('wysiwygClosePopups', function () {
wysiwyg.closeEditorPopup('widget_window' + wysiwyg.getId());
});
};
// Register plugin
tinymce.PluginManager.add('magentowidget', magentowidget);
};
});
+80
View File
@@ -0,0 +1,80 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable strict */
define([
'jquery',
'underscore',
'wysiwygAdapter',
'module',
'mage/translate',
'prototype',
'mage/adminhtml/events',
'mage/adminhtml/browser'
], function (jQuery, _, wysiwygAdapter, module) {
var baseConfig = module.config().config || {},
wysiwygSetup = Class.create({
wysiwygInstance: null
});
wysiwygSetup.prototype = {
/**
* @param {*} htmlId
* @param {Object} config
*/
initialize: function (htmlId, config) {
var WysiwygInstancePrototype = new wysiwygAdapter.getAdapterPrototype();
_.bindAll(this, 'openFileBrowser');
config = _.extend({}, baseConfig, config || {});
this.wysiwygInstance = new WysiwygInstancePrototype(htmlId, config);
this.wysiwygInstance.eventBus = this.eventBus = new window.varienEvents();
},
/**
* @param {*} mode
*/
setup: function (mode) {
this.wysiwygInstance.setup(mode);
},
/**
* @param {Object} o
*/
openFileBrowser: function (o) {
this.wysiwygInstance.openFileBrowser(o);
},
/**
* @return {Boolean}
*/
toggle: function () {
return this.wysiwygInstance.toggle();
},
/**
* On form validation.
*/
onFormValidation: function () {
this.wysiwygInstance.onFormValidation();
},
/**
* Encodes the content so it can be inserted into the wysiwyg
* @param {String} content - The content to be encoded
*
* @returns {*} - The encoded content
*/
updateContent: function (content) {
return this.wysiwygInstance.encodeContent(content);
}
};
window.wysiwygSetup = wysiwygSetup;
return wysiwygSetup;
});
@@ -0,0 +1,36 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
html {height: 100%;}
body, td, pre { color:#2f2f2f; font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:8px; }
body {background:#fff; min-height: calc(100% - 20px);}
body.mceForceColors { background:#fff; color:#2f2f2f; }
h1 {font-size: 2em}
h2 {font-size: 1.5em}
h3 {font-size: 1.17em}
h4 {font-size: 1em}
h5 {font-size: .83em}
h6 {font-size: .75em}
.mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;}
img {border:0; vertical-align:middle; }
table {cursor:default}
table td, table th {cursor:text}
ins {border-bottom:1px solid green; text-decoration: none; color:green}
del {color:red; text-decoration:line-through}
cite {border-bottom:1px dashed blue}
acronym {border-bottom:1px dotted #CCC; cursor:help}
abbr, html\:abbr {border-bottom:1px dashed #CCC; cursor:help}
/* IE */
* html body {
scrollbar-3dlight-color:#F0F0EE;
scrollbar-arrow-color:#676662;
scrollbar-base-color:#F0F0EE;
scrollbar-darkshadow-color:#DDD;
scrollbar-face-color:#E0E0DD;
scrollbar-highlight-color:#F0F0EE;
scrollbar-shadow-color:#F0F0EE;
scrollbar-track-color:#F5F5F5;
}
@@ -0,0 +1,67 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* Browse */
a.pickcolor, a.browse {text-decoration:none}
a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.png) -860px 0; border:1px solid #FFF; margin-left:1px;}
.mceOldBoxModel a.browse span {width:22px; height:20px;}
a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;}
a.browse span.disabled {border:1px solid white; opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)}
a.browse:hover span.disabled {border:1px solid white; background-color:transparent;}
a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.png) -840px 0; margin-left:2px;}
.mceOldBoxModel a.pickcolor span {width:21px; height:17px;}
a.pickcolor:hover span {background-color:#B2BBD0;}
a.pickcolor:hover span.disabled {}
/* Charmap */
table.charmap {border:1px solid #AAA; text-align:center}
td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;}
#charmap a {display:block; color:#000; text-decoration:none; border:0}
#charmap a:hover {background:#CCC;color:#2B6FB6}
#charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center}
#charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center}
/* Source */
.wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;}
.mceActionPanel {margin-top:5px;}
/* Tabs classes */
.tabs {width:100%; height:18px; line-height:normal; background:url(img/tabs.gif) repeat-x 0 -72px;}
.tabs ul {margin:0; padding:0; list-style:none;}
.tabs li {float:left; background:url(img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;}
.tabs li.current {background:url(img/tabs.gif) no-repeat 0 -18px; margin-right:2px;}
.tabs span {float:left; display:block; background:url(img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;}
.tabs .current span {background:url(img/tabs.gif) no-repeat right -54px;}
.tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;}
.tabs a:link, .tabs a:visited, .tabs a:hover {color:black;}
/* Panels */
.panel_wrapper div.panel {display:none;}
.panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;}
.panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;}
/* Columns */
.column {float:left;}
.properties {width:100%;}
.properties .column1 {}
.properties .column2 {text-align:left;}
/* Dialog specific */
#link .panel_wrapper, #link div.current {height:125px;}
#image .panel_wrapper, #image div.current {height:200px;}
#plugintable thead {font-weight:bold; background:#DDD;}
#plugintable, #about #plugintable td {border:1px solid #919B9C;}
#plugintable {width:96%; margin-top:10px;}
#pluginscontainer {height:290px; overflow:auto;}
#colorpicker #preview {float:right; width:50px; height:14px;line-height:1px; border:1px solid black; margin-left:5px;}
#colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;}
#colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;}
#colorpicker #light div {overflow:hidden;}
#colorpicker #previewblock {float:right; padding-left:10px; height:20px;}
#colorpicker .panel_wrapper div.current {height:175px;}
#colorpicker #namedcolors {width:150px;}
#colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;}
#colorpicker #colornamecontainer {margin-top:5px;}
#colorpicker #picker_panel fieldset {margin:auto;width:325px;}
+58
View File
@@ -0,0 +1,58 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
.magento-placeholder {
display: inline-block;
margin: 0 5px;
background: #dff7ff;
outline: 2px solid #c0dffa;
padding: 2px 4px;
vertical-align: bottom;
height: 20px;
cursor: pointer !important;
font-weight: normal;
font-style: normal;
font-size: 14px;
color: #000;
box-sizing: initial;
word-break: break-all;
}
.magento-placeholder-error {
display: inline-block;
margin: 0 5px;
background: #ffc0cb;
outline: 2px solid #F7AAAA !important;
padding: 2px 4px;
vertical-align: bottom;
height: 20px;
}
.magento-placeholder-error:before {
content: '';
display: inline-block;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABWUlEQVR42qVTS07DMBD1pggqcQAQEofINbrNvh977Au04gJtxZYiVZwLJJasAhJJ3LBrI4Xwxm3SKErCz9Koqec9e/xmnhBYdjK5tlo/R8ZsI63XIdGFqK1QSg+5MNY6scbMXobDU5eIpbyKiaZIpLExOX4/cdg6IOoXZP6OlbpDPjtgUks0y4l6An8esbl1iUPghgyA5ZPvnzAo0XphC/IRkyZKKVEnl8GVEK04+LsRY8yb4HJbAVpnLprJmVVqIcLx+DIieqiX2Bl8ITQB93wv0mDQb3pnGxkXLqsiu8WCufd2H5KBfM/Yepv/d0Du+2c/fQJjIilvyyfwhLEgvxHR7itZORFjHs82clcbuRNazwXm/uOvg4RKAoFSbkofVMjJN6MMzG5DNBI5XAVDTeG0XaE0a9JpJviADejM5LrgeT1UMsJmAOC8nLCqnbG3QQ6Y13ciWbTyC+DUOUqNY1A2AAAAAElFTkSuQmCC);
background-repeat: no-repeat;
background-position-x: 1px;
background-position-y: 1px;
width: 20px;
height: inherit;
margin-right: 4px;
vertical-align: middle;
}
.magento-placeholder-error img {
display: none;
}
.magento-placeholder-error[data-mce-selected] {
outline: 2px solid #E12525 !important;
}
.magento-placeholder-error img,
.magento-placeholder img {
vertical-align: middle;
max-height: 20px;
margin-right: 5px;
}
@@ -0,0 +1,772 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global popups, tinyMceEditors, MediabrowserUtility, Base64 */
/* eslint-disable strict */
define([
'jquery',
'underscore',
'tinymce',
'mage/adminhtml/events',
'mage/adminhtml/wysiwyg/events',
'mage/translate',
'prototype',
'jquery/ui'
], function (jQuery, _, tinyMCE, varienGlobalEvents, wysiwygEvents) {
'use strict';
var tinyMceWysiwyg = Class.create();
tinyMceWysiwyg.prototype = {
mediaBrowserOpener: null,
mediaBrowserTargetElementId: null,
magentoVariablesPlugin: null,
mode: 'exact',
/**
* @param {*} htmlId
* @param {Object} config
*/
initialize: function (htmlId, config) {
this.id = htmlId;
this.config = config;
_.bindAll(
this,
'beforeSetContent',
'saveContent',
'onChangeContent',
'openFileBrowser',
'updateTextArea',
'onUndo',
'removeEvents'
);
varienGlobalEvents.attachEventHandler('tinymceChange', this.onChangeContent);
varienGlobalEvents.attachEventHandler('tinymceBeforeSetContent', this.beforeSetContent);
varienGlobalEvents.attachEventHandler('tinymceSetContent', this.updateTextArea);
varienGlobalEvents.attachEventHandler('tinymceSaveContent', this.saveContent);
varienGlobalEvents.attachEventHandler('tinymceUndo', this.onUndo);
if (typeof tinyMceEditors === 'undefined') {
window.tinyMceEditors = $H({});
}
tinyMceEditors.set(this.id, this);
},
/**
* Ensures the undo operation works properly
*/
onUndo: function () {
this.addContentEditableAttributeBackToNonEditableNodes();
},
/**
* Setup TinyMCE editor
*/
setup: function (mode) {
var deferreds = [],
settings,
self = this;
this.turnOff();
if (this.config.plugins) {
this.config.plugins.forEach(function (plugin) {
var deferred;
self.addPluginToToolbar(plugin.name, '|');
if (!plugin.src) {
return;
}
deferred = jQuery.Deferred();
deferreds.push(deferred);
require([plugin.src], function (factoryFn) {
if (typeof factoryFn === 'function') {
factoryFn(plugin.options);
}
tinyMCE.PluginManager.load(plugin.name, plugin.src);
deferred.resolve();
});
});
}
if (jQuery.isReady) {
tinyMCE.dom.Event.domLoaded = true;
}
settings = this.getSettings();
if (mode === 'inline') {
settings.inline = true;
if (!isNaN(settings.toolbarZIndex)) {
tinyMCE.ui.FloatPanel.zIndex = settings.toolbarZIndex;
}
this.removeEvents(self.id);
}
jQuery.when.apply(jQuery, deferreds).done(function () {
tinyMCE.init(settings);
this.getPluginButtons().hide();
varienGlobalEvents.clearEventHandlers('open_browser_callback');
this.eventBus.clearEventHandlers('open_browser_callback');
this.eventBus.attachEventHandler('open_browser_callback', tinyMceEditors.get(self.id).openFileBrowser);
}.bind(this));
},
/**
* Remove events from instance.
*
* @param {String} wysiwygId
*/
removeEvents: function (wysiwygId) {
var editor;
if (typeof tinyMceEditors !== 'undefined' && tinyMceEditors.get(wysiwygId)) {
editor = tinyMceEditors.get(wysiwygId);
varienGlobalEvents.removeEventHandler('tinymceChange', editor.onChangeContent);
}
},
/**
* Add plugin to the toolbar if not added.
*
* @param {String} plugin
* @param {String} separator
*/
addPluginToToolbar: function (plugin, separator) {
var plugins = this.config.tinymce.plugins.split(' '),
toolbar = this.config.tinymce.toolbar.split(' ');
if (plugins.indexOf(plugin) === -1) {
plugins.push(plugin);
}
if (toolbar.indexOf(plugin) === -1) {
toolbar.push(separator || '', plugin);
}
this.config.tinymce.plugins = plugins.join(' ');
this.config.tinymce.toolbar = toolbar.join(' ');
},
/**
* Set the status of the toolbar to disabled or enabled (true for enabled, false for disabled)
* @param {Boolean} enabled
*/
setToolbarStatus: function (enabled) {
var controlIds = this.get(this.getId()).theme.panel.rootControl.controlIdLookup;
_.each(controlIds, function (controlId) {
controlId.disabled(!enabled);
controlId.canFocus = enabled;
if (controlId.tooltip) {
controlId.tooltip().state.set('rendered', enabled);
if (enabled) {
jQuery(controlId.getEl()).children('button').addBack().removeAttr('style');
} else {
jQuery(controlId.getEl()).children('button').addBack().attr('style', 'color: inherit;' +
'background-color: inherit;' +
'border-color: transparent;'
);
}
}
});
},
/**
* @return {Object}
*/
getSettings: function () {
var settings,
eventBus = this.eventBus;
settings = {
selector: '#' + this.getId(),
theme: 'silver',
skin: 'oxide',
'toolbar_mode': 'wrap',
'entity_encoding': 'raw',
'convert_urls': false,
'content_css': this.config.tinymce['content_css'],
'relative_urls': true,
'valid_children': '+body[style]',
menubar: false,
plugins: this.config.tinymce.plugins,
toolbar: this.config.tinymce.toolbar,
adapter: this,
'body_id': 'html-body',
/**
* @param {Object} editor
*/
setup: function (editor) {
var onChange;
editor.on('BeforeSetContent', function (evt) {
varienGlobalEvents.fireEvent('tinymceBeforeSetContent', evt);
eventBus.fireEvent(wysiwygEvents.beforeSetContent);
});
editor.on('SaveContent', function (evt) {
varienGlobalEvents.fireEvent('tinymceSaveContent', evt);
eventBus.fireEvent(wysiwygEvents.afterSave);
});
editor.on('paste', function (evt) {
varienGlobalEvents.fireEvent('tinymcePaste', evt);
eventBus.fireEvent(wysiwygEvents.afterPaste);
});
editor.on('PostProcess', function (evt) {
varienGlobalEvents.fireEvent('tinymceSaveContent', evt);
eventBus.fireEvent(wysiwygEvents.afterSave);
});
editor.on('undo', function (evt) {
varienGlobalEvents.fireEvent('tinymceUndo', evt);
eventBus.fireEvent(wysiwygEvents.afterUndo);
});
editor.on('focus', function () {
eventBus.fireEvent(wysiwygEvents.afterFocus);
});
editor.on('blur', function () {
eventBus.fireEvent(wysiwygEvents.afterBlur);
});
/**
* @param {*} evt
*/
onChange = function (evt) {
varienGlobalEvents.fireEvent('tinymceChange', evt);
eventBus.fireEvent(wysiwygEvents.afterChangeContent);
};
editor.on('Change', onChange);
editor.on('keyup', onChange);
editor.on('ExecCommand', function (cmd) {
varienGlobalEvents.fireEvent('tinymceExecCommand', cmd);
});
editor.on('init', function (args) {
varienGlobalEvents.fireEvent('wysiwygEditorInitialized', args.target);
eventBus.fireEvent(wysiwygEvents.afterInitialization);
});
}
};
// Set default initial height
settings['min_height'] = this.config.tinymce['min_height'] ? this.config.tinymce['min_height'] : 250;
if (this.config.skin) {
settings.skin = this.config.skin;
}
if (this.config['toolbar_mode']) {
settings['toolbar_mode'] = this.config['toolbar_mode'];
}
if (this.config.baseStaticUrl && this.config.baseStaticDefaultUrl) {
settings['document_base_url'] = this.config.baseStaticUrl;
}
// Set the document base URL
if (this.config['document_base_url']) {
settings['document_base_url'] = this.config['document_base_url'];
}
if (this.config['files_browser_window_url']) {
settings['file_picker_callback_types'] = 'file image media';
/**
* @param {*} callback
* @param {*} value
* @param {*} meta
*/
settings['file_picker_callback'] = function (callback, value, meta) {
var payload = {
callback: callback,
value: value,
meta: meta
};
varienGlobalEvents.fireEvent('open_browser_callback', payload);
this.eventBus.fireEvent('open_browser_callback', payload);
}.bind(this);
}
if (this.config.width) {
settings.width = this.config.width;
}
if (this.config.height) {
settings.height = this.config.height;
}
if (this.config.plugins) {
settings.magentoPluginsOptions = {};
_.each(this.config.plugins, function (plugin) {
settings.magentoPluginsOptions[plugin.name] = plugin.options;
});
}
if (this.config.settings) {
Object.extend(settings, this.config.settings);
}
return settings;
},
/**
* @param {String} id
*/
get: function (id) {
return tinyMCE.get(id);
},
/**
* @return {String|null}
*/
getId: function () {
return this.id || (this.activeEditor() ? this.activeEditor().id : null) || tinyMceEditors.values()[0].id;
},
/**
* @return {Object}
*/
activeEditor: function () {
return tinyMCE.activeEditor;
},
/**
* Insert content to active editor.
*
* @param {String} content
* @param {Boolean} ui
*/
insertContent: function (content, ui) {
this.activeEditor().execCommand('mceInsertContent', typeof ui !== 'undefined' ? ui : false, content);
},
/**
* Replace entire contents of wysiwyg with string content parameter
*
* @param {String} content
*/
setContent: function (content) {
this.get(this.getId()).setContent(content);
},
/**
* Set caret location in WYSIWYG editor.
*
* @param {Object} targetElement
*/
setCaretOnElement: function (targetElement) {
this.activeEditor().selection.select(targetElement);
this.activeEditor().selection.collapse();
},
/**
* @param {Object} o
*/
openFileBrowser: function (o) {
var typeTitle = this.translate('Select Images'),
storeId = this.config['store_id'] ? this.config['store_id'] : 0,
frameDialog = jQuery('div.mce-container[role="dialog"]'),
self = this,
wUrl = this.config['files_browser_window_url'] +
'target_element_id/' + this.getId() + '/' +
'store/' + storeId + '/';
this.mediaBrowserOpener = o.callback;
if (typeof o.meta.filetype !== 'undefined' && o.meta.filetype !== '') { //eslint-disable-line eqeqeq
wUrl = wUrl + 'type/' + o.meta.filetype + '/';
}
frameDialog.hide();
jQuery('.tox-tinymce-aux').hide();
require(['mage/adminhtml/browser'], function () {
MediabrowserUtility.openDialog(wUrl, false, false, typeTitle, {
/**
* Closed.
*/
closed: function () {
frameDialog.show();
jQuery('.tox-tinymce-aux').show();
},
targetElementId: self.activeEditor() ? self.activeEditor().id : null
}
);
});
},
/**
* @param {String} string
* @return {String}
*/
translate: function (string) {
return jQuery.mage.__ ? jQuery.mage.__(string) : string;
},
/**
* @return {null}
*/
getMediaBrowserOpener: function () {
return this.mediaBrowserOpener;
},
/**
* @return {null}
*/
getMediaBrowserTargetElementId: function () {
return this.mediaBrowserTargetElementId;
},
/**
* @return {jQuery|*|HTMLElement}
*/
getToggleButton: function () {
return $('toggle' + this.getId());
},
/**
* Get plugins button.
*/
getPluginButtons: function () {
return jQuery('#buttons' + this.getId() + ' > button.plugin');
},
/**
* @param {*} mode
* @return {wysiwygSetup}
*/
turnOn: function (mode) {
this.closePopups();
this.setup(mode);
this.getPluginButtons().hide();
return this;
},
/**
* @param {String} name
*/
closeEditorPopup: function (name) {
if (typeof popups !== 'undefined' && popups[name] !== undefined && !popups[name].closed) {
popups[name].close();
}
},
/**
* @return {wysiwygSetup}
*/
turnOff: function () {
this.closePopups();
this.getPluginButtons().show();
tinyMCE.execCommand('mceRemoveEditor', false, this.getId());
return this;
},
/**
* Close popups.
*/
closePopups: function () {
// close all popups to avoid problems with updating parent content area
varienGlobalEvents.fireEvent('wysiwygClosePopups');
this.closeEditorPopup('browser_window' + this.getId());
},
/**
* @return {Boolean}
*/
toggle: function () {
var content;
if (!tinyMCE.get(this.getId())) {
this.turnOn();
return true;
}
content = this.get(this.getId()) ? this.get(this.getId()).getContent() : this.getTextArea().val();
this.turnOff();
if (content.match(/{{.+?}}/g)) {
this.getTextArea().val(content.replace(/&quot;/g, '"'));
}
return false;
},
/**
* On form validation.
*/
onFormValidation: function () {
if (tinyMCE.get(this.getId())) {
$(this.getId()).value = tinyMCE.get(this.getId()).getContent();
}
},
/**
* On change content.
*/
onChangeContent: function () {
// Add "changed" to tab class if it exists
var tab;
this.updateTextArea();
if (this.config['tab_id']) {
tab = $$('a[id$=' + this.config['tab_id'] + ']')[0];
if ($(tab) != undefined && $(tab).hasClassName('tab-item-link')) { //eslint-disable-line eqeqeq
$(tab).addClassName('changed');
}
}
},
/**
* @param {Object} o
*/
beforeSetContent: function (o) {
o.content = this.encodeContent(o.content);
},
/**
* @param {Object} o
*/
saveContent: function (o) {
o.content = this.decodeContent(o.content);
},
/**
* Return the content stored in the WYSIWYG field
* @param {String} id
* @return {String}
*/
getContent: function (id) {
return id ? this.get(id).getContent() : this.get(this.getId()).getContent();
},
/**
* @returns {Object}
*/
getAdapterPrototype: function () {
return tinyMceWysiwyg;
},
/**
* Fix range selection placement when typing. This fixes MAGETWO-84769
* @param {Object} editor
*/
fixRangeSelection: function (editor) {
var selection = editor.selection,
dom = editor.dom,
rng = dom.createRng(),
doc = editor.getDoc(),
markerHtml,
marker;
// Validate the range we're trying to fix is contained within the current editors document
if (!selection.getContent().length && jQuery.contains(doc, selection.getRng().startContainer)) {
markerHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>';
selection.setContent(markerHtml);
marker = dom.get('mce_marker');
rng.setStartBefore(marker);
rng.setEndBefore(marker);
dom.remove(marker);
selection.setRng(rng);
}
},
/**
* Update text area.
*/
updateTextArea: function () {
var editor = this.get(this.getId()),
content;
if (!editor || editor.id !== this.activeEditor().id) {
return;
}
this.addContentEditableAttributeBackToNonEditableNodes();
content = editor.getContent();
content = this.decodeContent(content);
this.getTextArea().val(content).trigger('change');
},
/**
* @return {Object} jQuery textarea element
*/
getTextArea: function () {
return jQuery('#' + this.getId());
},
/**
* Set the status of the editor and toolbar
*
* @param {Boolean} enabled
*/
setEnabledStatus: function (enabled) {
if (this.activeEditor()) {
this.activeEditor().getBody().setAttribute('contenteditable', enabled);
this.activeEditor().readonly = !enabled;
this.setToolbarStatus(enabled);
}
if (enabled) {
this.getTextArea().prop('disabled', false);
} else {
this.getTextArea().prop('disabled', 'disabled');
}
},
/**
* Retrieve directives URL with substituted directive value.
*
* @param {String} directive
*/
makeDirectiveUrl: function (directive) {
return this.config['directives_url']
.replace(/directive/, 'directive/___directive/' + directive)
.replace(/\/$/, '');
},
/**
* Convert {{directive}} style attributes syntax to absolute URLs
* @param {Object} content
* @return {*}
*/
encodeDirectives: function (content) {
// collect all HTML tags with attributes that contain directives
// eslint-disable-next-line no-useless-escape
return content.gsub(/<([a-z0-9\-\_]+[^>]+?)([a-z0-9\-\_]+="[^"]*?\{\{.+?\}\}.*?".*?)>/i, function (match) {
var attributesString = match[2],
decodedDirectiveString;
// process tag attributes string
// eslint-disable-next-line no-useless-escape
attributesString = attributesString.gsub(/([a-z0-9\-\_]+)="(.*?)(\{\{.+?\}\})(.*?)"/i, function (m) {
decodedDirectiveString = encodeURIComponent(Base64.mageEncode(m[3].replace(/&quot;/g, '"') + m[4]));
return m[1] + '="' + m[2] + this.makeDirectiveUrl(decodedDirectiveString) + '"';
}.bind(this));
return '<' + match[1] + attributesString + '>';
}.bind(this));
},
/**
* Convert absolute URLs to {{directive}} style attributes syntax
* @param {Object} content
* @return {*}
*/
decodeDirectives: function (content) {
var directiveUrl = this.makeDirectiveUrl('%directive%').split('?')[0], // remove query string from directive
// escape special chars in directives url to use in regular expression
// eslint-disable-next-line no-useless-escape
regexEscapedDirectiveUrl = directiveUrl.replace(/([$^.?*!+:=()\[\]{}|\\])/g, '\\$1'),
regexDirectiveUrl = regexEscapedDirectiveUrl
.replace(
'%directive%',
'([a-zA-Z0-9,_-]+(?:%2[A-Z]|)+\/?)(?:(?!").)*' // eslint-disable-line no-useless-escape
) + '/?(\\\\?[^"]*)?', // allow optional query string
reg = new RegExp(regexDirectiveUrl);
return content.gsub(reg, function (match) {
return Base64.mageDecode(decodeURIComponent(match[1]).replace(/\/$/, '')).replace(/"/g, '&quot;');
});
},
/**
* @param {Object} attributes
* @return {Object}
*/
parseAttributesString: function (attributes) {
var result = {};
// Decode &quot; entity, as regex below does not support encoded quote
attributes = attributes.replace(/&quot;/g, '"');
attributes.gsub(
/(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/,
function (match) {
result[match[1]] = match[2];
}
);
return result;
},
/**
* @param {Object} content
* @return {*}
*/
decodeContent: function (content) {
if (this.config['add_directives']) {
content = this.decodeDirectives(content);
}
content = varienGlobalEvents.fireEventReducer('wysiwygDecodeContent', content);
return content;
},
/**
* @param {Object} content
* @return {*}
*/
encodeContent: function (content) {
if (this.config['add_directives']) {
content = this.encodeDirectives(content);
}
content = varienGlobalEvents.fireEventReducer('wysiwygEncodeContent', content);
return content;
},
/**
* Reinstate contenteditable attributes on .mceNonEditable nodes
*/
addContentEditableAttributeBackToNonEditableNodes: function () {
jQuery('.mceNonEditable', this.activeEditor().getDoc()).attr('contenteditable', false);
},
/**
* Calls the save method on all editor instances in the collection.
*/
triggerSave: function () {
tinyMCE.triggerSave();
}
};
return tinyMceWysiwyg.prototype;
});
+714
View File
@@ -0,0 +1,714 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global setLocation, Base64, updateElementAtCursor, varienGlobalEvents */
/* eslint-disable strict */
define([
'jquery',
'wysiwygAdapter',
'Magento_Ui/js/modal/alert',
'jquery/ui',
'mage/translate',
'mage/mage',
'mage/validation',
'mage/adminhtml/events',
'prototype',
'Magento_Ui/js/modal/modal'
], function (jQuery, wysiwyg, alert) {
var widgetTools = {
/**
* Sets the widget to be active and is the scope of the slide out if the value is set
*/
activeSelectedNode: null,
editMode: false,
cursorLocation: 0,
/**
* Set active selected node.
*
* @param {Object} activeSelectedNode
*/
setActiveSelectedNode: function (activeSelectedNode) {
this.activeSelectedNode = activeSelectedNode;
},
/**
* Get active selected node.
*
* @returns {null}
*/
getActiveSelectedNode: function () {
return this.activeSelectedNode;
},
/**
*
* @param {Boolean} editMode
*/
setEditMode: function (editMode) {
this.editMode = editMode;
},
/**
* @param {*} id
* @param {*} html
* @return {String}
*/
getDivHtml: function (id, html) {
if (!html) {
html = '';
}
return '<div id="' + id + '">' + html + '</div>';
},
/**
* @param {Object} transport
*/
onAjaxSuccess: function (transport) {
var response;
if (transport.responseText.isJSON()) {
response = transport.responseText.evalJSON();
if (response.error) {
throw response;
} else if (response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
}
},
dialogOpened: false,
/**
* @return {Number}
*/
getMaxZIndex: function () {
var max = 0,
cn = document.body.childNodes,
i, el, zIndex;
for (i = 0; i < cn.length; i++) {
el = cn[i];
zIndex = el.nodeType == 1 ? parseInt(el.style.zIndex, 10) || 0 : 0; //eslint-disable-line eqeqeq
if (zIndex < 10000) {
max = Math.max(max, zIndex);
}
}
return max + 10;
},
/**
* @param {String} widgetUrl
*/
openDialog: function (widgetUrl) {
var oThis = this,
title = 'Insert Widget',
mode = 'new',
dialog;
if (this.editMode) {
title = 'Edit Widget';
mode = 'edit';
}
if (this.dialogOpened) {
return;
}
this.dialogWindow = jQuery('<div/>').modal({
title: jQuery.mage.__(title),
type: 'slide',
buttons: [],
/**
* Opened.
*/
opened: function () {
dialog = jQuery(this).addClass('loading magento-message');
widgetUrl += 'mode/' + mode;
new Ajax.Updater($(this), widgetUrl, {
evalScripts: true,
/**
* On complete.
*/
onComplete: function () {
dialog.removeClass('loading');
}
});
},
/**
* @param {jQuery.Event} e
* @param {Object} modal
*/
closed: function (e, modal) {
modal.modal.remove();
oThis.dialogOpened = false;
}
});
this.dialogOpened = true;
this.dialogWindow.modal('openModal');
}
},
WysiwygWidget = {};
WysiwygWidget.Widget = Class.create();
WysiwygWidget.Widget.prototype = {
/**
* @param {HTMLElement} formEl
* @param {HTMLElement} widgetEl
* @param {*} widgetOptionsEl
* @param {*} optionsSourceUrl
* @param {*} widgetTargetId
*/
initialize: function (formEl, widgetEl, widgetOptionsEl, optionsSourceUrl, widgetTargetId) {
$(formEl).insert({
bottom: widgetTools.getDivHtml(widgetOptionsEl)
});
this.formEl = formEl;
this.widgetEl = $(widgetEl);
this.widgetOptionsEl = $(widgetOptionsEl);
this.optionsUrl = optionsSourceUrl;
this.optionValues = new Hash({});
this.widgetTargetId = widgetTargetId;
if (typeof wysiwyg != 'undefined' && wysiwyg.activeEditor()) { //eslint-disable-line eqeqeq
this.bMark = wysiwyg.activeEditor().selection.getBookmark();
}
// disable -- Please Select -- option from being re-selected
this.widgetEl.querySelector('option').setAttribute('disabled', 'disabled');
Event.observe(this.widgetEl, 'change', this.loadOptions.bind(this));
this.initOptionValues();
},
/**
* @return {String}
*/
getOptionsContainerId: function () {
return this.widgetOptionsEl.id + '_' + this.widgetEl.value.gsub(/\//, '_');
},
/**
* @param {*} containerId
*/
switchOptionsContainer: function (containerId) {
$$('#' + this.widgetOptionsEl.id + ' div[id^=' + this.widgetOptionsEl.id + ']').each(function (e) {
this.disableOptionsContainer(e.id);
}.bind(this));
if (containerId != undefined) { //eslint-disable-line eqeqeq
this.enableOptionsContainer(containerId);
}
this._showWidgetDescription();
},
/**
* @param {*} containerId
*/
enableOptionsContainer: function (containerId) {
var container = $(containerId);
container.select('.widget-option').each(function (e) {
e.removeClassName('skip-submit');
if (e.hasClassName('obligatory')) {
e.removeClassName('obligatory');
e.addClassName('required-entry');
}
});
container.removeClassName('no-display');
},
/**
* @param {*} containerId
*/
disableOptionsContainer: function (containerId) {
var container = $(containerId);
if (container.hasClassName('no-display')) {
return;
}
container.select('.widget-option').each(function (e) {
// Avoid submitting fields of unactive container
if (!e.hasClassName('skip-submit')) {
e.addClassName('skip-submit');
}
// Form validation workaround for unactive container
if (e.hasClassName('required-entry')) {
e.removeClassName('required-entry');
e.addClassName('obligatory');
}
});
container.addClassName('no-display');
},
/**
* Assign widget options values when existing widget selected in WYSIWYG.
*
* @return {Boolean}
*/
initOptionValues: function () {
var e, widgetCode;
if (!this.wysiwygExists()) {
return false;
}
e = this.getWysiwygNode();
if (e.localName === 'span') {
e = e.firstElementChild;
}
if (e != undefined && e.id) { //eslint-disable-line eqeqeq
// attempt to Base64-decode id on selected node; exception is thrown if it is in fact not a widget node
try {
widgetCode = Base64.idDecode(e.id);
} catch (ex) {
return false;
}
if (widgetCode.indexOf('{{widget') !== -1) {
this.optionValues = new Hash({});
widgetCode.gsub(/([a-z0-9\_]+)\s*\=\s*[\"]{1}([^\"]+)[\"]{1}/i, function (match) {
if (match[1] == 'type') { //eslint-disable-line eqeqeq
this.widgetEl.value = match[2];
} else {
this.optionValues.set(match[1], match[2]);
}
}.bind(this));
this.loadOptions();
}
}
},
/**
* Load options.
*/
loadOptions: function () {
var optionsContainerId,
params,
msg,
msgTmpl,
$wrapper,
typeName = this.optionValues.get('type_name');
if (!this.widgetEl.value) {
if (typeName) {
msgTmpl = jQuery.mage.__('The widget %1 is no longer available. Select a different widget.');
msg = jQuery.mage.__(msgTmpl).replace('%1', typeName);
jQuery('body').notification('clear').notification('add', {
error: true,
message: msg,
/**
* @param {String} message
*/
insertMethod: function (message) {
$wrapper = jQuery('<div/>').html(message);
$wrapper.insertAfter('.modal-slide .page-main-actions');
}
});
}
this.switchOptionsContainer();
return;
}
optionsContainerId = this.getOptionsContainerId();
if ($(optionsContainerId) != undefined) { //eslint-disable-line eqeqeq
this.switchOptionsContainer(optionsContainerId);
return;
}
this._showWidgetDescription();
params = {
'widget_type': this.widgetEl.value,
values: this.optionValues
};
new Ajax.Request(this.optionsUrl, {
parameters: {
widget: Object.toJSON(params)
},
/**
* On success.
*/
onSuccess: function (transport) {
try {
widgetTools.onAjaxSuccess(transport);
this.switchOptionsContainer();
if ($(optionsContainerId) == undefined) { //eslint-disable-line eqeqeq
this.widgetOptionsEl.insert({
bottom: widgetTools.getDivHtml(optionsContainerId, transport.responseText)
});
} else {
this.switchOptionsContainer(optionsContainerId);
}
} catch (e) {
alert({
content: e.message
});
}
}.bind(this)
});
},
/**
* @private
*/
_showWidgetDescription: function () {
var noteCnt = this.widgetEl.next().down('small'),
descrCnt = $('widget-description-' + this.widgetEl.selectedIndex),
description;
if (noteCnt != undefined) { //eslint-disable-line eqeqeq
description = descrCnt != undefined ? descrCnt.innerHTML : ''; //eslint-disable-line eqeqeq
noteCnt.update(description);
}
},
/**
* Validate field.
*/
validateField: function () {
jQuery(this.widgetEl).valid();
jQuery('#insert_button').removeClass('disabled');
},
/**
* Closes the modal
*/
closeModal: function () {
widgetTools.dialogWindow.modal('closeModal');
},
/* eslint-disable max-depth*/
/**
* Insert widget.
*/
insertWidget: function () {
var validationResult,
$form = jQuery('#' + this.formEl),
formElements,
i,
params,
editor,
activeNode;
// remove cached validator instance, which caches elements to validate
jQuery.data($form[0], 'validator', null);
$form.validate({
/**
* Ignores elements with .skip-submit, .no-display ancestor elements
*/
ignore: function () {
return jQuery(this).closest('.skip-submit, .no-display').length;
},
errorClass: 'mage-error'
});
validationResult = $form.valid();
if (validationResult) {
formElements = [];
i = 0;
Form.getElements($(this.formEl)).each(function (e) {
if (jQuery(e).closest('.skip-submit, .no-display').length === 0) {
formElements[i] = e;
i++;
}
});
// Add as_is flag to parameters if wysiwyg editor doesn't exist
params = Form.serializeElements(formElements);
if (!this.wysiwygExists()) {
params += '&as_is=1';
}
new Ajax.Request($(this.formEl).action, {
parameters: params,
onComplete: function (transport) {
try {
editor = wysiwyg.get(this.widgetTargetId);
widgetTools.onAjaxSuccess(transport);
widgetTools.dialogWindow.modal('closeModal');
if (editor) {
editor.focus();
activeNode = widgetTools.getActiveSelectedNode();
if (activeNode) {
editor.selection.select(activeNode);
editor.selection.setContent(transport.responseText);
editor.fire('Change');
} else if (this.bMark) {
editor.selection.moveToBookmark(this.bMark);
}
}
if (!activeNode) {
this.updateContent(transport.responseText);
}
} catch (e) {
alert({
content: e.message
});
}
}.bind(this)
});
}
},
/**
* @param {Object} content
*/
updateContent: function (content) {
var textarea;
if (this.wysiwygExists()) {
wysiwyg.insertContent(content, false);
} else {
textarea = document.getElementById(this.widgetTargetId);
updateElementAtCursor(textarea, content);
varienGlobalEvents.fireEvent('tinymceChange');
jQuery(textarea).trigger('change');
}
},
/**
* @return {Boolean}
*/
wysiwygExists: function () {
return typeof wysiwyg != 'undefined' && wysiwyg.get(this.widgetTargetId);
},
/**
* @return {null|wysiwyg.Editor|*}
*/
getWysiwyg: function () {
return wysiwyg.get(this.widgetTargetId);
},
/**
* @return {*|Element}
*/
getWysiwygNode: function () {
return widgetTools.getActiveSelectedNode() || wysiwyg.activeEditor().selection.getNode();
}
};
WysiwygWidget.chooser = Class.create();
WysiwygWidget.chooser.prototype = {
// HTML element A, on which click event fired when choose a selection
chooserId: null,
// Source URL for Ajax requests
chooserUrl: null,
// Chooser config
config: null,
// Chooser dialog window
dialogWindow: null,
// Chooser content for dialog window
dialogContent: null,
overlayShowEffectOptions: null,
overlayHideEffectOptions: null,
/**
* @param {*} chooserId
* @param {*} chooserUrl
* @param {*} config
*/
initialize: function (chooserId, chooserUrl, config) {
this.chooserId = chooserId;
this.chooserUrl = chooserUrl;
this.config = config;
},
/**
* @return {String}
*/
getResponseContainerId: function () {
return 'responseCnt' + this.chooserId;
},
/**
* @return {jQuery|*|HTMLElement}
*/
getChooserControl: function () {
return $(this.chooserId + 'control');
},
/**
* @return {jQuery|*|HTMLElement}
*/
getElement: function () {
return $(this.chooserId + 'value');
},
/**
* @return {jQuery|*|HTMLElement}
*/
getElementLabel: function () {
return $(this.chooserId + 'label');
},
/**
* Open.
*/
open: function () {
$(this.getResponseContainerId()).show();
},
/**
* Close.
*/
close: function () {
$(this.getResponseContainerId()).hide();
this.closeDialogWindow();
},
/**
* Choose.
*/
choose: function () {
// Open dialog window with previously loaded dialog content
var responseContainerId;
if (this.dialogContent) {
this.openDialogWindow(this.dialogContent);
return;
}
// Show or hide chooser content if it was already loaded
responseContainerId = this.getResponseContainerId();
// Otherwise load content from server
new Ajax.Request(this.chooserUrl, {
parameters: {
'element_value': this.getElementValue(),
'element_label': this.getElementLabelText()
},
/**
* On success.
*/
onSuccess: function (transport) {
try {
widgetTools.onAjaxSuccess(transport);
this.dialogContent = widgetTools.getDivHtml(responseContainerId, transport.responseText);
this.openDialogWindow(this.dialogContent);
} catch (e) {
alert({
content: e.message
});
}
}.bind(this)
});
},
/**
* Open dialog winodw.
*
* @param {*} content
*/
openDialogWindow: function (content) {
this.dialogWindow = jQuery('<div/>').modal({
title: this.config.buttons.open,
type: 'slide',
buttons: [],
/**
* Opened.
*/
opened: function () {
jQuery(this).addClass('magento-message');
},
/**
* @param {jQuery.Event} e
* @param {Object} modal
*/
closed: function (e, modal) {
modal.modal.remove();
this.dialogWindow = null;
}
});
this.dialogWindow.modal('openModal').append(content);
},
/**
* Close dialog window.
*/
closeDialogWindow: function () {
this.dialogWindow.modal('closeModal').remove();
},
/**
* @return {*|Number}
*/
getElementValue: function () {
return this.getElement().value;
},
/**
* @return {String}
*/
getElementLabelText: function () {
return this.getElementLabel().innerHTML;
},
/**
* @param {*} value
*/
setElementValue: function (value) {
this.getElement().value = value;
},
/**
* @param {*} value
*/
setElementLabel: function (value) {
this.getElementLabel().innerHTML = value;
}
};
window.WysiwygWidget = WysiwygWidget;
window.widgetTools = widgetTools;
});