docbrown/app/javascript/admin/controllers/confirmation_modal_controller.js
Arit Amana aa5f18b234
Admin Save Confirmation - Removing Badge Achievements (#14684)
* schema file undelete description

* update with main

* update with origin

* update

* create controller; hook up to badge_achievements

* almost done with implementation

* push up what I have

* complete implementation; generalize snackbar usage

* start writing tests

* add confirmation text entry step to test

* Fix delete via JS

* implement danger notice for errors

* complete cypress test

* create ErrorAlert CustomEvent and implement

* fix failing badge_achievements spec

* start applying PR review changes

* hook up Preact Modal

* fix cypress tests

* remove old comment

Co-authored-by: Nick Taylor <nick@forem.com>

* consolidate messaging functions

Co-authored-by: Michael Kohl <citizen428@forem.com>
Co-authored-by: Nick Taylor <nick@forem.com>
2021-09-15 21:25:01 -04:00

71 lines
2 KiB
JavaScript

import ModalController from '../controllers/modal_controller';
import { displayErrorAlert, displaySnackbar } from '../messageUtilities';
const confirmationText = (username) =>
`My username is @${username} and this action is 100% safe and appropriate.`;
export default class ConfirmationModalController extends ModalController {
static targets = ['itemId', 'username', 'endpoint'];
removeBadgeAchievement(id) {
return document.querySelector(`[data-row-id="${id}"]`).remove();
}
async sendToEndpoint({ itemId, endpoint }) {
try {
const response = await fetch(`${endpoint}/${itemId}`, {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector("meta[name='csrf-token']")
?.content,
},
credentials: 'same-origin',
});
const outcome = await response.json();
if (response.ok) {
this.removeBadgeAchievement(itemId);
displaySnackbar(outcome.message);
} else {
displayErrorAlert(outcome.error);
}
this.closeModal();
} catch (err) {
displayErrorAlert(err.message);
}
}
checkConfirmationText() {
const confirmationMismatchWarning = document.querySelector(
'#confirmation-modal-root #mismatch-warning',
);
const confirmationTextEntry = document.querySelector(
'#confirmation-modal-root #confirmation-text-field',
).value;
if (confirmationTextEntry == confirmationText(this.usernameValue)) {
this.closeModal();
this.sendToEndpoint({
itemId: this.itemIdValue,
endpoint: this.endpointValue,
});
} else {
confirmationMismatchWarning.classList.remove('hidden');
}
}
openModal(event) {
const { itemId, endpoint, username } = event.target.dataset;
this.itemIdValue = itemId;
this.usernameValue = username;
this.endpointValue = endpoint;
this.toggleModal();
}
}