forked from magento/magento2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmenu.js
819 lines (687 loc) · 27.9 KB
/
menu.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'matchMedia',
'jquery/ui',
'jquery/jquery.mobile.custom',
'mage/translate'
], function ($, mediaCheck) {
'use strict';
/**
* Menu Widget - this widget is a wrapper for the jQuery UI Menu
*/
$.widget('mage.menu', $.ui.menu, {
options: {
responsive: false,
expanded: false,
showDelay: 42,
hideDelay: 300,
delay: 300,
mediaBreakpoint: '(max-width: 768px)'
},
/**
* @private
*/
_create: function () {
var self = this;
this.delay = this.options.delay;
this._super();
$(window).on('resize', function () {
self.element.find('.submenu-reverse').removeClass('submenu-reverse');
});
},
/**
* @private
*/
_init: function () {
this._super();
if (this.options.expanded === true) {
this.isExpanded();
}
if (this.options.responsive === true) {
mediaCheck({
media: this.options.mediaBreakpoint,
entry: $.proxy(function () {
this._toggleMobileMode();
}, this),
exit: $.proxy(function () {
this._toggleDesktopMode();
}, this)
});
}
this._assignControls()._listen();
this._setActiveMenu();
},
/**
* @return {Object}
* @private
*/
_assignControls: function () {
this.controls = {
toggleBtn: $('[data-action="toggle-nav"]'),
swipeArea: $('.nav-sections')
};
return this;
},
/**
* @private
*/
_listen: function () {
var controls = this.controls,
toggle = this.toggle;
this._on(controls.toggleBtn, {
'click': toggle
});
this._on(controls.swipeArea, {
'swipeleft': toggle
});
},
/**
* Toggle.
*/
toggle: function () {
var html = $('html');
if (html.hasClass('nav-open')) {
html.removeClass('nav-open');
setTimeout(function () {
html.removeClass('nav-before-open');
}, this.options.hideDelay);
} else {
html.addClass('nav-before-open');
setTimeout(function () {
html.addClass('nav-open');
}, this.options.showDelay);
}
},
/**
* Tries to figure out the active category for current page and add appropriate classes:
* - 'active' class for active category
* - 'has-active' class for all parents of active category
*
* First, checks whether current URL is URL of category page,
* otherwise tries to retrieve category URL in case of current URL is product view page URL
* which has category tree path in it.
*
* @return void
* @private
*/
_setActiveMenu: function () {
var currentUrl = window.location.href.split('?')[0];
if (!this._setActiveMenuForCategory(currentUrl)) {
this._setActiveMenuForProduct(currentUrl);
}
},
/**
* Looks for category with provided URL and adds 'active' CSS class to it if it was not set before.
* If menu item has parent categories, sets 'has-active' class to all af them.
*
* @param {String} url - possible category URL
* @returns {Boolean} - true if active category was founded by provided URL, otherwise return false
* @private
*/
_setActiveMenuForCategory: function (url) {
var activeCategoryLink = this.element.find('a[href="' + url + '"]'),
classes,
classNav;
if (!activeCategoryLink || !activeCategoryLink.hasClass('ui-corner-all')) {
//category was not found by provided URL
return false;
} else if (!activeCategoryLink.parent().hasClass('active')) {
activeCategoryLink.parent().addClass('active');
classes = activeCategoryLink.parent().attr('class');
classNav = classes.match(/(nav\-)[0-9]+(\-[0-9]+)+/gi);
if (classNav) {
this._setActiveParent(classNav[0]);
}
}
return true;
},
/**
* Sets 'has-active' CSS class to all parent categories which have part of provided class in childClassName
*
* @example
* childClassName - 'nav-1-2-3'
* CSS class 'has-active' will be added to categories have 'nav-1-2' and 'nav-1' classes
*
* @param {String} childClassName - Class name of active category <li> element
* @return void
* @private
*/
_setActiveParent: function (childClassName) {
var parentElement,
parentClass = childClassName.substr(0, childClassName.lastIndexOf('-'));
if (parentClass.lastIndexOf('-') !== -1) {
parentElement = this.element.find('.' + parentClass);
if (parentElement) {
parentElement.addClass('has-active');
}
this._setActiveParent(parentClass);
}
},
/**
* Tries to retrieve category URL from current URL and mark this category as active
* @see _setActiveMenuForCategory(url)
*
* @example
* currentUrl - http://magento.com/category1/category12/product.html,
* category URLs has extensions .phtml - http://magento.com/category1.phtml
* method sets active category which has URL http://magento.com/category1/category12.phtml
*
* @param {String} currentUrl - current page URL without parameters
* @return void
* @private
*/
_setActiveMenuForProduct: function (currentUrl) {
var categoryUrlExtension,
lastUrlSection,
possibleCategoryUrl,
//retrieve first category URL to know what extension is used for category URLs
firstCategoryUrl = this.element.find('> li a').attr('href');
if (firstCategoryUrl) {
lastUrlSection = firstCategoryUrl.substr(firstCategoryUrl.lastIndexOf('/'));
categoryUrlExtension = lastUrlSection.lastIndexOf('.') !== -1 ?
lastUrlSection.substr(lastUrlSection.lastIndexOf('.')) : '';
possibleCategoryUrl = currentUrl.substr(0, currentUrl.lastIndexOf('/')) + categoryUrlExtension;
this._setActiveMenuForCategory(possibleCategoryUrl);
}
},
/**
* Add class for expanded option.
*/
isExpanded: function () {
var subMenus = this.element.find(this.options.menus),
expandedMenus = subMenus.find(this.options.menus);
expandedMenus.addClass('expanded');
},
/**
* @param {jQuery.Event} event
* @private
*/
_activate: function (event) {
window.location.href = this.active.find('> a').attr('href');
this.collapseAll(event);
},
/**
* @param {jQuery.Event} event
* @private
*/
_keydown: function (event) {
var match, prev, character, skip, regex,
preventDefault = true;
/* eslint-disable max-depth */
/**
* @param {String} value
*/
function escape(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
}
if (this.active.closest(this.options.menus).attr('aria-expanded') != 'true') { //eslint-disable-line eqeqeq
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:
if (this.active && !this.active.is('.ui-state-disabled')) {
this.expand(event);
}
break;
case $.ui.keyCode.LEFT:
this.previous(event);
break;
case $.ui.keyCode.RIGHT:
this.next(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) {
this.previousFilter = character;
this.filterTimer = this._delay(function () {
delete this.previousFilter;
}, 1000);
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
} else {
switch (event.keyCode) {
case $.ui.keyCode.DOWN:
this.next(event);
break;
case $.ui.keyCode.UP:
this.previous(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.LEFT:
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) {
this.previousFilter = character;
this.filterTimer = this._delay(function () {
delete this.previousFilter;
}, 1000);
} else {
delete this.previousFilter;
}
} else {
delete this.previousFilter;
}
}
}
/* eslint-enable max-depth */
if (preventDefault) {
event.preventDefault();
}
},
/**
* @private
*/
_toggleMobileMode: function () {
var subMenus;
$(this.element).off('mouseenter mouseleave');
this._on({
/**
* @param {jQuery.Event} event
*/
'click .ui-menu-item:has(a)': function (event) {
var target;
event.preventDefault();
target = $(event.target).closest('.ui-menu-item');
if (!target.hasClass('level-top') || !target.has('.ui-menu').length) {
window.location.href = target.find('> a').attr('href');
}
},
/**
* @param {jQuery.Event} event
*/
'click .ui-menu-item:has(.ui-state-active)': function (event) {
this.collapseAll(event, true);
}
});
subMenus = this.element.find('.level-top');
$.each(subMenus, $.proxy(function (index, item) {
var category = $(item).find('> a span').not('.ui-menu-icon').text(),
categoryUrl = $(item).find('> a').attr('href'),
menu = $(item).find('> .ui-menu');
this.categoryLink = $('<a>')
.attr('href', categoryUrl)
.text($.mage.__('All ') + category);
this.categoryParent = $('<li>')
.addClass('ui-menu-item all-category')
.html(this.categoryLink);
if (menu.find('.all-category').length === 0) {
menu.prepend(this.categoryParent);
}
}, this));
},
/**
* @private
*/
_toggleDesktopMode: function () {
var categoryParent, html;
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 {jQuer.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.select(event);
// Only set the mouseHandled flag if the event will bubble, see #9469.
if (!event.isPropagationStopped()) {
this.mouseHandled = true;
}
// Open submenu on click
if (target.has('.ui-menu').length) {
this.expand(event);
} else if (!this.element.is(':focus') &&
$(this.document[0].activeElement).closest('.ui-menu').length
) {
// 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),
submenu = this.options.menus,
ulElement,
ulElementWidth,
width,
targetPageX,
rightBound;
if (target.has(submenu)) {
ulElement = target.find(submenu);
ulElementWidth = ulElement.outerWidth(true);
width = target.outerWidth() * 2;
targetPageX = target.offset().left;
rightBound = $(window).width();
if (ulElementWidth + width + targetPageX > rightBound) {
ulElement.addClass('submenu-reverse');
}
if (targetPageX - ulElementWidth < 0) {
ulElement.removeClass('submenu-reverse');
}
}
// 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);
},
/**
* @param {jQuery.Event} event
*/
'mouseleave': function (event) {
this.collapseAll(event, true);
},
/**
* Mouse leave.
*/
'mouseleave .ui-menu': 'collapseAll'
});
categoryParent = this.element.find('.all-category');
html = $('html');
categoryParent.remove();
if (html.hasClass('nav-open')) {
html.removeClass('nav-open');
setTimeout(function () {
html.removeClass('nav-before-open');
}, this.options.hideDelay);
}
},
/**
* @param {*} handler
* @param {Number} delay
* @return {Number}
* @private
*/
_delay: function (handler, delay) {
var instance = this,
/**
* @return {*}
*/
handlerProxy = function () {
return (typeof handler === 'string' ? instance[handler] : handler).apply(instance, arguments);
};
return setTimeout(handlerProxy, delay || 0);
},
/**
* @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) {
if (newItem.closest('.ui-menu').is(':visible') &&
newItem.closest('.ui-menu').has('.all-categories')
) {
return;
}
// remove the active state class from the siblings
this.active.siblings().children('.ui-state-active').removeClass('ui-state-active');
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
*/
select: function (event) {
var ui;
this.active = this.active || $(event.target).closest('.ui-menu-item');
if (this.active.is('.all-category')) {
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);
}
});
$.widget('mage.navigation', $.mage.menu, {
options: {
responsiveAction: 'wrap', //option for responsive handling
maxItems: null, //option to set max number of menu items
container: '#menu', //container to check against navigation length
moreText: $.mage.__('more'),
breakpoint: 768
},
/**
* @private
*/
_init: function () {
var that, responsive;
this._super();
that = this;
responsive = this.options.responsiveAction;
this.element
.addClass('ui-menu-responsive')
.attr('responsive', 'main');
this.setupMoreMenu();
this.setMaxItems();
//check responsive option
if (responsive == 'onResize') { //eslint-disable-line eqeqeq
$(window).on('resize', function () {
if ($(window).width() > that.options.breakpoint) {
that._responsive();
$('[responsive=more]').show();
} else {
that.element.children().show();
$('[responsive=more]').hide();
}
});
} else if (responsive == 'onReload') { //eslint-disable-line eqeqeq
this._responsive();
}
},
/**
* Setup more menu.
*/
setupMoreMenu: function () {
var moreListItems = this.element.children().clone(),
moreLink = $('<a>' + this.options.moreText + '</a>');
moreListItems.hide();
moreLink.attr('href', '#');
this.moreItemsList = $('<ul>')
.append(moreListItems);
this.moreListContainer = $('<li>')
.append(moreLink)
.append(this.moreItemsList);
this.responsiveMenu = $('<ul>')
.addClass('ui-menu-more')
.attr('responsive', 'more')
.append(this.moreListContainer)
.menu({
position: {
my: 'right top',
at: 'right bottom'
}
})
.insertAfter(this.element);
},
/**
* @private
*/
_responsive: function () {
var container = $(this.options.container),
containerSize = container.width(),
width = 0,
items = this.element.children('li'),
more = $('.ui-menu-more > li > ul > li a');
items = items.map(function () {
var item = {};
item.item = $(this);
item.itemSize = $(this).outerWidth();
return item;
});
$.each(items, function (index) {
var itemText = items[index].item
.find('a:first')
.text();
width += parseInt(items[index].itemSize, null); //eslint-disable-line radix
if (width < containerSize) {
items[index].item.show();
more.each(function () {
var text = $(this).text();
if (text === itemText) {
$(this).parent().hide();
}
});
} else if (width > containerSize) {
items[index].item.hide();
more.each(function () {
var text = $(this).text();
if (text === itemText) {
$(this).parent().show();
}
});
}
});
},
/**
* Set max items.
*/
setMaxItems: function () {
var items = this.element.children('li'),
itemsCount = items.length,
maxItems = this.options.maxItems,
overflow = itemsCount - maxItems,
overflowItems = items.slice(overflow);
overflowItems.hide();
overflowItems.each(function () {
var itemText = $(this).find('a:first').text();
$(this).hide();
$('.ui-menu-more > li > ul > li a').each(function () {
var text = $(this).text();
if (text === itemText) {
$(this).parent().show();
}
});
});
}
});
return {
menu: $.mage.menu,
navigation: $.mage.navigation
};
});