Skip to main content

max / makenotwork

1.9 KB · 50 lines History Blame Raw
1 (function() {
2 document.querySelectorAll('.pwyw-cart-input').forEach(function(input) {
3 var debounce;
4 input.addEventListener('change', function() {
5 clearTimeout(debounce);
6 var itemId = this.dataset.itemId;
7 var dollars = parseFloat(this.value) || 0;
8 var cents = Math.round(dollars * 100);
9 debounce = setTimeout(function() {
10 fetch('/api/cart/' + itemId, {
11 method: 'PUT',
12 headers: Object.assign({'Content-Type': 'application/json'}, csrfHeaders()),
13 body: JSON.stringify({ amount_cents: cents })
14 }).then(function(r) {
15 if (!r.ok) return r.json().then(function(d) { showToast(d.error || 'Invalid amount'); });
16 }).catch(function() { showToast('Failed to update amount'); });
17 }, 300);
18 });
19 });
20 })();
21
22 window.removeCartGroup = function(btn) {
23 var name = btn.dataset.sellerName || 'this creator';
24 if (!confirm('Remove all items from ' + name + '?')) return;
25 var group = btn.closest('.cart-group');
26 if (!group) return;
27 var rows = group.querySelectorAll('tr[id^="cart-row-"]');
28 if (rows.length === 0) return;
29 btn.disabled = true;
30 var headers = csrfHeaders();
31 var pending = rows.length;
32 var failed = false;
33 function finish() {
34 if (--pending !== 0) return;
35 if (failed) {
36 showToast('Some items could not be removed. Refreshing.');
37 window.location.reload();
38 } else {
39 window.location.reload();
40 }
41 }
42 rows.forEach(function(row) {
43 var id = row.id.replace('cart-row-', '');
44 fetch('/api/cart/' + id, { method: 'DELETE', headers: headers })
45 .then(function(r) { if (!r.ok) failed = true; })
46 .catch(function() { failed = true; })
47 .finally(finish);
48 });
49 };
50