-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadmodal.js
More file actions
251 lines (215 loc) · 8.09 KB
/
loadmodal.js
File metadata and controls
251 lines (215 loc) · 8.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/**
* Author: Conan C. Albrecht <ca@byu.edu>
* License: MIT
* Version: 2.0.0
*
* Dependencies:
* - Bootstrap 5 (tested against v5)
*/
(function (window) {
'use strict';
window.loadmodal = function (options) {
// allow a simple url to be sent as the single option
if (typeof options === 'string') {
options = {
url: options,
};
}
// default options
const defaults = {
url: null,
id: 'loadmodal-js',
idBody: 'loadmodal-js-body',
prependToSelector: null,
appendToSelector: null,
title: document.title || 'Dialog',
width: '400px',
dlgClass: 'fade',
size: 'modal-lg',
closeButton: true,
buttons: {},
modal: {
keyboard: false,
},
fetch: {
method: 'GET',
},
onSuccess: null,
onCreate: null,
onShow: null,
onClose: null,
};
// merge options
const userFetch = options.fetch || {};
const userModal = options.modal || {};
options = Object.assign({}, defaults, options);
// Deep merge for fetch and modal options
options.fetch = Object.assign({}, defaults.fetch, userFetch);
options.modal = Object.assign({}, defaults.modal, userModal);
// ensure we have a url
options.url = options.fetch.url || options.url;
if (!options.url) {
throw new Error('loadmodal requires a url.');
}
// ensure callbacks are arrays
const forceFuncArray = (ar) => {
if (!ar) return [];
if (Array.isArray(ar)) return ar;
return [ar];
};
options.onSuccess = forceFuncArray(options.onSuccess);
options.onCreate = forceFuncArray(options.onCreate);
options.onShow = forceFuncArray(options.onShow);
options.onClose = forceFuncArray(options.onClose);
// close any dialog with this id first
const existingModalEl = document.getElementById(options.id);
if (existingModalEl) {
const existingModal = bootstrap.Modal.getInstance(existingModalEl);
if (existingModal) {
existingModal.hide();
} else {
// If instance not found but element exists, remove it
existingModalEl.remove();
}
}
// Perform the fetch
const fetchPromise = fetch(options.url, options.fetch)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then((data) => {
// call onSuccess methods
for (const func of options.onSuccess) {
const ret = func(data);
if (ret === false) return Promise.reject('cancelled');
if (typeof ret === 'string') data = ret;
}
// create the modal html
const div = document.createElement('div');
div.id = options.id;
div.className = `modal ${options.dlgClass} loadmodal-js`;
div.tabIndex = -1; // Bootstrap 5 uses -1 usually
div.setAttribute('aria-labelledby', `${options.id}-title`);
// div.setAttribute('aria-hidden', 'true'); // BS5 adds this automatically
const closeButtonHtml = options.closeButton
? '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>'
: '';
div.innerHTML = `
<div class="modal-dialog ${options.size}">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="${options.id}-title">${options.title}</h5>
${closeButtonHtml}
</div>
<div class="modal-body" id="${options.idBody}">
${data}
</div>
</div>
</div>
`;
// add the new modal div to the body
if (options.prependToSelector) {
const el = document.querySelector(options.prependToSelector) || document.body;
el.insertBefore(div, el.firstChild);
} else if (options.appendToSelector) {
const el = document.querySelector(options.appendToSelector);
if (el) el.appendChild(div);
else document.body.appendChild(div);
} else {
// Default prepend to body (as per original logic "prepend to body is usually preferred")
document.body.insertBefore(div, document.body.firstChild);
}
// Set width if specified (applied to modal-dialog)
if (options.width) {
const dialog = div.querySelector('.modal-dialog');
if (dialog) dialog.style.width = options.width;
// Note: BS5 handles width via max-width usually, but we'll set width directly as requested.
// However, BS5 responsive classes (modal-lg) are preferred.
}
// add buttons
if (Object.keys(options.buttons).length > 0) {
const modalBody = div.querySelector('.modal-body');
// Or use a custom panel inside body? Original used .button-panel inside body.
// Let's stick to original behavior: append to body.
// But wait, original appended to .modal-body.
const btnPanel = document.createElement('div');
btnPanel.className = 'mt-3 text-end'; // Add some spacing
let buttonClass = 'btn btn-primary';
for (const [key, func] of Object.entries(options.buttons)) {
const button = document.createElement('button');
button.className = buttonClass;
button.textContent = key;
button.type = 'button';
button.addEventListener('click', (evt) => {
let closeDialog = true;
if (func && func(evt) === false) {
closeDialog = false;
}
if (closeDialog) {
const instance = bootstrap.Modal.getInstance(div);
if (instance) instance.hide();
}
});
btnPanel.appendChild(button);
// Add spacing between buttons
btnPanel.appendChild(document.createTextNode(' '));
buttonClass = 'btn btn-secondary'; // subsequent buttons
}
modalBody.appendChild(btnPanel);
}
// Z-index handling
// BS5 handles z-index well, but if we want to ensure it's on top:
// Calculate max z-index
// This is a bit complex in vanilla without jQuery's selectors.
// skipping z-index manual adjustment unless requested, as BS5 manages it via backdrop.
// Trigger onCreate
for (const func of options.onCreate) {
if (func.call(div, data) === false) return Promise.reject('cancelled');
}
// Create Bootstrap Modal instance
const modalInstance = new bootstrap.Modal(div, options.modal);
// Event listeners
div.addEventListener('shown.bs.modal', (event) => {
// Autofocus
const autofocusEl = div.querySelector('[autofocus]');
if (autofocusEl) {
autofocusEl.focus();
} else {
const firstInput = div.querySelector('.modal-body :is(input, select, textarea, button):not([disabled])'); // Simplified
if (firstInput) firstInput.focus();
}
// callbacks
for (const func of options.onShow) {
func.call(div, event);
}
});
div.addEventListener('hidden.bs.modal', (event) => {
for (const func of options.onClose) {
func.call(div, event);
}
modalInstance.dispose();
div.remove();
});
// Show the modal
modalInstance.show();
return div; // Return the DOM element
});
// Add methods to the promise
fetchPromise.create = function (func) {
options.onCreate.push(func);
return this;
};
fetchPromise.show = function (func) {
options.onShow.push(func);
return this;
};
fetchPromise.close = function (func) {
options.onClose.push(func);
return this;
};
return fetchPromise;
};
})(window);