-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
621 lines (531 loc) · 20.8 KB
/
script.js
File metadata and controls
621 lines (531 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// Global state
let currentDirection = 'btc_to_item'; // 'btc_to_item' or 'item_to_btc'
let currentUnit = 'btc'; // 'btc' or 'sats'
let debounceTimer = null;
let currentItem = '';
let itemsData = {};
// DOM elements
let btcInput = document.getElementById('btc-input');
let itemSelect = document.getElementById('item-select');
let btcToggle = document.getElementById('btc-toggle');
let satsToggle = document.getElementById('sats-toggle');
const swapBtn = document.getElementById('swap-direction');
const refreshBtn = document.getElementById('refresh-btn');
const quantityValue = document.getElementById('quantity-value');
const quantityUnit = document.getElementById('quantity-unit');
const itemPrice = document.getElementById('item-price');
const totalValue = document.getElementById('total-value');
const btcPrice = document.getElementById('btc-price');
const loadingSpinner = document.getElementById('loading-spinner');
const historicalSection = document.getElementById('historical-section');
const fromDate = document.getElementById('from-date');
const toDate = document.getElementById('to-date');
const loadHistoricalBtn = document.getElementById('load-historical');
// Initialize app
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM loaded, initializing app...');
setDefaultDates();
updateUIForDirection();
// Test if CanvasJS is loaded
setTimeout(() => {
if (typeof CanvasJS === 'undefined') {
console.error('CanvasJS failed to load from CDN');
showToast('Chart library failed to load. Charts will not be available.', 'error');
} else {
console.log('CanvasJS loaded successfully');
}
}, 1000);
// Ensure items are loaded after a brief delay to let the DOM settle
setTimeout(() => {
console.log('Loading items after DOM setup...');
loadItems();
}, 200);
});
function setupEventListeners() {
console.log('Setting up event listeners...');
// Input change with debouncing
if (btcInput) {
btcInput.addEventListener('input', debounceConvert);
}
if (itemSelect) {
itemSelect.addEventListener('change', handleItemChange);
}
// Unit toggles
if (btcToggle) {
btcToggle.addEventListener('click', () => setUnit('btc'));
}
if (satsToggle) {
satsToggle.addEventListener('click', () => setUnit('sats'));
}
// Direction swap
if (swapBtn) {
swapBtn.addEventListener('click', swapDirection);
}
// Refresh button
if (refreshBtn) {
refreshBtn.addEventListener('click', () => {
if (currentItem) {
performConversion();
}
});
}
// Historical data
if (loadHistoricalBtn) {
loadHistoricalBtn.addEventListener('click', loadHistoricalData);
}
// Auto-reload chart when date inputs change
if (fromDate) {
fromDate.addEventListener('change', debounceHistoricalLoad);
}
if (toDate) {
toDate.addEventListener('change', debounceHistoricalLoad);
}
}
function debounceConvert() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
if (currentItem && btcInput.value) {
performConversion();
}
}, 300);
}
function debounceHistoricalLoad() {
clearTimeout(debounceTimer);
// Show visual feedback that chart will update
const chartContainer = document.getElementById('chartContainer');
if (chartContainer) {
chartContainer.style.opacity = '0.6';
}
debounceTimer = setTimeout(() => {
if (currentItem && historicalSection.style.display !== 'none') {
console.log('Auto-updating chart with new date range...');
loadHistoricalData();
}
}, 800); // Longer delay for API calls
}
function setUnit(unit) {
currentUnit = unit;
btcToggle.classList.toggle('active', unit === 'btc');
satsToggle.classList.toggle('active', unit === 'sats');
// Update placeholder and convert existing value
if (unit === 'btc') {
btcInput.placeholder = '0.1';
btcInput.step = 'any';
if (btcInput.value && currentUnit !== 'btc') {
btcInput.value = (parseFloat(btcInput.value) / 100000000).toString();
}
} else {
btcInput.placeholder = '10000000';
btcInput.step = '1';
if (btcInput.value && currentUnit !== 'sats') {
btcInput.value = Math.round(parseFloat(btcInput.value) * 100000000).toString();
}
}
debounceConvert();
}
function swapDirection() {
currentDirection = currentDirection === 'btc_to_item' ? 'item_to_btc' : 'btc_to_item';
updateUIForDirection();
debounceConvert();
}
function updateUIForDirection() {
const inputSide = document.querySelector('.input-side');
const outputSide = document.querySelector('.output-side');
if (currentDirection === 'btc_to_item') {
// BTC input, item output
inputSide.innerHTML = `
<div class="input-group">
<label for="btc-input">Bitcoin Amount</label>
<div class="input-wrapper">
<input type="number" id="btc-input" placeholder="${currentUnit === 'btc' ? '0.1' : '10000000'}" step="${currentUnit === 'btc' ? 'any' : '1'}" min="0">
<div class="unit-toggle">
<button id="btc-toggle" class="unit-btn ${currentUnit === 'btc' ? 'active' : ''}" data-unit="btc">BTC</button>
<button id="sats-toggle" class="unit-btn ${currentUnit === 'sats' ? 'active' : ''}" data-unit="sats">sats</button>
</div>
</div>
</div>
`;
outputSide.innerHTML = `
<div class="input-group">
<label for="item-select">Item</label>
<select id="item-select">
<option value="">Select an item...</option>
</select>
</div>
<div class="result-container">
<div id="result-display" class="result-display">
<div class="quantity-result">
<span id="quantity-value">--</span>
<span id="quantity-unit"></span>
</div>
<div class="price-breakdown">
<div class="price-row">
<span>Item Price:</span>
<span id="item-price">$--</span>
</div>
<div class="price-row">
<span>Total Value:</span>
<span id="total-value">$--</span>
</div>
<div class="price-row">
<span>BTC Price:</span>
<span id="btc-price">$--</span>
</div>
</div>
</div>
</div>
`;
} else {
// Item input, BTC output
inputSide.innerHTML = `
<div class="input-group">
<label for="item-select">Item</label>
<select id="item-select">
<option value="">Select an item...</option>
</select>
</div>
<div class="input-group">
<label for="quantity-input">Quantity</label>
<input type="number" id="quantity-input" placeholder="1" step="any" min="0">
</div>
`;
outputSide.innerHTML = `
<div class="input-group">
<label>Bitcoin Needed</label>
<div class="unit-toggle">
<button id="btc-toggle" class="unit-btn ${currentUnit === 'btc' ? 'active' : ''}" data-unit="btc">BTC</button>
<button id="sats-toggle" class="unit-btn ${currentUnit === 'sats' ? 'active' : ''}" data-unit="sats">sats</button>
</div>
</div>
<div class="result-container">
<div id="result-display" class="result-display">
<div class="quantity-result">
<span id="quantity-value">--</span>
<span id="quantity-unit">${currentUnit}</span>
</div>
<div class="price-breakdown">
<div class="price-row">
<span>Item Price:</span>
<span id="item-price">$--</span>
</div>
<div class="price-row">
<span>Total Value:</span>
<span id="total-value">$--</span>
</div>
<div class="price-row">
<span>BTC Price:</span>
<span id="btc-price">$--</span>
</div>
</div>
</div>
</div>
`;
}
// Re-setup event listeners for new elements
setupEventListenersAfterDirectionChange();
}
function setupEventListenersAfterDirectionChange() {
// Re-get DOM elements
const newBtcInput = document.getElementById('btc-input');
const newQuantityInput = document.getElementById('quantity-input');
const newItemSelect = document.getElementById('item-select');
const newBtcToggle = document.getElementById('btc-toggle');
const newSatsToggle = document.getElementById('sats-toggle');
// Setup listeners based on direction
if (currentDirection === 'btc_to_item' && newBtcInput) {
newBtcInput.addEventListener('input', debounceConvert);
} else if (currentDirection === 'item_to_btc' && newQuantityInput) {
newQuantityInput.addEventListener('input', debounceConvert);
}
if (newItemSelect) {
newItemSelect.addEventListener('change', handleItemChange);
}
if (newBtcToggle) {
newBtcToggle.addEventListener('click', () => setUnit('btc'));
}
if (newSatsToggle) {
newSatsToggle.addEventListener('click', () => setUnit('sats'));
}
// Update global references
btcInput = newBtcInput;
itemSelect = newItemSelect;
btcToggle = newBtcToggle;
satsToggle = newSatsToggle;
}
async function loadItems() {
try {
// Fetch items from the API
const response = await fetch('/api/items');
if (!response.ok) {
throw new Error('Failed to fetch items');
}
const categories = await response.json();
const select = document.getElementById('item-select');
if (!select) {
console.error('Could not find item-select element');
return;
}
select.innerHTML = '<option value="">Select an item...</option>';
Object.entries(categories).forEach(([category, items]) => {
const optgroup = document.createElement('optgroup');
optgroup.label = category;
items.forEach(item => {
const option = document.createElement('option');
option.value = item.key;
option.textContent = item.name;
option.dataset.historicalSupport = item.historical_support;
option.dataset.unit = item.unit;
optgroup.appendChild(option);
});
select.appendChild(optgroup);
});
itemsData = categories;
console.log('Items loaded successfully:', Object.keys(categories).length, 'categories');
} catch (error) {
console.error('Error loading items:', error);
showToast('Failed to load items: ' + error.message, 'error');
}
}
function handleItemChange() {
const select = document.getElementById('item-select');
currentItem = select.value;
if (currentItem) {
const option = select.querySelector(`option[value="${currentItem}"]`);
const hasHistoricalSupport = option?.dataset.historicalSupport === 'true';
// Show/hide historical section
if (hasHistoricalSupport) {
historicalSection.style.display = 'block';
// Automatically load historical chart
setTimeout(() => {
loadHistoricalData();
}, 500); // Small delay to let the UI update
} else {
historicalSection.style.display = 'none';
}
// Update quantity unit
const unitSpan = document.getElementById('quantity-unit');
if (unitSpan && currentDirection === 'btc_to_item') {
const unit = option?.dataset.unit;
if (unit) {
unitSpan.textContent = unit;
}
}
debounceConvert();
} else {
historicalSection.style.display = 'none';
clearResults();
}
}
async function performConversion() {
const inputElement = currentDirection === 'btc_to_item'
? document.getElementById('btc-input')
: document.getElementById('quantity-input');
if (!inputElement || !inputElement.value || !currentItem) {
return;
}
const inputValue = parseFloat(inputElement.value);
if (inputValue <= 0) {
showToast('Please enter a positive value', 'error');
return;
}
showLoading(true);
try {
const params = new URLSearchParams({
item: currentItem,
direction: currentDirection,
sats: currentUnit === 'sats' ? 'true' : 'false'
});
if (currentDirection === 'btc_to_item') {
params.append('btc_amount', inputValue);
} else {
params.append('quantity', inputValue);
}
const response = await fetch(`/api/convert?${params}`);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Conversion failed');
}
const data = await response.json();
updateResults(data);
} catch (error) {
showToast(error.message, 'error');
clearResults();
} finally {
showLoading(false);
}
}
function updateResults(data) {
document.getElementById('quantity-value').textContent = data.quantity.toLocaleString();
document.getElementById('item-price').textContent = `$${data.usd_item.toLocaleString()}`;
document.getElementById('total-value').textContent = `$${data.usd_total.toLocaleString()}`;
document.getElementById('btc-price').textContent = `$${data.btc_price.toLocaleString()}`;
}
function clearResults() {
document.getElementById('quantity-value').textContent = '--';
document.getElementById('item-price').textContent = '$--';
document.getElementById('total-value').textContent = '$--';
document.getElementById('btc-price').textContent = '$--';
}
async function loadHistoricalData() {
console.log('loadHistoricalData called for item:', currentItem);
if (!currentItem) {
showToast('Please select an item first', 'error');
return;
}
const fromDateValue = fromDate.value;
const toDateValue = toDate.value;
console.log('Date values:', fromDateValue, toDateValue);
if (!fromDateValue || !toDateValue) {
console.log('Missing dates, using defaults');
// Use default dates if not set
setDefaultDates();
}
showLoading(true);
try {
const params = new URLSearchParams({
item: currentItem,
from_date: fromDate.value,
to_date: toDate.value
});
console.log('Fetching historical data with params:', params.toString());
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
const response = await fetch(`/api/historical?${params}`, {
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to load historical data');
}
const data = await response.json();
console.log('Historical data received:', data);
renderChart(data);
} catch (error) {
console.error('Error loading historical data:', error);
let errorMessage = error.message;
if (error.name === 'AbortError') {
errorMessage = 'Request timed out. Please try again.';
} else if (error.message.includes('Failed to fetch')) {
errorMessage = 'Network error. Please check your connection.';
}
showToast(errorMessage, 'error');
} finally {
showLoading(false);
}
}
function renderChart(data, retryCount = 0) {
console.log(`Attempting to render chart (attempt ${retryCount + 1})`);
// Check if CanvasJS is loaded, with retry logic
if (typeof CanvasJS === 'undefined') {
if (retryCount < 3) {
console.log('CanvasJS not ready, retrying in 1 second...');
setTimeout(() => renderChart(data, retryCount + 1), 1000);
return;
} else {
showToast('Chart library failed to load after multiple attempts. Please refresh the page.', 'error');
return;
}
}
// Check if chart container exists
const container = document.getElementById('chartContainer');
if (!container) {
if (retryCount < 2) {
console.log('Chart container not ready, retrying...');
setTimeout(() => renderChart(data, retryCount + 1), 500);
return;
} else {
showToast('Chart container not found', 'error');
return;
}
}
console.log('Rendering chart with data:', data);
// Validate data
if (!data || !data.dates || !data.btc_prices || data.dates.length === 0) {
showToast('No chart data available', 'error');
return;
}
const dataPoints = data.dates.map((date, index) => ({
x: new Date(date),
y: data.btc_prices[index]
}));
console.log('Chart data points:', dataPoints.slice(0, 3)); // Log first 3 points
try {
// Clear any existing chart
container.innerHTML = '';
const chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: `${currentItem.replace('_', ' ').toUpperCase()} Price in BTC`
},
axisX: {
valueFormatString: "MMM YYYY",
crosshair: {
enabled: true,
snapToDataPoint: true
}
},
axisY: {
title: "BTC",
includeZero: false,
prefix: "₿",
crosshair: {
enabled: true
}
},
toolTip: {
shared: true
},
data: [{
type: "spline",
name: "Price in BTC",
showInLegend: true,
dataPoints: dataPoints
}]
});
chart.render();
console.log('✅ Chart rendered successfully');
// Restore chart opacity
const chartContainer = document.getElementById('chartContainer');
if (chartContainer) {
chartContainer.style.opacity = '1';
}
// Only show success toast on first attempt
if (retryCount === 0) {
showToast('Chart loaded successfully!', 'success');
}
} catch (error) {
console.error('❌ Error rendering chart:', error);
if (retryCount < 2) {
console.log('Retrying chart render...');
setTimeout(() => renderChart(data, retryCount + 1), 1000);
} else {
showToast('Error rendering chart after multiple attempts: ' + error.message, 'error');
}
}
}
function setDefaultDates() {
const today = new Date();
const oneYearAgo = new Date();
oneYearAgo.setFullYear(today.getFullYear() - 1);
toDate.value = today.toISOString().split('T')[0];
fromDate.value = oneYearAgo.toISOString().split('T')[0];
}
function showLoading(show) {
loadingSpinner.style.display = show ? 'flex' : 'none';
}
function showToast(message, type = 'info') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.textContent = message;
document.getElementById('toast-container').appendChild(toast);
setTimeout(() => {
toast.remove();
}, 4000);
}
// Error handling for unhandled promise rejections
window.addEventListener('unhandledrejection', function(event) {
showToast('An unexpected error occurred', 'error');
console.error('Unhandled promise rejection:', event.reason);
});