This commit is contained in:
2026-09-15 10:26:34 +08:00
commit ecf36afa56
10493 changed files with 1404888 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
$.widget('mage.actionLink', {
/**
* Button creation
* @protected
*/
_create: function () {
this._bind();
},
/**
* Bind handler on button click
* @protected
*/
_bind: function () {
var keyCode = $.ui.keyCode;
this._on({
/**
* @param {jQuery.Event} e
*/
mousedown: function (e) {
this._stopPropogation(e);
},
/**
* @param {jQuery.Event} e
*/
mouseup: function (e) {
this._stopPropogation(e);
},
/**
* @param {jQuery.Event} e
*/
click: function (e) {
this._stopPropogation(e);
this._triggerEvent();
},
/**
* @param {jQuery.Event} e
*/
keydown: function (e) {
switch (e.keyCode) {
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
this._stopPropogation(e);
this._triggerEvent();
break;
}
},
/**
* @param {jQuery.Event} e
*/
keyup: function (e) {
switch (e.keyCode) {
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
this._stopPropogation(e);
break;
}
}
});
},
/**
* @param {Object} e - event object
* @private
*/
_stopPropogation: function (e) {
e.stopImmediatePropagation();
e.preventDefault();
},
/**
* @private
*/
_triggerEvent: function () {
$(this.options.related || this.element)
.trigger(this.options.event, this.options.eventData ? [this.options.eventData] : [{}]);
}
});
return $.mage.actionLink;
});
+120
View File
@@ -0,0 +1,120 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global FORM_KEY */
define([
'jquery',
'mage/apply/main',
'mage/backend/notification',
'Magento_Ui/js/lib/knockout/bootstrap',
'mage/mage',
'mage/translate'
], function ($, mage, notification) {
'use strict';
var bootstrap;
$.ajaxSetup({
/*
* @type {string}
*/
type: 'POST',
/**
* Ajax before send callback.
*
* @param {Object} jqXHR - The jQuery XMLHttpRequest object returned by $.ajax()
* @param {Object} settings
*/
beforeSend: function (jqXHR, settings) {
var formKey = typeof FORM_KEY !== 'undefined' ? FORM_KEY : null;
if (!settings.url.match(new RegExp('[?&]isAjax=true',''))) {
settings.url = settings.url.match(
new RegExp('\\?', 'g')) ?
settings.url + '&isAjax=true' :
settings.url + '?isAjax=true';
}
if (!settings.data) {
settings.data = {
'form_key': formKey
};
} else if (typeof settings.data === 'string' &&
settings.data.indexOf('form_key=') === -1) {
settings.data += '&' + $.param({
'form_key': formKey
});
} else if ($.isPlainObject(settings.data) && !settings.data['form_key']) {
settings.data['form_key'] = formKey;
}
},
/**
* Ajax complete callback.
*
* @param {Object} jqXHR - The jQuery XMLHttpRequest object returned by $.ajax()
*/
complete: function (jqXHR) {
var jsonObject;
if (jqXHR.readyState === 4) {
try {
jsonObject = JSON.parse(jqXHR.responseText);
if (jsonObject.ajaxExpired && jsonObject.ajaxRedirect) { //eslint-disable-line max-depth
window.location.replace(jsonObject.ajaxRedirect);
}
} catch (e) {}
}
},
/**
* Error callback.
*
* @param {Object} jqXHR - The jQuery XMLHttpRequest object returned by $.ajax()
* @param {String} textStatus
*/
error: function (jqXHR, textStatus) {
$('body').notification('clear');
if (jqXHR.readyState !== 0 && textStatus !== 'abort') {
$('body').notification('add', {
error: true,
message: $.mage.__(
'A technical problem with the server created an error. ' +
'Try again to continue what you were doing. If the problem persists, try again later.'
),
/**
* @param {String} message
*/
insertMethod: function (message) {
var $wrapper = $('<div></div>').html(message);
$('.page-main-actions').after($wrapper);
}
});
}
}
});
/**
* Bootstrap application.
*/
bootstrap = function () {
/**
* Init all components defined via data-mage-init attribute
* and subscribe init action on contentUpdated event
*/
mage.apply();
/*
* Initialization of notification widget
*/
notification({}, $('body'));
};
$(bootstrap);
});
+53
View File
@@ -0,0 +1,53 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
$.widget('ui.button', $.ui.button, {
options: {
eventData: {},
waitTillResolved: true
},
/**
* Button creation.
* @protected
*/
_create: function () {
if (this.options.event) {
this.options.target = this.options.target || this.element;
this._bind();
}
this._super();
},
/**
* Bind handler on button click.
* @protected
*/
_bind: function () {
this.element
.off('click.button')
.on('click.button', $.proxy(this._click, this));
},
/**
* Button click handler.
* @protected
*/
_click: function () {
var options = this.options;
$(options.target).trigger(options.event, [options.eventData]);
}
});
return $.ui.button;
});
+352
View File
@@ -0,0 +1,352 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* @deprecated since version 2.2.0
*/
/* global EditableMultiselect */
/* eslint-disable strict */
define([
'jquery',
'Magento_Ui/js/modal/alert',
'Magento_Ui/js/modal/confirm',
'jquery/editableMultiselect/js/jquery.editable',
'jquery/editableMultiselect/js/jquery.multiselect'
], function ($, alert, confirm) {
/**
* Editable multiselect wrapper for multiselects
* This class is defined in global scope ('var' is not needed).
*
* @param {Object} settings - settings object.
* @param {String} settings.add_button_caption - caption of the 'Add New Value' button
* @param {String} settings.new_url - URL to which new request has to be submitted
* @param {String} settings.save_url - URL to which save request has to be submitted
* @param {String} settings.delete_url - URL to which delete request has to be submitted
* @param {String} settings.delete_confirm_message - confirmation message that is shown to user during
* delete operation
* @param {String} settings.target_select_id - HTML ID of target select element
* @param {Hash} settings.submit_data - extra parameters to send with new/edit/delete requests
* @param {String} settings.entity_value_name - name of the request parameter that represents select option text
* @param {String} settings.entity_id_name - name of the request parameter that represents select option value
* @param {Boolean} settings.is_entry_editable - flag that shows if user can add/edit/remove data
*
* @constructor
*/
window.EditableMultiselect = function (settings) {
this.settings = settings || {};
this.addButtonCaption = this.settings['add_button_caption'] || 'Add new value';
this.newUrl = this.settings['new_url'];
this.saveUrl = this.settings['save_url'];
this.deleteUrl = this.settings['delete_url'];
this.deleteConfirmMessage = this.settings['delete_confirm_message'];
this.targetSelectId = this.settings['target_select_id'];
this.submitData = this.settings['submit_data'] || {};
this.entityIdName = this.settings['entity_id_name'] || 'entity_id';
this.entityValueName = this.settings['entity_value_name'] || 'entity_value';
this.isEntityEditable = this.settings['is_entity_editable'] || false;
/**
* Initialize editable multiselect (make it visible in UI)
*/
EditableMultiselect.prototype.init = function () {
var self = this,
mselectOptions = {
addText: this.addButtonCaption,
/**
* @param {*} value
* @param {*} options
*/
mselectInputSubmitCallback: function (value, options) {
self.createEntity(value, options);
}
},
mselectList;
if (!this.isEntityEditable) {
// Override default layout of editable multiselect
mselectOptions.layout = '<section class="block %mselectListClass%">' +
'<div class="block-content"><div class="%mselectItemsWrapperClass%">' +
'%items%' +
'</div></div>' +
'<div class="%mselectInputContainerClass%">' +
'<input type="text" class="%mselectInputClass%" title="%inputTitle%"/>' +
'<span class="%mselectButtonCancelClass%" title="%cancelText%"></span>' +
'<span class="%mselectButtonSaveClass%" title="Add"></span>' +
'</div>' +
'</section>';
}
$('#' + this.targetSelectId).multiselect(mselectOptions);
// Make multiselect editable if needed
if (this.isEntityEditable) {
this.makeMultiselectEditable();
// Root element of HTML markup that represents select element in UI
mselectList = $('#' + this.targetSelectId).next();
this.attachEventsToControls(mselectList);
}
};
/**
* Attach required event handlers to control elements of editable multiselect
*
* @param {Object} mselectList
*/
EditableMultiselect.prototype.attachEventsToControls = function (mselectList) {
mselectList.on('click.mselect-delete', '.mselect-delete', {
container: this
}, function (event) {
// Pass the clicked button to container
event.data.container.deleteEntity({
'delete_button': this
});
});
mselectList.on('click.mselect-checked', '.mselect-list-item input', {
container: this
}, function (event) {
var el = $(this),
checkedClassName = 'mselect-checked';
el[el.is(':checked') ? 'addClass' : 'removeClass'](checkedClassName);
event.data.container.makeMultiselectEditable();
});
mselectList.on('click.mselect-edit', '.mselect-edit', {
container: this
}, function (event) {
event.data.container.makeMultiselectEditable();
$(this).parent().find('label span').trigger('dblclick');
});
};
/**
* Make multiselect editable
*/
EditableMultiselect.prototype.makeMultiselectEditable = function () {
var entityIdName = this.entityIdName,
entityValueName = this.entityValueName,
selectList = $('#' + this.targetSelectId).next();
selectList.find('.mselect-list-item:not(.mselect-list-item-not-editable) label span').editable(this.saveUrl,
{
type: 'text',
submit: '<button class="mselect-save" title="Save" type="submit"></button>',
cancel: '<span class="mselect-cancel" title="Cancel"></span>',
event: 'dblclick',
placeholder: '',
/**
* Is checked.
*/
isChecked: function () {
var that = $(this),
checked;
if (!that.closest('.mselect-list-item').hasClass('mselect-disabled')) {
checked = that.parent().find('[type=checkbox]').prop('disabled');
that.parent().find('[type=checkbox]').prop({
disabled: !checked
});
}
},
/**
* @param {*} value
* @param {Object} sett
* @return {*}
*/
data: function (value, sett) {
var retval;
sett.isChecked.apply(this, [sett]);
if (typeof value === 'string') {
retval = value.unescapeHTML();
return retval;
}
return value;
},
submitdata: this.submitData,
onblur: 'cancel',
name: entityValueName,
ajaxoptions: {
dataType: 'json'
},
/**
* @param {Object} sett
* @param {*} original
*/
onsubmit: function (sett, original) {
var select = $(original).closest('.mselect-list').prev(),
current = $(original).closest('.mselect-list-item').index(),
entityId = select.find('option').eq(current).val(),
entityInfo = {};
entityInfo[entityIdName] = entityId;
sett.submitdata = $.extend(sett.submitdata || {}, entityInfo);
},
/**
* @param {Object} result
* @param {Object} sett
*/
callback: function (result, sett) {
var select, current;
sett.isChecked.apply(this, [sett]);
select = $(this).closest('.mselect-list').prev();
current = $(this).closest('.mselect-list-item').index();
if (result.success) {
if (typeof result[entityValueName] === 'string') {
select.find('option').eq(current).val(result[entityIdName]).text(result[entityValueName]);
$(this).html(result[entityValueName].escapeHTML());
}
} else {
alert({
content: result['error_message']
});
}
}
});
};
/**
* Callback function that is called when admin adds new value to select
*
* @param {*} value
* @param {Object} options - list of settings of multiselect
*/
EditableMultiselect.prototype.createEntity = function (value, options) {
var select, entityIdName, entityValueName, entityInfo, postData, ajaxOptions;
if (!value) {
return;
}
select = $('#' + this.targetSelectId),
entityIdName = this.entityIdName,
entityValueName = this.entityValueName,
entityInfo = {};
entityInfo[entityIdName] = null;
entityInfo[entityValueName] = value;
postData = $.extend(entityInfo, this.submitData);
ajaxOptions = {
type: 'POST',
data: postData,
dataType: 'json',
url: this.newUrl,
/**
* @param {Object} result
*/
success: function (result) {
var resultEntityValueName, mselectItemHtml, sectionBlock, itemsWrapper, inputSelector;
if (result.success) {
resultEntityValueName = '';
if (typeof result[entityValueName] === 'string') {
resultEntityValueName = result[entityValueName].escapeHTML();
} else {
resultEntityValueName = result[entityValueName];
}
// Add item to initial select element
select.append('<option value="' + result[entityIdName] + '" selected="selected">' +
resultEntityValueName + '</option>');
// Add editable multiselect item
mselectItemHtml = $(options.item.replace(/%value%|%label%/gi, resultEntityValueName)
.replace(/%mselectDisabledClass%|%iseditable%|%isremovable%/gi, '')
.replace(/%mselectListItemClass%/gi, options.mselectListItemClass))
.find('[type=checkbox]')
.addClass(options.mselectCheckedClass)
.prop('checked', true)
.end();
sectionBlock = select.nextAll('section.block:first');
itemsWrapper = sectionBlock.find('.' + options.mselectItemsWrapperClass + '');
if (itemsWrapper.children('.' + options.mselectListItemClass + '').length) {
itemsWrapper.children('.' + options.mselectListItemClass + ':last').after(mselectItemHtml);
} else {
itemsWrapper.prepend(mselectItemHtml);
}
// Trigger blur event on input field, that is used to add new value, to hide it
inputSelector = '.' + options.mselectInputContainerClass + ' [type=text].' +
options.mselectInputClass + '';
sectionBlock.find(inputSelector).trigger('blur');
} else {
alert({
content: result['error_message']
});
}
}
};
$.ajax(ajaxOptions);
};
/**
* Callback function that is called when user tries to delete value from select
*
* @param {Object} options
*/
EditableMultiselect.prototype.deleteEntity = function (options) {
var self = this;
if (options['delete_button']) {
confirm({
content: this.deleteConfirmMessage,
actions: {
/**
* Confirm.
*/
confirm: function () {
// Button that has been clicked
var deleteButton = $(options['delete_button']),
index = deleteButton.parent().index(),
select = deleteButton.closest('.mselect-list').prev(),
entityId = select.find('option').eq(index).val(),
entityInfo = {},
postData, ajaxOptions;
entityInfo[self.entityIdName] = entityId;
postData = $.extend(entityInfo, self.submitData);
ajaxOptions = {
type: 'POST',
data: postData,
dataType: 'json',
url: self.deleteUrl,
/**
* @param {Object} result
*/
success: function (result) {
if (result.success) {
deleteButton.parent().remove();
select.find('option').eq(index).remove();
} else {
alert({
content: result['error_message']
});
}
}
};
$.ajax(ajaxOptions);
}
}
});
}
};
};
});
+112
View File
@@ -0,0 +1,112 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
$.widget('mage.floatingHeader', {
options: {
placeholderAttrs: {
'class': 'page-actions-placeholder'
},
fixedClass: '_fixed',
hiddenClass: '_hidden',
title: '.page-title-wrapper .page-title',
pageMainActions: '.page-main-actions',
contains: '[data-role=modal]'
},
/**
* Widget initialization
* @private
*/
_create: function () {
var title = $(this.options.title).text(),
wrapped = this.element.find('.page-actions-buttons').children();
if (this.element.parents(this.options.contains).length) {
return this;
}
this._setVars();
this._bind();
this.element.find('script').remove();
if (wrapped.length) {
wrapped
.unwrap() // .page-actions-buttons
.unwrap(); // .page-actions-inner
}
this.element.wrapInner($('<div></div>', {
'class': 'page-actions-buttons'
}));
this.element.wrapInner($('<div></div>', {
'class': 'page-actions-inner', 'data-title': title
}));
this.element.removeClass('floating-header');
},
/**
* Set privat variables on load, for performance purposes
* @private
*/
_setVars: function () {
this._placeholder = this.element.before($('<div/>', this.options.placeholderAttrs)).prev();
this._offsetTop = this._placeholder.offset().top;
this._height = this.element
.parents(this.options.pageMainActions)
.outerHeight();
},
/**
* Event binding, will monitor scroll and resize events (resize events left for backward compat)
* @private
*/
_bind: function () {
this._on(window, {
scroll: this._handlePageScroll,
resize: this._handlePageScroll
});
},
/**
* Event handler for setting fixed positioning
* @private
*/
_handlePageScroll: function () {
var isActive = $(window).scrollTop() > this._offsetTop;
if (isActive) {
this.element
.addClass(this.options.fixedClass)
.parents(this.options.pageMainActions)
.addClass(this.options.hiddenClass);
} else {
this.element
.removeClass(this.options.fixedClass)
.parents(this.options.pageMainActions)
.removeClass(this.options.hiddenClass);
}
this._placeholder.height(isActive ? this._height : '');
},
/**
* Widget destroy functionality
* @private
*/
_destroy: function () {
if (this._placeholder) {
this._placeholder.remove();
}
this._off($(window));
}
});
return $.mage.floatingHeader;
});
+204
View File
@@ -0,0 +1,204 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
$.widget('mage.form', {
options: {
handlersData: {
save: {},
saveAndContinueEdit: {
action: {
args: {
back: 'edit'
}
}
},
preview: {
target: '_blank'
}
}
},
/**
* Form creation
* @protected
*/
_create: function () {
this._bind();
},
/**
* Set form attributes to initial state
* @protected
*/
_rollback: function () {
if (this.oldAttributes) {
this.element.prop(this.oldAttributes);
}
},
/**
* Check if field value is changed
* @protected
* @param {Object} e - event object
*/
_changesObserver: function (e) {
var target = $(e.target),
changed;
if (e.type === 'focus' || e.type === 'focusin') {
this.currentField = {
statuses: {
checked: target.is(':checked'),
selected: target.is(':selected')
},
val: target.val()
};
} else {
if (this.currentField) { //eslint-disable-line no-lonely-if
changed = target.val() !== this.currentField.val ||
target.is(':checked') !== this.currentField.statuses.checked ||
target.is(':selected') !== this.currentField.statuses.selected;
if (changed) { //eslint-disable-line max-depth
target.trigger('changed');
}
}
}
},
/**
* Get array with handler names
* @protected
* @return {Array} Array of handler names
*/
_getHandlers: function () {
var handlers = [];
$.each(this.options.handlersData, function (key) {
handlers.push(key);
});
return handlers;
},
/**
* Store initial value of form attribute
* @param {String} attrName - name of attribute
* @protected
*/
_storeAttribute: function (attrName) {
var prop;
this.oldAttributes = this.oldAttributes || {};
if (!this.oldAttributes[attrName]) {
prop = this.element.attr(attrName);
this.oldAttributes[attrName] = prop ? prop : '';
}
},
/**
* Bind handlers
* @protected
*/
_bind: function () {
this.element
.on(this._getHandlers().join(' '), $.proxy(this._submit, this))
.on('focus blur focusin focusout', $.proxy(this._changesObserver, this));
},
/**
* Get action url for form
* @param {Object|String} data - object with parameters for action url or url string
* @return {String} action url
*/
_getActionUrl: function (data) {
if (typeof data === 'object') {
return this._buildURL(this.oldAttributes.action, data.args);
}
return typeof data === 'string' ? data : this.oldAttributes.action;
},
/**
* Add additional parameters into URL
* @param {String} url - original url
* @param {Object} params - object with parameters for action url
* @return {String} action url
* @private
*/
_buildURL: function (url, params) {
var concat = /\?/.test(url) ? ['&', '='] : ['/', '/'];
url = url.replace(/[\/&]+$/, '');
$.each(params, function (key, value) {
url += concat[0] + key + concat[1] + window.encodeURIComponent(value);
});
return url + (concat[0] === '/' ? '/' : '');
},
/**
* Prepare data for form attributes
* @protected
* @param {Object} data
* @return {Object}
*/
_processData: function (data) {
$.each(data, $.proxy(function (attrName, attrValue) {
this._storeAttribute(attrName);
if (attrName === 'action') {
data[attrName] = this._getActionUrl(attrValue);
}
}, this));
return data;
},
/**
* Get additional data before form submit
* @protected
* @param {String} handlerName
* @param {Object} data
*/
_beforeSubmit: function (handlerName, data) {
var submitData = {},
event = new $.Event('beforeSubmit');
this.element.trigger(event, [submitData, handlerName]);
data = $.extend(
true, {},
this.options.handlersData[handlerName] || {},
submitData,
data
);
this.element.prop(this._processData(data));
return !event.isDefaultPrevented();
},
/**
* Submit the form
* @param {Object} e - event object
* @param {Object} data - event data object
*/
_submit: function (e, data) {
this._rollback();
if (this._beforeSubmit(e.type, data) !== false) {
this.element.trigger('submit', e);
}
}
});
return $.mage.form;
});
+779
View File
@@ -0,0 +1,779 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
$.widget('mage.menu', {
widgetEventPrefix: 'menu',
version: '1.10.1',
defaultElement: '<ul>',
delay: 300,
options: {
icons: {
submenu: 'ui-icon-carat-1-e'
},
menus: 'ul',
position: {
my: 'left top',
at: 'right top'
},
role: 'menu',
// callbacks
blur: null,
focus: null,
select: null
},
/**
* @private
*/
_create: function () {
this.activeMenu = this.element;
// flag used to prevent firing of the click handler
// as the event bubbles up through nested menus
this.mouseHandled = false;
this.element
.uniqueId()
.addClass('ui-menu ui-widget ui-widget-content ui-corner-all')
.toggleClass('ui-menu-icons', !!this.element.find('.ui-icon').length)
.attr({
role: this.options.role,
tabIndex: 0
})
// need to catch all clicks on disabled menu
// not possible through _on
.on('click' + this.eventNamespace, $.proxy(function (event) {
if (this.options.disabled) {
event.preventDefault();
}
}, this));
if (this.options.disabled) {
this.element
.addClass('ui-state-disabled')
.attr('aria-disabled', 'true');
}
this._on({
/**
* Prevent focus from sticking to links inside menu after clicking
* them (focus should always stay on UL during navigation).
*/
'mousedown .ui-menu-item > a': function (event) {
event.preventDefault();
},
/**
* Prevent focus from sticking to links inside menu after clicking
* them (focus should always stay on UL during navigation).
*/
'click .ui-state-disabled > a': function (event) {
event.preventDefault();
},
/**
* @param {jQuery.Event} event
*/
'click .ui-menu-item:has(a)': function (event) {
var target = $(event.target).closest('.ui-menu-item');
if (!this.mouseHandled && target.not('.ui-state-disabled').length) {
this.mouseHandled = true;
this.select(event);
// Open submenu on click
if (target.has('.ui-menu').length) {
this.expand(event);
} else if (!this.element.is(':focus')) {
// Redirect focus to the menu
this.element.trigger('focus', [true]);
// If the active item is on the top level, let it stay active.
// Otherwise, blur the active item since it is no longer visible.
if (this.active && this.active.parents('.ui-menu').length === 1) { //eslint-disable-line
clearTimeout(this.timer);
}
}
}
},
/**
* @param {jQuery.Event} event
*/
'mouseenter .ui-menu-item': function (event) {
var target = $(event.currentTarget);
// Remove ui-state-active class from siblings of the newly focused menu item
// to avoid a jump caused by adjacent elements both having a class with a border
target.siblings().children('.ui-state-active').removeClass('ui-state-active');
this.focus(event, target);
},
mouseleave: 'collapseAll',
'mouseleave .ui-menu': 'collapseAll',
/**
* @param {jQuery.Event} event
* @param {*} keepActiveItem
*/
focus: function (event, keepActiveItem) {
// If there's already an active item, keep it active
// If not, activate the first item
var item = this.active || this.element.children('.ui-menu-item').eq(0);
if (!keepActiveItem) {
this.focus(event, item);
}
},
/**
* @param {jQuery.Event} event
*/
blur: function (event) {
this._delay(function () {
if (!$.contains(this.element[0], this.document[0].activeElement)) {
this.collapseAll(event);
}
});
},
keydown: '_keydown'
});
this.refresh();
// Clicks outside of a menu collapse any open menus
this._on(this.document, {
/**
* @param {jQuery.Event} event
*/
click: function (event) {
if (!$(event.target).closest('.ui-menu').length) {
this.collapseAll(event);
}
// Reset the mouseHandled flag
this.mouseHandled = false;
}
});
},
/**
* @private
*/
_destroy: function () {
// Destroy (sub)menus
this.element
.removeAttr('aria-activedescendant')
.find('.ui-menu').addBack()
.removeClass('ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons')
.removeAttr('role')
.removeAttr('tabIndex')
.removeAttr('aria-labelledby')
.removeAttr('aria-expanded')
.removeAttr('aria-hidden')
.removeAttr('aria-disabled')
.removeUniqueId()
.show();
// Destroy menu items
this.element.find('.ui-menu-item')
.removeClass('ui-menu-item')
.removeAttr('role')
.removeAttr('aria-disabled')
.children('a')
.removeUniqueId()
.removeClass('ui-corner-all ui-state-hover')
.removeAttr('tabIndex')
.removeAttr('role')
.removeAttr('aria-haspopup')
.children().each(function () {
var elem = $(this);
if (elem.data('ui-menu-submenu-carat')) {
elem.remove();
}
});
// Destroy menu dividers
this.element.find('.ui-menu-divider').removeClass('ui-menu-divider ui-widget-content');
},
/**
* @param {jQuery.Event} event
* @private
*/
_keydown: function (event) {
var match, prev, character, skip, regex,
preventDefault = true;
/**
* @param {String} value
*/
function escape(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
}
switch (event.keyCode) {
case $.ui.keyCode.PAGE_UP:
this.previousPage(event);
break;
case $.ui.keyCode.PAGE_DOWN:
this.nextPage(event);
break;
case $.ui.keyCode.HOME:
this._move('first', 'first', event);
break;
case $.ui.keyCode.END:
this._move('last', 'last', event);
break;
case $.ui.keyCode.UP:
this.previous(event);
break;
case $.ui.keyCode.DOWN:
this.next(event);
break;
case $.ui.keyCode.LEFT:
this.collapse(event);
break;
case $.ui.keyCode.RIGHT:
if (this.active && !this.active.is('.ui-state-disabled')) {
this.expand(event);
}
break;
case $.ui.keyCode.ENTER:
case $.ui.keyCode.SPACE:
this._activate(event);
break;
case $.ui.keyCode.ESCAPE:
this.collapse(event);
break;
default:
preventDefault = false;
prev = this.previousFilter || '';
character = String.fromCharCode(event.keyCode);
skip = false;
clearTimeout(this.filterTimer);
if (character === prev) {
skip = true;
} else {
character = prev + character;
}
regex = new RegExp('^' + escape(character), 'i');
match = this.activeMenu.children('.ui-menu-item').filter(function () {
return regex.test($(this).children('a').text());
});
match = skip && match.index(this.active.next()) !== -1 ?
this.active.nextAll('.ui-menu-item') :
match;
// If no matches on the current filter, reset to the last character pressed
// to move down the menu to the first item that starts with that character
if (!match.length) {
character = String.fromCharCode(event.keyCode);
regex = new RegExp('^' + escape(character), 'i');
match = this.activeMenu.children('.ui-menu-item').filter(function () {
return regex.test($(this).children('a').text());
});
}
if (match.length) {
this.focus(event, match);
if (match.length > 1) { //eslint-disable-line max-depth
this.previousFilter = character;
this.filterTimer = this._delay(function () {
delete this.previousFilter;
}, 1000);
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
if (preventDefault) {
event.preventDefault();
}
},
/**
* @param {jQuery.Event} event
* @private
*/
_activate: function (event) {
if (!this.active.is('.ui-state-disabled')) {
if (this.active.children('a[aria-haspopup="true"]').length) {
this.expand(event);
} else {
this.select(event);
}
}
},
/**
* Refresh.
*/
refresh: function () {
var menus,
icon = this.options.icons.submenu,
submenus = this.element.find(this.options.menus);
// Initialize nested menus
submenus.filter(':not(.ui-menu)')
.addClass('ui-menu ui-widget ui-widget-content ui-corner-all')
.hide()
.attr({
role: this.options.role,
'aria-hidden': 'true',
'aria-expanded': 'false'
})
.each(function () {
var menu = $(this),
item = menu.prev('a'),
submenuCarat = $('<span>')
.addClass('ui-menu-icon ui-icon ' + icon)
.data('ui-menu-submenu-carat', true);
item
.attr('aria-haspopup', 'true')
.prepend(submenuCarat);
menu.attr('aria-labelledby', item.attr('id'));
});
menus = submenus.add(this.element);
// Don't refresh list items that are already adapted
menus.children(':not(.ui-menu-item):has(a)')
.addClass('ui-menu-item')
.attr('role', 'presentation')
.children('a')
.uniqueId()
.addClass('ui-corner-all')
.attr({
tabIndex: -1,
role: this._itemRole()
});
// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
menus.children(':not(.ui-menu-item)').each(function () {
var item = $(this);
// hyphen, em dash, en dash
if (!/[^\-\u2014\u2013\s]/.test(item.text())) {
item.addClass('ui-widget-content ui-menu-divider');
}
});
// Add aria-disabled attribute to any disabled menu item
menus.children('.ui-state-disabled').attr('aria-disabled', 'true');
// If the active item has been removed, blur the menu
if (this.active && !$.contains(this.element[0], this.active[0])) {
this.blur();
}
},
/**
* @return {*}
* @private
*/
_itemRole: function () {
return {
menu: 'menuitem',
listbox: 'option'
}[this.options.role];
},
/**
* @param {String} key
* @param {*} value
* @private
*/
_setOption: function (key, value) {
if (key === 'icons') {
this.element.find('.ui-menu-icon')
.removeClass(this.options.icons.submenu)
.addClass(value.submenu);
}
this._super(key, value);
},
/**
* @param {jQuery.Event} event
* @param {Object} item
*/
focus: function (event, item) {
var nested, focused;
this.blur(event, event && event.type === 'focus');
this._scrollIntoView(item);
this.active = item.first();
focused = this.active.children('a').addClass('ui-state-focus');
// Only update aria-activedescendant if there's a role
// otherwise we assume focus is managed elsewhere
if (this.options.role) {
this.element.attr('aria-activedescendant', focused.attr('id'));
}
// Highlight active parent menu item, if any
this.active
.parent()
.closest('.ui-menu-item')
.children('a:first')
.addClass('ui-state-active');
if (event && event.type === 'keydown') {
this._close();
} else {
this.timer = this._delay(function () {
this._close();
}, this.delay);
}
nested = item.children('.ui-menu');
if (nested.length && /^mouse/.test(event.type)) {
this._startOpening(nested);
}
this.activeMenu = item.parent();
this._trigger('focus', event, {
item: item
});
},
/**
* @param {Object} item
* @private
*/
_scrollIntoView: function (item) {
var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
if (this._hasScroll()) {
borderTop = parseFloat($.css(this.activeMenu[0], 'borderTopWidth')) || 0;
paddingTop = parseFloat($.css(this.activeMenu[0], 'paddingTop')) || 0;
offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
scroll = this.activeMenu.scrollTop();
elementHeight = this.activeMenu.height();
itemHeight = item.height();
if (offset < 0) {
this.activeMenu.scrollTop(scroll + offset);
} else if (offset + itemHeight > elementHeight) {
this.activeMenu.scrollTop(scroll + offset - elementHeight + itemHeight);
}
}
},
/**
* @param {jQuery.Event} event
* @param {*} fromFocus
*/
blur: function (event, fromFocus) {
if (!fromFocus) {
clearTimeout(this.timer);
}
if (!this.active) {
return;
}
this.active.children('a').removeClass('ui-state-focus');
this.active = null;
this._trigger('blur', event, {
item: this.active
});
},
/**
* @param {*} submenu
* @private
*/
_startOpening: function (submenu) {
clearTimeout(this.timer);
// Don't open if already open fixes a Firefox bug that caused a .5 pixel
// shift in the submenu position when mousing over the carat icon
if (submenu.attr('aria-hidden') !== 'true') {
return;
}
this.timer = this._delay(function () {
this._close();
this._open(submenu);
}, this.delay);
},
/**
* @param {*} submenu
* @private
*/
_open: function (submenu) {
var position = $.extend({
of: this.active
}, this.options.position);
clearTimeout(this.timer);
this.element.find('.ui-menu').not(submenu.parents('.ui-menu'))
.hide()
.attr('aria-hidden', 'true');
submenu
.show()
.removeAttr('aria-hidden')
.attr('aria-expanded', 'true')
.position(position);
},
/**
* @param {jQuery.Event} event
* @param {*} all
*/
collapseAll: function (event, all) {
clearTimeout(this.timer);
this.timer = this._delay(function () {
// If we were passed an event, look for the submenu that contains the event
var currentMenu = all ? this.element :
$(event && event.target).closest(this.element.find('.ui-menu'));
// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
if (!currentMenu.length) {
currentMenu = this.element;
}
this._close(currentMenu);
this.blur(event);
this.activeMenu = currentMenu;
}, this.delay);
},
// With no arguments, closes the currently active menu - if nothing is active
// it closes all menus. If passed an argument, it will search for menus BELOW
/**
* With no arguments, closes the currently active menu - if nothing is active
* it closes all menus. If passed an argument, it will search for menus BELOW.
*
* @param {*} startMenu
* @private
*/
_close: function (startMenu) {
if (!startMenu) {
startMenu = this.active ? this.active.parent() : this.element;
}
startMenu
.find('.ui-menu')
.hide()
.attr('aria-hidden', 'true')
.attr('aria-expanded', 'false')
.end()
.find('a.ui-state-active')
.removeClass('ui-state-active');
},
/**
* @param {jQuery.Event} event
*/
collapse: function (event) {
var newItem = this.active &&
this.active.parent().closest('.ui-menu-item', this.element);
if (newItem && newItem.length) {
this._close();
this.focus(event, newItem);
}
},
/**
* @param {jQuery.Event} event
*/
expand: function (event) {
var newItem = this.active &&
this.active
.children('.ui-menu ')
.children('.ui-menu-item')
.first();
if (newItem && newItem.length) {
this._open(newItem.parent());
// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
this._delay(function () {
this.focus(event, newItem);
});
}
},
/**
* @param {jQuery.Event} event
*/
next: function (event) {
this._move('next', 'first', event);
},
/**
* @param {jQuery.Event} event
*/
previous: function (event) {
this._move('prev', 'last', event);
},
/**
* @return {null|Boolean}
*/
isFirstItem: function () {
return this.active && !this.active.prevAll('.ui-menu-item').length;
},
/**
* @return {null|Boolean}
*/
isLastItem: function () {
return this.active && !this.active.nextAll('.ui-menu-item').length;
},
/**
* @param {*} direction
* @param {*} filter
* @param {jQuery.Event} event
* @private
*/
_move: function (direction, filter, event) {
var next;
if (this.active) {
if (direction === 'first' || direction === 'last') {
next = this.active
[direction === 'first' ? 'prevAll' : 'nextAll']('.ui-menu-item')
.eq(-1);
} else {
next = this.active
[direction + 'All']('.ui-menu-item')
.eq(0);
}
}
if (!next || !next.length || !this.active) {
next = this.activeMenu.children('.ui-menu-item')[filter]();
}
this.focus(event, next);
},
/**
* @param {jQuery.Event} event
*/
nextPage: function (event) {
var item, base, height;
if (!this.active) {
this.next(event);
return;
}
if (this.isLastItem()) {
return;
}
if (this._hasScroll()) {
base = this.active.offset().top;
height = this.element.height();
this.active.nextAll('.ui-menu-item').each(function () {
item = $(this);
return item.offset().top - base - height < 0;
});
this.focus(event, item);
} else {
this.focus(event, this.activeMenu.children('.ui-menu-item')
[!this.active ? 'first' : 'last']());
}
},
/**
* @param {jQuery.Event} event
*/
previousPage: function (event) {
var item, base, height;
if (!this.active) {
this.next(event);
return;
}
if (this.isFirstItem()) {
return;
}
if (this._hasScroll()) {
base = this.active.offset().top;
height = this.element.height();
this.active.prevAll('.ui-menu-item').each(function () {
item = $(this);
return item.offset().top - base + height > 0;
});
this.focus(event, item);
} else {
this.focus(event, this.activeMenu.children('.ui-menu-item').first());
}
},
/**
* @return {Boolean}
* @private
*/
_hasScroll: function () {
return this.element.outerHeight() < this.element.prop('scrollHeight');
},
/**
* @param {jQuery.Event} event
*/
select: function (event) {
// TODO: It should never be possible to not have an active item at this
// point, but the tests don't trigger mouseenter before click.
var ui;
this.active = this.active || $(event.target).closest('.ui-menu-item');
ui = {
item: this.active
};
if (!this.active.has('.ui-menu').length) {
this.collapseAll(event, true);
}
this._trigger('select', event, ui);
}
});
return $.mage.menu;
});
+84
View File
@@ -0,0 +1,84 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'mage/template',
'jquery/ui'
], function ($, mageTemplate) {
'use strict';
$.widget('mage.notification', {
options: {
templates: {
global: '<div data-role="messages" id="messages">' +
'<div class="message <% if (data.error) { %>error<% } %>"><div><%- data.message %></div></div>' +
'</div>',
error: '<div data-role="messages" id="messages">' +
'<div class="messages"><div class="message message-error error">' +
'<div data-ui-id="messages-message-error"><%- data.message %></div></div>' +
'</div></div>'
}
},
placeholder: '[data-role=messages]',
/**
* Notification creation
* @protected
*/
_create: function () {
$(document).on('ajaxComplete ajaxError', $.proxy(this._add, this));
},
/**
* Add new message
* @protected
* @param {Object} event - object
* @param {Object} jqXHR - The jQuery XMLHttpRequest object returned by $.ajax()
*/
_add: function (event, jqXHR) {
var response;
try {
response = JSON.parse(jqXHR.responseText);
if (response && response.error && response['html_message']) {
$(this.placeholder).html(response['html_message']);
}
} catch (e) {}
},
/**
* Adds new message.
*
* @param {Object} data - Data with a message to be displayed.
*/
add: function (data) {
var template = data.error ? this.options.templates.error : this.options.templates.global,
message = mageTemplate(template, {
data: data
}),
messageContainer;
if (typeof data.insertMethod === 'function') {
data.insertMethod(message);
} else {
messageContainer = data.messageContainer || this.placeholder;
$(messageContainer).prepend(message);
}
return this;
},
/**
* Removes error messages.
*/
clear: function () {
$(this.placeholder).html('');
}
});
return $.mage.notification;
});
File diff suppressed because it is too large Load Diff
+429
View File
@@ -0,0 +1,429 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global FORM_KEY */
define([
'jquery',
'jquery/ui',
'jquery/ui-modules/widgets/tabs'
], function ($) {
'use strict';
var rhash, isLocal;
// mage.tabs base functionality
$.widget('mage.tabs', $.ui.tabs, {
options: {
spinner: false,
groups: null,
tabPanelClass: '',
excludedPanel: ''
},
/**
* Tabs creation
* @protected
*/
_create: function () {
var activeIndex = this._getTabIndex(this.options.active);
this.options.active = activeIndex >= 0 ? activeIndex : 0;
this._super();
},
/**
* @override
* @private
* @return {Array} Array of DOM-elements
*/
_getList: function () {
if (this.options.groups) {
return this.element.find(this.options.groups);
}
return this._super();
},
/**
* Get active anchor
* @return {Element}
*/
activeAnchor: function () {
return this.anchors.eq(this.option('active'));
},
/**
* Get tab index by tab id
* @protected
* @param {String} id - id of tab
* @return {Number}
*/
_getTabIndex: function (id) {
var anchors = this.anchors ?
this.anchors :
this._getList().find('> li > a[href]');
return anchors.index($('#' + id));
},
/**
* Switch between tabs
* @protected
* @param {Object} event - event object
* @param {undefined|Object} eventData
*/
_toggle: function (event, eventData) {
var anchor = $(eventData.newTab).find('a');
if ($(eventData.newTab).find('a').data().tabType === 'link') {
location.href = anchor.prop('href');
} else {
this._superApply(arguments);
}
}
});
rhash = /#.*$/;
/**
* @param {*} anchor
* @return {Boolean}
*/
isLocal = function (anchor) {
return anchor.hash.length > 1 &&
anchor.href.replace(rhash, '') ===
location.href.replace(rhash, '')
// support: Safari 5.1
// Safari 5.1 doesn't encode spaces in window.location
// but it does encode spaces from anchors (#8777)
.replace(/\s/g, '%20');
};
// Extension for mage.tabs - Move panels in destination element
$.widget('mage.tabs', $.mage.tabs, {
/**
* Move panels in destination element on creation
* @protected
* @override
*/
_create: function () {
this._super();
this._movePanelsInDestination(this.panels);
},
/**
* Get panel for tab. If panel no exist in tabs container, then find panel in destination element
* @protected
* @override
* @param {Element} tab - tab "li" DOM-element
* @return {Element}
*/
_getPanelForTab: function (tab) {
var panel = this._superApply(arguments),
id;
if (!panel.length) {
id = $(tab).attr('aria-controls');
panel = $(this.options.destination).find(this._sanitizeSelector('#' + id));
}
return panel;
},
/**
* @private
*/
_processTabs: function () {
var that = this;
this.tablist = this._getList()
.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all')
.attr('role', 'tablist');
this.tabs = this.tablist.find('> li:has(a[href])')
.addClass('ui-state-default ui-corner-top')
.attr({
role: 'tab',
tabIndex: -1
});
this.anchors = this.tabs.map(function () {
return $('a', this)[ 0 ];
})
.addClass('ui-tabs-anchor')
.attr({
role: 'presentation',
tabIndex: -1
});
this.panels = $();
this.anchors.each(function (i, anchor) {
var selector, panel, panelId,
anchorId = $(anchor).uniqueId().attr('id'),
tab = $(anchor).closest('li'),
originalAriaControls = tab.attr('aria-controls');
// inline tab
if (isLocal(anchor)) {
selector = anchor.hash;
panel = that.document.find(that._sanitizeSelector(selector));
// remote tab
} else {
panelId = tab.attr('aria-controls') || $({}).uniqueId()[ 0 ].id;
selector = '#' + panelId;
panel = that.element.find(selector);
if (!panel.length) {
panel = that._createPanel(panelId);
panel.insertAfter(that.panels[ i - 1 ] || that.tablist);
}
panel.attr('aria-live', 'polite');
}
if (panel.length) {
that.panels = that.panels.add(panel);
}
if (originalAriaControls) {
tab.data('ui-tabs-aria-controls', originalAriaControls);
}
tab.attr({
'aria-controls': selector.substring(1),
'aria-labelledby': anchorId
});
panel.attr('aria-labelledby', anchorId);
if (that.options.excludedPanel.indexOf(anchorId + '_content') < 0) {
panel.addClass(that.options.tabPanelClass);
}
});
this.panels
.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
.attr('role', 'tabpanel');
},
/**
* Move panels in destination element
* @protected
* @override
*/
_movePanelsInDestination: function (panels) {
if (this.options.destination && !panels.parents(this.options.destination).length) {
this.element.trigger('beforePanelsMove', panels);
panels.find('script:not([type]), script[type="text/javascript"]').remove();
panels.appendTo(this.options.destination)
.each($.proxy(function (i, panel) {
$(panel).trigger('move.tabs', this.anchors.eq(i));
}, this));
}
},
/**
* Move panels in destination element on tabs switching
* @protected
* @override
* @param {Object} event - event object
* @param {Object} eventData
*/
_toggle: function (event, eventData) {
this._movePanelsInDestination(eventData.newPanel);
this._superApply(arguments);
}
});
// Extension for mage.tabs - Ajax functionality for tabs
$.widget('mage.tabs', $.mage.tabs, {
options: {
/**
* Add form key to ajax call
* @param {Object} event - event object
* @param {Object} ui
*/
beforeLoad: function (event, ui) {
ui.ajaxSettings.type = 'POST';
ui.ajaxSettings.hasContent = true;
ui.jqXHR.setRequestHeader('Content-Type', ui.ajaxSettings.contentType);
ui.ajaxSettings.data = jQuery.param(
{
isAjax: true,
'form_key': typeof FORM_KEY !== 'undefined' ? FORM_KEY : null
},
ui.ajaxSettings.traditional
);
},
/**
* Replacing href attribute with loaded panel id
* @param {Object} event - event object
* @param {Object} ui
*/
load: function (event, ui) {
var panel = $(ui.panel);
$(ui.tab).prop('href', '#' + panel.prop('id'));
panel.trigger('contentUpdated');
}
}
});
// Extension for mage.tabs - Attach event handlers to tabs
$.widget('mage.tabs', $.mage.tabs, {
options: {
tabIdArgument: 'tab',
tabsBlockPrefix: null
},
/**
* Attach event handlers to tabs, on creation
* @protected
* @override
*/
_refresh: function () {
this._super();
$.each(this.tabs, $.proxy(function (i, tab) {
$(this._getPanelForTab(tab))
.off('changed' + this.eventNamespace)
.off('highlight.validate' + this.eventNamespace)
.off('focusin' + this.eventNamespace)
.on('changed' + this.eventNamespace, {
index: i
}, $.proxy(this._onContentChange, this))
.on('highlight.validate' + this.eventNamespace, {
index: i
}, $.proxy(this._onInvalid, this))
.on('focusin' + this.eventNamespace, {
index: i
}, $.proxy(this._onFocus, this));
}, this));
($(this.options.destination).is('form') ?
$(this.options.destination) :
$(this.options.destination).closest('form'))
.off('beforeSubmit' + this.eventNamespace)
.on('beforeSubmit' + this.eventNamespace, $.proxy(this._onBeforeSubmit, this));
},
/**
* Mark tab as changed if some field inside tab panel is changed
* @protected
* @param {Object} e - event object
*/
_onContentChange: function (e) {
var cssChanged = '_changed';
this.anchors.eq(e.data.index).addClass(cssChanged);
this._updateNavTitleMessages(e, cssChanged);
},
/**
* Clone messages (tooltips) from anchor to parent element
* @protected
* @param {Object} e - event object
* @param {String} messageType - changed or error
*/
_updateNavTitleMessages: function (e, messageType) {
var curAnchor = this.anchors.eq(e.data.index),
curItem = curAnchor.parents('[data-role="container"]').find('[data-role="title"]'),
curItemMessages = curItem.find('[data-role="title-messages"]'),
activeClass = '_active';
if (curItemMessages.is(':empty')) {
curAnchor
.find('[data-role="item-messages"]')
.clone()
.appendTo(curItemMessages);
}
curItemMessages.find('.' + messageType).addClass(activeClass);
},
/**
* Mark tab as error if some field inside tab panel is not passed validation
* @param {Object} e - event object
* @protected
*/
_onInvalid: function (e) {
var cssError = '_error',
fakeEvent = e;
fakeEvent.currentTarget = $(this.anchors).eq(e.data.index);
this._eventHandler(fakeEvent);
this.anchors.eq(e.data.index).addClass(cssError).find('.' + cssError).show();
this._updateNavTitleMessages(e, cssError);
},
/**
* Show tab panel if focus event triggered of some field inside tab panel
* @param {Object} e - event object
* @protected
*/
_onFocus: function (e) {
this.option('_active', e.data.index);
},
/**
* Add active tab id in data object when "beforeSubmit" event is triggered
* @param {Object} e - event object
* @param {Object} data - event data object
* @protected
*/
_onBeforeSubmit: function (e, data) { //eslint-disable-line no-unused-vars
var activeAnchor = this.activeAnchor(),
activeTabId = activeAnchor.prop('id'),
options;
if (this.options.tabsBlockPrefix) {
if (activeAnchor.is('[id*="' + this.options.tabsBlockPrefix + '"]')) {
activeTabId = activeAnchor.prop('id').substr(this.options.tabsBlockPrefix.length);
}
}
$(this.anchors).removeClass('error');
options = {
action: {
args: {}
}
};
options.action.args[this.options.tabIdArgument] = activeTabId;
}
});
// Extension for mage.tabs - Shadow tabs functionality
$.widget('mage.tabs', $.mage.tabs, {
/**
* Add shadow tabs functionality on creation
* @protected
* @override
*/
_refresh: function () {
var anchors, shadowTabs, tabs;
this._super();
anchors = this.anchors;
shadowTabs = this.options.shadowTabs;
tabs = this.tabs;
if (shadowTabs) {
anchors.each($.proxy(function (i, anchor) {
var anchorId = $(anchor).prop('id');
if (shadowTabs[anchorId]) {
$(anchor).parents('li').on('click', $.proxy(function () {
$.each(shadowTabs[anchorId], $.proxy(function (key, id) {
this.load($(tabs).index($('#' + id).parents('li')), {});
}, this));
}, this));
}
}, this));
}
}
});
return $.mage.tabs;
});
+269
View File
@@ -0,0 +1,269 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'jquery/ui',
'jquery/jstree/jquery.jstree',
'mage/backend/suggest'
], function ($) {
'use strict';
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
var hover_node, dehover_node, select_node, init;
$.extend(true, $, {
// @TODO: Move method 'treeToList' in file with utility functions
mage: {
/**
* @param {Array} list
* @param {Object} nodes
* @param {*} level
* @param {*} path
* @return {*}
*/
treeToList: function (list, nodes, level, path) {
$.each(nodes, function () {
if (typeof this === 'object') {
list.push({
label: this.label,
id: this.id,
level: level,
item: this,
path: path + this.label
});
if (this.children) {
$.mage.treeToList(list, this.children, level + 1, path + this.label + ' / ');
}
}
});
return list;
}
}
});
hover_node = $.jstree.core.prototype.hover_node;
dehover_node = $.jstree.core.prototype.dehover_node;
select_node = $.jstree.core.prototype.select_node;
init = $.jstree.core.prototype.init;
$.extend(true, $.jstree.core.prototype, {
/**
* @override
*/
init: function () {
this.get_container()
.show()
.on('keydown', $.proxy(function (e) {
var o;
if (e.keyCode === $.ui.keyCode.ENTER) {
o = this.data.ui.hovered || this.data.ui.last_selected || -1;
this.select_node(o, true);
}
}, this));
init.call(this);
},
/**
* @override
*/
hover_node: function (obj) {
hover_node.apply(this, arguments);
obj = this._get_node(obj);
if (!obj.length) {
return false;
}
this.get_container().trigger('hover_node', [{
item: obj.find('a:first')
}]);
},
/**
* @override
*/
dehover_node: function () {
dehover_node.call(this);
this.get_container().trigger('dehover_node');
},
/**
* @override
*/
select_node: function (o) {
var node;
select_node.apply(this, arguments);
node = this._get_node(o);
(node ? $(node) : this.data.ui.last_selected)
.trigger('select_tree_node');
}
});
$.widget('mage.treeSuggest', $.mage.suggest, {
widgetEventPrefix: 'suggest',
options: {
template:
'<% if (data.items.length) { %>' +
'<% if (data.allShown()) { %>' +
'<% if (typeof data.nested === "undefined") { %>' +
'<div style="display:none;" data-mage-init="{&quot;jstree&quot;:{&quot;plugins&quot;:[&quot;themes&quot;,&quot;html_data&quot;,&quot;ui&quot;,&quot;hotkeys&quot;],&quot;themes&quot;:{&quot;theme&quot;:&quot;default&quot;,&quot;dots&quot;:false,&quot;icons&quot;:false}}}">' + //eslint-disable-line max-len
'<% } %>' +
'<ul>' +
'<% _.each(data.items, function(value) { %>' +
'<li class="<% if (data.itemSelected(value)) { %>mage-suggest-selected<% } %>' +
' <% if (value.is_active == 0) { %> mage-suggest-not-active<% } %>">' +
'<a href="#" <%= data.optionData(value) %>><%- value.label %></a>' +
'<% if (value.children && value.children.length) { %>' +
'<%= data.renderTreeLevel(value.children) %>' +
'<% } %>' +
'</li>' +
'<% }); %>' +
'</ul>' +
'<% if (typeof data.nested === "undefined") { %>' +
'</div>' +
'<% } %>' +
'<% } else { %>' +
'<ul data-mage-init="{&quot;menu&quot;:[]}">' +
'<% _.each(data.items, function(value) { %>' +
'<% if (!data.itemSelected(value)) {%>' +
'<li <%= data.optionData(value) %>>' +
'<a href="#">' +
'<span class="category-label"><%- value.label %></span>' +
'<span class="category-path"><%- value.path %></span>' +
'</a>' +
'</li>' +
'<% } %>' +
'<% }); %>' +
'</ul>' +
'<% } %>' +
'<% } else { %>' +
'<span class="mage-suggest-no-records"><%- data.noRecordsText %></span>' +
'<% } %>',
controls: {
selector: ':ui-menu, :mage-menu, .jstree',
eventsMap: {
focus: ['menufocus', 'hover_node'],
blur: ['menublur', 'dehover_node'],
select: ['menuselect', 'select_tree_node']
}
}
},
/**
* @override
*/
_bind: function () {
this._super();
this._on({
/**
* @param {jQuery.Event} event
*/
keydown: function (event) {
var keyCode = $.ui.keyCode;
switch (event.keyCode) {
case keyCode.LEFT:
case keyCode.RIGHT:
if (this.isDropdownShown()) {
event.preventDefault();
this._proxyEvents(event);
}
break;
}
}
});
},
/**
* @override
*/
close: function (e) {
var eType = e ? e.type : null;
if (eType === 'select_tree_node') {
this.element.focus();
} else {
this._superApply(arguments);
}
},
/**
* @override
*/
_filterSelected: function (items, context) {
if (context._allShown) {
return items;
}
return this._superApply(arguments);
},
/**
* @override
*/
_prepareDropdownContext: function () {
var context = this._superApply(arguments),
optionData = context.optionData,
templates = this.templates,
tmplName = this.templateName;
/**
* @param {Object} item
* @return {*|String}
*/
context.optionData = function (item) {
item = $.extend({}, item);
delete item.children;
return optionData(item);
};
return $.extend(context, {
/**
* @param {*} children
* @return {*|jQuery}
*/
renderTreeLevel: function (children) {
var _context = $.extend({}, this, {
items: children,
nested: true
}),
tmpl = templates[tmplName];
tmpl = tmpl({
data: _context
});
return $('<div>').append($(tmpl)).html();
}
});
},
/**
* @override
*/
_processResponse: function (e, items, context) {
var control;
if (context && !context._allShown) {
items = this.filter($.mage.treeToList([], items, 0, ''), this._term);
}
control = this.dropdown.find(this._control.selector);
if (control.length && control.hasClass('jstree')) {
control.jstree('destroy');
}
this._superApply([e, items, context]);
}
});
return $.mage.treeSuggest;
});
+302
View File
@@ -0,0 +1,302 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* global BASE_URL, alertAlreadyDisplayed */
define([
'jquery',
'underscore',
'Magento_Ui/js/modal/alert',
'jquery/ui',
'jquery/validate',
'mage/translate',
'mage/validation'
], function ($, _, alert) {
'use strict';
$.extend(true, $.validator.prototype, {
/**
* Focus invalid fields
*/
focusInvalid: function () {
if (this.settings.focusInvalid) {
try {
$(this.errorList.length && this.errorList[0].element || [])
.trigger('focus')
.trigger('focusin');
} catch (e) {
// ignore IE throwing errors when focusing hidden elements
}
}
},
/**
* Elements.
*/
elements: function () {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find('input, select, textarea')
.not(this.settings.forceIgnore)
.not(':submit, :reset, :image, [disabled]')
.not(this.settings.ignore)
.filter(function () {
if (!this.name && validator.settings.debug && window.console) {
console.error('%o has no name assigned', this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
}
});
$.extend($.fn, {
/**
* ValidationDelegate overridden for those cases where the form is located in another form,
* to avoid not correct working of validate plug-in
* @override
* @param {String} delegate - selector, if event target matched against this selector,
* then event will be delegated
* @param {String} type - event type
* @param {Function} handler - event handler
* @return {Element}
*/
validateDelegate: function (delegate, type, handler) {
return this.on(type, $.proxy(function (event) {
var target = $(event.target),
form = target[0].form;
if (form && $(form).is(this) && $.data(form, 'validator') && target.is(delegate)) {
return handler.apply(target, arguments);
}
}, this));
}
});
$.widget('mage.validation', $.mage.validation, {
options: {
messagesId: 'messages',
forceIgnore: '',
ignore: ':disabled, .ignore-validate, .no-display.template, ' +
':disabled input, .ignore-validate input, .no-display.template input, ' +
':disabled select, .ignore-validate select, .no-display.template select, ' +
':disabled textarea, .ignore-validate textarea, .no-display.template textarea',
errorElement: 'label',
errorUrl: typeof BASE_URL !== 'undefined' ? BASE_URL : null,
/**
* @param {HTMLElement} element
*/
highlight: function (element) {
if ($.validator.defaults.highlight && typeof $.validator.defaults.highlight === 'function') {
$.validator.defaults.highlight.apply(this, arguments);
}
$(element).trigger('highlight.validate');
},
/**
* @param {HTMLElement} element
*/
unhighlight: function (element) {
if ($.validator.defaults.unhighlight && typeof $.validator.defaults.unhighlight === 'function') {
$.validator.defaults.unhighlight.apply(this, arguments);
}
$(element).trigger('unhighlight.validate');
}
},
/**
* Validation creation
* @protected
*/
_create: function () {
if (!this.options.submitHandler && typeof this.options.submitHandler !== 'function') {
if (!this.options.frontendOnly && this.options.validationUrl) {
this.options.submitHandler = $.proxy(this._ajaxValidate, this);
} else {
this.options.submitHandler = $.proxy(this._submit, this);
}
}
this.element.on('resetElement', function (e) {
$(e.target).rules('remove');
});
this._super('_create');
},
/**
* ajax validation
* @protected
*/
_ajaxValidate: function () {
$.ajax({
url: this.options.validationUrl,
type: 'POST',
dataType: 'json',
data: this.element.serialize(),
context: $('body'),
success: $.proxy(this._onSuccess, this),
error: $.proxy(this._onError, this),
showLoader: true,
dontHide: false
});
},
/**
* Process ajax success.
*
* @protected
* @param {Object} response
*/
_onSuccess: function (response) {
if (!response.error) {
this._submit();
} else {
this._showErrors(response);
$(this.element[0]).trigger('afterValidate.error');
$('body').trigger('processStop');
}
},
/**
* Submitting a form.
* @private
*/
_submit: function () {
$(this.element[0]).trigger('afterValidate.beforeSubmit');
this.element[0].submit();
},
/**
* Displays errors after backend validation.
*
* @param {Object} data - Data that came from backend.
*/
_showErrors: function (data) {
$('body').notification('clear')
.notification('add', {
error: data.error,
message: data.message,
/**
* @param {*} message
*/
insertMethod: function (message) {
$('.messages:first').html(message);
}
});
},
/**
* Tries to retrieve element either by id or by inputs' name property.
* @param {String} code - String to search by.
* @returns {jQuery} jQuery element.
*/
_getByCode: function (code) {
var parent = this.element[0],
element;
element = parent.querySelector('#' + code) || parent.querySelector('input[name=' + code + ']');
return $(element);
},
/**
* Process ajax error
* @protected
*/
_onError: function () {
$(this.element[0]).trigger('afterValidate.error');
$('body').trigger('processStop');
if (this.options.errorUrl) {
location.href = this.options.errorUrl;
}
}
});
_.each({
'validate-greater-zero-based-on-option': [
function (v, el) {
var optionType = $(el)
.closest('.form-list')
.prev('.fieldset-alt')
.find('select.select-product-option-type'),
optionTypeVal = optionType.val();
v = Number(v) || 0;
if (optionType && (optionTypeVal == 'checkbox' || optionTypeVal == 'multi') && v <= 0) { //eslint-disable-line
return false;
}
return true;
},
$.mage.__('Please enter a number greater 0 in this field.')
],
'validate-rating': [
function () {
var ratings = $('#detailed_rating').find('.field-rating'),
noError = true;
ratings.each(function (index, rating) {
noError = noError && $(rating).find('input:checked').length > 0;
});
return noError;
},
$.mage.__('Please select one of each ratings above.')
],
'validate-downloadable-file': [
function (v, element) {
var elmParent = $(element).parent(),
linkType = elmParent.find('input[value="file"]'),
newFileContainer;
if (linkType.is(':checked') && (v === '' || v === '[]')) {
newFileContainer = elmParent.find('.new-file');
if (!alertAlreadyDisplayed && (newFileContainer.empty() || newFileContainer.is(':visible'))) {
window.alertAlreadyDisplayed = true;
alert({
content: $.mage.__('There are files that were selected but not uploaded yet. ' +
'Please upload or remove them first')
});
}
return false;
}
return true;
},
'Please upload a file.'
],
'validate-downloadable-url': [
function (v, element) {
var linkType = $(element).parent().find('input[value="url"]');
if (linkType.is(':checked') && v === '') {
return false;
}
return true;
},
$.mage.__('Please specify Url.')
]
}, function (rule, i) {
rule.unshift(i);
$.validator.addMethod.apply($.validator, rule);
});
return $.mage.validation;
});