form-stamp/form-stamp.js

71 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-06-05 02:27:56 +02:00
/* jshint esversion: 6 */
const defaults = {
nameToReplace: 'idx',
removeSelector: '.remove'
}
export function formStamp(element, options = {})
{
const {
nameToReplace,
removeSelector
} = { ...defaults, ...element.dataset, ...options };
const container = element.parentElement;
const template = element.querySelector('template');
const itemSelector = '.' + template.content.firstElementChild.className.replace(/ /g, '.');
const initialItemCount = container.querySelectorAll(itemSelector).length;
let created = 0;
2024-10-16 23:12:11 +02:00
const afterDomManipulation = () => {
element.dispatchEvent(new CustomEvent('afterStampDomManipulation'));
}
const removeRow = (removeItem) => () => {
const rowToDelete = removeItem.closest(itemSelector);
2024-06-05 02:27:56 +02:00
// Flow renders identity fields directly at the form tag, so we need to look
if (rowToDelete.dataset.stampRemoveWithMe) {
container.closest('form')
.querySelectorAll(rowToDelete.dataset.stampRemoveWithMe)
.forEach(child => child.remove())
}
if (element.dispatchEvent(new CustomEvent(
'beforeStampRemoval',
{
cancelable: true,
detail: {
toBeRemoved: rowToDelete
}
}
))) {
rowToDelete.remove();
2024-10-16 23:12:11 +02:00
afterDomManipulation();
}
2024-06-05 02:27:56 +02:00
}
element.addEventListener('click', () => {
const clone = template.content.cloneNode(true);
clone.querySelectorAll('input, select, textarea').forEach(child => {
child.name = child.name.replace(nameToReplace, initialItemCount + created);
});
clone.querySelectorAll(removeSelector).forEach(child => {
child.onclick = removeRow(child);
});
2024-09-28 17:21:03 +02:00
if (element.dispatchEvent(new CustomEvent(
'beforeStampInsert',
{
detail: {
i: initialItemCount + created,
node: clone
},
cancelable: true
}
))) {
element.before(clone);
2024-10-16 23:12:11 +02:00
afterDomManipulation();
2024-09-28 17:21:03 +02:00
created++;
}
2024-06-05 02:27:56 +02:00
});
container.querySelectorAll(removeSelector).forEach(child => {
child.onclick = removeRow(child);
});
}
export default formStamp;