PluginProbe
Filter Everything — WordPress & WooCommerce Filters / 1.9.7
Filter Everything — WordPress & WooCommerce Filters v1.9.7
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.9.7, at assets/js/wpc-filter-set-admin.js

2,021 lines 78.2 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.9.7
3 */
4 (function($) {
5 "use strict";
6 let filtersFormValid = false;
7 let postTypesTaxList = wpcSetVars.postTypesTaxList;
8 let numFieldNoTaxes = wpcSetVars.numFieldNoTaxes;
9 let numFieldAttrs = wpcSetVars.numFieldAttrs;
10 let isLimitFilterSet = wpcSetVars.isLimitFilterSet;
11
12 function validateFiltersForm( $el )
13 {
14 let $spinner = $('#publishing-action .spinner');
15 let requestParams = {};
16
17 const keepFields = [
18 '_wpnonce',
19 '_flrt_nonce',
20 '_wp_http_referer',
21 'user_ID',
22 'action',
23 'originalaction',
24 'post_author',
25 'post_type',
26 'original_post_status',
27 'post_ID',
28 'post_title',
29 'save',
30 'post_status',
31 'wpc_filter_set_json_data',
32 ];
33
34 $spinner.addClass( 'is-active' );
35 /**
36 * @todo checkboxes does not validates correctly because they send the same value !!! IMPORTANT
37 * independently from checked status
38 */
39
40 requestParams.validateData = JSON.stringify(wpcSerialize( $el ));
41
42 wp.ajax.post( 'wpc-validate-filters', requestParams )
43 .always( function() {
44 $spinner.removeClass( 'is-active' );
45 })
46 .done( function( response ) {
47 filtersFormValid = true;
48
49 const wpcHiddenInput = document.createElement('input');
50 wpcHiddenInput.type = 'hidden';
51 wpcHiddenInput.name = 'wpc_filter_set_json_data';
52 wpcHiddenInput.value = JSON.stringify(wpcSerialize( $el ));
53 $el.append(wpcHiddenInput);
54
55 // Find the elements that need to be "disabled"
56 const $toDisable = $el.find('[name]').not(keepFields.map(n => `[name="${n}"]`).join(','));
57
58 // Save name and remove before submit
59 $toDisable.each(function() {
60 $(this).attr('data-name', $(this).attr('name')).removeAttr('name');
61 });
62
63 $el.submit();
64
65 // Restore name after submit
66 $toDisable.each(function() {
67 $(this).attr('name', $(this).attr('data-name')).removeAttr('data-name');
68 });
69 })
70 .fail( function( response ) {
71
72 let notices = [];
73 let filterContainer = '';
74
75 if( typeof response.errors !== 'undefined' ){
76 $.each( response.errors, function ( index, error ){
77
78 if( typeof error.id !== 'undefined'){
79 addFieldError( error.id, error.message );
80
81 // Open filter container to show error
82 filterContainer = $('#'+error.id).parents('.wpc-filter-item');
83 openFilter(filterContainer);
84
85 // Open additional fields if errors are there
86 if( $('#'+error.id).parents('.wpc-filter-additional-fields').length > 0 ){
87 openAdditional(filterContainer);
88 }
89 }else{
90 notices.push( error.message );
91 }
92
93 });
94
95 if( notices.length < 1 ){
96 notices.push( 'Error: Set was not saved.' );
97 }
98
99 addNotice( notices );
100 }
101 });
102
103 return false;
104 }
105
106 function removeElement($el)
107 {
108 $el.fadeTo(100, 0, function() {
109 $el.slideUp(100, function() {
110 $el.remove();
111 });
112 });
113 }
114
115 function addFieldError( fieldId, message )
116 {
117 let target = $('#'+fieldId);
118 let html = '<div class="wpc-field-notice wpc-field-notice-error"><p>'+message+'</p></div>';
119 if( typeof target !== 'undefined' ){
120 target.before( html );
121 }
122 }
123
124 function addNotice( messages )
125 {
126 let target = $('form#post');
127 let text = '';
128 $.each( messages, function ( index, message ) {
129 text += '<p>' + message + '</p>';
130 });
131
132 let html = '<div id="message" class="error notice notice-error is-dismissible">'
133 + text +
134 '<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>' +
135 '</div>';
136 if( typeof target !== 'undefined' ){
137 if( $("#message").length > 0 ){
138 $("#message").remove();
139 }
140 target.before( html );
141 }
142 }
143
144 function openFilter($el)
145 {
146 let head = $el.find('.wpc-filter-head'),
147 body = head.next('.wpc-filter-body');
148 head.addClass('wpc-opened');
149 body.slideDown({
150 duration: 200,
151 complete: function (){
152 body.addClass('wpc-opened');
153 }
154 });
155 }
156
157 function closeFilter($el)
158 {
159 let head = $el.find('.wpc-filter-head'),
160 body = head.next('.wpc-filter-body');
161
162 head.removeClass('wpc-opened');
163 body.slideUp({
164 duration: 200,
165 complete: function (){
166 body.removeClass('wpc-opened');
167 }
168 });
169 }
170
171 function closeAdditional($el)
172 {
173 $el.find('.wpc-filter-additional-fields').slideUp({
174 duration: 200,
175 complete: function (){
176 $(this).removeClass('wpc-opened');
177 }
178 });
179 }
180
181 function openAdditional($el)
182 {
183 $el.find('.wpc-filter-additional-fields').slideDown({
184 duration: 200,
185 complete: function (){
186 $(this).addClass('wpc-opened');
187 }
188 });
189 }
190
191 /**
192 * Creates array with taxonomies that do not belong to the Post type
193 * selected in Filter Set
194 * @returns {[]|*[]}
195 */
196 function getForbiddenTaxes()
197 {
198 if( typeof wpcSetVars.postTypesTaxList !== 'undefined'){
199 let postType = $('#wpc_set_fields-post_type').val();
200 let allowedTaxes = [];
201 let forbiddenTaxes = [];
202
203 if( typeof wpcSetVars.postTypesTaxList[postType] !== 'undefined' ){
204 $.each( wpcSetVars.postTypesTaxList[postType], function ( iNdex, taxProps ){
205 allowedTaxes.push(taxProps['name']);
206 });
207 }
208
209 $.each( wpcSetVars.postTypesTaxList, function ( pType, taxesArray ){
210 if( pType !== postType ){
211 $.each( taxesArray, function ( index, theTax ){
212 if( allowedTaxes.includes(theTax['name']) === false ){
213 forbiddenTaxes.push(theTax['name']);
214 }
215 } )
216 }
217 });
218
219 return forbiddenTaxes;
220 }
221
222 return [];
223 }
224
225 /**
226 * Retrieves already selected filter entities to disable double using of them
227 * @param $inputs - select tags, where we collect used entities. Usually .wpc-field-entity
228 * @param excludeInput
229 * @returns {boolean|[]}
230 */
231 function getUsedEntities( $inputs, excludeInput )
232 {
233 let usedEntities = [];
234 let currentVal = '';
235 // Pass through these entities
236 let doNotInclude = ['post_meta', 'post_meta_num', 'post_meta_exists', 'tax_numeric', 'post_meta_date'];
237
238 if ( $inputs.length > 0 ) {
239 $inputs.each( function(){
240 currentVal = $(this).val();
241
242 // Continue
243 if( $(this).attr('id') == excludeInput.attr('id') ){
244 return;
245 }
246
247 if( doNotInclude.includes( currentVal ) ){
248 return;
249 }
250 if( currentVal ) {
251 usedEntities.push( currentVal );
252 }
253 });
254
255 return usedEntities;
256 }
257 return false;
258 }
259
260 /**
261 * Pass through new filter entity options and set as disabled already used taxonomies
262 * @param $theSelect - the select element with options to set. Usually it is .wpc-field-entity
263 * @param dropdownClass - class of the select element where we have to set option status
264 * @param noChange
265 * @returns {boolean}
266 */
267 function setAvailableEntities( $theSelect, noChange )
268 { // .wpc-field-entity
269 let currentVal = '';
270 let selectClass = $theSelect.attr('class');
271 const excludeRaw = getUsedEntities( $( '.'+selectClass ), $theSelect );
272 const exclude = Array.isArray(excludeRaw) ? excludeRaw : [];
273 let forbiddenTaxes = getForbiddenTaxes(); //
274
275 $theSelect.find('option').each( function (){
276 currentVal = $(this).val();
277
278 if( currentVal === 'post_meta_exists' && ( wpcSetVars.filtersPro < 1 ) ) {
279 return;
280 }
281 if( currentVal === 'tax_numeric' && ( wpcSetVars.filtersPro < 1 ) ) {
282 return;
283 }
284
285 if( exclude.includes( currentVal ) || forbiddenTaxes.includes( currentVal ) ){
286 $(this).attr( 'disabled', 'disabled' );
287 }else{
288 $(this).removeAttr( 'disabled' );
289 }
290 } );
291
292 // If currently selected option is disabled, make first available option selected.
293 let disabled = $theSelect.find('option:selected').attr('disabled');
294 // if noChange === false this works
295 if( disabled === 'disabled' && ! noChange ){
296 $theSelect.find('option:not([disabled]):first').prop('selected', true)
297 .trigger('change');
298 }
299
300 return true;
301 }
302
303 function handleShowTerms( select )
304 {
305 let currentVal = select.val();
306 let currentFid = select.parents('.wpc-filter-item').data('fid');
307 currentVal = wpcShortenEname( currentVal );
308
309 let $formTable = $( "#wpc-filter-id-"+currentFid+" .wpc-form-fields-table" );
310 if ( wpcSetVars.swatchesTaxonomies.includes( currentVal ) ){
311 $formTable.addClass("taxonomy-has-swatches");
312 } else {
313 $formTable.removeClass("taxonomy-has-swatches");
314 }
315
316 if ( wpcSetVars.brandEntities.includes( currentVal ) ){
317 $formTable.addClass("wpc-filter-has-brands");
318 } else {
319 $formTable.removeClass("wpc-filter-has-brands");
320 }
321
322 if ( wpcSetVars.ratingTaxonomies.includes( currentVal ) ){
323 $formTable.addClass("selected-and-above-show");
324 } else {
325 $formTable.removeClass("selected-and-above-show");
326 }
327 }
328
329 function passNewEntities( select )
330 {
331 let time = 0;
332
333 $('.wpc-new-filter-item .wpc-field-entity').each( function () {
334 let select = $(this);
335 let noChange = false;
336 // Do not change current select tag
337 if( $(this).attr('id') == select.attr('id') ) {
338 noChange = true;
339 }
340
341 setTimeout( function(){ setAvailableEntities( select, noChange ); }, time);
342 time += 100;
343 });
344 }
345
346 $.fn.getCursorPosition = function() {
347 var input = this.get(0);
348 if (!input) return; // No (input) element found
349 if ('selectionStart' in input) {
350 // Standard-compliant browsers
351 return input.selectionStart;
352 } else if (document.selection) {
353 // IE
354 input.focus();
355 var sel = document.selection.createRange();
356 var selLen = document.selection.createRange().text.length;
357 sel.moveStart('character', -input.value.length);
358 return sel.text.length - selLen;
359 }
360 }
361
362 $(document).ready(function (){
363
364 $('form#post').on('submit', function(e){
365 // Clear all errors
366 removeElement( $('.wpc-field-notice') );
367
368 // Clear Notice
369 removeElement( $('#message') );
370
371 // Close All Filters
372 closeFilter( $(".wpc-filter-item") );
373
374 if( ! filtersFormValid ){
375 e.preventDefault();
376 // Validate form. We will submit it from validation method
377 validateFiltersForm($(this));
378 }
379 });
380
381
382 $('.wpc-add-filter').on('click', function (e){
383 e.preventDefault();
384
385 let html = $('#wpc-new-filter').html();
386 let $el = $(html);
387 let search = 'wpc_new_id';
388 let replace = uniqId('filter_');
389 let replaceAttr = function(i, value){
390 return value.replace( search, replace );
391 }
392
393 let filtersListContainer = $('#wpc-filters-list');
394
395 $el.find('[id*="' + search + '"]').attr('id', replaceAttr);
396 $el.find('[for*="' + search + '"]').attr('for', replaceAttr);
397 $el.find('[name*="' + search + '"]').attr('name', replaceAttr);
398 $el.find('[class*="' + search + '"]').attr('class', replaceAttr);
399 $el.data('fid', replace);
400 $el.attr('id', 'wpc-filter-id-'+replace);
401
402 let latestElem = $(".wpc-filter-item").last();
403 if ( latestElem.hasClass('wpc-filter-not-listed') ) {
404 let prevLatestElem = latestElem.prev('.wpc-filter-item');
405 if ( prevLatestElem.hasClass('wpc-filter-not-listed') ) {
406 prevLatestElem.before($el);
407 } else {
408 latestElem.before($el);
409 }
410 } else {
411 filtersListContainer.append($el);
412 }
413
414 let select = $el.find('.wpc-field-entity');
415
416 syncEntityWithPrefix(select);
417 handleMetaKeyField(select);
418 setEntityTableClass(select);
419 syncEntityWithView(select);
420 syncEntityWithSortTerms(select);
421
422 // Make already used entities unavailable to selection
423 setAvailableEntities( select );
424 handleHierarchyField( select );
425 handleShowTerms( select );
426 // handleUsedForVariationsField( select );
427
428 $el.find('.wpc-field-exclude').select2({
429 width: '100%',
430 placeholder: wpcSetVars.excludePlaceholder,
431 });
432
433 // Fire this event to load exclude terms for first filter
434 if( $(".wpc-filter-item:not(.wpc-filter-not-listed)").length === 1 ){
435 select.trigger('change');
436 }
437
438 $('.wpc-help-tip').tipTip({
439 'attribute': 'data-tip',
440 'fadeIn': 50,
441 'fadeOut': 50,
442 'delay': 200,
443 'keepAlive': true,
444 'maxWidth': "220px",
445 });
446
447 openFilter($el);
448
449 renderMenuOrder();
450 handleNoFiltersMessage();
451
452 // Update Parent filter dropdown
453 wpcAddNewFilterToParentList();
454
455 /**
456 * @todo There is problem with down arrow when we adding new filter !!! IMPORTANT
457 */
458
459 });
460
461 $('.wpc-form-fields-table:not(.wpc-filter-tax_numeric) .wpc-field-exclude, .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({
462 width: '100%',
463 placeholder: wpcSetVars.excludePlaceholder
464 });
465
466 $('body').on('click', '.notice-dismiss', function(e){
467 e.preventDefault();
468 removeElement( $('#message') );
469 });
470
471 // Show delete buttons
472 $('body').on('click', '.wpc-button-link-delete', function(e){
473 e.preventDefault();
474 $(this).parents('.wpc-filter-label-td')
475 .next('.wpc-filter-field-td')
476 .children('.wpc-filter-delete-wrapper').css('visibility', 'visible');
477 });
478
479 $('body').on('click', '.wpc-filter-delete-cancel', function(e){
480 e.preventDefault();
481 removeElement( $('.wpc-field-notice') );
482 $(this).parents('.wpc-filter-delete-wrapper').css('visibility', 'hidden');
483 });
484
485 $('body').on('click', '.wpc-done-action', function(e){
486 $(this).parents('.wpc-filter-body').slideToggle(200)
487 .toggleClass('wpc-opened')
488 .children('.wpc-filter-additional-fields').removeClass('wpc-additional-opened')
489 .hide();
490 $(this).parents('.wpc-filter-body').prev('.wpc-filter-head').toggleClass('wpc-opened');
491 // Hide delete buttons
492 $(this).parents('.wpc-filter-field-td')
493 .next('.wpc-filter-field-td')
494 .find('.wpc-filter-delete-wrapper').css('visibility', 'hidden');
495 });
496
497 $('body').on('click', '.wpc-advice-head', function(e){
498 // let body = $(this).next('.wpc-advice-body');
499 $(this).toggleClass('wpc-opened');
500 // body.slideToggle(200)
501 // body.toggle(200)
502 // body.toggleClass('wpc-opened');
503 });
504
505 $('body').on('click', '.wpc-title-action', function(e){
506 let head = $(this).parent('.wpc-filter-head'),
507 body = head.next('.wpc-filter-body');
508 head.toggleClass('wpc-opened');
509 body.slideToggle(200)
510 .toggleClass('wpc-opened')
511 .children('.wpc-filter-additional-fields').removeClass('wpc-additional-opened')
512 .hide();
513 body.find('.wpc-filter-delete-wrapper').css('visibility', 'hidden');
514
515 let moreOptions = body.find('.wpc-more-options-toggle');
516 if( moreOptions.hasClass('wpc-opened') ){
517 moreOptions.trigger('click');
518 }
519 });
520
521 $('body').on('click', '.wpc-more-options-toggle', function(e){
522 e.preventDefault();
523
524 let moreText = $(this).text();
525
526 if( moreText === wpcSetVars.moreOptions ){
527 $(this).text( wpcSetVars.lessOptions);
528 }else{
529 $(this).text( wpcSetVars.moreOptions);
530 }
531
532 $(this).toggleClass('wpc-opened');
533 $(this).parents('.wpc-filter-body').find('.wpc-filter-additional-fields').slideToggle(200)
534 .toggleClass('wpc-additional-opened');
535 });
536
537 $('body').on('change', 'select.wpc-field-ename', function(e){
538 let time = 0;
539 // let fid = $(this).parents('.wpc-filter-item').data('fid');
540
541 $( $('.wpc-new-filter-item select.wpc-field-ename').get().reverse() ).each( function () {
542 let eNameSelect = $(this);
543
544 setTimeout( function(){ setAvailableEntities( eNameSelect, false ); }, time);
545 time += 100;
546 });
547 });
548
549 $('body').on('change', '.wpc-field-entity', function(e){
550 let thisSelect = $(this);
551 let theTitle = '';
552
553 // Set available entities again
554 passNewEntities(thisSelect);
555 syncEntityWithPrefix(thisSelect);
556 handleMetaKeyField(thisSelect);
557 handleLogicField(thisSelect);
558 setEntityTableClass(thisSelect);
559 syncEntityWithView(thisSelect);
560 syncEntityWithSortTerms(thisSelect);
561
562 handleHierarchyField(thisSelect);
563 handleShowTerms( thisSelect );
564 // handleUsedForVariationsField(select);
565
566 // Load terms for exclude
567 let entity = $(this).val();
568 let fid = $(this).parents('.wpc-filter-item').data('fid');
569
570 if ( entity === 'tax_numeric' ) {
571 $('#wpc_filter_fields-'+fid+'-e_name').trigger('change');
572 }
573
574 // replace with includes
575 if ( [ 'tax_numeric', 'post_meta', 'post_meta_num', 'post_meta_exists', 'post_date', 'post_meta_date' ].includes(entity) ) {
576 let target = $('#wpc_filter_fields-'+fid+'-exclude');
577 target.select2({
578 disabled: true,
579 width: '100%'
580 });
581 }else{
582 loadExcludeItems(entity, fid);
583 }
584
585 let entityLabel = $(this).find('option:selected').text();
586 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-entity');
587 target.text(entityLabel);
588
589 theTitle = $("#wpc_filter_fields-"+fid+"-label").val();
590
591 if( ! theTitle ){
592 theTitle = wpcSetVars.newFilter;
593 }
594
595 $(".wpc-field-parent-filter option[value='"+fid+"'").each(function (index, element){
596 $(this).text( theTitle + " (" +wpcShortenEname( entity )+ ")" );
597 if( entity === 'post_meta_num' || entity === 'tax_numeric' || entity === 'taxonomy_product_visibility' ){
598 $(this).attr('disabled', 'disabled');
599 }else{
600 $(this).removeAttr('disabled');
601 }
602 });
603 });
604
605 // Try to prepend slug if it already exists
606 $('body').on('input change', '.wpc-field-ename', function(){
607 let ename = $(this).val();
608 let fid = $(this).parents('.wpc-filter-item').data('fid');
609 let entity = $('#wpc_filter_fields-'+fid+'-entity').val();
610 let val = '';
611 let slugs = wpcSetVars.filterSlugs;
612
613 if ( entity === 'post_meta_num' ) {
614 val = 'post_meta_num_' + ename;
615 } else if ( entity === 'tax_numeric' ) {
616 val = 'tax_numeric_' + ename;
617 } else if ( entity === 'post_meta_exists' ) {
618 val = 'post_meta_exists_' + ename;
619 } else if ( entity === 'post_meta_date' ) {
620 val = 'post_meta_date_' + ename;
621 }else {
622 val = 'post_meta_' + ename;
623 }
624
625 if( typeof slugs[val] !== 'undefined' ){
626 $('#wpc_filter_fields-'+fid+'-slug').val( slugs[val] )
627 .trigger('input');
628
629 // Do not load exclude terms for Post Meta Num and Tax Numeric
630 if( entity !== 'post_meta_num' && entity !== 'tax_numeric'){
631 loadExcludeItems(entity, fid, ename);
632 }
633
634 }else{
635 $('#wpc_filter_fields-'+fid+'-slug').val('')
636 .trigger('input');
637 $('#wpc_filter_fields-'+fid+'-exclude').select2({
638 disabled: true,
639 width: '100%',
640 });
641 }
642 });
643
644 $('body').on('input', '.wpc-field-value-step', function (){
645 $(this).val( $(this).val().replace(/,/g, '.') );
646 $(this).val( $(this).val().replace(/[^\d\.]/g, '') );
647 });
648
649 $('body').on('input keydown', '#wpc_set_fields-apply_button_text', function (){
650 let target = $("#wpc-filter-id-apply-button").find('.wpc-button-apply');
651 cpaLiveWrite( $(this), target );
652 });
653
654 $('body').on('input keydown', '#wpc_set_fields-reset_button_text', function (){
655 let target = $("#wpc-filter-id-apply-button").find('.wpc-button-reset');
656 cpaLiveWrite( $(this), target );
657 });
658
659 $('body').on('input keydown', '#wpc_set_fields-search_field_placeholder', function (){
660 let target = $("#wpc-filter-id-search-field").find('.wpc-text-input-search');
661 target.attr('placeholder', $(this).val());
662 });
663
664 $('body').on('input keydown', '#wpc_set_fields-search_field_label', function (){
665 let target = $("#wpc-filter-id-search-field").find('.wpc-filter-label');
666 cpaLiveWrite( $(this), target );
667 // target.attr('placeholder', $(this).val());
668 });
669
670 $('body').on('input keydown', '.wpc-field-slug', function (){
671 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-slug');
672 cpaLiveWrite( $(this), target );
673 });
674
675 $('body').on('input keydown', '.wpc-field-label', function (){
676 let target = $(this).parents('.wpc-filter-item').find('.wpc-filter-head li.wpc-filter-label');
677 cpaLiveWrite( $(this), target );
678
679 let fid = $(this).parents(".wpc-filter-item").data('fid');
680 let eName = $("#wpc_filter_fields-"+fid+"-entity").val();
681 eName = wpcShortenEname( eName );
682 let theTitle = $(this).val();
683
684 $(".wpc-field-parent-filter option[value='"+fid+"'").each(function (index, element){
685 $(this).text( theTitle + " (" + eName + ")" );
686 });
687 });
688
689 $('body').on('change', '.wpc-field-show-range-list', function (){
690 let rangeListButtonChecked = $(this).prop( "checked" );
691 if( rangeListButtonChecked ){
692 $(".wpc-view-range").addClass('wpc-view-range-list');
693 }else{
694 $(".wpc-view-range").removeClass('wpc-view-range-list');
695 }
696 });
697
698 $('body').on('change', '.wpc-field-view', function(){
699 const $this = $(this);
700 const $option = $this.find('option:selected');
701 const optionName = $option.text();
702 const optionVal = $option.val();
703 const $divFilterItem = $this.parents('.wpc-filter-item');
704
705 // Update View Label in Header
706 $divFilterItem.find('.wpc-filter-head li.wpc-filter-view').text(optionName);
707
708 // Handle visibility of Search and More/Less fields
709 const allowedViews = ['checkboxes', 'radio', 'labels'];
710 const showExtraFields = allowedViews.includes(optionVal);
711 $divFilterItem.find('.wpc-field-search-tr, .wpc-field-more-less-tr').toggle(showExtraFields);
712
713 // Handle CSS classes for the fields table
714 const $fieldsTable = $divFilterItem.find('.wpc-form-fields-table');
715 const classesToRemove = 'wpc-view-checkboxes wpc-view-dropdown wpc-view-rating wpc-view-range selected-and-above-show';
716
717 // Map option values to their specific CSS classes
718 const viewClasses = {
719 'checkboxes': 'wpc-view-checkboxes',
720 'rating': 'wpc-view-rating',
721 'range': 'wpc-view-range',
722 'dropdown': 'wpc-view-dropdown'
723 };
724
725 // Reset classes first
726 $fieldsTable.removeClass(classesToRemove);
727
728 // Add specific class if exists in map
729 if (viewClasses[optionVal]) {
730 $fieldsTable.addClass(viewClasses[optionVal]);
731 }
732
733 // Handle special case for 'rating'
734 if (optionVal === 'rating') {
735 $fieldsTable.addClass('selected-and-above-show');
736 }
737 });
738
739 $( '.wpc-filter-set-wrapper .wpc-filters-list' ).sortable({
740 items: "> div.wpc-filter-item",
741 delay: 150,
742 placeholder: "wpc-filter-item-shadow",
743 refreshPositions: true,
744 cursor: 'move',
745 handle: ".wpc-filter-order",
746 axis: 'y',
747 update: function( event, ui ) {
748 renderMenuOrder();
749 },
750 start: function ( event, ui ){
751 let head = ui.item.children('.wpc-filter-head'),
752 inside = ui.item.children('.wpc-filter-body');
753
754 if ( inside.hasClass('wpc-opened') ) {
755 inside.removeClass('wpc-opened')
756 .hide();
757 head.removeClass('wpc-opened');
758 $(this).sortable('refreshPositions');
759 }
760
761 $('.wpc-filter-item-shadow').css('min-height', head.height() + 'px');
762 }
763
764 });
765
766 $('.wpc-filter-set-wrapper .wpc-filters-list').keydown(function(e){
767 if (e.keyCode == 65 && (e.ctrlKey || e.metaKey) ) {
768 e.target.select()
769 }
770 })
771
772 $( ".wpc-filters-list" ).disableSelection();
773
774 // Deleter filter
775 $('body').on('click', '.wpc-filter-delete', function (){
776 removeElement( $('.wpc-field-notice') );
777 let $spinner = $(this).prev('.spinner');
778 $spinner.addClass( 'is-active' );
779 let requestParams = {};
780 requestParams._wpnonce = $("#wpc_set_nonce").val();
781 requestParams.fid = $(this).data('fid');
782
783 // @feature localize this var
784 if( requestParams.fid === 'wpc_new_id' ){
785 let $filterItem = $(this).parents('.wpc-filter-item');
786 $filterItem.slideUp({
787 duration: 200,
788 complete: function (){
789 $(this).remove();
790 renderMenuOrder();
791 handleNoFiltersMessage();
792 }
793 })
794 }
795
796 // Remove current filter from Parent filters list
797 let dataFid = $(this).parents('.wpc-filter-item').data('fid');
798 wpcDeleteFilterFromParentList( dataFid );
799
800 wp.ajax.post( 'wpc-delete-filter', requestParams )
801 .always( function() {
802 $spinner.removeClass( 'is-active' );
803 })
804 .done( function( response ) {
805
806 if( typeof response !== 'undefined' && typeof response.fid !== 'undefined' ){
807 $("#wpc-filter-id-"+response.fid).slideUp({
808 duration: 200,
809 complete: function (){
810 $(this).remove();
811 renderMenuOrder();
812 handleNoFiltersMessage();
813
814 // Set available entities again
815 // @todo doesn't work properly if there are several new filters exists on a page !!! IMPORTANT
816 // doesn't make some entities available, but should.
817 passNewEntities();
818
819 }
820 })
821 }
822 })
823
824 .fail( function(response) {
825 if( typeof response !== 'undefined'){
826 addFieldError( 'wpc-filter-delete-wrapper-'+response.fid, response.message );
827 }
828 });
829 });
830
831 // Get set location fields
832 let selected_link = $('#wpc_set_fields-post_type option:selected').data('link');
833 if(selected_link != ''){
834 $('.wpc-location-preview-not-pro').removeClass('display-none');
835 }
836
837 $('body').on('change', '#wpc_set_fields-post_type', function (){
838
839 let postType = $(this).val();
840 $("#wpc-filters-list").attr('data-posttype', postType );
841 let link = $('option:selected', this).data('link');
842 $('.wpc-location-preview-not-pro').attr('href', link);
843
844 if(link != ''){
845 $('.wpc-location-preview-not-pro').removeClass('display-none');
846 }else{
847 $('.wpc-location-preview-not-pro').addClass('display-none');
848 }
849
850 setAvailableEntities( $('.wpc-new-filter-item .wpc-field-entity') );
851
852 removeElement( $('.wpc-field-notice') );
853
854 // Update Post type related location terms
855 let selected = $('#wpc_set_fields-wp_page_type').val();
856 if( typeof selected !== 'undefined' /*&& selected === 'common:common'*/ ){
857 wpcGetLocationTerms( selected );
858 }
859
860 let selectEntity = $("select.wpc-field-entity");
861
862 const postMetaValues = ['post_meta', 'post_meta_num', 'post_meta_exists', 'post_meta_date'];
863
864 // Change options in all select.wpc-field-ename
865 let eNameSelect = $("select.wpc-field-ename");
866 if(postMetaValues.includes(selectEntity.val())){
867 handleMetaKeyField(selectEntity);
868 return;
869 }
870
871 if( eNameSelect.length > 0 ) {
872 fillTaxNumSelect( eNameSelect, postType );
873 }
874
875 });
876
877 // Filtered WP_Query location
878 $('body').on('change', '#wpc_set_fields-wp_page_type', function(){
879 wpcGetLocationTerms( $(this).val() );
880 });
881
882 // Apply button location
883 $('body').on('change', '#wpc_set_fields-apply_button_page_type', function(){
884 wpcGetApplyLocationTerms( $(this).val() );
885 });
886
887 $('body').on('change', '#wpc_set_fields-post_name', function (e){
888 let filterPagelink = $('option:selected', this).data('link');
889
890 if( typeof filterPagelink !== 'undefined'){
891 wpcGetWpQueries( filterPagelink );
892 }
893 });
894
895 $('body').on( 'change', '.wpc-date-format', function (e){
896 let otherFieldName = $(this).attr('name');
897 let $customField = $( '.wpc-date-custom-format[name="'+otherFieldName+'"]' );
898 if ( $(this).attr('value') === 'other' ) {
899 $customField.removeAttr('disabled');
900 } else {
901 $customField.val( $(this).val() );
902 $customField.attr('disabled', 'disabled');
903 }
904 });
905
906 $('body').on('change', '.wpc-date-type', function (e){
907
908 let dataFid = $(this).parents('.wpc-filter-item').data('fid');
909
910 let $spinner = $( '.wpc_filter_fields-'+dataFid+'-date_format-wrap' ).children( '.spinner' );
911 $spinner.addClass( 'is-active' );
912
913 // Set up AJAX request
914 let requestParams = {};
915 //requestParams._wpnonce = $("#wpc_set_nonce").val();
916 requestParams.setId = $("#post_ID").val();
917 requestParams.dateType = $("#wpc_filter_fields-"+dataFid+"-date_type").val();
918 requestParams.fid = dataFid;
919
920 wp.ajax.post( 'wpc_get_date_formats', requestParams )
921 .always( function() {
922 $spinner.removeClass( 'is-active' );
923 })
924 .done( function( response ) {
925 if ( typeof response.html !== 'undefined' ) {
926 let setDefault = true;
927 let radioList = $(response.html).find('ul');
928
929 $.each( radioList.find('input.wpc-date-format'), function( key, value ){
930 let theOption = $(this);
931 if( theOption.is(':checked') ){
932 setDefault = false;
933 return;
934 }
935 });
936
937 if( setDefault === true ) {
938 radioList.find('input.wpc-date-format:first').attr('checked', 'checked');
939 }
940
941 $( '.wpc_filter_fields-'+dataFid+'-date_format-wrap ul' ).replaceWith(radioList);
942 }
943 })
944 .fail( function(response) {
945 // {"success":false}
946 });
947 });
948
949 $('body').on('change', '.wpc-field-parent-filter', function (){
950 let parentNo = ['no', '-1'];
951 let parentVal = $(this).val();
952 let fid = $(this).parents('.wpc-filter-item').data('fid');
953 let hideTr = $("#wpc-filter-id-"+fid+" .wpc-field-hide-until-parent-tr");
954
955 if( parentNo.includes(parentVal) ){
956 hideTr.removeClass('wpc-opened');
957 }else{
958 hideTr.addClass('wpc-opened');
959 }
960 });
961
962 $('body').on('click', '#wpc_set_fields-use_apply_button', function (){
963 let applyButtonChecked = $(this).prop( "checked" );
964
965 if( applyButtonChecked ){
966 $("#wpc-filter-id-apply-button").addClass('wpc-opened');
967 $(".wpc-field-apply-button-text-tr").addClass('wpc-opened');
968 $(".wpc-field-apply-button-page-type-tr").addClass('wpc-opened');
969 $(".wpc-field-reset-button-text-tr").addClass('wpc-opened');
970 $('.wpc-no-filters').hide();
971 }else{
972 $("#wpc-filter-id-apply-button").removeClass('wpc-opened');
973 $(".wpc-field-apply-button-text-tr").removeClass('wpc-opened');
974 $(".wpc-field-apply-button-page-type-tr").removeClass('wpc-opened');
975 $(".wpc-field-reset-button-text-tr").removeClass('wpc-opened');
976
977 if( $(".wpc-filter-item:visible").length < 1 ){
978 $('.wpc-no-filters').show();
979 }
980 }
981 });
982
983 $('body').on('click', '#wpc_set_fields-horizontal_view', function (){
984 let applyButtonChecked = $(this).prop( "checked" );
985 $("#wpc_set_fields-horizontal_view_priority").val('filter_set');
986 if( applyButtonChecked ){
987 $(".wpc-field-horizontal-view-column-tr").addClass('wpc-opened');
988 }else{
989 $(".wpc-field-horizontal-view-column-tr").removeClass('wpc-opened');
990 }
991 });
992
993 $('body').on('click', '#wpc_set_fields-use_search_field', function (){
994 let searchFieldChecked = $(this).prop( "checked" );
995
996 if( searchFieldChecked ){
997 $("#wpc-filter-id-search-field").addClass('wpc-opened');
998
999 $(".wpc-search-field-placeholder-tr").addClass('wpc-opened');
1000 $(".wpc-search-field-label-tr").addClass('wpc-opened');
1001
1002 $('.wpc-no-filters').hide();
1003 }else{
1004 $("#wpc-filter-id-search-field").removeClass('wpc-opened');
1005
1006 $(".wpc-search-field-placeholder-tr").removeClass('wpc-opened');
1007 $(".wpc-search-field-label-tr").removeClass('wpc-opened');
1008
1009 if( $(".wpc-filter-item:visible").length < 1 ){
1010 $('.wpc-no-filters').show();
1011 }
1012 }
1013 });
1014
1015 $('body').on('focus keypress blur', '.wpc-field-min-num-label, .wpc-field-max-num-label', function (e){
1016 let wpcPosition = $(this).getCursorPosition();
1017 $(this).data('caret', wpcPosition);
1018 });
1019
1020 $('body').on('click', '.wpc-variable-inserter', function (e){
1021 let wrapper = $(this).parents('.wpc-filter-field-min-max-labels-wrap');
1022 $.each( wrapper.find('input[type="text"]'), function( i, field ){
1023 let inputField = $( field );
1024 let valueVar = '{value}';
1025 let caretPos = inputField.data('caret');
1026
1027 if( caretPos === 0 ){
1028 valueVar = valueVar+' ';
1029 }else if( caretPos === inputField.val().length ){
1030 valueVar = ' '+valueVar;
1031 }else{
1032 // Undefined or position in the end
1033 valueVar = ' '+valueVar+' ';
1034 }
1035
1036 insertAtCaret( inputField, valueVar, caretPos );
1037 } );
1038
1039 });
1040
1041
1042 let filterPagelink = $('option:selected', $('#wpc_set_fields-post_name')).data('link');
1043 $('.wpc-location-preview').addClass('display-none');
1044
1045 if( typeof filterPagelink !== 'undefined' && filterPagelink ){
1046 $('.wpc-location-preview').removeClass('display-none');
1047 wpcGetWpQueries( filterPagelink );
1048 }
1049
1050 let notProFilterPagelink = $('option:selected', $('#wpc_set_fields-post_type')).data('link');
1051 if( typeof notProFilterPagelink !== 'undefined' && notProFilterPagelink ){
1052 $('.wpc-location-preview-not-pro').attr('href', notProFilterPagelink);
1053 $('.wpc-location-preview-not-pro').removeClass('display-none');
1054 }
1055 });
1056 $('body').on('click', '.wpc-field-show-range-list-input', function (e){
1057 e.preventDefault();
1058 let $prevRow = $(this).prev('.range-list-value');
1059 const $currentRangeValues = $(this)
1060 .parent()
1061 .find('.range-list-value');
1062 if($('.wpc-range-list-value-error-button').length > 0){
1063 $('.wpc-range-list-value-error-button').remove();
1064 }
1065 if($prevRow.length > 0 && $prevRow.find('.wpc-range-list-min-value').val() === '' && $prevRow.find('.wpc-range-list-max-value').val() === ''){
1066 let error_html = `<div class="wpc-range-list-value-error-button"><span>${wpcSetVars.rangeListTexts.error}</span></div>`;
1067 $(this).after(error_html);
1068 return false;
1069 }
1070
1071 const name = $(this).attr('name');
1072
1073
1074 let lastRangeListNumber = 1;
1075
1076 if ($currentRangeValues.length) {
1077 lastRangeListNumber =
1078 Math.max(
1079 ...$currentRangeValues.map(function () {
1080 return Number($(this).data('list-number')) || 0;
1081 }).get()
1082 ) + 1;
1083 }
1084
1085 let html = `<div class="range-list-value" data-list-number="${lastRangeListNumber}">
1086 <div class="wpc-range-list-inputs">
1087 <div><input type="number" class="wpc-range-list-min-value" name="${name}[${lastRangeListNumber}][range_list_min_val]" placeholder="${wpcSetVars.rangeListTexts.min_value}"></div>
1088 <div><input type="number" class="wpc-range-list-max-value" name="${name}[${lastRangeListNumber}][range_list_max_val]" placeholder="${wpcSetVars.rangeListTexts.max_value}"></div>
1089 <div><input type="text" class="wpc-range-list-range-text" name="${name}[${lastRangeListNumber}][range_list_range_text]" placeholder="${wpcSetVars.rangeListTexts.label}"></div>
1090 <div><button class="button remove-range-list-value">${wpcSetVars.rangeListValueToRemove}</button></div>
1091 </div>
1092 </div>`;
1093 $(this).before(html);
1094 if(wpcSetVars.limitForRangeList <= $(this).parent().find('.range-list-value').length){
1095 $(this).prop('disabled', true);
1096 return false;
1097 }
1098
1099 changeRangeListInputStatus();
1100 });
1101
1102 $(document).on('keyup change mouseup', '.wpc-range-list-min-value, .wpc-range-list-max-value', function (e){
1103 let $currentRow = $(this).parents('.range-list-value');
1104 let $rangeListMin = $currentRow.find('.wpc-range-list-min-value');
1105 let $rangeListMax = $currentRow.find('.wpc-range-list-max-value');
1106 let rangeListTextVal = '';
1107
1108 let $prevRow = $currentRow.prev('.range-list-value');
1109 let rangeMinVal = $rangeListMin.val();
1110 let rangeMaxVal = $rangeListMax.val();
1111
1112
1113 if ($rangeListMin.val() === '') {
1114 rangeMinVal = wpcSetVars.rangeListTexts.up_to;
1115 }
1116
1117
1118 if ($rangeListMax.val() === '') {
1119 rangeMaxVal = wpcSetVars.rangeListTexts.and_up;
1120 }
1121
1122 if ($prevRow.length > 0) {
1123 if ($prevRow.find('.wpc-range-list-max-value').val() !== '' && $prevRow.find('.wpc-range-list-max-value').val() !== 0) {
1124 if(typeof $rangeListMin.val() !== 'undefined'){
1125 rangeMinVal = $prevRow.find('.wpc-range-list-max-value').val();
1126 if (e.type === 'change' && $rangeListMin.val() === '' && parseFloat(rangeMinVal) <= parseFloat($rangeListMax.val())) {
1127 $rangeListMin.val(rangeMinVal);
1128 }
1129 }
1130
1131 }
1132 }
1133
1134 if($rangeListMin.val() !== '') {
1135 rangeMinVal = $rangeListMin.val();
1136 }
1137
1138 if($rangeListMin.val() === '' && parseFloat(rangeMinVal) >= parseFloat($rangeListMax.val())){
1139 rangeMinVal = wpcSetVars.rangeListTexts.up_to;
1140 }
1141
1142 if(typeof rangeMinVal === 'undefined'){
1143 rangeMinVal = wpcSetVars.rangeListTexts.up_to;
1144 }
1145
1146 rangeListTextVal += rangeMinVal + ' - ' + rangeMaxVal;
1147 if($rangeListMin.val() === '' && $rangeListMax.val() === '' ) {
1148 rangeListTextVal = '';
1149 }else{
1150 if($currentRow.find('.wpc-range-list-value-error').length > 0){
1151 $currentRow.find('.wpc-range-list-value-error').remove();
1152 }
1153 }
1154
1155 if($('.wpc-range-list-value-error-button').length > 0){
1156 $('.wpc-range-list-value-error-button').remove();
1157 }
1158
1159 if(e.type === 'change'){
1160 if ($rangeListMin.val() != '' && $rangeListMax.val() != '' && parseFloat($rangeListMin.val()) >= parseFloat($rangeListMax.val())) {
1161 let html_val_error = `<div class="wpc-range-list-value-error"><span>${wpcSetVars.rangeListTexts.value_error}</span></div>`;
1162 $currentRow.append(html_val_error);
1163 }
1164 }
1165 $currentRow.find('.wpc-range-list-range-text').val(rangeListTextVal);
1166 });
1167
1168 $(document).on('click', '.remove-range-list-value', function (e){
1169 e.preventDefault();
1170 $(this).parents('.range-list-value').remove();
1171 if($('.range-list-value').length < wpcSetVars.limitForRangeList && $('.wpc-field-show-range-list-input').is(':disabled')){
1172 $('.wpc-field-show-range-list-input').removeAttr('disabled');
1173 }
1174 if($('.wpc-range-list-value-error-button').length > 0){
1175 $('.wpc-range-list-value-error-button').remove();
1176 }
1177 changeRangeListInputStatus();
1178 });
1179
1180 function changeRangeListInputStatus(){
1181 let $rangeListValues = $('.wpc-field-show-range-list-input-tr').find('.range-list-value');
1182 $rangeListValues.removeClass('wpc-is-first-range-list-value wpc-is-last-range-list-value');
1183 $rangeListValues.first().addClass('wpc-is-first-range-list-value');
1184 $rangeListValues.last().addClass('wpc-is-last-range-list-value');
1185 /* if(!$rangeListValues.last().hasClass('wpc-is-first-range-list-value')){
1186 $rangeListValues.last().addClass('wpc-is-last-range-list-value');
1187 }*/
1188 }
1189
1190 function wpcShortenEname( eName ){
1191 let shortenName = eName;
1192
1193 if( eName.includes( 'taxonomy_' ) ){
1194 if( eName.slice(0, 9) === 'taxonomy_' ){
1195 shortenName = eName.slice(9);
1196 }
1197 }else if( eName.includes( 'author_' ) ){
1198 if( eName.slice(0, 7) === 'author_' ){
1199 shortenName = eName.slice(7);
1200 }
1201 }
1202
1203 return shortenName;
1204 }
1205
1206 function wpcAddNewFilterToParentList(){
1207 let allIds = {};
1208 let theFid = 0;
1209 let theTitle = ''
1210 let theEname = '';
1211 let theNoVal = false;
1212 let possibleOption = false;
1213 let newOption = false;
1214
1215 $(".wpc-filter-item:not(.wpc-filter-not-listed)").each( function ( index, elem ){
1216 theFid = $(this).data('fid');
1217 theTitle = $("#wpc_filter_fields-"+theFid+"-label").val();
1218
1219 if( ! theTitle ){
1220 theTitle = wpcSetVars.newFilter;
1221 }
1222
1223 theEname = $("#wpc_filter_fields-"+theFid+"-entity").val();
1224 // theEname = wpcShortenEname(theEname);
1225
1226 allIds[theFid] = { 'id' : theFid.toString(), 'title': theTitle, 'ename': theEname};
1227 } );
1228
1229 // In case if there is only single filter in Set
1230 if( Object.keys(allIds).length < 2 ){
1231 //console.log('Less than 2');
1232 return;
1233 }
1234
1235 // If there are 2 or more filters
1236 $.each( allIds, function ( index, elem ){
1237
1238 theNoVal = $( "#wpc_filter_fields-"+elem['id']+"-parent_filter > option[value='no']");
1239 if( theNoVal.length > 0 ){
1240 theNoVal.val( '-1' );
1241 theNoVal.text( wpcSetVars.selectFilter );
1242 }
1243
1244 $.each( allIds, function ( inindex, inelem ){
1245 if( elem['id'] === inindex ){
1246 return;
1247 }
1248
1249 possibleOption = $( "#wpc_filter_fields-"+elem['id']+"-parent_filter > option[value='"+inindex+"']");
1250 if( possibleOption.length < 1 ){
1251 newOption = $('<option>', {
1252 value: inindex,
1253 text: inelem['title']+" ("+wpcShortenEname( inelem['ename'] )+")"
1254 });
1255
1256 if( inelem['ename'] === 'post_meta_num' || inelem['ename'] === 'tax_numeric' ){
1257 newOption.attr("disabled", "disabled");
1258 }
1259
1260 $( "#wpc_filter_fields-"+elem['id']+"-parent_filter").append( newOption );
1261 }
1262 });
1263 });
1264 }
1265
1266 function wpcDeleteFilterFromParentList( filterId )
1267 {
1268 let theOption = false;
1269
1270 $(".wpc-field-parent-filter option[value='"+filterId+"'").each(function (index, element){
1271 theOption = $(this);
1272 let theSelect = theOption.parents("select");
1273
1274 if( theOption.is(':selected') ){
1275 theSelect.val( theSelect.find("option:first").val() );
1276 }
1277
1278 theOption.remove();
1279
1280 if( theSelect.find("option").length === 1 ){
1281 theOption = theSelect.find("option:first");
1282 theOption.val('no');
1283 theOption.text(wpcSetVars.addFilter);
1284 theSelect.val('no');
1285 }
1286
1287 });
1288 }
1289
1290 function wpcGetWpQueries( filterPagelink ){
1291
1292 if( filterPagelink === '' ){
1293 return true;
1294 }
1295
1296 removeElement( $('.wpc-field-notice') );
1297 // 1 Get current Post type to try to find its query
1298
1299 // let selected = $('#wpc_set_fields-post_type').val();
1300 let $spinner = $( '.wpc_set_fields-wp_filter_query-wrap' ).children( '.spinner' );
1301 let postType = $("#wpc_set_fields-post_type").val();
1302
1303 // Set up AJAX request
1304 let requestParams = {};
1305 requestParams._wpnonce = $("#wpc_set_nonce").val();
1306 requestParams.wpPageType = $('#wpc_set_fields-wp_page_type').val();
1307 requestParams.postType = postType;
1308 requestParams.postId = $("#post_ID").val();
1309 requestParams.action = 'wpc_get_wp_queries';
1310
1311 let chooseButtonLink = new URL(filterPagelink);
1312
1313 chooseButtonLink.searchParams.set('flrt_get_html_selector', '1');
1314 chooseButtonLink.searchParams.set('flrt_set_id', requestParams.postId);
1315
1316
1317 $.ajax({
1318 'method': 'POST',
1319 'data': requestParams,
1320 'url': filterPagelink,
1321 'dataType': 'html',
1322 beforeSend: function () {
1323 $spinner.addClass( 'is-active' );
1324 $(".wpc-location-preview").attr('href', filterPagelink);
1325 $("#wpc-choose-selector-button").attr('href', chooseButtonLink.href);
1326 },
1327 complete: function () {
1328 $spinner.removeClass( 'is-active' );
1329 },
1330 success: function (response) {
1331 let wpcWpQueriesSelect = $(response).find('#wpc_set_fields-wp_filter_query');
1332 let wpcWpQueriesHidden = $(response).find('#wpc_query_vars');
1333
1334 if( wpcWpQueriesSelect !== '' && wpcWpQueriesSelect.length > 0 ){
1335 $("#"+wpcSetVars.wPQuerySelectId).replaceWith(wpcWpQueriesSelect);
1336 }
1337
1338 if( wpcWpQueriesHidden.length > 0 ){
1339 $('#wpc_query_vars').replaceWith(wpcWpQueriesHidden);
1340 }
1341 },
1342
1343 error: function (response) {
1344 //
1345 }
1346 });
1347 }
1348
1349 function wpcGetApplyLocationTerms( selected ){
1350
1351 let $spinner = $( '.wpc_set_fields-apply_button_post_name-wrap' ).children( '.spinner' );
1352 $spinner.addClass( 'is-active' );
1353 // Clear all errors
1354 removeElement( $('.wpc-field-notice') );
1355 let postType = $("#wpc_set_fields-post_type").val();
1356
1357 // Set up AJAX request
1358 let requestParams = {};
1359 requestParams._wpnonce = $("#wpc_set_nonce").val();
1360 requestParams.wpPageType = selected;
1361 requestParams.postType = postType;
1362 requestParams.postId = $("#post_ID").val();
1363 requestParams.fieldKey = 'apply_button_post_name';
1364
1365 wp.ajax.post( 'wpc-get-set-location-terms', requestParams )
1366 .always( function() {
1367 $spinner.removeClass( 'is-active' );
1368 })
1369 .done( function( response ) {
1370 //
1371 let locationTermsSelect = $(response.html).find('#wpc_set_fields-apply_button_post_name');
1372 $( '#wpc_set_fields-apply_button_post_name' ).replaceWith(locationTermsSelect);
1373 })
1374
1375 .fail( function(response) {
1376 // {"success":false}
1377 if( typeof response !== 'undefined'){
1378 addFieldError('wpc_set_fields-apply_button_post_name', response.message);
1379 }
1380 });
1381 }
1382
1383 function wpcGetLocationTerms( selected ){
1384
1385 let $spinner = $( '.wpc_set_fields-post_name-wrap' ).children( '.spinner' );
1386 $spinner.addClass( 'is-active' );
1387 // Clear all errors
1388 removeElement( $('.wpc-field-notice') );
1389 let postType = $("#wpc_set_fields-post_type").val();
1390
1391 // Set up AJAX request
1392 let requestParams = {};
1393 requestParams._wpnonce = $("#wpc_set_nonce").val();
1394 requestParams.wpPageType = selected;
1395 requestParams.postType = postType;
1396 requestParams.postId = $("#post_ID").val();
1397
1398 const isFreeVersion = Number(wpcSetVars.filtersPro) < 1;
1399 const $addFilterDiv = $('.wpc-add-filter-div');
1400 const $submitButton = $('#publishing-action input[type=submit]');
1401 const $publishingActionDiv = $('#publishing-action');
1402 const applyFreeFiltersUiState = (isLimited, isLoading) => {
1403 if (!isFreeVersion) return;
1404
1405 $addFilterDiv.toggleClass('wpc_under_limit_filter_set', Boolean(isLimited));
1406 $publishingActionDiv.toggleClass('wpc_under_limit_filter_set_publish', Boolean(isLimited));
1407
1408 if (isLoading) {
1409 $submitButton.addClass('disabled').prop('disabled', true);
1410 } else {
1411 $submitButton.removeClass('disabled').prop('disabled', false);
1412 }
1413 };
1414
1415 applyFreeFiltersUiState(isLimitFilterSet, true);
1416
1417 wp.ajax.post( 'wpc-get-set-location-terms', requestParams )
1418 .always( function() {
1419 $spinner.removeClass( 'is-active' );
1420 })
1421 .done( function( response ) {
1422 //
1423 let locationTermsSelect = $(response.html).find('#wpc_set_fields-post_name');
1424 $( '#wpc_set_fields-post_name' ).replaceWith(locationTermsSelect);
1425
1426 isLimitFilterSet = response.isLimitFilterSet;
1427 applyFreeFiltersUiState(isLimitFilterSet, false);
1428
1429 let filterPagelink = $('option:selected', $('#wpc_set_fields-post_name') ).data('link');
1430 if( typeof filterPagelink !== 'undefined'){
1431 wpcGetWpQueries( filterPagelink );
1432 }
1433 })
1434
1435 .fail( function(response) {
1436 // {"success":false}
1437 if( typeof response !== 'undefined'){
1438 addFieldError('wpc_set_fields-post_name', response.message);
1439 }
1440 });
1441 }
1442
1443 function cpaLiveWrite( readFrom, writeTo ) {
1444 let cpaText;
1445 // readFrom.on('input', function() {
1446 cpaText = readFrom.val(); //$(this).val();
1447 writeTo.text(cpaText);
1448 // });
1449 }
1450
1451 /**
1452 * Calculates correct menu order in accordance with filter position in list
1453 */
1454 function renderMenuOrder()
1455 {
1456 $(".wpc-filter-item").each( function ( index, element ) {
1457 var num = index + 1;
1458 $(element).find('.wpc-menu-order-field').attr( 'value', num );
1459 $(element).find('.wpc-filter-order').attr( 'title', num );
1460 });
1461 }
1462
1463 function handleNoFiltersMessage()
1464 {
1465 if( $(".wpc-filter-item:not(.wpc-filter-not-listed)").length > 0 ){
1466 $('.wpc-no-filters').hide();
1467 }else{
1468 if ( $(".wpc-filter-not-listed").hasClass('wpc-opened') === false ){
1469 $('.wpc-no-filters').show();
1470 }
1471 }
1472 }
1473
1474 function setEntityTableClass( entitySelect )
1475 {
1476 let val = entitySelect.val();
1477 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
1478 let additionalClass = '';
1479
1480 if( val.startsWith('taxonomy_pa_') ){
1481 additionalClass = ' taxonomy-product-attribute';
1482 }
1483
1484 if( val.indexOf('taxonomy') !== -1 ){
1485 val = 'taxonomy';
1486 }
1487
1488 $("#wpc-filter-id-"+fid+" .wpc-form-fields-table").attr('class', 'wpc-form-fields-table wpc-filter-'+val+additionalClass);
1489 }
1490
1491 function syncEntityWithPrefix( entitySelect )
1492 {
1493 let val = entitySelect.val();
1494 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
1495
1496 if( typeof wpcSetVars.filterSlugs[val] !== 'undefined'){
1497 let prefix = wpcSetVars.filterSlugs[val];
1498 $('#wpc_filter_fields-'+fid+'-slug').val(prefix)
1499 .attr('readonly', 'readonly')
1500 .trigger('input');
1501 } else {
1502 $('#wpc_filter_fields-'+fid+'-slug').val('')
1503 .removeAttr('readonly')
1504 .trigger('input');
1505 }
1506
1507 }
1508
1509 function syncEntityWithSortTerms( entitySelect ){
1510 let val = entitySelect.val();
1511 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
1512
1513 if( ! val.includes('taxonomy_pa') ) {
1514 $('#wpc_filter_fields-'+fid+'-orderby option[value="menuasc"]').attr('disabled', 'disabled');
1515 $('#wpc_filter_fields-'+fid+'-orderby option[value="menudesc"]').attr('disabled', 'disabled');
1516 }else{
1517 $('#wpc_filter_fields-'+fid+'-orderby option[value="menuasc"]').removeAttr('disabled');
1518 $('#wpc_filter_fields-'+fid+'-orderby option[value="menudesc"]').removeAttr('disabled');
1519 }
1520 }
1521
1522 function syncEntityWithView( entitySelect ){
1523 let val = entitySelect.val();
1524 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
1525 if( val === 'post_meta_num' || val === 'tax_numeric' ) {
1526 $('#wpc_filter_fields-' + fid + '-view option:not([value="range"])').attr('disabled', 'disabled');
1527 $('#wpc_filter_fields-' + fid + '-view option[value="range"]').removeAttr('disabled').prop('selected', true);
1528 $('#wpc_filter_fields-' + fid + '-view').trigger('change');
1529 } else if ( val === 'taxonomy_product_visibility' ) {
1530 $('#wpc_filter_fields-' + fid + '-view option[value="rating"]').removeAttr('disabled')
1531 .prop('selected', true);
1532 $('.wpc-form-fields-table').addClass('wpc-view-rating');
1533 }
1534 else if ( val === 'post_date' || val === 'post_meta_date' ) {
1535 $('#wpc_filter_fields-' + fid + '-view option:not([value="date"])').attr('disabled', 'disabled');
1536 $('#wpc_filter_fields-' + fid + '-view option[value="date"]').removeAttr('disabled')
1537 .prop('selected', true);
1538 $('#wpc_filter_fields-' + fid + '-view').trigger('change');
1539 }else{
1540 $('#wpc_filter_fields-'+fid+'-view option').removeAttr('disabled')
1541 $('#wpc_filter_fields-'+fid+'-view option:not([disabled]):first').prop('selected', true);
1542 $('#wpc_filter_fields-'+fid+'-view option[value="range"]').attr('disabled', 'disabled');
1543 $('#wpc_filter_fields-'+fid+'-view option[value="rating"]').attr('disabled', 'disabled');
1544 $('#wpc_filter_fields-'+fid+'-view option[value="date"]').attr('disabled', 'disabled');
1545 $('#wpc_filter_fields-'+fid+'-view').trigger('change');
1546 }
1547 }
1548
1549
1550 function handleLogicField( entitySelect )
1551 {
1552 let val = entitySelect.val();
1553 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
1554
1555 if ( val === 'author_author' || val === 'post_meta_exists' || val === 'taxonomy_product_visibility' ) {
1556 $( '#wpc_filter_fields-' + fid + '-logic option[value="and"]' ).attr( 'disabled', 'disabled' );
1557 $( '#wpc_filter_fields-'+fid+'-logic option[value="or"]' ).removeAttr( 'disabled' );
1558 $( '#wpc_filter_fields-' + fid + '-logic option[value="or"]' ).prop( 'selected', true );
1559 } else if ( val === 'post_meta_num' || val === 'tax_numeric' || val === 'post_date' || val === 'post_meta_date' ) {
1560 // If filter is numeric logic can be AND only
1561 $( '#wpc_filter_fields-' + fid + '-logic option[value="or"]' ).attr( 'disabled', 'disabled' );
1562 $( '#wpc_filter_fields-' + fid + '-logic option[value="and"]' ).removeAttr( 'disabled');
1563 $( '#wpc_filter_fields-' + fid + '-logic option[value="and"]' ).prop( 'selected', true );
1564 } else {
1565 $( '#wpc_filter_fields-'+fid+'-logic option[value="and"]' ).removeAttr( 'disabled' );
1566 $( '#wpc_filter_fields-'+fid+'-logic option[value="or"]' ).removeAttr( 'disabled' );
1567 }
1568
1569 return true;
1570 }
1571
1572 function handleHierarchyField( entitySelect )
1573 {
1574 let val = entitySelect.val();
1575 let $divFilterItem = entitySelect.parents('.wpc-filter-item');
1576
1577 if( val.indexOf('taxonomy') !== -1 ){
1578 $.each( wpcSetVars.postTypesTaxList, function ( pType, taxesArray ){
1579 $.each( taxesArray, function ( index, theTax ){
1580 if( theTax['name'] === val ){
1581 if( theTax['hierarchical'] ){
1582 $divFilterItem.find('.wpc-form-fields-table').addClass('taxonomy-hierarchical');
1583 }else{
1584 $divFilterItem.find('.wpc-form-fields-table').removeClass('taxonomy-hierarchical');
1585 }
1586 }
1587 });
1588 });
1589 } else {
1590 $divFilterItem.find('.wpc-form-fields-table').removeClass('taxonomy-hierarchical');
1591 }
1592 }
1593
1594 function handleMetaKeyField( entitySelect )
1595 {
1596 let val = entitySelect.val();
1597 let fid = entitySelect.parents('.wpc-filter-item').data('fid');
1598 let postType = $("#wpc_set_fields-post_type").val();
1599
1600 if ( val === 'post_meta' || val === 'post_meta_num' || val === 'post_meta_exists' || val === 'post_meta_date' ) {
1601 let eNameTag = $('#wpc_filter_fields-'+fid+'-e_name');
1602 if ( eNameTag.prop("tagName").toLowerCase() === 'select' && eNameTag.is('[readonly]')) {
1603 let eNameInput = $('<input>');
1604
1605 eNameInput.attr( 'class', eNameTag.attr('class') )
1606 .attr( 'type', 'text' )
1607 .attr( 'name', eNameTag.attr('name') )
1608 .attr( 'id', eNameTag.attr('id') );
1609
1610 eNameTag.val('');
1611 eNameTag.removeAttr('readonly');
1612 eNameTag.replaceWith(eNameInput);
1613
1614 eNameInput.parents('.wpc-field-ename-tr').show();
1615 } else {
1616 if (eNameTag.length > 0 && eNameTag.hasClass('select2-hidden-accessible')) {
1617 eNameTag.select2('destroy');
1618 eNameTag.empty();
1619 eNameTag.off();
1620 }
1621 let eNameSelect = $('<select>');
1622 eNameSelect
1623 .attr('class', eNameTag.attr('class'))
1624 .attr('name', eNameTag.attr('name'))
1625 .attr('id', eNameTag.attr('id'));
1626
1627 eNameTag.val('');
1628 eNameTag.replaceWith(eNameSelect);
1629
1630 const defaultCustomMetaKeys = wpcSetVars.defaultCustomMetaKeys;
1631
1632 const ptItems = defaultCustomMetaKeys?.[postType]?.[val];
1633 const allItems = defaultCustomMetaKeys?.['all_post_types']?.[val];
1634
1635 const getItems = (items) => {
1636 if (items && typeof items === 'object') {
1637 Object.entries(items).forEach(function ([key, value]) {
1638 items[key] = value;
1639 });
1640 return items;
1641 }
1642 return [];
1643 }
1644
1645 let tItems = [];
1646
1647 tItems = getItems(ptItems);
1648 if (tItems.length > 0) {
1649 tItems.push(getItems(allItems));
1650 }
1651
1652 const prefillItems = Object.entries(tItems).map(([key, value]) => ({
1653 id: key,
1654 text: value
1655 }));
1656
1657 let minimumInputLength = 1;
1658 if(prefillItems.length > 0){
1659 minimumInputLength = 0;
1660 }
1661
1662 eNameSelect.select2({
1663 width: '100%',
1664 ajax: {
1665 url: ajaxurl,
1666 dataType: 'json',
1667 data: function (params) {
1668 return {
1669 action: 'wpc_search_meta_keys',
1670 _flrt_nonce: $('#wpc_set_nonce').val(),
1671 post_type: postType,
1672 post_meta_type: val,
1673 q: params.term || ''
1674 };
1675 },
1676 transport: function (params, success, failure) {
1677 let dots = 0;
1678 let animatedDotInterval;
1679 const startAnimation = (el)=> {
1680 if (!animatedDotInterval) { // Prevent multiple intervals
1681 animatedDotInterval = setInterval(function() {
1682 if (dots < 3) {
1683 el.append('.');
1684 dots++;
1685 } else {
1686 el.text(''); // Clear dots
1687 dots = 0;
1688 }
1689 }, 400); // Interval in milliseconds
1690 }
1691 }
1692 if($('.loading-dots-search').length > 0){
1693 startAnimation($('.loading-dots-search'));
1694 }
1695
1696 let term = (params.data && (params.data.q || params.data.term)) || '';
1697
1698 if (!term && prefillItems.length > 0) {
1699 success({ items: prefillItems });
1700 return {
1701 abort: function () {}
1702 };
1703 }
1704
1705
1706 let delayTime = term ? 0 : 1000;
1707 let doRequest = function () {
1708 let $request = $.ajax(params);
1709 $request.then(success);
1710 $request.fail(failure);
1711 return $request;
1712 };
1713 if (delayTime > 0) {
1714 let timeout = setTimeout(doRequest, delayTime);
1715 return {
1716 abort: function () { clearTimeout(timeout); }
1717 };
1718 }
1719 return doRequest();
1720 },
1721 processResults: function (data, params) {
1722 let items = (data && data.items) ? data.items : [];
1723 if (!params || !params.term || !params.q) {
1724 if (!items.length && prefillItems.length) {
1725 return { results: prefillItems };
1726 }
1727 }
1728
1729 if (items.length > 0) {
1730 items.forEach((el, index) => {
1731 if(el.text !== '' && el.text !== el.id && !el.text.startsWith(el.id)){
1732 el.text = el.id + '<span class="wpc-select2-dots">:</span><span class="wpc-select2-info">' + el.text + '</span>';
1733 } else if (el.text !== '' && el.text !== el.id && el.text.startsWith(el.id)) {
1734 }else{
1735 el.text = el.id;
1736 }
1737 items[index] = el;
1738 });
1739 }
1740
1741 return { results: items };
1742 },
1743 cache: false
1744
1745 },
1746 placeholder: wpcSetVars.selectMetaKeyPlaceholder,
1747 allowClear: true,
1748 minimumInputLength: minimumInputLength,
1749 templateSelection: function (data, container) {
1750 if (data.id === '' || !data.id) {
1751 return wpcSetVars.selectMetaKeyPlaceholder;
1752 }
1753 return data.id;
1754 },
1755 escapeMarkup: function (markup) { return markup; },
1756 language: {
1757 searching: function () {
1758 return $('<span>' + wpcSetVars.metaKeySearchText +'</span><span class="loading-dots-search"></span>')
1759
1760 },
1761 errorLoading: function () {
1762 return $('<span>' + wpcSetVars.metaKeySearchText + '</span><span class="loading-dots-search"></span>')
1763 }
1764 },
1765 });
1766
1767 eNameSelect.parents('.wpc-field-ename-tr').show();
1768 }
1769
1770 $('#wpc-filter-id-'+fid+' .wpc-field-ename-tr p.wpc-field-description').text( numFieldAttrs['post_meta_num']['description'] );
1771 $('#wpc-filter-id-'+fid+' .wpc-field-ename-tr label.wpc-filter-label span.wpc-label-text').text( numFieldAttrs['post_meta_num']['label'] );
1772 $('#wpc-filter-id-'+fid+' .wpc-field-ename-tr p.description').css('visibility', 'visible');
1773
1774 } else if ( val === 'tax_numeric' ) {
1775 let eNameTag = $('#wpc_filter_fields-'+fid+'-e_name');
1776 if (eNameTag.length > 0 && eNameTag.hasClass('select2-hidden-accessible')) {
1777 eNameTag.select2('destroy');
1778 eNameTag.empty();
1779 eNameTag.off();
1780 }
1781
1782 let postType = $("#wpc_set_fields-post_type").val();
1783 let tagName = eNameTag.prop("tagName").toLowerCase();
1784
1785 if ( tagName === 'input') {
1786 let eNameSelect = $('<select>');
1787
1788 eNameSelect.attr( 'class', eNameTag.attr('class') )
1789 .attr( 'name', eNameTag.attr('name') )
1790 .attr( 'id', eNameTag.attr('id') );
1791
1792 eNameTag.removeAttr( 'readonly' );
1793 eNameTag.replaceWith( eNameSelect );
1794 //@todo - if already existing tax_numeric slug presents, it should be inserted as usual
1795 //@todo - if filter by this tax numeric entity exists, it should be deactivated in the Tax num dropdown
1796 fillTaxNumSelect( eNameSelect, postType );
1797 eNameSelect.parents('.wpc-field-ename-tr').show();
1798 } else {
1799 fillTaxNumSelect( eNameTag, postType );
1800 eNameTag.parents('.wpc-field-ename-tr').show();
1801 }
1802
1803 $('#wpc-filter-id-'+fid+' .wpc-field-ename-tr p.wpc-field-description').text( numFieldAttrs['tax_numeric']['description'] );
1804 $('#wpc-filter-id-'+fid+' .wpc-field-ename-tr label.wpc-filter-label span.wpc-label-text').text( numFieldAttrs['tax_numeric']['label'] );
1805 $('#wpc-filter-id-'+fid+' .wpc-field-ename-tr p.description').css('visibility', 'hidden');
1806
1807 } else {
1808 let eNameTag = $('#wpc_filter_fields-'+fid+'-e_name');
1809 if ( eNameTag.prop("tagName").toLowerCase() === 'select') {
1810
1811 if (eNameTag.length > 0 && eNameTag.hasClass('select2-hidden-accessible')) {
1812 eNameTag.select2('destroy');
1813 eNameTag.empty();
1814 eNameTag.off();
1815 }
1816
1817 let eNameInput = $('<input>');
1818 eNameInput.attr( 'class', eNameTag.attr('class') )
1819 .attr( 'type', 'text' )
1820 .attr( 'name', eNameTag.attr('name') )
1821 .attr( 'id', eNameTag.attr('id') )
1822 .attr( 'value', '');
1823
1824 eNameTag.replaceWith(eNameInput);
1825 $('#wpc_filter_fields-'+fid+'-e_name').parents('.wpc-field-ename-tr').hide();
1826 }
1827 }
1828
1829 // Numeric values can not be in URL path
1830 if( val === 'post_meta_num' || val === 'tax_numeric' || val === 'post_date' || val === 'post_meta_date' ){
1831 $('#wpc_filter_fields-'+fid+'-in_path').prop( "checked", false );
1832 // $('#wpc_filter_fields-'+fid+'-show_chips').prop( "checked", false );
1833 }else{
1834 $('#wpc_filter_fields-'+fid+'-in_path').prop( "checked", true );
1835 // $('#wpc_filter_fields-'+fid+'-show_chips').prop( "checked", true );
1836 }
1837 }
1838
1839 function loadExcludeItems( entity, fid, ename )
1840 {
1841 removeElement( $('.wpc-field-notice') );
1842 let requestParams = {};
1843 let target = $('#wpc_filter_fields-'+fid+'-exclude');
1844 requestParams._wpnonce = $("#wpc_set_nonce").val();
1845 requestParams.fid = fid;
1846 requestParams.entity = entity;
1847
1848 if( typeof ename !== 'undefined' ){
1849 requestParams.ename = ename;
1850 }
1851
1852 let $spinner = target.parent('.wpc-after-spinner-container').prev( '.spinner' );
1853 $spinner.addClass( 'is-active' );
1854
1855 wp.ajax.post( 'wpc-load-exclude-terms', requestParams )
1856 .always( function() {
1857 $spinner.removeClass( 'is-active' );
1858 })
1859 .done( function( response ) {
1860 if( typeof response.fid !== 'undefined' ){
1861 target.select2('destroy');
1862 target.html('');
1863 target.select2({
1864 width: '100%',
1865 placeholder: wpcSetVars.excludePlaceholder,
1866 data: response.terms,
1867 disabled: false
1868 })
1869 }
1870 })
1871
1872 .fail( function(response) {
1873 // if( typeof response !== 'undefined'){
1874 // addFieldError( 'wpc_filter_fields-'+response.fid+'-exclude', response.message );
1875 // }
1876 });
1877
1878 }
1879
1880 function wpcSerialize( $el ){
1881
1882 let obj = {};
1883 let inputs = $el.find('select, textarea, input').serializeArray();
1884
1885 for( let i = 0; i < inputs.length; i++ ) {
1886 wpcBuildObject( obj, inputs[i].name, inputs[i].value );
1887 }
1888 return obj;
1889 }
1890
1891 function wpcBuildObject( obj, name, value ){
1892 name = name.replace('[]', '[%%index%%]');
1893
1894 var keys = name.match(/([^\[\]])+/g);
1895 if( !keys ) return;
1896 var length = keys.length;
1897 var ref = obj;
1898
1899 for( var i = 0; i < length; i++ ) {
1900 var key = String( keys[i] );
1901 if( i == length - 1 ) {
1902 if( key === '%%index%%' ) {
1903 ref.push( value );
1904 } else {
1905 ref[ key ] = value;
1906 }
1907 } else {
1908 if( keys[i+1] === '%%index%%' ) {
1909 if( !wpcIsArray(ref[ key ]) ) {
1910 ref[ key ] = [];
1911 }
1912 } else {
1913 if( !wpcIsObject(ref[ key ]) ) {
1914 ref[ key ] = {};
1915 }
1916 }
1917 ref = ref[ key ];
1918 }
1919 }
1920 };
1921
1922 function wpcIsArray( a ){
1923 return Array.isArray(a);
1924 };
1925
1926 function wpcIsObject( a ){
1927 return ( typeof a === 'object' );
1928 }
1929
1930 /**
1931 * Fills Tax Num Select with options
1932 * @param $el (object) The select element
1933 * @param postType Post type selected to filter
1934 */
1935 function fillTaxNumSelect( $el, postType ) {
1936 $el.find('option')
1937 .remove()
1938 .end();
1939
1940 if ( postType in postTypesTaxList ) {
1941 $( postTypesTaxList[ postType ] ).each( function() {
1942 $el.append( $("<option>").attr('value', this.name ).text( this.label ) );
1943 });
1944 } else {
1945 $el.append( $("<option>").attr('value', -1 ).text( numFieldNoTaxes ) );
1946 }
1947 }
1948
1949 })(jQuery);
1950
1951 function insertAtCaret( target, text, caretPos )
1952 {
1953 let textAreaTxt = target.val();
1954 let result = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
1955 result = result.replace(/ +(?= )/g,'');
1956 target.val(result);
1957
1958 return true;
1959 }
1960
1961 // Important!!!
1962 // When field Filter by is selected, it is required to make AJAX request to find the same
1963 // entity in filters already. And if it is exists, to predefine field "slug" defined in previous
1964 // selection of
1965
1966 function uniqId (prefix, moreEntropy) {
1967 // discuss at: https://locutus.io/php/uniqid/
1968 // original by: Kevin van Zonneveld (https://kvz.io)
1969 // revised by: Kankrelune (https://www.webfaktory.info/)
1970 // note 1: Uses an internal counter (in locutus global) to avoid collision
1971 // example 1: var $id = uniqid()
1972 // example 1: var $result = $id.length === 13
1973 // returns 1: true
1974 // example 2: var $id = uniqid('foo')
1975 // example 2: var $result = $id.length === (13 + 'foo'.length)
1976 // returns 2: true
1977 // example 3: var $id = uniqid('bar', true)
1978 // example 3: var $result = $id.length === (23 + 'bar'.length)
1979 // returns 3: true
1980
1981 if (typeof prefix === 'undefined') {
1982 prefix = '';
1983 }
1984
1985 var retId;
1986 var _formatSeed = function (seed, reqWidth) {
1987 seed = parseInt(seed, 10).toString(16); // to hex str
1988 if (reqWidth < seed.length) {
1989 // so long we split
1990 return seed.slice(seed.length - reqWidth);
1991 }
1992 if (reqWidth > seed.length) {
1993 // so short we pad
1994 return Array(1 + (reqWidth - seed.length)).join('0') + seed;
1995 }
1996 return seed;
1997 }
1998
1999 var $global = (typeof window !== 'undefined' ? window : global);
2000 $global.$locutus = $global.$locutus || {}
2001 var $locutus = $global.$locutus;
2002 $locutus.php = $locutus.php || {}
2003
2004 if (!$locutus.php.uniqidSeed) {
2005 // init seed with big random int
2006 $locutus.php.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
2007 }
2008 $locutus.php.uniqidSeed++;
2009
2010 // start with prefix, add current milliseconds hex string
2011 retId = prefix;
2012 retId += _formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
2013 // add seed hex string
2014 retId += _formatSeed($locutus.php.uniqidSeed, 5);
2015 if (moreEntropy) {
2016 // for more entropy we add a float lower to 10
2017 retId += (Math.random() * 10).toFixed(8).toString();
2018 }
2019
2020 return retId;
2021 }