alpineInit.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Set up various Alpine things after it's initialized
  2. export default function alpineInit() {
  3. // Bulk edit forms
  4. Alpine.bind('BulkEdit', () => ({
  5. /** @param {SubmitEvent} evt */
  6. '@submit'(evt) {
  7. evt.preventDefault();
  8. document.querySelectorAll('.js-unit-checkbox').forEach((el) => {
  9. if (el.checked) {
  10. const input = document.createElement('input');
  11. input.type = 'hidden';
  12. input.name = el.name;
  13. input.value = el.value;
  14. evt.target.appendChild(input);
  15. }
  16. });
  17. evt.target.submit();
  18. },
  19. }));
  20. // Form state
  21. Alpine.store('form', {
  22. dirty: false,
  23. makeDirty() {
  24. this.dirty = true;
  25. },
  26. });
  27. document
  28. .querySelectorAll('#main-form input, #main-form select, #main-form textarea')
  29. .forEach((el) => {
  30. el.addEventListener('change', () => {
  31. Alpine.store('form').makeDirty();
  32. });
  33. });
  34. // Notifications methods called by the view code
  35. Alpine.data('notifications', () => ({
  36. initialized: false,
  37. open: false,
  38. notifications: [],
  39. toggle() {
  40. this.open = !this.open;
  41. if (!this.initialized) {
  42. this.list();
  43. }
  44. },
  45. async list() {
  46. const token = document.querySelector('#token').getAttribute('token');
  47. const res = await fetch(`/list/notifications/?ajax=1&token=${token}`);
  48. this.initialized = true;
  49. if (!res.ok) {
  50. throw new Error('An error occurred while listing notifications.');
  51. }
  52. this.notifications = Object.values(await res.json());
  53. },
  54. async remove(id) {
  55. const token = document.querySelector('#token').getAttribute('token');
  56. await fetch(`/delete/notification/?delete=1&notification_id=${id}&token=${token}`);
  57. this.notifications = this.notifications.filter((notification) => notification.ID != id);
  58. if (this.notifications.length === 0) {
  59. this.open = false;
  60. }
  61. },
  62. async removeAll() {
  63. const token = document.querySelector('#token').getAttribute('token');
  64. await fetch(`/delete/notification/?delete=1&token=${token}`);
  65. this.notifications = [];
  66. this.open = false;
  67. },
  68. }));
  69. }