HTMX लोडिंग सूचकों के लिए SweetAlert का उपयोग
परिचय
एक कार्य परियोजना पर मैं एक admin UI बनाने के लिए HTMX का उपयोग और दुरुपयोग कर रहा हूँ SweetAlert जावास्क्रिप्ट लाइब्रेरी मेरे पुष्टि संवाद के लिएयह बहुत अच्छा काम करता है लेकिन मैं भी अपने HTMX लोडिंग सूचकों को बदलने के लिए इन का उपयोग करना चाहता था
यह एक चुनौती साबित हुई इसलिए मैंने सोचा कि मैं इसे यहाँ दस्तावेज़ करूँगा ताकि आपको वही पीड़ा बचाया जा सके
Warning I'm a C# coder my Javascript is likely horrible.
[TOC]समस्या
तो HTMX बहुत चतुर है hx-indicator सामान्यतः आप को अपने HTMX अनुरोधों के लिए लोडिंग सूचक सेट करने की अनुमति देता है
<div id="loading-modal" class="modal htmx-indicator">
<div class="modal-box flex flex-col items-center justify-center bg-base-200 border border-base-300 shadow-xl rounded-xl text-base-content dark text-center ">
<div class="flex flex-col items-center space-y-4">
<h2 class="text-lg font-semibold tracking-wide">Loading...</h2>
<span class="loading loading-dots loading-xl text-4xl text-stone-200"></span>
</div>
</div>
</div>
फिर जब आप इसे उपयोग करना चाहते हैं तो आप HTMX अनुरोध को decorate के साथ hx-indicator="#loading-modal" और यह मोडल दिखाएगा जब अनुरोध प्रगति में है (विस्तृत जानकारी के लिए यहाँ देखें).
अब एचटीएमएक्स कुछ चुने हुए जादू का उपयोग एक request वस्तु यह आंतरिक रूप से ट्रैक करता है
function addRequestIndicatorClasses(elt) {
let indicators = /** @type Element[] */ (findAttributeTargets(elt, 'hx-indicator'))
if (indicators == null) {
indicators = [elt]
}
forEach(indicators, function(ic) {
const internalData = getInternalData(ic)
internalData.requestCount = (internalData.requestCount || 0) + 1
ic.classList.add.call(ic.classList, htmx.config.requestClass)
})
return indicators
}
इन को बदलना इसलिए एक थोड़ा चुनौती है
एक समाधान
इसलिए मैंने HTMX लोडिंग सूचक को SweetAlert के साथ बदलने के लिए :)) लाईन करने के लिए मुझे ज़रूरी थी, इसलिए मैं नहीं था किसी भी तरह यहाँ-' है कोड मैं के साथ आया
आप या तो अपने एचटीएमएल में SweetAlert importing से आरंभ करेंइस के लिए उनके डक देखें
इसे स्थापित करने के बाद आप यह इस तरह अपने JS फ़ाइल में आयात कर सकते हैं
import Swal from 'sweetalert2';
तो मेरा मुख्य कोड इस तरह दिखता है
import Swal from 'sweetalert2';
const SWEETALERT_PATH_KEY = 'swal-active-path'; // Stores the path of the current SweetAlert
const SWEETALERT_HISTORY_RESTORED_KEY = 'swal-just-restored'; // Flag for navigation from browser history
const SWEETALERT_TIMEOUT_MS = 10000; // Timeout for automatically closing the loader
let swalTimeoutHandle = null;
export function registerSweetAlertHxIndicator() {
document.body.addEventListener('htmx:configRequest', function (evt) {
const trigger = evt.detail.elt;
const indicatorAttrSource = getIndicatorSource(trigger);
if (!indicatorAttrSource) return;
const path = getRequestPath(evt.detail);
if (!path) return;
const currentPath = sessionStorage.getItem(SWEETALERT_PATH_KEY);
// Show SweetAlert only if the current request path differs from the previous one
if (currentPath !== path) {
closeSweetAlertLoader();
sessionStorage.setItem(SWEETALERT_PATH_KEY, path);
evt.detail.indicator = null; // Disable HTMX's default indicator behavior
Swal.fire({
title: 'Loading...',
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: false,
theme: 'dark',
didOpen: () => {
// Cancel immediately if restored from browser history
if (sessionStorage.getItem(SWEETALERT_HISTORY_RESTORED_KEY) === 'true') {
sessionStorage.removeItem(SWEETALERT_HISTORY_RESTORED_KEY);
Swal.close();
return;
}
Swal.showLoading();
document.dispatchEvent(new CustomEvent('sweetalert:opened'));
// Set timeout to auto-close if something hangs
clearTimeout(swalTimeoutHandle);
swalTimeoutHandle = setTimeout(() => {
if (Swal.isVisible()) {
console.warn('SweetAlert loading modal closed after timeout.');
closeSweetAlertLoader();
}
}, SWEETALERT_TIMEOUT_MS);
},
didClose: () => {
document.dispatchEvent(new CustomEvent('sweetalert:closed'));
sessionStorage.removeItem(SWEETALERT_PATH_KEY);
clearTimeout(swalTimeoutHandle);
swalTimeoutHandle = null;
}
});
} else {
// Suppress HTMX indicator if the path is already being handled
evt.detail.indicator = null;
}
});
//Add events to close the loader
document.body.addEventListener('htmx:afterRequest', maybeClose);
document.body.addEventListener('htmx:responseError', maybeClose);
document.body.addEventListener('sweetalert:close', closeSweetAlertLoader);
// Set a flag so we can suppress the loader immediately if navigating via browser history
document.body.addEventListener('htmx:historyRestore', () => {
sessionStorage.setItem(SWEETALERT_HISTORY_RESTORED_KEY, 'true');
});
window.addEventListener('popstate', () => {
sessionStorage.setItem(SWEETALERT_HISTORY_RESTORED_KEY, 'true');
});
}
// Returns the closest element with an indicator attribute
function getIndicatorSource(el) {
return el.closest('[hx-indicator], [data-hx-indicator]');
}
// Determines the request path, including query string if appropriate
function getRequestPath(detail) {
const responsePath =
typeof detail?.pathInfo?.responsePath === 'string'
? detail.pathInfo.responsePath
: (typeof detail?.pathInfo?.path === 'string'
? detail.pathInfo.path
: (typeof detail?.path === 'string' ? detail.path : '')
);
const elt = detail.elt;
// If not a form and has an hx-indicator, use the raw path
if (elt.hasAttribute("hx-indicator") && elt.tagName !== "FORM") {
return responsePath;
}
const isGet = (detail.verb ?? '').toUpperCase() === 'GET';
const form = elt.closest('form');
// Append query params for GET form submissions
if (isGet && form) {
const params = new URLSearchParams();
for (const el of form.elements) {
if (!el.name || el.disabled) continue;
const type = el.type;
if ((type === 'checkbox' || type === 'radio') && !el.checked) continue;
if (type === 'submit') continue;
params.append(el.name, el.value);
}
const queryString = params.toString();
return queryString ? `${responsePath}?${queryString}` : responsePath;
}
return responsePath;
}
// Closes the SweetAlert loader if the path matches
function maybeClose(evt) {
const activePath = sessionStorage.getItem(SWEETALERT_PATH_KEY);
const path = getRequestPath(evt.detail);
if (activePath && path && activePath === path) {
closeSweetAlertLoader();
}
}
// Close and clean up SweetAlert loader state
function closeSweetAlertLoader() {
if (Swal.getPopup()) {
Swal.close();
document.dispatchEvent(new CustomEvent('sweetalert:closed'));
sessionStorage.removeItem(SWEETALERT_PATH_KEY);
clearTimeout(swalTimeoutHandle);
swalTimeoutHandle = null;
}
}
आप इस ( को कॉन्फ़िगर करें यदि आप main.js इस तरह का फ़ाइल
import { registerSweetAlertHxIndicator } from './hx-sweetalert-indicator.js';
registerSweetAlertHxIndicator();
हमारे तत्वों को ढूंढना
आप' देखेंगे कि मैं उपयोग करता हूँ getIndicatorSource HTMX अनुरोध को ट्रिगर करने वाला तत्व ढूंढने के लिए फ़ंक्शन. यह महत्वपूर्ण है क्योंकि हमें यह जानने की जरूरत है कि जिस तत्व ने अनुरोध को triggered तो हम मोडल बंद कर सकते हैं जब यह पूरा हो जाता है
function getIndicatorSource(el) {
return el.closest('[hx-indicator], [data-hx-indicator]');
}
फिर किसी भी HTMX अनुरोध पर (so hx-get या hx-post) आप का उपयोग कर सकते हैं hx-indicator SweetAlert को निर्दिष्ट करने के लिए विशेषता
चलो यह सब कैसे काम करता है
इस के साथ Hooking registerSweetAlertHxIndicator()
यह बाहर प्रविष्टि बिन्दु के रूप में कार्य करता है htmx:configRequest घटना. यह निष्क्रिय होता है जब HTMX अनुरोध करने के बारे में है
फिर यह तत्व जो घटना में ट्रिगर किया है प्राप्त करता है evt.detail.elt और जाँच करता है कि क्या यह एक hx-indicator विशेषता.
अंत में, यह SweetAlert को दिखाता है Swal.fire().
rt function registerSweetAlertHxIndicator() {
document.body.addEventListener('htmx:configRequest', function (evt) {
const trigger = evt.detail.elt;
const indicatorAttrSource = getIndicatorSource(trigger);
if (!indicatorAttrSource) return;
अनुरोध पथ प्राप्त कर रहा है
अगर यह करता है, यह अनुरोध पथ का उपयोग कर लेता है getRequestPath(evt.detail) और इसे सत्र भंडारण में भंडारित करता है
नीव एचटीएमएस एक पेचीदा बगल है, यह जीवन चक्र में आप कहाँ हैं पर निर्भर करता है विभिन्न स्थानों में रास्ता भंडारित करता है detail?.pathInfo?.path ?? detail?.path ?? '';
यह पता चला है कि HTMX भंडारित मांग मार्ग में detail.path और प्रतिक्रिया पथ ( के लिए document.body.addEventListener('htmx:afterRequest', maybeClose); document.body.addEventListener('htmx:responseError', maybeClose);) में detail.PathInfo.responsePath तो हम दोनों को संभालने की जरूरत है
हमें भी संभालने की जरूरत है GET फ़ॉर्म्स; उनके जवाब के रूप में संभवतः यूआरएल तत्व इस रूप में पारित शामिल होंगे <input > मान ताकि प्रतिक्रिया यूआरएल अलग हो सकता है
// Returns the closest element with an indicator attribute
function getIndicatorSource(el) {
return el.closest('[hx-indicator], [data-hx-indicator]');
}
// Determines the request path, including query string if appropriate
function getRequestPath(detail) {
const responsePath =
typeof detail?.pathInfo?.responsePath === 'string'
? detail.pathInfo.responsePath
: (typeof detail?.pathInfo?.path === 'string'
? detail.pathInfo.path
: (typeof detail?.path === 'string' ? detail.path : '')
);
const elt = detail.elt;
// If not a form and has an hx-indicator, use the raw path
if (elt.hasAttribute("hx-indicator") && elt.tagName !== "FORM") {
return responsePath;
}
const isGet = (detail.verb ?? '').toUpperCase() === 'GET';
const form = elt.closest('form');
// Append query params for GET form submissions
if (isGet && form) {
const params = new URLSearchParams();
for (const el of form.elements) {
if (!el.name || el.disabled) continue;
const type = el.type;
if ((type === 'checkbox' || type === 'radio') && !el.checked) continue;
if (type === 'submit') continue;
params.append(el.name, el.value);
}
const queryString = params.toString();
return queryString ? `${responsePath}?${queryString}` : responsePath;
}
return responsePath;
}
नोट: यह विशेष रूप से मामला है यदि आप का उपयोग करते हैं HX-Push-Url शीर्षिका जो इतिहास के लिए HTMX भंडारित अनुरोध का यूआरएल बदलता है
फ़ॉर्म
HttpGet फ़ॉर्में थोड़ा मुश्किल है तो हम कोड का एक टुकड़ा है जो पता चलेगा अगर आप submit एक फ़ॉर्म के भीतर बटन और जवाब यूआरएल से तुलना करने के लिए उन पेस्क इनपुटों द्वारा उत्पन्न क्वेरी स्ट्रिंग पैरामीटर जोड़ें
const isGet = (detail.verb ?? '').toUpperCase() === 'GET';
const form = elt.closest('form');
// Append query params for GET form submissions
if (isGet && form) {
const params = new URLSearchParams();
for (const el of form.elements) {
if (!el.name || el.disabled) continue;
const type = el.type;
if ((type === 'checkbox' || type === 'radio') && !el.checked) continue;
if (type === 'submit') continue;
params.append(el.name, el.value);
}
const queryString = params.toString();
return queryString ? `${responsePath}?${queryString}` : responsePath;
}
return responsePath;
```
This is important as HTMX will use the response URL to determine if the request is the same as the previous one. So we need to ensure we have the same URL in both places.
### Extensions
I use this little `Response` extension method to set the `HX-Push-Url` header in my ASP.NET Core app. I also added a second extension which will immediately close the modal (useful if you mess with the request and need to close it immediately).
```csharp
public static class ResponseExtensions
{
public static void PushUrl(this HttpResponse response, HttpRequest request)
{
response.Headers["HX-Push-Url"] = request.GetEncodedUrl();
}
}
public static void CloseSweetAlert(this HttpResponse response)
{
response.Headers.Append("HX-Trigger" , JsonSerializer.Serialize(new
{
sweetalert = "closed"
}));
}
}
यह दूसरा यहाँ चलाया जाता है
document.body.addEventListener('sweetalert:close', closeSweetAlertLoader);
पथ सहेज रहा है
ठीक है तो अब हम पथ, क्या हम इसे करने के लिए क्या कर रहे हैं? अच्छी तरह से उस अनुरोध की ट्रैक रखने के लिए SweetAlert को ट्रिगर किया था मौड्यूल में हम इसे भंडारित sessionStorage उपयोग sessionStorage.setItem(SWEETALERT_PATH_KEY, path);.
(अभी आप इसे अधिक जटिल कर सकते हैं और सुनिश्चित करें कि आपको एक ही है अगर आप की जरूरत है
मोडल दिखा रहा है
हम फिर सरलता से SweetAlert2 मोडल का उपयोग करते हुए दिखाएँ Swal.fire()नोट हम यहाँ विकल्पों की एक गुच्छा है
खोलने पर सत्र भंडारण कुंजी की जाँच करता है SWEETALERT_HISTORY_RESTORED_KEY जो जब इतिहास को पुनर्स्थापित किया जाता है सेट होता है. यदि यह है तो हम तुरंत मोडल बंद करते हैं
हम एक घटना भी चलाएँ sweetalert:opened जो आप किसी भी पसंदीदा तर्क को करने के लिए उपयोग कर सकते हैं आपको जरूरत है.
Swal.fire({
title: 'Loading...',
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: false,
theme: 'dark',
didOpen: () => {
// Cancel immediately if restored from browser history
if (sessionStorage.getItem(SWEETALERT_HISTORY_RESTORED_KEY) === 'true') {
sessionStorage.removeItem(SWEETALERT_HISTORY_RESTORED_KEY);
Swal.close();
return;
}
Swal.showLoading();
document.dispatchEvent(new CustomEvent('sweetalert:opened'));
// Set timeout to auto-close if something hangs
clearTimeout(swalTimeoutHandle);
swalTimeoutHandle = setTimeout(() => {
if (Swal.isVisible()) {
console.warn('SweetAlert loading modal closed after timeout.');
closeSweetAlertLoader();
}
}, SWEETALERT_TIMEOUT_MS);
},
didClose: () => {
document.dispatchEvent(new CustomEvent('sweetalert:closed'));
sessionStorage.removeItem(SWEETALERT_PATH_KEY);
clearTimeout(swalTimeoutHandle);
swalTimeoutHandle = null;
}
});
साथ ही हम एक समय समाप्ति के लिए मामलों को संभालने के लिए सेट करते हैं जहां अनुरोध लंबित है, जब यह महत्वपूर्ण है क्योंकि HTMX नहीं करता है hx-boost). यह यहाँ सेट है const SWEETALERT_TIMEOUT_MS = 10000; // Timeout for automatically closing the loader तो हम मोडल बंद कर सकते हैं अगर कुछ गलत हो जाता है
इसे बंद कर रहा है
तो अब हम मॉडल खुला है ',' जब अनुरोध पूरा हो जाता है, हमें इसे बंद करने की जरूरत है '.' यह करने के लिए हम कहते हैं maybeClose फ़ंक्शन. यह तब बुलाया जाता है जब अनुरोध पूरा हो जाता है (चाहे सफलतापूर्वक या त्रुटि के साथ
उपयोग htmx:afterRequest और htmx:responseError घटनाएँ. ये घटनाएं एक बार जब HTMX ने अनुरोध को पूरा किया है तो जलती हैं HX-Boost जो कि क्या घटनाओं के बारे में यह फायर करता है एक छोटा सा हास्यास्पद हो सकता है
document.body.addEventListener('htmx:afterRequest', maybeClose);
document.body.addEventListener('htmx:responseError', maybeClose);
function maybeClose(evt) {
const activePath = sessionStorage.getItem(SWEETALERT_PATH_KEY);
const path = getRequestPath(evt.detail);
if (activePath && path && activePath === path) {
Swal.close();
sessionStorage.removeItem(SWEETALERT_PATH_KEY);
}
}
यह फ़ंक्शन जाँचता है कि क्या सत्र भंडारण में पथ अनुरोध की पथ के समान है
यह' का इतिहास
एचटीएमएस के इतिहास को संभालने का एक बहुत ही अच्छा तरीका है जो एक पृष्ठ के पीछे करने पर मोडल 'stuck' खुले छोड़ सकता है।
//Add events to close the loader
document.body.addEventListener('htmx:afterRequest', maybeClose);
document.body.addEventListener('htmx:responseError', maybeClose);
document.body.addEventListener('sweetalert:close', closeSweetAlertLoader);
// Set a flag so we can suppress the loader immediately if navigating via browser history
document.body.addEventListener('htmx:historyRestore', () => {
sessionStorage.setItem(SWEETALERT_HISTORY_RESTORED_KEY, 'true');
});
window.addEventListener('popstate', () => {
sessionStorage.setItem(SWEETALERT_HISTORY_RESTORED_KEY, 'true');
});`
आपll see we also set the sessionStorage.setItem(SWEETALERT_HISTORY_RESTORED_KEY, 'true'); जो हम के लिए जाँच didOpen घटना
didOpen: () => {
// Cancel immediately if restored from browser history
if (sessionStorage.getItem(SWEETALERT_HISTORY_RESTORED_KEY) === 'true') {
sessionStorage.removeItem(SWEETALERT_HISTORY_RESTORED_KEY);
Swal.close();
return;
}
हम इसे उस स्थिति में करते हैं जैसे मोडल नहीं खोलता है-' popstate \ htmx:historyRestore especially if you have a lot of history). So we need to check for it in the didOpen घटना (इसीलिए यह सत्र कुंजी में है
BONUS - मेरे पेजिंग टैगHelper के लिए
अगर आप ' अपने उपयोग कर रहे हैं पेजिंग टैगHelper वहाँ' के साथ एक समस्या है PageSize और SweetAlert ; का उपयोग करने के कारण यह है कि ALSO hooking htmx:configRequest
(() => {
if (window.__pageSizeListenerAdded) return;
document.addEventListener('htmx:configRequest', event => {
const { elt } = event.detail;
if (elt?.matches('[name="pageSize"]')) {
const params = new URLSearchParams(window.location.search);
params.set('pageSize', elt.value);
const paramObj = Object.fromEntries(params.entries());
event.detail.parameters = paramObj;
const pageSizeEvent = new CustomEvent('pagesize:updated', {
detail: {
params: paramObj,
elt,
},
});
document.dispatchEvent(pageSizeEvent);
}
});
window.__pageSizeListenerAdded = true;
})();
इसे ठीक करने के लिए आपको एक छोटा फ़ंक्शन जोड़ने की जरूरत है
/**
* Appends the current pageSize from the browser's URL to the HTMX request path,
* modifying event.detail.path directly.
*
* @param {CustomEvent['detail']} detail - The HTMX event.detail object
*/
export function getPathWithPageSize(detail) {
const originalPath = detail.path;
if (!originalPath) return null;
const selectedValue = detail.elt?.value ?? '';
const url = new URL(originalPath, window.location.origin);
// Use the current location's query string, update pageSize
const locationParams = new URLSearchParams(window.location.search);
locationParams.set('pageSize', selectedValue);
url.search = locationParams.toString();
return url.pathname + url.search;
}
यह सिर्फ अनुरोध प्राप्त करता है और जोड़ता है pagesize इसके लिए पैरामीटर. फिर इस फ़ंक्शन आयात
import { getPathWithPageSize } from './pagesize-sweetalert'
export function registerSweetAlertHxIndicator() {
document.body.addEventListener('htmx:configRequest', function (evt) {
const trigger = evt.detail.elt;
const indicatorAttrSource = getIndicatorSource(trigger);
if (!indicatorAttrSource) return;
// ✅ If this is a pageSize-triggered request, use our custom path
let path;
if (evt.detail.headers?.['HX-Trigger-Name'] === 'pageSize') {
path = getPathWithPageSize(evt.detail);
console.debug('[SweetAlert] Using custom path with updated pageSize:', path);
} else {
path = getRequestPath(evt.detail);
}
...rest of code
आप यहाँ देख सकते हैं कि हम पता लगाने के लिए pageSize ट्रिगर और जब यह इसे खोजता है ( तो आप पृष्ठ साइज को बदल दिया गया है getPathWithPageSize नया पथ प्राप्त करने के लिए फ़ंक्शन pageSize कोड पाइपलाइन में बाद में इसे बदलेगा लेकिन यह सही पता लगाने के लिए इसे अनुमति देता है तो यह उम्मीद की तरह बंद करता है
अंत में
तो यह है कि HTMX लोडिंग सूचक के रूप में SweetAlert का उपयोग कैसे कर सकते हैं