PluginProbe
Filter Everything — WordPress & WooCommerce Filters / 1.2.4
Filter Everything — WordPress & WooCommerce Filters v1.2.4
1.9.7 1.9.6 1.9.5 1.9.4 1.9.3 1.9.2.2 1.9.2.1 trunk 1.2.1 1.2.3 1.2.4 1.2.5 1.3.0 1.3.1 1.3.2 1.4.1 1.4.4 1.4.5 1.4.8 1.4.9 1.5.0 1.5.1 1.6.0 1.6.1 1.6.2 All 52 releases
filter-everything / assets / js / wpc-filter-set-admin.js

wpc-filter-set-admin.js in Filter Everything — WordPress & WooCommerce Filters 1.2.4, at assets/js/wpc-filter-set-admin.js

1,039 lines 35.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /*!
2 * Filter Everything set admin 1.2.3
3 */
4 (function($) {
5 "use strict";
6 let filtersFormValid = false;
7
8 function validateFiltersForm( $el )
9 {
10 let $spinner = $('#publishing-action .spinner');
11 let requestParams = {};
12
13 $spinner.addClass( 'is-active' );
14 /**
15 * @todo checkboxes does not validates correctly because they send the same value !!! IMPORTANT
16 * independently from checked status
17 */
18
19 requestParams.validateData = wpcSerialize( $el );
20
21 wp.ajax.post( 'wpc-validate-filters', requestParams )
22 .always( function() {
23 $spinner.removeClass( 'is-active' );
24 })
25 .done( function( response ) {
26 filtersFormValid = true;
27 $el.submit();
28 })
29 .fail( function( response ) {
30
31 let notices = [];
32 let filterContainer = '';
33
34 if( typeof response.errors !== 'undefined' ){
35 $.each( response.errors, function ( index, error ){
36
37 if( typeof error.id !== 'undefined'){
38 addFieldError( error.id, error.message );
39
40 // Open filter container to show error
41 filterContainer = $('#'+error.id).parents('.wpc-filter-item');
42 openFilter(filterContainer);
43
44 // Open additional fields if errors are there
45 if( $('#'+error.id).parents('.wpc-filter-additional-fields').length > 0 ){
46 openAdditional(filterContainer);
47 }
48 }else{
49 notices.push( error.message );
50 }
51
52 });
53
54 if( notices.length < 1 ){
55 notices.push( 'Error: Set was not saved.' );
56 }
57
58 addNotice( notices );
59 }
60 });
61
62 return false;
63 }
64
65 function removeElement($el)
66 {
67 $el.fadeTo(100, 0, function() {
68 $el.slideUp(100, function() {
69 $el.remove();
70 });
71 });
72 }
73
74 function addFieldError( fieldId, message )
75 {
76 let target = $('#'+fieldId);
77 let html = '<div class="wpc-field-notice wpc-field-notice-error"><p>'+message+'</p></div>';
78 if( typeof target !== 'undefined' ){
79 target.before( html );
80 }
81 }
82
83 function addNotice( messages )
84 {
85 let target = $('form#post');
86 let text = '';
87 $.each( messages, function ( index, message ) {
88 text += '<p>' + message + '</p>';
89 });
90
91 let html = '<div id="message" class="error notice notice-error is-dismissible">'
92 + text +
93 '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>' +
94 '</div>';
95 if( typeof target !== 'undefined' ){
96 if( $("#message").length > 0 ){
97 $("#message").remove();
98 }
99 target.before( html );
100 }
101 }
102
103 function openFilter($el)
104 {
105 let head = $el.find('.wpc-filter-head'),
106 body = head.next('.wpc-filter-body');
107 head.addClass('wpc-opened');
108 body.slideDown({
109 duration: 200,
110 complete: function (){
111 body.addClass('wpc-opened');
112 }
113 });
114 }
115
116 function closeFilter($el)
117 {
118 let head = $el.find('.wpc-filter-head'),
119 body = head.next('.wpc-filter-body');
120
121 head.removeClass('wpc-opened');
122 body.slideUp({
123 duration: 200,
124 complete: function (){
125 body.removeClass('wpc-opened');
126 }
127 });
128 }
129
130 function closeAdditional($el)
131 {
132 $el.find('.wpc-filter-additional-fields').slideUp({
133 duration: 200,
134 complete: function (){
135 $(this).removeClass('wpc-opened');
136 }
137 });
138 }
139
140 function openAdditional($el)
141 {
142 $el.find('.wpc-filter-additional-fields').slideDown({
143 duration: 200,
144 complete: function (){
145 $(this).addClass('wpc-opened');
146 }
147 });
148 }
149
150 function getForbiddenTaxes()
151 {
152 if( typeof wpcSetVars.postTypesTaxList !== 'undefined'){
153 let postType = $('#wpc_set_fields-post_type').val();
154 let allowedTaxes = [];
155 let forbiddenTaxes = [];
156
157 if( typeof wpcSetVars.postTypesTaxList[postType] !== 'undefined' ){
158 $.each( wpcSetVars.postTypesTaxList[postType], function ( iNdex, taxProps ){
159 allowedTaxes.push(taxProps['name']);
160 });
161 }
162
163 $.each( wpcSetVars.postTypesTaxList, function ( pType, taxesArray ){
164 if( pType !== postType ){
165 $.each( taxesArray, function ( index, theTax ){
166 if( allowedTaxes.includes(theTax['name']) === false ){
167 forbiddenTaxes.push(theTax['name']);
168 }
169 } )
170 }
171 });
172
173 return forbiddenTaxes;
174 }
175
176 return [];
177 }
178
179 function getUsedEntities( $inputs, excludeInput )
180 {
181 let usedEntities = [];
182 let currentVal = '';
183 let doNotInclude = ['post_meta', 'post_meta_num', 'post_meta_exists'];
184
185 if( $inputs.length > 0 ){
186 $inputs.each(function(){
187 currentVal = $(this).val();
188
189 if( $(this).attr('id') == excludeInput.attr('id') ){
190 return;
191 }
192
193 if( doNotInclude.includes( currentVal ) ){
194 return;
195 }
196 usedEntities.push( $(this).val() );
197 });
198
199 return usedEntities;
200 }
201 return false;
202 }
203
204 function setAvailableEntities( $el, noChange )
205 {
206 let currentVal = '';
207 let exclude = getUsedEntities( $('.wpc-field-entity'), $el );
208 let forbiddenTaxes = getForbiddenTaxes();
209
210 $el.find('option').each( function (){
211 currentVal = $(this).val();
212
213 if( currentVal === 'post_meta_exists' && ( wpcSetVars.filtersPro < 1) ){
214 return;
215 }
216
217 if( exclude.includes( currentVal ) || forbiddenTaxes.includes(currentVal) ){
218 $(this).attr( 'disabled', 'disabled' );
219 }else{
220 $(this).removeAttr( 'disabled' );
221 }
222 } );
223
224 // If currently selected option is disabled, make first available option selected.
225 let disabled = $el.find('option:selected').attr('disabled');
226 if( disabled === 'disabled' && ! noChange ){
227 $el.find('option:not([disabled]):first').prop('selected', true)
228 .trigger('change');
229 }
230
231 return true;
232 }
233
234 function passNewEntities(select)
235 {
236 let time = 0;
237
238 $('.wpc-new-filter-item .wpc-field-entity').each(function (){
239 let select = $(this);
240 let noChange = false;
241
242 if( $(this).attr('id') == select.attr('id') ){
243 noChange = true;
244 }
245
246 setTimeout( function(){ setAvailableEntities( select, noChange ); }, time);
247 time += 100;
248 });
249 }
250
251 $(document).ready(function (){
252
253 $('form#post').on('submit', function(e){
254
255 // Clear all errors
256 removeElement( $('.wpc-field-notice') );
257
258 // Clear Notice
259 removeElement( $('#message') );
260
261 // Close All Filters
262 closeFilter( $(".wpc-filter-item") );
263
264 if( ! filtersFormValid ){
265 e.preventDefault();
266 // Validate form. We will submit it from validation method
267 validateFiltersForm($(this));
268 }
269 });
270
271 $('.wpc-add-filter').on('click', function (e){
272 e.preventDefault();
273 var html = $('#wpc-new-filter').html();
274 var $el = $(html);
275 var search = 'wpc_new_id';
276 var replace = uniqId('filter_');
277 var replaceAttr = function(i, value){
278 return value.replace( search, replace );
279 }
280
281 $el.find('[id*="' + search + '"]').attr('id', replaceAttr);
282 $el.find('[for*="' + search + '"]').attr('for', replaceAttr);
283 $el.find('[name*="' + search + '"]').attr('name', replaceAttr);
284 $el.data('fid', replace);
285 $el.attr('id', 'wpc-filter-id-'+replace);
286 $('.wpc-filters-list').append($el);
287
288 let select = $el.find('.wpc-field-entity');
289
290 syncEntityWithPrefix(select);
291 handleMetaKeyField(select);
292 setEntityTableClass(select);
293 syncEntityWithView(select);
294 syncEntityWithSortTerms(select);
295
296 // Make already used entities unavailable to selection
297 setAvailableEntities( select );
298 handleHierarchyField( select );
299
300 $el.find('.wpc-field-exclude').select2({
301 width: '100%',
302 placeholder: wpcSelect2Vars.excludePlaceholder,
303 });
304
305 $el.find('.wpc-field-ename').select2({
306 width: '100%',
307 tags: true,
308 placeholder: wpcSelect2Vars.enamePlaceHolder
309 });
310
311 // Fire this event to load exclude terms for first filter
312 if( $('.wpc-filter-item').length === 1 ){
313 select.trigger('change');
314 }
315
316 $('.wpc-help-tip').tipTip({
317 'attribute': 'data-tip',
318 'fadeIn': 50,
319 'fadeOut': 50,
320 'delay': 200,
321 'keepAlive': true,
322 'maxWidth': "220px",
323 });
324
325 openFilter($el);
326
327 renderMenuOrder();
328 handleNoFiltersMessage();
329 /**
330 * @todo There is problem with down arrow when we adding new filter !!! IMPORTANT
331 */
332
333 });
334
335 $('.wpc-form-fields-table:not(.wpc-filter-post_meta_num) .wpc-field-exclude, .wpc-form-fields-table:not(.wpc-filter-post_meta_exists) .wpc-field-exclude').select2({
336
337 width: '100%',
338 placeholder: wpcSelect2Vars.excludePlaceholder
339 });
340
341 $('body').on('click', '.notice-dismiss', function(e){
342 e.preventDefault();
343 removeElement( $('#message') );
344 });
345
346 // Show delete buttons
347 $('body').on('click', '.wpc-button-link-delete', function(e){
348 e.preventDefault();
349 $(this).parents('.wpc-filter-label-td')
350 .next('.wpc-filter-field-td')
351 .children('.wpc-filter-delete-wrapper').css('visibility', 'visible');
352 });
353
354 $('body').on('click', '.wpc-filter-delete-cancel', function(e){
355 e.preventDefault();
356 removeElement( $('.wpc-field-notice') );
357 $(this).parents('.wpc-filter-delete-wrapper').css('visibility', 'hidden');
358 });
359
360 $('body').on('click', '.wpc-done-action', function(e){
361 $(this).parents('.wpc-filter-body').slideToggle(200)
362 .toggleClass('wpc-opened')
363 .children('.wpc-filter-additional-fields').removeClass('wpc-additional-opened')
364 .hide();
365 $(this).parents('.wpc-filter-body').prev('.wpc-filter-head').toggleClass('wpc-opened');
366 // Hide delete buttons
367 $(this).parents('.wpc-filter-field-td')
368 .next('.wpc-filter-field-td')
369 .find('.wpc-filter-delete-wrapper').css('visibility', 'hidden');
370 });
371
372 $('body').on('click', '.wpc-title-action', function(e){
373 let head = $(this).parent('.wpc-filter-head'),
374 body = head.next('.wpc-filter-body');
375 head.toggleClass('wpc-opened');
376 body.slideToggle(200)
377 .toggleClass('wpc-opened')
378 .children('.wpc-filter-additional-fields').removeClass('wpc-additional-opened')
379 .hide();
380 body.find('.wpc-filter-delete-wrapper').css('visibility', 'hidden');
381
382 let moreOptions = body.find('.wpc-more-options-toggle');
383 if( moreOptions.hasClass('wpc-opened') ){
384 moreOptions.trigger('click');
385 }
386 });
387
388 $('body').on('click', '.wpc-more-options-toggle', function(e){
389 e.preventDefault();
390
391 let moreText = $(this).text();
392
393 if( moreText === wpcSetVars.moreOptions ){
394 $(this).text( wpcSetVars.lessOptions);
395 }else{
396 $(this).text( wpcSetVars.moreOptions);
397 }
398
399 $(this).toggleClass('wpc-opened');
400 $(this).parents('.wpc-filter-body').find('.wpc-filter-additional-fields').slideToggle(200)
401 .toggleClass('wpc-additional-opened');
402 });
403
404 $('body').on('change', '.wpc-field-entity', function(e){
405 let select = $(this);
406
407 // Set available entities again
408 passNewEntities(select);
409 syncEntityWithPrefix(select);
410 handleMetaKeyField(select);
411 handleLogicField(select);
412 setEntityTableClass(select);
413 syncEntityWithView(select);
414 syncEntityWithSortTerms(select);
415
416 handleHierarchyField(select);
417
418 // Load terms for exclude
419 let entity = $(this).val();
420 let fid = $(this).parents('.wpc-filter-item').data('fid');
421
422 if( entity === 'post_meta' || entity === 'post_meta_num' || entity === 'post_meta_exists' ){
423 let target = $('#wpc_filter_fields-'+fid+'-exclude');
424 target.select2({
425 disabled: true,
426 width: '100%'
427 });
428 }else{
429 loadExcludeItems(entity, fid);
430 }
431
432 let entityLabel = $(this).find('option:selected').text();
433 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-entity');
434 target.text(entityLabel);
435 });
436
437 // Try to prepend slug if it already exists
438 $('body').on('input change', '.wpc-field-ename', function(){
439 let ename = $(this).val();
440 let fid = $(this).parents('.wpc-filter-item').data('fid');
441 let entity = $('#wpc_filter_fields-'+fid+'-entity').val();
442 let val = '';
443 let slugs = wpcSetVars.filterSlugs;
444
445 if( entity === 'post_meta_num' ){
446 val = 'post_meta_num_' + ename;
447 }else if( entity === 'post_meta_exists' ){
448 val = 'post_meta_exists_' + ename;
449 }else{
450 val = 'post_meta_' + ename;
451 }
452
453 if( typeof slugs[val] !== 'undefined' ){
454 $('#wpc_filter_fields-'+fid+'-slug').val( slugs[val] )
455 .trigger('input');
456
457 // Do not load exclude terms for Post Meta Num and Post Meta Exists
458 if( entity !== 'post_meta_num' ){
459 loadExcludeItems(entity, fid, ename);
460 }
461
462 }else{
463 $('#wpc_filter_fields-'+fid+'-slug').val('')
464 .trigger('input');
465 $('#wpc_filter_fields-'+fid+'-exclude').select2({
466 disabled: true,
467 width: '100%',
468 });
469 }
470 });
471
472 $('body').on('input', '.wpc-field-value-step', function (){
473 $(this).val( $(this).val().replace(/,/g, '.') );
474 $(this).val( $(this).val().replace(/[^\d\.]/g, '') );
475 });
476
477 $('body').on('input', '.wpc-field-slug', function (){
478 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-slug');
479 cpaLiveWrite( $(this), target );
480 });
481
482 $('body').on('input', '.wpc-field-label', function (){
483 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-label');
484 cpaLiveWrite( $(this), target );
485 });
486
487 $('body').on('change', '.wpc-field-view', function(){
488 let val = $(this).find('option:selected').text();
489 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-view');
490 target.text(val);
491 });
492
493 $( '.wpc-filter-set-wrapper .wpc-filters-list' ).sortable({
494 items: "> div.wpc-filter-item",
495 delay: 150,
496 placeholder: "wpc-filter-item-shadow",
497 refreshPositions: true,
498 cursor: 'move',
499 handle: ".wpc-filter-order",
500 axis: 'y',
501 update: function( event, ui ) {
502 renderMenuOrder();
503 },
504 start: function ( event, ui ){
505 var height, $this = $(this), // .wpc-filters-list
506 head = ui.item.children('.wpc-filter-head'),
507 inside = ui.item.children('.wpc-filter-body');
508
509 if (inside.hasClass('wpc-opened') ) {
510 inside.removeClass('wpc-opened')
511 .hide();
512 head.removeClass('wpc-opened');
513 $(this).sortable('refreshPositions');
514 }
515
516 $('.wpc-filter-item-shadow').css('min-height', head.height() + 'px');
517 }
518
519 });
520
521 $('.wpc-filter-set-wrapper .wpc-filters-list').keydown(function(e){
522 if (e.keyCode == 65 && (e.ctrlKey || e.metaKey) ) {
523 e.target.select()
524 }
525 })
526
527 $( ".wpc-filters-list" ).disableSelection();
528
529 // Deleter filter
530 $('body').on('click', '.wpc-filter-delete', function (){
531 removeElement( $('.wpc-field-notice') );
532 let $spinner = $(this).prev('.spinner');
533 $spinner.addClass( 'is-active' );
534 let requestParams = {};
535 requestParams._wpnonce = $("#wpc_set_nonce").val();
536 requestParams.fid = $(this).data('fid');
537
538 // @feature localize this var
539 if( requestParams.fid === 'wpc_new_id' ){
540 let $filterItem = $(this).parents('.wpc-filter-item');
541 $filterItem.slideUp({
542 duration: 200,
543 complete: function (){
544 $(this).remove();
545 renderMenuOrder();
546 handleNoFiltersMessage();
547 }
548 })
549 }
550
551 wp.ajax.post( 'wpc-delete-filter', requestParams )
552 .always( function() {
553 $spinner.removeClass( 'is-active' );
554 })
555 .done( function( response ) {
556
557 if( typeof response !== 'undefined' && typeof response.fid !== 'undefined' ){
558 $("#wpc-filter-id-"+response.fid).slideUp({
559 duration: 200,
560 complete: function (){
561 $(this).remove();
562 renderMenuOrder();
563 handleNoFiltersMessage();
564
565 // Set available entities again
566 // @todo doesn't work properly if there are several new filters exists on a page !!! IMPORTANT
567 // doesn't make some entities available, but should.
568 passNewEntities();
569
570 }
571 })
572 }
573 })
574
575 .fail( function(response) {
576 if( typeof response !== 'undefined'){
577 addFieldError( 'wpc-filter-delete-wrapper-'+response.fid, response.message );
578 }
579 });
580
581 });
582
583 // Get set location fields
584 $('body').on('change', '#wpc_set_fields-post_type', function (){
585
586 if( wpcSetVars.filtersPro < 1){
587 return true;
588 }
589 setAvailableEntities( $('.wpc-new-filter-item .wpc-field-entity') );
590
591 removeElement( $('.wpc-field-notice') );
592
593 // Update Post type related location terms
594 let selected = $('#wpc_set_fields-wp_page_type').val();
595 if( typeof selected !== 'undefined' /*&& selected === 'common:common'*/ ){
596 wpcGetLocationTerms( selected );
597 }
598 });
599
600 $('body').on('change', '#wpc_set_fields-wp_page_type', function(){
601 wpcGetLocationTerms( $(this).val() );
602 });
603
604 makeNoticesDismissible();
605
606 $('body').on('change', '#wpc_set_fields-post_name', function (e){
607 let filterPagelink = $('option:selected', this).data('link');
608 if( typeof filterPagelink !== 'undefined'){
609 wpcGetWpQueries( filterPagelink );
610 }
611 });
612
613 let filterPagelink = $('option:selected', $('#wpc_set_fields-post_name')).data('link');
614
615 if( typeof filterPagelink !== 'undefined' && filterPagelink ){
616 wpcGetWpQueries( filterPagelink );
617 }
618
619 });
620
621 function wpcGetWpQueries( filterPagelink ){
622 if( wpcSetVars.filtersPro < 1){
623 return true;
624 }
625
626 if( filterPagelink === '' ){
627 return true;
628 }
629
630 removeElement( $('.wpc-field-notice') );
631 // 1 Get current Post type to try to find its query
632
633 // let selected = $('#wpc_set_fields-post_type').val();
634 let $spinner = $( '.wpc_set_fields-wp_filter_query-wrap' ).children( '.spinner' );
635 let postType = $("#wpc_set_fields-post_type").val();
636
637 // Set up AJAX request
638 let requestParams = {};
639 requestParams._wpnonce = $("#wpc_set_nonce").val();
640 requestParams.wpPageType = $('#wpc_set_fields-wp_page_type').val();
641 requestParams.postType = postType;
642 requestParams.postId = $("#post_ID").val();
643 requestParams.action = 'wpc_get_wp_queries';
644
645
646 $.ajax({
647 'method': 'POST',
648 'data': requestParams,
649 'url': filterPagelink,
650 'dataType': 'html',
651 beforeSend: function () {
652 $spinner.addClass( 'is-active' );
653 },
654 complete: function () {
655 $spinner.removeClass( 'is-active' );
656 },
657 success: function (response) {
658 let wpcWpQueriesSelect = $(response).find('#wpc_set_fields-wp_filter_query');
659 let wpcWpQueriesHidden = $(response).find('#wpc_query_vars');
660
661 if( wpcWpQueriesSelect !== '' && wpcWpQueriesSelect.length > 0 ){
662 $("#"+wpcSetVars.wPQuerySelectId).replaceWith(wpcWpQueriesSelect);
663 }
664
665 if( wpcWpQueriesHidden.length > 0 ){
666 $('#wpc_query_vars').replaceWith(wpcWpQueriesHidden);
667 }
668 },
669
670 error: function (response) {
671 //
672 }
673 });
674 }
675
676 function wpcGetLocationTerms( selected ){
677 let $spinner = $( '.wpc_set_fields-post_name-wrap' ).children( '.spinner' );
678 $spinner.addClass( 'is-active' );
679 // Clear all errors
680 removeElement( $('.wpc-field-notice') );
681 let postType = $("#wpc_set_fields-post_type").val();
682
683 // Set up AJAX request
684 let requestParams = {};
685 requestParams._wpnonce = $("#wpc_set_nonce").val();
686 requestParams.wpPageType = selected;
687 requestParams.postType = postType;
688 requestParams.postId = $("#post_ID").val();
689
690 wp.ajax.post( 'wpc-get-set-location-terms', requestParams )
691 .always( function() {
692 $spinner.removeClass( 'is-active' );
693 })
694 .done( function( response ) {
695 //
696 let locationTermsSelect = $(response.html).find('#wpc_set_fields-post_name');
697 $( '#wpc_set_fields-post_name' ).replaceWith(locationTermsSelect);
698
699 let filterPagelink = $('option:selected', $('#wpc_set_fields-post_name') ).data('link');
700 if( typeof filterPagelink !== 'undefined'){
701 wpcGetWpQueries( filterPagelink );
702 }
703 })
704
705 .fail( function(response) {
706 // {"success":false}
707 if( typeof response !== 'undefined'){
708 addFieldError('wpc_set_fields-post_name', response.message);
709 }
710 });
711 }
712
713 function cpaLiveWrite( readFrom, writeTo ) {
714 let cpaText;
715
716 readFrom.on('input', function() {
717 cpaText = $(this).val();
718 writeTo.text(cpaText);
719 });
720 }
721
722 /**
723 * Calculates correct menu order in accordance with filter position in list
724 */
725 function renderMenuOrder()
726 {
727 $(".wpc-filter-item").each( function ( index, element ) {
728 var num = index + 1;
729 $(element).find('.wpc-menu-order-field').attr('value', num );
730 $(element).find('.wpc-filter-sortable-handle').text(num);
731 });
732 }
733
734 function handleNoFiltersMessage()
735 {
736 if( $(".wpc-filter-item").length > 0 ){
737 $('.wpc-no-filters').hide();
738 }else{
739 $('.wpc-no-filters').show();
740 }
741 }
742
743 function setEntityTableClass( entitySelect )
744 {
745 let val = entitySelect.val();
746 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
747
748 if( val.indexOf('taxonomy') !== -1 ){
749 val = 'taxonomy';
750 }
751
752 $("#wpc-filter-id-"+fid+" .wpc-form-fields-table").attr('class', 'wpc-form-fields-table wpc-filter-'+val);
753 }
754
755 function syncEntityWithPrefix( entitySelect )
756 {
757 let val = entitySelect.val();
758 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
759
760 if( typeof wpcSetVars.filterSlugs[val] !== 'undefined'){
761 let prefix = wpcSetVars.filterSlugs[val];
762 $('#wpc_filter_fields-'+fid+'-slug').val(prefix)
763 .attr('readonly', 'readonly')
764 .trigger('input');
765 } else {
766 $('#wpc_filter_fields-'+fid+'-slug').val('')
767 .removeAttr('readonly')
768 .trigger('input');
769 }
770
771 }
772
773 function syncEntityWithSortTerms( entitySelect ){
774 let val = entitySelect.val();
775 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
776
777 if( ! val.includes('taxonomy_pa') ) {
778 $('#wpc_filter_fields-'+fid+'-orderby option[value="menuasc"]').attr('disabled', 'disabled');
779 $('#wpc_filter_fields-'+fid+'-orderby option[value="menudesc"]').attr('disabled', 'disabled');
780 }else{
781 $('#wpc_filter_fields-'+fid+'-orderby option[value="menuasc"]').removeAttr('disabled');
782 $('#wpc_filter_fields-'+fid+'-orderby option[value="menudesc"]').removeAttr('disabled');
783 }
784 }
785
786 function syncEntityWithView( entitySelect ){
787 let val = entitySelect.val();
788 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
789
790 if( val === 'post_meta_num' ) {
791 $('#wpc_filter_fields-'+fid+'-view option:not([value="range"])').attr('disabled', 'disabled');
792 $('#wpc_filter_fields-'+fid+'-view option[value="range"]').removeAttr('disabled')
793 .prop('selected', true);
794
795 }else{
796 $('#wpc_filter_fields-'+fid+'-view option').removeAttr('disabled')
797 $('#wpc_filter_fields-'+fid+'-view option:not([disabled]):first').prop('selected', true);
798 $('#wpc_filter_fields-'+fid+'-view option[value="range"]').attr('disabled', 'disabled');
799 }
800 }
801
802
803 function handleLogicField( entitySelect )
804 {
805 let val = entitySelect.val();
806 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
807
808 if( val === 'author_author' || val === 'post_meta_exists' ) {
809 $('#wpc_filter_fields-' + fid + '-logic option[value="and"]').attr('disabled', 'disabled');
810 $('#wpc_filter_fields-' + fid + '-logic option[value="or"]').prop('selected', true);
811
812 }else if( val === 'post_meta_num' ){
813 $('#wpc_filter_fields-' + fid + '-logic option[value="or"]').attr('disabled', 'disabled');
814 $('#wpc_filter_fields-' + fid + '-logic option[value="and"]').prop('selected', true);
815 }else{
816 $('#wpc_filter_fields-'+fid+'-logic option[value="and"]').removeAttr('disabled');
817 $('#wpc_filter_fields-'+fid+'-logic option[value="or"]').removeAttr('disabled');
818 }
819
820 return true;
821 }
822
823 function handleHierarchyField( entitySelect )
824 {
825 let val = entitySelect.val();
826 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
827
828 if( val.indexOf('taxonomy') !== -1 ){
829 $.each( wpcSetVars.postTypesTaxList, function ( pType, taxesArray ){
830 $.each( taxesArray, function ( index, theTax ){
831 if( theTax['name'] === val ){
832 if( theTax['hierarchical'] ){
833 $("#wpc-filter-id-"+fid+" .wpc-field-hierarchy-tr").show();
834 }else{
835 $("#wpc-filter-id-"+fid+" .wpc-field-hierarchy-tr").hide();
836 }
837 return;
838 }
839 });
840 });
841 }
842 }
843
844 function handleMetaKeyField( entitySelect )
845 {
846 let val = entitySelect.val();
847 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
848
849 if( val === 'post_meta' || val === 'post_meta_num' || val === 'post_meta_exists' ){
850 $('#wpc_filter_fields-'+fid+'-e_name').val('')
851 .removeAttr('readonly')
852 .parents('.wpc-field-ename-tr').show();
853 }else{
854 $('#wpc_filter_fields-'+fid+'-e_name').parents('.wpc-field-ename-tr').hide();
855 }
856
857 if( val === 'post_meta_num' ){
858 $('#wpc_filter_fields-'+fid+'-in_path').prop( "checked", false );
859 // $('#wpc_filter_fields-'+fid+'-show_chips').prop( "checked", false );
860 }else{
861 $('#wpc_filter_fields-'+fid+'-in_path').prop( "checked", true );
862 // $('#wpc_filter_fields-'+fid+'-show_chips').prop( "checked", true );
863 }
864 }
865
866 function loadExcludeItems( entity, fid, ename )
867 {
868 // let val = entitySelect.val();
869 // let fid = entitySelect.parents('.wpc-filter-item').data('fid');
870 removeElement( $('.wpc-field-notice') );
871 let requestParams = {};
872 let target = $('#wpc_filter_fields-'+fid+'-exclude');
873 requestParams._wpnonce = $("#wpc_set_nonce").val();
874 requestParams.fid = fid;
875 requestParams.entity = entity;
876
877 if( typeof ename !== 'undefined' ){
878 requestParams.ename = ename;
879 }
880
881 let $spinner = target.parent('.wpc-after-spinner-container').prev( '.spinner' );
882 $spinner.addClass( 'is-active' );
883
884 wp.ajax.post( 'wpc-load-exclude-terms', requestParams )
885 .always( function() {
886 $spinner.removeClass( 'is-active' );
887 })
888 .done( function( response ) {
889 if( typeof response.fid !== 'undefined' ){
890 target.select2('destroy');
891 target.html('');
892 target.select2({
893 width: '100%',
894 placeholder: wpcSelect2Vars.excludePlaceholder,
895 data: response.terms,
896 disabled: false
897 })
898 }
899 })
900
901 .fail( function(response) {
902 // if( typeof response !== 'undefined'){
903 // addFieldError( 'wpc_filter_fields-'+response.fid+'-exclude', response.message );
904 // }
905 });
906
907 }
908
909 function makeNoticesDismissible() {
910 $( '.wpc-error.is-dismissible' ).each( function() {
911 var $el = $( this ),
912 $button = $el.find('.notice-dismiss');
913 // Ensure plain text.
914 $button.on( 'click', function( event ) {
915 event.preventDefault();
916 $el.fadeTo( 100, 0, function() {
917 $el.slideUp( 100, function() {
918 $el.remove();
919 });
920 });
921 });
922
923 $el.append( $button );
924 });
925 }
926
927 function wpcSerialize( $el ){
928
929 var obj = {};
930 var inputs = $el.find('select, textarea, input').serializeArray();
931
932 for( var i = 0; i < inputs.length; i++ ) {
933 wpcBuildObject( obj, inputs[i].name, inputs[i].value );
934 }
935 return obj;
936 };
937
938 function wpcBuildObject( obj, name, value ){
939 name = name.replace('[]', '[%%index%%]');
940
941 var keys = name.match(/([^\[\]])+/g);
942 if( !keys ) return;
943 var length = keys.length;
944 var ref = obj;
945
946 for( var i = 0; i < length; i++ ) {
947 var key = String( keys[i] );
948 if( i == length - 1 ) {
949 if( key === '%%index%%' ) {
950 ref.push( value );
951 } else {
952 ref[ key ] = value;
953 }
954 } else {
955 if( keys[i+1] === '%%index%%' ) {
956 if( !wpcIsArray(ref[ key ]) ) {
957 ref[ key ] = [];
958 }
959 } else {
960 if( !wpcIsObject(ref[ key ]) ) {
961 ref[ key ] = {};
962 }
963 }
964 ref = ref[ key ];
965 }
966 }
967 };
968
969 function wpcIsArray( a ){
970 return Array.isArray(a);
971 };
972
973 function wpcIsObject( a ){
974 return ( typeof a === 'object' );
975 }
976
977 })(jQuery);
978
979 // Important!!!
980 // When field Filter by is selected, it is required to make AJAX request to find the same
981 // entity in filters already. And if it is exists, to predefine field "slug" defined in previous
982 // selection of
983
984 function uniqId (prefix, moreEntropy) {
985 // discuss at: https://locutus.io/php/uniqid/
986 // original by: Kevin van Zonneveld (https://kvz.io)
987 // revised by: Kankrelune (https://www.webfaktory.info/)
988 // note 1: Uses an internal counter (in locutus global) to avoid collision
989 // example 1: var $id = uniqid()
990 // example 1: var $result = $id.length === 13
991 // returns 1: true
992 // example 2: var $id = uniqid('foo')
993 // example 2: var $result = $id.length === (13 + 'foo'.length)
994 // returns 2: true
995 // example 3: var $id = uniqid('bar', true)
996 // example 3: var $result = $id.length === (23 + 'bar'.length)
997 // returns 3: true
998
999 if (typeof prefix === 'undefined') {
1000 prefix = '';
1001 }
1002
1003 var retId;
1004 var _formatSeed = function (seed, reqWidth) {
1005 seed = parseInt(seed, 10).toString(16); // to hex str
1006 if (reqWidth < seed.length) {
1007 // so long we split
1008 return seed.slice(seed.length - reqWidth);
1009 }
1010 if (reqWidth > seed.length) {
1011 // so short we pad
1012 return Array(1 + (reqWidth - seed.length)).join('0') + seed;
1013 }
1014 return seed;
1015 }
1016
1017 var $global = (typeof window !== 'undefined' ? window : global);
1018 $global.$locutus = $global.$locutus || {}
1019 var $locutus = $global.$locutus;
1020 $locutus.php = $locutus.php || {}
1021
1022 if (!$locutus.php.uniqidSeed) {
1023 // init seed with big random int
1024 $locutus.php.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
1025 }
1026 $locutus.php.uniqidSeed++;
1027
1028 // start with prefix, add current milliseconds hex string
1029 retId = prefix;
1030 retId += _formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
1031 // add seed hex string
1032 retId += _formatSeed($locutus.php.uniqidSeed, 5);
1033 if (moreEntropy) {
1034 // for more entropy we add a float lower to 10
1035 retId += (Math.random() * 10).toFixed(8).toString();
1036 }
1037
1038 return retId;
1039 }