Refactor mute rule handling to use request.js

This commit is contained in:
Andreas Nedbal 2022-08-31 21:46:47 +02:00
parent d521800a59
commit 812c9617ff
1 changed files with 21 additions and 20 deletions

View File

@ -1,4 +1,5 @@
import Rails from '@rails/ujs';
import { destroy, post } from '@rails/request.js';
function createSubmitEvent(
submit: HTMLButtonElement,
@ -10,28 +11,30 @@ function createSubmitEvent(
event.preventDefault();
submit.disabled = true;
Rails.ajax({
url: '/ajax/mute',
type: 'POST',
dataType: 'json',
data: new URLSearchParams({muted_phrase: textEntry.value}).toString(),
success: (data) => {
post('/ajax/mute', {
body: {
muted_phrase: textEntry.value
},
contentType: 'application/json'
})
.then(async response => {
const data = await response.json;
submit.disabled = false;
if (!data.success) return;
const newEntryFragment = template.content.cloneNode(true) as Element;
newEntryFragment.querySelector<HTMLInputElement>('input').value = textEntry.value;
const newDeleteButton = newEntryFragment.querySelector<HTMLButtonElement>('button')
const newDeleteButton = newEntryFragment.querySelector<HTMLButtonElement>('button');
newDeleteButton.dataset.id = String(data.id);
newDeleteButton.onclick = createDeleteEvent(
newEntryFragment.querySelector('.form-group'),
newDeleteButton
)
);
rulesList.appendChild(newEntryFragment)
textEntry.value = ''
}
rulesList.appendChild(newEntryFragment);
textEntry.value = '';
});
};
}
@ -43,18 +46,16 @@ function createDeleteEvent(
return () => {
deleteButton.disabled = true;
Rails.ajax({
url: '/ajax/mute/' + deleteButton.dataset.id,
type: 'DELETE',
dataType: 'json',
success: (data) => {
destroy(`/ajax/mute/${deleteButton.dataset.id}`)
.then(async response => {
const data = await response.json;
if (data.success) {
entry.parentElement.removeChild(entry)
} else {
deleteButton.disabled = false;
}
}
})
});
}
}