78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
/**
|
|
* Select2 Initialization for AgdarCentre
|
|
* Handles Select2 initialization with RTL support and HTMX compatibility
|
|
*/
|
|
|
|
(function() {
|
|
'use strict';
|
|
|
|
/**
|
|
* Initialize Select2 on elements with .select2 class
|
|
* @param {HTMLElement|jQuery} scope - Optional scope to limit initialization
|
|
*/
|
|
function initSelect2(scope) {
|
|
const $scope = scope ? $(scope) : $(document);
|
|
|
|
$scope.find('.select2').each(function() {
|
|
const $element = $(this);
|
|
|
|
// Skip if already initialized
|
|
if ($element.hasClass('select2-hidden-accessible')) {
|
|
return;
|
|
}
|
|
|
|
// Get RTL direction from document
|
|
const dir = document.documentElement.getAttribute('dir') === 'rtl' ? 'rtl' : 'ltr';
|
|
|
|
// Get placeholder from data attribute or default
|
|
const placeholder = $element.data('placeholder') || '';
|
|
|
|
// Initialize Select2
|
|
$element.select2({
|
|
width: '100%',
|
|
dir: dir,
|
|
allowClear: true,
|
|
placeholder: placeholder,
|
|
language: dir === 'rtl' ? 'ar' : 'en'
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Destroy Select2 instances before re-initialization
|
|
* @param {HTMLElement|jQuery} scope - Optional scope to limit destruction
|
|
*/
|
|
function destroySelect2(scope) {
|
|
const $scope = scope ? $(scope) : $(document);
|
|
|
|
$scope.find('.select2-hidden-accessible').each(function() {
|
|
$(this).select2('destroy');
|
|
});
|
|
}
|
|
|
|
// Initialize on DOM ready
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
initSelect2();
|
|
});
|
|
|
|
// Re-initialize after HTMX swaps
|
|
document.body.addEventListener('htmx:afterSwap', function(e) {
|
|
initSelect2(e.target);
|
|
});
|
|
|
|
// Re-initialize after HTMX settles (for dynamic forms)
|
|
document.body.addEventListener('htmx:afterSettle', function(e) {
|
|
initSelect2(e.target);
|
|
});
|
|
|
|
// Clean up before HTMX removes content
|
|
document.body.addEventListener('htmx:beforeSwap', function(e) {
|
|
destroySelect2(e.target);
|
|
});
|
|
|
|
// Expose globally for manual initialization if needed
|
|
window.initSelect2 = initSelect2;
|
|
window.destroySelect2 = destroySelect2;
|
|
|
|
})();
|