Start implementing search

This commit is contained in:
Tetrakern 2024-03-13 00:25:05 +01:00
parent 08e4108e80
commit fa9154bc23
4 changed files with 122 additions and 3 deletions

View file

@ -163,3 +163,53 @@ function fcnen_ajax_subscribe() {
}
add_action( 'wp_ajax_fcnen_ajax_subscribe', 'fcnen_ajax_subscribe' );
add_action( 'wp_ajax_nopriv_fcnen_ajax_subscribe', 'fcnen_ajax_subscribe' );

/**
* AJAX callback to search content
*
* @since 0.1.0
*/

function fcnen_ajax_search_content() {
// Verify
if ( ! wp_doing_ajax() ) {
wp_send_json_error( __( 'Invalid request.', 'fcnen' ) );
}

if ( ! check_ajax_referer( 'fcnen-subscribe', 'nonce', false ) ) {
wp_send_json_error(
array( 'notice' => __( 'Nonce verification failed. Please reload and try again.', 'fcnen' ) )
);
}

// Setup
$search = sanitize_text_field( $_REQUEST['search'] ?? '' );
$page = absint( $_REQUEST['page'] ?? 1 );
$output = [];

// Query
// $query = new WP_Query(
// array(
// 'post_status' => 'publish',
// 'orderby' => 'date',
// 'order' => 'desc',
// 'posts_per_page' => 10,
// 'paged' => $page,
// 's' => $search,
// 'update_post_meta_cache' => false, // Improve performance
// 'update_post_term_cache' => false // Improve performance
// )
// );

$output[] = '<li class="fcnen-dialog-modal__advanced-li" data-id="#" data-type="foo"><span>Dummy result!</span></li>';


// Response
wp_send_json_success(
array(
'html' => implode( '', $output )
)
);
}
add_action( 'wp_ajax_fcnen_ajax_search_content', 'fcnen_ajax_search_content' );
add_action( 'wp_ajax_nopriv_fcnen_ajax_search_content', 'fcnen_ajax_search_content' );

View file

@ -1 +1 @@
const fcnen_modal=document.getElementById("fcnen-subscription-modal"),fcnen_targetContainer=fcnen_modal?.querySelector('[data-target="fcnen-modal-loader"]'),fcnen_url_params=Object.fromEntries(new URLSearchParams(window.location.search).entries());function fcnen_addEventListeners(){document.querySelector('[data-click-action="auth-mode"]')?.addEventListener("click",(()=>{fcnen_modal.querySelector('[data-target="auth-mode"]').hidden=!1,fcnen_modal.querySelector('[data-target="submit-mode"]').hidden=!0})),document.querySelector('[data-click-action="submit-mode"]')?.addEventListener("click",(()=>{fcnen_modal.querySelector('[data-target="auth-mode"]').hidden=!0,fcnen_modal.querySelector('[data-target="submit-mode"]').hidden=!1})),document.getElementById("fcnen-modal-submit-button")?.addEventListener("click",(e=>{fcnen_subscribe_or_update(e.currentTarget)})),document.getElementById("fcnen-modal-auth-button")?.addEventListener("click",(()=>{fcnen_getModalForm("edit")})),document.querySelector('[data-click-action="fcnen-delete-subscription"]')?.addEventListener("click",(()=>{fcnen_unsubscribe()})),document.getElementById("fcnen-modal-checkbox-scope-everything")?.addEventListener("change",(e=>{fcnen_modal.querySelector("form").classList.toggle("_everything",e.currentTarget.checked)}))}function fcnen_toggleInProgress(e=!0){fcnen_targetContainer.classList.toggle("ajax-in-progress",e)}function fcnen_getPreparedFormData(e){let n=new FormData(e),t={};for(let[e,c]of n.entries()){let n=e.replace(/\[\]/g,"");t.modifiedKey?t[n].push(c):t[n]=[c]}for(let e in t)Array.isArray(t[e])&&(t[e]=t[e].join(","));return t}function fcnen_getModalForm(e="new"){if("new"==e&&document.getElementById("fcnen-subscription-form"))return;const n=fcnen_url_params["fcnen-email"]??document.getElementById("fcnen-modal-auth-email")?.value??0,t=fcnen_url_params["fcnen-code"]??document.getElementById("fcnen-modal-auth-code")?.value??0;if("edit"==e&&!n&&!t)return;"edit"==e&&fcnen_toggleInProgress();fcn_ajaxPost({action:"fcnen_ajax_get_form_content","auth-email":n,"auth-code":t}).then((e=>{e.success&&(fcnen_targetContainer.innerHTML=e.data.html)})).then((()=>{fcnen_toggleInProgress(!1),fcnen_addEventListeners()}))}function fcnen_subscribe_or_update(e){const n=e.closest("form"),t=document.getElementById("fcnen-modal-submit-email")?.value,c=fcnen_getPreparedFormData(n);if(!t)return void n.reportValidity();fcnen_toggleInProgress();let a={action:"fcnen_ajax_subscribe_or_update",email:t,nonce:fcnen_modal.querySelector('input[name="nonce"]')?.value??""};a={...a,...c},fcn_ajaxPost(a).then((e=>{fcnen_targetContainer.innerHTML=`<div class="fcnen-dialog-modal__notice"><p>${e.data.notice}</p></div>`,fcnen_toggleInProgress(!1)}))}function fcnen_unsubscribe(){fcnen_toggleInProgress();const e={action:"fcnen_ajax_subscribe",email:document.getElementById("fcnen-modal-submit-email")?.value??"",code:document.getElementById("fcnen-modal-submit-code")?.value??0,nonce:fcnen_modal.querySelector('input[name="nonce"]')?.value??""};fcn_ajaxPost(e).then((e=>{fcnen_targetContainer.innerHTML=`<div class="fcnen-dialog-modal__notice"><span>${e.data.notice}</span></div>`,fcnen_toggleInProgress(!1)}))}fcnen_modal&&(document.querySelectorAll('[data-click-action*="fcnen-load-modal-form"]').forEach((e=>{e.addEventListener("click",(()=>{fcnen_getModalForm()}),{once:!0})})),fcnen_url_params["fcnen-email"]&&fcnen_url_params["fcnen-code"]&&document.addEventListener("DOMContentLoaded",(()=>{setTimeout((()=>{fcnen_modal.showModal(),fcnen_getModalForm()}),100)}))),history.replaceState&&history.replaceState(null,"",location.pathname+location.search.replace(/[?&](fcnen-email|fcnen-code|fcnen-action|fcnen|)=[^&]+/g,"").replace(/^[?&]/,"?")+location.hash);
const fcnen_modal=document.getElementById("fcnen-subscription-modal"),fcnen_targetContainer=fcnen_modal?.querySelector('[data-target="fcnen-modal-loader"]'),fcnen_url_params=Object.fromEntries(new URLSearchParams(window.location.search).entries());function fcnen_addEventListeners(){document.querySelector('[data-click-action="auth-mode"]')?.addEventListener("click",(()=>{fcnen_modal.querySelector('[data-target="auth-mode"]').hidden=!1,fcnen_modal.querySelector('[data-target="submit-mode"]').hidden=!0})),document.querySelector('[data-click-action="submit-mode"]')?.addEventListener("click",(()=>{fcnen_modal.querySelector('[data-target="auth-mode"]').hidden=!0,fcnen_modal.querySelector('[data-target="submit-mode"]').hidden=!1})),document.getElementById("fcnen-modal-submit-button")?.addEventListener("click",(e=>{fcnen_subscribe_or_update(e.currentTarget)})),document.getElementById("fcnen-modal-auth-button")?.addEventListener("click",(()=>{fcnen_getModalForm("edit")})),document.querySelector('[data-click-action="fcnen-delete-subscription"]')?.addEventListener("click",(()=>{fcnen_unsubscribe()})),document.getElementById("fcnen-modal-checkbox-scope-everything")?.addEventListener("change",(e=>{fcnen_modal.querySelector("form").classList.toggle("_everything",e.currentTarget.checked)})),fcnen_initializeSearch()}function fcnen_toggleInProgress(e=!0){fcnen_targetContainer.classList.toggle("ajax-in-progress",e)}function fcnen_getPreparedFormData(e){let n=new FormData(e),t={};for(let[e,c]of n.entries()){let n=e.replace(/\[\]/g,"");t.modifiedKey?t[n].push(c):t[n]=[c]}for(let e in t)Array.isArray(t[e])&&(t[e]=t[e].join(","));return t}function fcnen_getModalForm(e="new"){if("new"==e&&document.getElementById("fcnen-subscription-form"))return;const n=fcnen_url_params["fcnen-email"]??document.getElementById("fcnen-modal-auth-email")?.value??0,t=fcnen_url_params["fcnen-code"]??document.getElementById("fcnen-modal-auth-code")?.value??0;if("edit"==e&&!n&&!t)return;"edit"==e&&fcnen_toggleInProgress();fcn_ajaxPost({action:"fcnen_ajax_get_form_content","auth-email":n,"auth-code":t}).then((e=>{e.success&&(fcnen_targetContainer.innerHTML=e.data.html)})).then((()=>{fcnen_toggleInProgress(!1),fcnen_addEventListeners()}))}function fcnen_subscribe_or_update(e){const n=e.closest("form"),t=document.getElementById("fcnen-modal-submit-email")?.value,c=fcnen_getPreparedFormData(n);if(!t)return void n.reportValidity();fcnen_toggleInProgress();let a={action:"fcnen_ajax_subscribe_or_update",email:t,nonce:fcnen_modal.querySelector('input[name="nonce"]')?.value??""};a={...a,...c},fcn_ajaxPost(a).then((e=>{fcnen_targetContainer.innerHTML=`<div class="fcnen-dialog-modal__notice"><p>${e.data.notice}</p></div>`,fcnen_toggleInProgress(!1)}))}function fcnen_unsubscribe(){fcnen_toggleInProgress();const e={action:"fcnen_ajax_subscribe",email:document.getElementById("fcnen-modal-submit-email")?.value??"",code:document.getElementById("fcnen-modal-submit-code")?.value??0,nonce:fcnen_modal.querySelector('input[name="nonce"]')?.value??""};fcn_ajaxPost(e).then((e=>{fcnen_targetContainer.innerHTML=`<div class="fcnen-dialog-modal__notice"><span>${e.data.notice}</span></div>`,fcnen_toggleInProgress(!1)}))}var fcncn_searchTimer;function fcnen_initializeSearch(){document.querySelectorAll('[data-input-target="fcnen-search"]').forEach((e=>{e.addEventListener("input",(()=>{clearTimeout(fcncn_searchTimer),fcncn_searchTimer=setTimeout((()=>{const n=e.closest(".fcnen-dialog-modal__advanced").querySelector('[data-target="fcnen-sources"]');if(n.innerHTML="",n.appendChild(document.querySelector('[data-target="fcnen-spinner-template"]').content.cloneNode(!0)),e.value>200&&(e.value=e.value.slice(0,200)),""==e.value)return n.innerHTML="",void n.appendChild(document.querySelector('[data-target="fcnen-no-matches"]').content.cloneNode(!0));fcnen_searchContent({action:"fcnen_ajax_search_content",search:e.value,nonce:fcnen_modal.querySelector('input[name="nonce"]')?.value??""},n)}),800)}))}))}function fcnen_searchContent(e,n){fcn_ajaxPost(e).then((e=>{e.success&&(n.innerHTML=e.data.html)}))}fcnen_modal&&(document.querySelectorAll('[data-click-action*="fcnen-load-modal-form"]').forEach((e=>{e.addEventListener("click",(()=>{fcnen_getModalForm()}),{once:!0})})),fcnen_url_params["fcnen-email"]&&fcnen_url_params["fcnen-code"]&&document.addEventListener("DOMContentLoaded",(()=>{setTimeout((()=>{fcnen_modal.showModal(),fcnen_getModalForm()}),100)}))),history.replaceState&&history.replaceState(null,"",location.pathname+location.search.replace(/[?&](fcnen-email|fcnen-code|fcnen-action|fcnen|)=[^&]+/g,"").replace(/^[?&]/,"?")+location.hash);

View file

@ -126,14 +126,23 @@ function fcnen_get_modal_content() {

<div class="dialog-modal__row fcnen-dialog-modal__advanced">
<div class="fcnen-dialog-modal__advanced-search">
<input type="search" id="fcnen-modal-search" class="fcnen-dialog-modal__advanced-search-string" placeholder="<?php _e( 'Type to search for anything…', 'fcnen' ); ?>" autocomplete="off" autocorrect="off" spellcheck="false">
<input type="search" id="fcnen-modal-search" class="fcnen-dialog-modal__advanced-search-string" placeholder="<?php _e( 'Type to search for anything…', 'fcnen' ); ?>" autocomplete="off" autocorrect="off" spellcheck="false" data-input-target="fcnen-search">
</div>
<div class="fcnen-dialog-modal__advanced-lists">
<ol class="fcnen-dialog-modal__advanced-sources">
<ol class="fcnen-dialog-modal__advanced-sources" data-target="fcnen-sources">
<li class="fcnen-dialog-modal__advanced-li _disabled _no-match"><span><?php _e( 'No matches found.', 'fcnen' ); ?></span></li>
</ol>
<ol class="fcnen-dialog-modal__advanced-selection"></ol>
</div>
<template data-target="fcnen-spinner-template">
<li class="fcnen-dialog-modal__advanced-li _disabled" data-target="fcnen-loading-observer">
<i class="fa-solid fa-spinner fa-spin" style="--fa-animation-duration: .8s;"></i>
<span><?php _e( 'Loading', 'fcnen' ); ?></span>
</li>
</template>
<template data-target="fcnen-no-matches">
<li class="fcnen-dialog-modal__advanced-li _disabled _no-match"><span><?php _e( 'No matches found.', 'fcnen' ); ?></span></li>
</template>
</div>

</div>

View file

@ -81,6 +81,9 @@ function fcnen_addEventListeners() {
document.getElementById('fcnen-modal-checkbox-scope-everything')?.addEventListener('change', event => {
fcnen_modal.querySelector('form').classList.toggle('_everything', event.currentTarget.checked);
});

// Search
fcnen_initializeSearch();
}

/**
@ -245,3 +248,60 @@ function fcnen_unsubscribe() {
fcnen_toggleInProgress(false);
});
}

// =============================================================================
// SEARCH & SELECT
// =============================================================================

var fcncn_searchTimer;

function fcnen_initializeSearch() {
document.querySelectorAll('[data-input-target="fcnen-search"]').forEach(search => {
search.addEventListener('input', () => {
// Clear previous timer (if any)
clearTimeout(fcncn_searchTimer);

// Trigger search after delay
fcncn_searchTimer = setTimeout(() => {
// Get elements and values
const wrapper = search.closest('.fcnen-dialog-modal__advanced');
const sourceList = wrapper.querySelector('[data-target="fcnen-sources"]');

// Clear source list and add spinner
sourceList.innerHTML = '';
sourceList.appendChild(document.querySelector('[data-target="fcnen-spinner-template"]').content.cloneNode(true));

// Crop search input
if (search.value > 200) {
search.value = search.value.slice(0, 200);
}

// Search empty?
if (search.value == '') {
sourceList.innerHTML = '';
sourceList.appendChild(document.querySelector('[data-target="fcnen-no-matches"]').content.cloneNode(true));
return;
}

// Prepare payload
const payload = {
'action': 'fcnen_ajax_search_content',
'search': search.value,
'nonce': fcnen_modal.querySelector('input[name="nonce"]')?.value ?? ''
};

// Request
fcnen_searchContent(payload, sourceList);
}, 800);
});
});
}

function fcnen_searchContent(payload, sourceList) {
fcn_ajaxPost(payload)
.then(response => {
if (response.success) {
sourceList.innerHTML = response.data.html;
}
})
}