Skip to main content

max / makenotwork

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