modified layout and made it so you can switch between card modals and keep the pricing chart
This commit is contained in:
@@ -2,7 +2,6 @@ import Chart from 'chart.js/auto';
|
|||||||
|
|
||||||
const CONDITIONS = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
const CONDITIONS = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
||||||
|
|
||||||
// Match the $tiers colors from your SCSS exactly
|
|
||||||
const CONDITION_COLORS = {
|
const CONDITION_COLORS = {
|
||||||
"Near Mint": { active: 'rgba(156, 204, 102, 1)', muted: 'rgba(156, 204, 102, 0.67)' },
|
"Near Mint": { active: 'rgba(156, 204, 102, 1)', muted: 'rgba(156, 204, 102, 0.67)' },
|
||||||
"Lightly Played": { active: 'rgba(211, 225, 86, 1)', muted: 'rgba(211, 225, 86, 0.67)' },
|
"Lightly Played": { active: 'rgba(211, 225, 86, 1)', muted: 'rgba(211, 225, 86, 0.67)' },
|
||||||
@@ -11,7 +10,7 @@ const CONDITION_COLORS = {
|
|||||||
"Damaged": { active: 'rgba(255, 167, 36, 1)', muted: 'rgba(255, 167, 36, 0.67)' },
|
"Damaged": { active: 'rgba(255, 167, 36, 1)', muted: 'rgba(255, 167, 36, 0.67)' },
|
||||||
};
|
};
|
||||||
|
|
||||||
const RANGE_DAYS = { '1m': 30, '3m': 90 };
|
const RANGE_DAYS = { '1m': 30, '3m': 90, '6m': 180, '1y': 365, 'all': Infinity };
|
||||||
|
|
||||||
let chartInstance = null;
|
let chartInstance = null;
|
||||||
let allHistory = [];
|
let allHistory = [];
|
||||||
@@ -24,8 +23,19 @@ function formatDate(dateStr) {
|
|||||||
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function setEmptyState(isEmpty) {
|
||||||
|
const modal = document.getElementById('cardModal');
|
||||||
|
const empty = modal?.querySelector('#priceHistoryEmpty');
|
||||||
|
const canvasWrapper = empty?.nextElementSibling;
|
||||||
|
if (!empty || !canvasWrapper) return;
|
||||||
|
empty.classList.toggle('d-none', !isEmpty);
|
||||||
|
canvasWrapper.classList.toggle('d-none', isEmpty);
|
||||||
|
}
|
||||||
|
|
||||||
function buildChartData(history, rangeKey) {
|
function buildChartData(history, rangeKey) {
|
||||||
const cutoff = new Date(Date.now() - RANGE_DAYS[rangeKey] * 86_400_000);
|
const cutoff = RANGE_DAYS[rangeKey] === Infinity
|
||||||
|
? new Date(0)
|
||||||
|
: new Date(Date.now() - RANGE_DAYS[rangeKey] * 86_400_000);
|
||||||
|
|
||||||
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
||||||
|
|
||||||
@@ -40,17 +50,22 @@ function buildChartData(history, rangeKey) {
|
|||||||
lookup[row.condition][row.calculatedAt] = Number(row.marketPrice);
|
lookup[row.condition][row.calculatedAt] = Number(row.marketPrice);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check specifically whether the active condition has any data points
|
||||||
|
const activeConditionDates = allDates.filter(
|
||||||
|
date => lookup[activeCondition]?.[date] != null
|
||||||
|
);
|
||||||
|
const activeConditionHasData = activeConditionDates.length > 0;
|
||||||
|
|
||||||
const datasets = CONDITIONS.map(condition => {
|
const datasets = CONDITIONS.map(condition => {
|
||||||
const isActive = condition === activeCondition;
|
const isActive = condition === activeCondition;
|
||||||
const colors = CONDITION_COLORS[condition];
|
const colors = CONDITION_COLORS[condition];
|
||||||
const data = allDates.map(date => lookup[condition]?.[date] ?? null);
|
const data = allDates.map(date => lookup[condition]?.[date] ?? null);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
label: condition,
|
label: condition,
|
||||||
data,
|
data,
|
||||||
borderColor: isActive ? colors.active : colors.muted,
|
borderColor: isActive ? colors.active : colors.muted,
|
||||||
borderWidth: isActive ? 2.5 : 1,
|
borderWidth: isActive ? 2 : 1,
|
||||||
pointRadius: isActive ? 3 : 0,
|
pointRadius: isActive ? 2.5 : 0,
|
||||||
pointHoverRadius: isActive ? 5 : 3,
|
pointHoverRadius: isActive ? 5 : 3,
|
||||||
pointBackgroundColor: isActive ? colors.active : colors.muted,
|
pointBackgroundColor: isActive ? colors.active : colors.muted,
|
||||||
tension: 0.3,
|
tension: 0.3,
|
||||||
@@ -60,12 +75,20 @@ function buildChartData(history, rangeKey) {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return { labels, datasets };
|
return { labels, datasets, hasData: allDates.length > 0, activeConditionHasData };
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateChart() {
|
function updateChart() {
|
||||||
if (!chartInstance) return;
|
if (!chartInstance) return;
|
||||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
const { labels, datasets, hasData, activeConditionHasData } = buildChartData(allHistory, activeRange);
|
||||||
|
|
||||||
|
// Show empty state if no data at all, or if the active condition specifically has no data
|
||||||
|
if (!hasData || !activeConditionHasData) {
|
||||||
|
setEmptyState(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setEmptyState(false);
|
||||||
chartInstance.data.labels = labels;
|
chartInstance.data.labels = labels;
|
||||||
chartInstance.data.datasets = datasets;
|
chartInstance.data.datasets = datasets;
|
||||||
chartInstance.update('none');
|
chartInstance.update('none');
|
||||||
@@ -85,11 +108,18 @@ function initPriceChart(canvas) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!allHistory.length) {
|
if (!allHistory.length) {
|
||||||
console.warn('No price history data for this card');
|
setEmptyState(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
const { labels, datasets, hasData, activeConditionHasData } = buildChartData(allHistory, activeRange);
|
||||||
|
|
||||||
|
if (!hasData || !activeConditionHasData) {
|
||||||
|
setEmptyState(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setEmptyState(false);
|
||||||
|
|
||||||
chartInstance = new Chart(canvas.getContext('2d'), {
|
chartInstance = new Chart(canvas.getContext('2d'), {
|
||||||
type: 'line',
|
type: 'line',
|
||||||
@@ -151,43 +181,32 @@ function initPriceChart(canvas) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupObserver() {
|
function initFromCanvas(canvas) {
|
||||||
const modal = document.getElementById('cardModal');
|
|
||||||
if (!modal) {
|
|
||||||
console.error('cardModal element not found');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const observer = new MutationObserver(() => {
|
|
||||||
const canvas = document.getElementById('priceHistoryChart');
|
|
||||||
if (!canvas) return;
|
|
||||||
|
|
||||||
// Disconnect immediately so tab switches don't retrigger initPriceChart
|
|
||||||
observer.disconnect();
|
|
||||||
|
|
||||||
activeCondition = "Near Mint";
|
activeCondition = "Near Mint";
|
||||||
activeRange = '1m';
|
activeRange = '1m';
|
||||||
document.querySelectorAll('.price-range-btn').forEach(b => {
|
const modal = document.getElementById('cardModal');
|
||||||
|
modal?.querySelectorAll('.price-range-btn').forEach(b => {
|
||||||
b.classList.toggle('active', b.dataset.range === '1m');
|
b.classList.toggle('active', b.dataset.range === '1m');
|
||||||
});
|
});
|
||||||
|
|
||||||
initPriceChart(canvas);
|
initPriceChart(canvas);
|
||||||
});
|
}
|
||||||
|
|
||||||
observer.observe(modal, { childList: true, subtree: true });
|
function setup() {
|
||||||
|
const modal = document.getElementById('cardModal');
|
||||||
|
if (!modal) return;
|
||||||
|
|
||||||
|
modal.addEventListener('card-modal:swapped', () => {
|
||||||
|
const canvas = modal.querySelector('#priceHistoryChart');
|
||||||
|
if (canvas) initFromCanvas(canvas);
|
||||||
|
});
|
||||||
|
|
||||||
modal.addEventListener('hidden.bs.modal', () => {
|
modal.addEventListener('hidden.bs.modal', () => {
|
||||||
if (chartInstance) {
|
if (chartInstance) { chartInstance.destroy(); chartInstance = null; }
|
||||||
chartInstance.destroy();
|
|
||||||
chartInstance = null;
|
|
||||||
}
|
|
||||||
allHistory = [];
|
allHistory = [];
|
||||||
// Reconnect so the next card open is detected
|
|
||||||
observer.observe(modal, { childList: true, subtree: true });
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('shown.bs.tab', (e) => {
|
document.addEventListener('shown.bs.tab', (e) => {
|
||||||
|
if (!modal.contains(e.target)) return;
|
||||||
const target = e.target?.getAttribute('data-bs-target');
|
const target = e.target?.getAttribute('data-bs-target');
|
||||||
const conditionMap = {
|
const conditionMap = {
|
||||||
'#nav-nm': 'Near Mint',
|
'#nav-nm': 'Near Mint',
|
||||||
@@ -204,11 +223,12 @@ document.addEventListener('shown.bs.tab', (e) => {
|
|||||||
|
|
||||||
document.addEventListener('click', (e) => {
|
document.addEventListener('click', (e) => {
|
||||||
const btn = e.target?.closest('.price-range-btn');
|
const btn = e.target?.closest('.price-range-btn');
|
||||||
if (!btn) return;
|
if (!btn || !modal.contains(btn)) return;
|
||||||
document.querySelectorAll('.price-range-btn').forEach(b => b.classList.remove('active'));
|
modal.querySelectorAll('.price-range-btn').forEach(b => b.classList.remove('active'));
|
||||||
btn.classList.add('active');
|
btn.classList.add('active');
|
||||||
activeRange = btn.dataset.range ?? '1m';
|
activeRange = btn.dataset.range ?? '1m';
|
||||||
updateChart();
|
updateChart();
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
setupObserver();
|
setup();
|
||||||
@@ -41,7 +41,6 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Modal nav buttons, rendered outside modal-content so they survive htmx swaps -->
|
|
||||||
<button id="modalPrevBtn" class="modal-nav-btn modal-nav-prev d-none" aria-label="Previous card">
|
<button id="modalPrevBtn" class="modal-nav-btn modal-nav-prev d-none" aria-label="Previous card">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16">
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 16 16">
|
||||||
<path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"/>
|
<path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"/>
|
||||||
@@ -58,7 +57,7 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
<script is:inline>
|
<script is:inline>
|
||||||
(function () {
|
(function () {
|
||||||
|
|
||||||
// ── Global helpers (called from card-modal partial onclick) ───────────────
|
// ── Global helpers ────────────────────────────────────────────────────────
|
||||||
window.copyImage = async function(img) {
|
window.copyImage = async function(img) {
|
||||||
try {
|
try {
|
||||||
const canvas = document.createElement("canvas");
|
const canvas = document.createElement("canvas");
|
||||||
@@ -67,7 +66,6 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
canvas.height = img.naturalHeight;
|
canvas.height = img.naturalHeight;
|
||||||
ctx.drawImage(img, 0, 0);
|
ctx.drawImage(img, 0, 0);
|
||||||
|
|
||||||
// Try modern clipboard API first (requires HTTPS + permissions)
|
|
||||||
if (navigator.clipboard && navigator.clipboard.write) {
|
if (navigator.clipboard && navigator.clipboard.write) {
|
||||||
const blob = await new Promise((resolve, reject) => {
|
const blob = await new Promise((resolve, reject) => {
|
||||||
canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
|
canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
|
||||||
@@ -75,13 +73,11 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
|
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
|
||||||
showCopyToast('📋 Image copied!', '#198754');
|
showCopyToast('📋 Image copied!', '#198754');
|
||||||
} else {
|
} else {
|
||||||
// Fallback: copy the image URL to clipboard as text
|
|
||||||
const url = img.src;
|
const url = img.src;
|
||||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||||
await navigator.clipboard.writeText(url);
|
await navigator.clipboard.writeText(url);
|
||||||
showCopyToast('📋 Image URL copied!', '#198754');
|
showCopyToast('📋 Image URL copied!', '#198754');
|
||||||
} else {
|
} else {
|
||||||
// Last resort: execCommand (deprecated but broadly supported)
|
|
||||||
const input = document.createElement('input');
|
const input = document.createElement('input');
|
||||||
input.value = url;
|
input.value = url;
|
||||||
document.body.appendChild(input);
|
document.body.appendChild(input);
|
||||||
@@ -115,7 +111,7 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
}, 2000);
|
}, 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── State ────────────────────────────────────────────────────────────────
|
// ── State ─────────────────────────────────────────────────────────────────
|
||||||
const cardIndex = [];
|
const cardIndex = [];
|
||||||
let currentCardId = null;
|
let currentCardId = null;
|
||||||
let isNavigating = false;
|
let isNavigating = false;
|
||||||
@@ -177,6 +173,16 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Fire card-modal:swapped so the partial's script can init the chart ────
|
||||||
|
// Deferred one rAF so the canvas has real dimensions before Chart.js measures it.
|
||||||
|
function initChartAfterSwap(modal) {
|
||||||
|
const canvas = modal.querySelector('#priceHistoryChart');
|
||||||
|
if (!canvas) return;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
modal.dispatchEvent(new CustomEvent('card-modal:swapped', { bubbles: false }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async function loadCard(cardId, direction = null) {
|
async function loadCard(cardId, direction = null) {
|
||||||
if (!cardId || isNavigating) return;
|
if (!cardId || isNavigating) return;
|
||||||
isNavigating = true;
|
isNavigating = true;
|
||||||
@@ -187,16 +193,18 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
const url = `/partials/card-modal?cardId=${cardId}`;
|
const url = `/partials/card-modal?cardId=${cardId}`;
|
||||||
|
|
||||||
const { idx, total } = getAdjacentIds();
|
const { idx, total } = getAdjacentIds();
|
||||||
if (idx >= total - 3) {
|
if (idx >= total - 3) tryTriggerSentinel();
|
||||||
tryTriggerSentinel();
|
|
||||||
}
|
|
||||||
|
|
||||||
const doSwap = async () => {
|
const doSwap = async () => {
|
||||||
const response = await fetch(url);
|
const response = await fetch(url);
|
||||||
const html = await response.text();
|
const html = await response.text();
|
||||||
|
|
||||||
|
if (modal._reconnectChartObserver) modal._reconnectChartObserver();
|
||||||
|
|
||||||
modal.innerHTML = html;
|
modal.innerHTML = html;
|
||||||
if (typeof htmx !== 'undefined') htmx.process(modal);
|
if (typeof htmx !== 'undefined') htmx.process(modal);
|
||||||
updateNavButtons(modal);
|
updateNavButtons(modal);
|
||||||
|
initChartAfterSwap(modal);
|
||||||
};
|
};
|
||||||
|
|
||||||
if (document.startViewTransition && direction) {
|
if (document.startViewTransition && direction) {
|
||||||
@@ -210,9 +218,7 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
isNavigating = false;
|
isNavigating = false;
|
||||||
|
|
||||||
const { idx: newIdx, total: newTotal } = getAdjacentIds();
|
const { idx: newIdx, total: newTotal } = getAdjacentIds();
|
||||||
if (newIdx >= newTotal - 3) {
|
if (newIdx >= newTotal - 3) tryTriggerSentinel();
|
||||||
tryTriggerSentinel();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function navigatePrev() {
|
function navigatePrev() {
|
||||||
@@ -255,7 +261,7 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
else navigatePrev();
|
else navigatePrev();
|
||||||
}, { passive: true });
|
}, { passive: true });
|
||||||
|
|
||||||
// ── Hook into HTMX card-modal opens ──────────────────────────────────────
|
// ── HTMX card-modal opens ─────────────────────────────────────────────────
|
||||||
document.body.addEventListener('htmx:beforeRequest', async (e) => {
|
document.body.addEventListener('htmx:beforeRequest', async (e) => {
|
||||||
if (e.detail.elt.getAttribute('hx-target') !== '#cardModal') return;
|
if (e.detail.elt.getAttribute('hx-target') !== '#cardModal') return;
|
||||||
|
|
||||||
@@ -270,30 +276,29 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
const target = document.getElementById('cardModal');
|
const target = document.getElementById('cardModal');
|
||||||
const sourceImg = cardEl?.querySelector('img');
|
const sourceImg = cardEl?.querySelector('img');
|
||||||
|
|
||||||
// ── Fetch first, THEN transition ──────────────────────────────────────
|
|
||||||
const response = await fetch(url, { headers: { 'HX-Request': 'true' } });
|
const response = await fetch(url, { headers: { 'HX-Request': 'true' } });
|
||||||
if (!response.ok) throw new Error(`Failed to load modal: ${response.status}`);
|
if (!response.ok) throw new Error(`Failed to load modal: ${response.status}`);
|
||||||
const html = await response.text();
|
const html = await response.text();
|
||||||
|
|
||||||
// Use a unique name per transition to avoid duplicate view-transition-name conflicts
|
|
||||||
const transitionName = `card-hero-${currentCardId}`;
|
const transitionName = `card-hero-${currentCardId}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (sourceImg) {
|
if (sourceImg) {
|
||||||
sourceImg.style.viewTransitionName = transitionName;
|
sourceImg.style.viewTransitionName = transitionName;
|
||||||
sourceImg.style.opacity = '0'; // hide original immediately after capture
|
sourceImg.style.opacity = '0';
|
||||||
}
|
}
|
||||||
|
|
||||||
const transition = document.startViewTransition(async () => {
|
const transition = document.startViewTransition(async () => {
|
||||||
// Clear source name BEFORE setting it on the destination
|
|
||||||
if (sourceImg) sourceImg.style.viewTransitionName = '';
|
if (sourceImg) sourceImg.style.viewTransitionName = '';
|
||||||
|
|
||||||
|
if (target._reconnectChartObserver) target._reconnectChartObserver();
|
||||||
|
|
||||||
target.innerHTML = html;
|
target.innerHTML = html;
|
||||||
if (typeof htmx !== 'undefined') htmx.process(target);
|
if (typeof htmx !== 'undefined') htmx.process(target);
|
||||||
|
|
||||||
const destImg = target.querySelector('img.card-image');
|
const destImg = target.querySelector('img.card-image');
|
||||||
if (destImg) {
|
if (destImg) {
|
||||||
destImg.style.viewTransitionName = transitionName; // same unique name
|
destImg.style.viewTransitionName = transitionName;
|
||||||
if (!destImg.complete) {
|
if (!destImg.complete) {
|
||||||
await new Promise(resolve => {
|
await new Promise(resolve => {
|
||||||
destImg.addEventListener('load', resolve, { once: true });
|
destImg.addEventListener('load', resolve, { once: true });
|
||||||
@@ -305,6 +310,7 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
|
|
||||||
await transition.finished;
|
await transition.finished;
|
||||||
updateNavButtons(target);
|
updateNavButtons(target);
|
||||||
|
initChartAfterSwap(target);
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[card-modal] transition failed:', err);
|
console.error('[card-modal] transition failed:', err);
|
||||||
@@ -312,17 +318,18 @@ import BackToTop from "./BackToTop.astro"
|
|||||||
} finally {
|
} finally {
|
||||||
if (sourceImg) {
|
if (sourceImg) {
|
||||||
sourceImg.style.viewTransitionName = '';
|
sourceImg.style.viewTransitionName = '';
|
||||||
sourceImg.style.opacity = ''; // restore after transition
|
sourceImg.style.opacity = '';
|
||||||
}
|
}
|
||||||
const destImg = target.querySelector('img.card-image');
|
const destImg = target.querySelector('img.card-image');
|
||||||
if (destImg) destImg.style.viewTransitionName = '';
|
if (destImg) destImg.style.viewTransitionName = '';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Show/hide nav buttons with Bootstrap modal events ────────────────────
|
// ── Bootstrap modal events ────────────────────────────────────────────────
|
||||||
const cardModal = document.getElementById('cardModal');
|
const cardModal = document.getElementById('cardModal');
|
||||||
cardModal.addEventListener('shown.bs.modal', () => {
|
cardModal.addEventListener('shown.bs.modal', () => {
|
||||||
updateNavButtons(cardModal);
|
updateNavButtons(cardModal);
|
||||||
|
initChartAfterSwap(cardModal);
|
||||||
});
|
});
|
||||||
cardModal.addEventListener('hidden.bs.modal', () => {
|
cardModal.addEventListener('hidden.bs.modal', () => {
|
||||||
currentCardId = null;
|
currentCardId = null;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import SetIcon from '../../components/SetIcon.astro';
|
|||||||
import EnergyIcon from '../../components/EnergyIcon.astro';
|
import EnergyIcon from '../../components/EnergyIcon.astro';
|
||||||
import RarityIcon from '../../components/RarityIcon.astro';
|
import RarityIcon from '../../components/RarityIcon.astro';
|
||||||
import { db } from '../../db/index';
|
import { db } from '../../db/index';
|
||||||
|
import { priceHistory, skus } from '../../db/schema';
|
||||||
|
import { eq, inArray } from 'drizzle-orm';
|
||||||
import FirstEditionIcon from "../../components/FirstEditionIcon.astro";
|
import FirstEditionIcon from "../../components/FirstEditionIcon.astro";
|
||||||
|
|
||||||
export const partial = true;
|
export const partial = true;
|
||||||
@@ -15,13 +17,7 @@ const cardId = Number(searchParams.get('cardId')) || 0;
|
|||||||
const card = await db.query.cards.findFirst({
|
const card = await db.query.cards.findFirst({
|
||||||
where: { cardId: Number(cardId) },
|
where: { cardId: Number(cardId) },
|
||||||
with: {
|
with: {
|
||||||
prices: {
|
prices: true,
|
||||||
with: {
|
|
||||||
history: {
|
|
||||||
orderBy: (ph, { asc }) => [asc(ph.calculatedAt)],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
set: true,
|
set: true,
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -53,36 +49,97 @@ const calculatedAt = (() => {
|
|||||||
return new Date(Math.max(...dates.map(d => d.getTime())));
|
return new Date(Math.max(...dates.map(d => d.getTime())));
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// Flatten all price history across all skus into a single array for the chart,
|
// ── Fetch price history + compute volatility ──────────────────────────────
|
||||||
// normalising calculatedAt to a YYYY-MM-DD string to avoid timezone/dedup issues
|
const cardSkus = card?.prices?.length
|
||||||
const priceHistoryForChart = (card?.prices ?? []).flatMap(sku =>
|
? await db.select().from(skus).where(eq(skus.cardId, cardId))
|
||||||
(sku.history ?? []).map(ph => ({
|
: [];
|
||||||
condition: sku.condition,
|
|
||||||
calculatedAt: ph.calculatedAt
|
const skuIds = cardSkus.map(s => s.skuId);
|
||||||
? new Date(ph.calculatedAt).toISOString().split('T')[0]
|
|
||||||
|
const historyRows = skuIds.length
|
||||||
|
? await db
|
||||||
|
.select({
|
||||||
|
skuId: priceHistory.skuId,
|
||||||
|
calculatedAt: priceHistory.calculatedAt,
|
||||||
|
marketPrice: priceHistory.marketPrice,
|
||||||
|
condition: skus.condition,
|
||||||
|
})
|
||||||
|
.from(priceHistory)
|
||||||
|
.innerJoin(skus, eq(priceHistory.skuId, skus.skuId))
|
||||||
|
.where(inArray(priceHistory.skuId, skuIds))
|
||||||
|
.orderBy(priceHistory.calculatedAt)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// Rolling 30-day cutoff for volatility calculation
|
||||||
|
const thirtyDaysAgo = new Date(Date.now() - 30 * 86_400_000);
|
||||||
|
|
||||||
|
const byCondition: Record<string, number[]> = {};
|
||||||
|
for (const row of historyRows) {
|
||||||
|
if (row.marketPrice == null) continue;
|
||||||
|
if (!row.calculatedAt) continue;
|
||||||
|
if (new Date(row.calculatedAt) < thirtyDaysAgo) continue;
|
||||||
|
const price = Number(row.marketPrice);
|
||||||
|
if (price <= 0) continue;
|
||||||
|
if (!byCondition[row.condition]) byCondition[row.condition] = [];
|
||||||
|
byCondition[row.condition].push(price);
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeVolatility(prices: number[]): { label: string; monthlyVol: number } {
|
||||||
|
if (prices.length < 2) return { label: '—', monthlyVol: 0 };
|
||||||
|
const returns: number[] = [];
|
||||||
|
for (let i = 1; i < prices.length; i++) {
|
||||||
|
returns.push(Math.log(prices[i] / prices[i - 1]));
|
||||||
|
}
|
||||||
|
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
|
||||||
|
const variance = returns.reduce((sum, r) => sum + (r - mean) ** 2, 0) / (returns.length - 1);
|
||||||
|
const monthlyVol = Math.sqrt(variance) * Math.sqrt(30);
|
||||||
|
const label = monthlyVol >= 0.30 ? 'High'
|
||||||
|
: monthlyVol >= 0.15 ? 'Medium'
|
||||||
|
: 'Low';
|
||||||
|
return { label, monthlyVol: Math.round(monthlyVol * 100) / 100 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const volatilityByCondition: Record<string, { label: string; monthlyVol: number }> = {};
|
||||||
|
for (const [condition, prices] of Object.entries(byCondition)) {
|
||||||
|
volatilityByCondition[condition] = computeVolatility(prices);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Price history for chart (full history, not windowed) ──────────────────
|
||||||
|
const priceHistoryForChart = historyRows.map(row => ({
|
||||||
|
condition: row.condition,
|
||||||
|
calculatedAt: row.calculatedAt
|
||||||
|
? new Date(row.calculatedAt).toISOString().split('T')[0]
|
||||||
: null,
|
: null,
|
||||||
marketPrice: ph.marketPrice,
|
marketPrice: row.marketPrice,
|
||||||
}))
|
})).filter(r => r.calculatedAt !== null);
|
||||||
).filter(r => r.calculatedAt !== null);
|
|
||||||
|
// ── Determine which range buttons to show ────────────────────────────────
|
||||||
|
// Find the oldest data point to know what ranges are meaningful
|
||||||
|
const now = Date.now();
|
||||||
|
const oldestDate = historyRows.length
|
||||||
|
? Math.min(...historyRows
|
||||||
|
.filter(r => r.calculatedAt)
|
||||||
|
.map(r => new Date(r.calculatedAt!).getTime()))
|
||||||
|
: now;
|
||||||
|
|
||||||
|
const dataSpanDays = (now - oldestDate) / 86_400_000;
|
||||||
|
|
||||||
|
const showRanges = {
|
||||||
|
'1m': dataSpanDays >= 1,
|
||||||
|
'3m': dataSpanDays >= 60, // meaningful if at least 2 months of data
|
||||||
|
'6m': dataSpanDays >= 180, // meaningful if at least 6 months of data
|
||||||
|
'1y': dataSpanDays >= 365, // meaningful if at least 9 months of data
|
||||||
|
'all': dataSpanDays >= 400, // meaningful if more than ~13 months of data
|
||||||
|
};
|
||||||
|
|
||||||
const conditionOrder = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
const conditionOrder = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
||||||
|
|
||||||
const conditionAttributes = (price: any) => {
|
const conditionAttributes = (price: any) => {
|
||||||
const volatility = (() => {
|
const condition: string = price?.condition || "Near Mint";
|
||||||
const market = price?.marketPrice;
|
const vol = volatilityByCondition[condition] ?? { label: '—', monthlyVol: 0 };
|
||||||
const low = price?.lowestPrice;
|
|
||||||
const high = price?.highestPrice;
|
|
||||||
if (market == null || low == null || high == null || Number(market) === 0) {
|
|
||||||
return "Indeterminate";
|
|
||||||
}
|
|
||||||
const spreadPct = (Number(high) - Number(low)) / Number(market) * 100;
|
|
||||||
if (spreadPct >= 81) return "High";
|
|
||||||
if (spreadPct >= 59) return "Medium";
|
|
||||||
return "Low";
|
|
||||||
})();
|
|
||||||
|
|
||||||
const volatilityClass = (() => {
|
const volatilityClass = (() => {
|
||||||
switch (volatility) {
|
switch (vol.label) {
|
||||||
case "High": return "alert-danger";
|
case "High": return "alert-danger";
|
||||||
case "Medium": return "alert-warning";
|
case "Medium": return "alert-warning";
|
||||||
case "Low": return "alert-success";
|
case "Low": return "alert-success";
|
||||||
@@ -90,14 +147,16 @@ const conditionAttributes = (price: any) => {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const condition: string = price?.condition || "Near Mint";
|
const volatilityDisplay = vol.label === '—'
|
||||||
|
? '—'
|
||||||
|
: `${vol.label} (${(vol.monthlyVol * 100).toFixed(0)}%)`;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"Near Mint": { label: "nav-nm", volatility, volatilityClass, class: "show active" },
|
"Near Mint": { label: "nav-nm", volatility: volatilityDisplay, volatilityClass, class: "show active" },
|
||||||
"Lightly Played": { label: "nav-lp", volatility, volatilityClass },
|
"Lightly Played": { label: "nav-lp", volatility: volatilityDisplay, volatilityClass },
|
||||||
"Moderately Played":{ label: "nav-mp", volatility, volatilityClass },
|
"Moderately Played":{ label: "nav-mp", volatility: volatilityDisplay, volatilityClass },
|
||||||
"Heavily Played": { label: "nav-hp", volatility, volatilityClass },
|
"Heavily Played": { label: "nav-hp", volatility: volatilityDisplay, volatilityClass },
|
||||||
"Damaged": { label: "nav-dmg", volatility, volatilityClass }
|
"Damaged": { label: "nav-dmg", volatility: volatilityDisplay, volatilityClass }
|
||||||
}[condition];
|
}[condition];
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -153,32 +212,32 @@ const altSearchUrl = (card: any) => {
|
|||||||
<ul class="nav nav-tabs nav-fill border-0 me-3 mb-2" id="myTab" role="tablist">
|
<ul class="nav nav-tabs nav-fill border-0 me-3 mb-2" id="myTab" role="tablist">
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link nm active" id="nm-tab" data-bs-toggle="tab" data-bs-target="#nav-nm" type="button" role="tab" aria-controls="nav-nm" aria-selected="true">
|
<button class="nav-link nm active" id="nm-tab" data-bs-toggle="tab" data-bs-target="#nav-nm" type="button" role="tab" aria-controls="nav-nm" aria-selected="true">
|
||||||
<span class="d-none d-lg-inline">Near Mint</span><span class="d-lg-none">NM</span>
|
<span class="d-none d-xxl-inline">Near Mint</span><span class="d-xxl-none">NM</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link lp" id="lp-tab" data-bs-toggle="tab" data-bs-target="#nav-lp" type="button" role="tab" aria-controls="nav-lp" aria-selected="false">
|
<button class="nav-link lp" id="lp-tab" data-bs-toggle="tab" data-bs-target="#nav-lp" type="button" role="tab" aria-controls="nav-lp" aria-selected="false">
|
||||||
<span class="d-none d-lg-inline">Lightly Played</span><span class="d-lg-none">LP</span>
|
<span class="d-none d-xxl-inline">Lightly Played</span><span class="d-xxl-none">LP</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link mp" id="mp-tab" data-bs-toggle="tab" data-bs-target="#nav-mp" type="button" role="tab" aria-controls="nav-mp" aria-selected="false">
|
<button class="nav-link mp" id="mp-tab" data-bs-toggle="tab" data-bs-target="#nav-mp" type="button" role="tab" aria-controls="nav-mp" aria-selected="false">
|
||||||
<span class="d-none d-lg-inline">Moderately Played</span><span class="d-lg-none">MP</span>
|
<span class="d-none d-xxl-inline">Moderately Played</span><span class="d-xxl-none">MP</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link hp" id="hp-tab" data-bs-toggle="tab" data-bs-target="#nav-hp" type="button" role="tab" aria-controls="nav-hp" aria-selected="false">
|
<button class="nav-link hp" id="hp-tab" data-bs-toggle="tab" data-bs-target="#nav-hp" type="button" role="tab" aria-controls="nav-hp" aria-selected="false">
|
||||||
<span class="d-none d-lg-inline">Heavily Played</span><span class="d-lg-none">HP</span>
|
<span class="d-none d-xxl-inline">Heavily Played</span><span class="d-xxl-none">HP</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link dmg" id="dmg-tab" data-bs-toggle="tab" data-bs-target="#nav-dmg" type="button" role="tab" aria-controls="nav-dmg" aria-selected="false">
|
<button class="nav-link dmg" id="dmg-tab" data-bs-toggle="tab" data-bs-target="#nav-dmg" type="button" role="tab" aria-controls="nav-dmg" aria-selected="false">
|
||||||
<span class="d-none d-lg-inline">Damaged</span><span class="d-lg-none">DMG</span>
|
<span class="d-none d-xxl-inline">Damaged</span><span class="d-xxl-none">DMG</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
<li class="nav-item" role="presentation">
|
<li class="nav-item" role="presentation">
|
||||||
<button class="nav-link vendor d-none" id="vendor-tab" data-bs-toggle="tab" data-bs-target="#nav-vendor" type="button" role="tab" aria-controls="nav-vendor" aria-selected="false">
|
<button class="nav-link vendor d-none" id="vendor-tab" data-bs-toggle="tab" data-bs-target="#nav-vendor" type="button" role="tab" aria-controls="nav-vendor" aria-selected="false">
|
||||||
<span class="d-none d-lg-inline">Inventory</span><span class="d-lg-none">+/-</span>
|
<span class="d-none d-xxl-inline">Inventory</span><span class="d-xxl-none">+/-</span>
|
||||||
</button>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -188,37 +247,68 @@ const altSearchUrl = (card: any) => {
|
|||||||
const attributes = conditionAttributes(price);
|
const attributes = conditionAttributes(price);
|
||||||
return (
|
return (
|
||||||
<div class={`tab-pane fade ${attributes?.label} ${attributes?.class ?? ''}`} id={`${attributes?.label}`} role="tabpanel" tabindex="0">
|
<div class={`tab-pane fade ${attributes?.label} ${attributes?.class ?? ''}`} id={`${attributes?.label}`} role="tabpanel" tabindex="0">
|
||||||
<!-- Price stat cards only — chart lives outside tabs -->
|
<div class="d-flex flex-column gap-1">
|
||||||
<div class="d-flex flex-row flex-wrap gap-1 mb-1">
|
|
||||||
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
|
<!-- Stat cards -->
|
||||||
|
<div class="d-flex flex-fill flex-row gap-1">
|
||||||
|
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
||||||
<h6 class="mb-auto">Market Price</h6>
|
<h6 class="mb-auto">Market Price</h6>
|
||||||
<p class="mb-0 mt-1">${price.marketPrice}</p>
|
<p class="mb-0 mt-1">${price.marketPrice}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
|
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
||||||
<h6 class="mb-auto">Lowest Price</h6>
|
<h6 class="mb-auto">Lowest Price</h6>
|
||||||
<p class="mb-0 mt-1">${price.lowestPrice}</p>
|
<p class="mb-0 mt-1">${price.lowestPrice}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
|
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
|
||||||
<h6 class="mb-auto">Highest Price</h6>
|
<h6 class="mb-auto">Highest Price</h6>
|
||||||
<p class="mb-0 mt-1">${price.highestPrice}</p>
|
<p class="mb-0 mt-1">${price.highestPrice}</p>
|
||||||
</div>
|
</div>
|
||||||
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-1 ${attributes?.volatilityClass}`}>
|
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-0 ${attributes?.volatilityClass}`}>
|
||||||
<h6 class="mb-auto">Volatility</h6>
|
<h6 class="mb-auto">Volatility</h6>
|
||||||
<p class="mb-0 mt-1">{attributes?.volatility}</p>
|
<p class="mb-0 mt-1">{attributes?.volatility}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Table only — chart is outside the tab panes -->
|
||||||
|
<div class="w-100">
|
||||||
|
<div class="alert alert-dark rounded p-2 mb-0 table-responsive">
|
||||||
|
<h6>Latest Verified Sales</h6>
|
||||||
|
<table class="table table-sm mb-0">
|
||||||
|
<caption class="small">Filtered to remove mismatched language variants</caption>
|
||||||
|
<thead class="table-dark">
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Date</th>
|
||||||
|
<th scope="col">Title</th>
|
||||||
|
<th scope="col">Price</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><td> </td><td> </td><td> </td></tr>
|
||||||
|
<tr><td> </td><td> </td><td> </td></tr>
|
||||||
|
<tr><td> </td><td> </td><td> </td></tr>
|
||||||
|
<tr><td> </td><td> </td><td> </td></tr>
|
||||||
|
<tr><td> </td><td> </td><td> </td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0">
|
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0"></div>
|
||||||
<div class="row g-2 mt-2"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Chart lives outside tabs so it persists across condition switches -->
|
<!-- Chart lives permanently outside tab-content so Bootstrap never hides it. -->
|
||||||
<div class="alert alert-dark rounded p-2 mt-2">
|
<div class="d-block d-lg-flex gap-1 mt-1">
|
||||||
|
<div class="col-12">
|
||||||
|
<div class="alert alert-dark rounded p-2 mb-0">
|
||||||
<h6>Market Price History</h6>
|
<h6>Market Price History</h6>
|
||||||
|
<div id="priceHistoryEmpty" class="d-none text-secondary text-center py-4">
|
||||||
|
No sales data for the selected period/condition
|
||||||
|
</div>
|
||||||
<div class="position-relative" style="height: 200px;">
|
<div class="position-relative" style="height: 200px;">
|
||||||
<canvas
|
<canvas
|
||||||
id="priceHistoryChart"
|
id="priceHistoryChart"
|
||||||
@@ -228,11 +318,17 @@ const altSearchUrl = (card: any) => {
|
|||||||
</canvas>
|
</canvas>
|
||||||
</div>
|
</div>
|
||||||
<div class="btn-group btn-group-sm d-flex flex-row gap-1 justify-content-end mt-2" role="group" aria-label="Time range">
|
<div class="btn-group btn-group-sm d-flex flex-row gap-1 justify-content-end mt-2" role="group" aria-label="Time range">
|
||||||
<button type="button" class="btn btn-dark price-range-btn active" data-range="1m">1M</button>
|
{showRanges['1m'] && <button type="button" class="btn btn-dark price-range-btn active" data-range="1m">1M</button>}
|
||||||
<button type="button" class="btn btn-dark price-range-btn" data-range="3m">3M</button>
|
{showRanges['3m'] && <button type="button" class="btn btn-dark price-range-btn" data-range="3m">3M</button>}
|
||||||
|
{showRanges['6m'] && <button type="button" class="btn btn-dark price-range-btn d-none" data-range="6m">6M</button>}
|
||||||
|
{showRanges['1y'] && <button type="button" class="btn btn-dark price-range-btn d-none" data-range="1y">1Y</button>}
|
||||||
|
{showRanges['all'] && <button type="button" class="btn btn-dark price-range-btn d-none" data-range="all">All</button>}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- External links column -->
|
<!-- External links column -->
|
||||||
<div class="col-sm-12 col-md-2 mt-0 mt-md-5 d-flex flex-row flex-md-column">
|
<div class="col-sm-12 col-md-2 mt-0 mt-md-5 d-flex flex-row flex-md-column">
|
||||||
@@ -248,181 +344,3 @@ const altSearchUrl = (card: any) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
|
||||||
import Chart from 'chart.js/auto';
|
|
||||||
|
|
||||||
const CONDITIONS = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
|
|
||||||
|
|
||||||
const CONDITION_COLORS = {
|
|
||||||
"Near Mint": { active: '#22c55e', muted: 'rgba(34,197,94,0.2)' },
|
|
||||||
"Lightly Played": { active: '#eab308', muted: 'rgba(234,179,8,0.2)' },
|
|
||||||
"Moderately Played": { active: '#f97316', muted: 'rgba(249,115,22,0.2)' },
|
|
||||||
"Heavily Played": { active: '#ef4444', muted: 'rgba(239,68,68,0.2)' },
|
|
||||||
"Damaged": { active: '#a855f7', muted: 'rgba(168,85,247,0.2)' },
|
|
||||||
};
|
|
||||||
|
|
||||||
const RANGE_DAYS = { '1m': 30, '3m': 90, '6m': 180, '1y': 365, 'all': Infinity };
|
|
||||||
|
|
||||||
let chartInstance = null;
|
|
||||||
let allHistory = [];
|
|
||||||
let activeCondition = "Near Mint";
|
|
||||||
let activeRange = '1m';
|
|
||||||
|
|
||||||
function formatDate(dateStr) {
|
|
||||||
const [year, month, day] = dateStr.split('-');
|
|
||||||
const d = new Date(Number(year), Number(month) - 1, Number(day));
|
|
||||||
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildChartData(history, rangeKey) {
|
|
||||||
const cutoff = rangeKey === 'all'
|
|
||||||
? new Date(0)
|
|
||||||
: new Date(Date.now() - RANGE_DAYS[rangeKey] * 86_400_000);
|
|
||||||
|
|
||||||
const filtered = history.filter(r => new Date(r.calculatedAt) >= cutoff);
|
|
||||||
|
|
||||||
const allDates = [...new Set(filtered.map(r => r.calculatedAt))]
|
|
||||||
.sort((a, b) => new Date(a) - new Date(b));
|
|
||||||
|
|
||||||
const labels = allDates.map(formatDate);
|
|
||||||
|
|
||||||
const lookup = {};
|
|
||||||
for (const row of filtered) {
|
|
||||||
if (!lookup[row.condition]) lookup[row.condition] = {};
|
|
||||||
lookup[row.condition][row.calculatedAt] = Number(row.marketPrice);
|
|
||||||
}
|
|
||||||
|
|
||||||
const datasets = CONDITIONS.map(condition => {
|
|
||||||
const isActive = condition === activeCondition;
|
|
||||||
const colors = CONDITION_COLORS[condition];
|
|
||||||
const data = allDates.map(date => lookup[condition]?.[date] ?? null);
|
|
||||||
return {
|
|
||||||
label: condition,
|
|
||||||
data,
|
|
||||||
borderColor: isActive ? colors.active : colors.muted,
|
|
||||||
borderWidth: isActive ? 2 : 1,
|
|
||||||
pointRadius: isActive ? 3 : 0,
|
|
||||||
pointHoverRadius: isActive ? 5 : 2,
|
|
||||||
tension: 0.3,
|
|
||||||
fill: false,
|
|
||||||
spanGaps: true,
|
|
||||||
order: isActive ? 0 : 1,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
return { labels, datasets };
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateChart() {
|
|
||||||
if (!chartInstance) return;
|
|
||||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
|
||||||
chartInstance.data.labels = labels;
|
|
||||||
chartInstance.data.datasets = datasets;
|
|
||||||
chartInstance.update('none');
|
|
||||||
}
|
|
||||||
|
|
||||||
function initPriceChart(canvas) {
|
|
||||||
if (chartInstance) {
|
|
||||||
chartInstance.destroy();
|
|
||||||
chartInstance = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
allHistory = JSON.parse(canvas.dataset.history ?? '[]');
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to parse price history:', err);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!allHistory.length) return;
|
|
||||||
|
|
||||||
const { labels, datasets } = buildChartData(allHistory, activeRange);
|
|
||||||
|
|
||||||
chartInstance = new Chart(canvas.getContext('2d'), {
|
|
||||||
type: 'line',
|
|
||||||
data: { labels, datasets },
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: false,
|
|
||||||
interaction: { mode: 'index', intersect: false },
|
|
||||||
plugins: {
|
|
||||||
legend: { display: false },
|
|
||||||
tooltip: {
|
|
||||||
backgroundColor: 'rgba(0,0,0,0.85)',
|
|
||||||
titleColor: 'rgba(255,255,255,0.9)',
|
|
||||||
bodyColor: 'rgba(255,255,255,0.65)',
|
|
||||||
callbacks: {
|
|
||||||
label: (ctx) => {
|
|
||||||
const isActive = ctx.dataset.label === activeCondition;
|
|
||||||
const price = ctx.parsed.y != null ? `$${ctx.parsed.y.toFixed(2)}` : '—';
|
|
||||||
return isActive
|
|
||||||
? ` ${ctx.dataset.label}: ${price} ◀`
|
|
||||||
: ` ${ctx.dataset.label}: ${price}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
scales: {
|
|
||||||
x: {
|
|
||||||
grid: { color: 'rgba(255,255,255,0.05)' },
|
|
||||||
ticks: { color: 'rgba(255,255,255,0.4)', maxTicksLimit: 6, maxRotation: 0 },
|
|
||||||
},
|
|
||||||
y: {
|
|
||||||
grid: { color: 'rgba(255,255,255,0.05)' },
|
|
||||||
ticks: {
|
|
||||||
color: 'rgba(255,255,255,0.4)',
|
|
||||||
callback: (val) => `$${Number(val).toFixed(2)}`,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function setupListeners() {
|
|
||||||
const modal = document.getElementById('cardModal');
|
|
||||||
if (!modal) return;
|
|
||||||
|
|
||||||
modal.addEventListener('shown.bs.modal', () => {
|
|
||||||
activeCondition = "Near Mint";
|
|
||||||
activeRange = '1m';
|
|
||||||
document.querySelectorAll('.price-range-btn').forEach(b => {
|
|
||||||
b.classList.toggle('active', b.dataset.range === '1m');
|
|
||||||
});
|
|
||||||
const canvas = document.getElementById('priceHistoryChart');
|
|
||||||
if (canvas) initPriceChart(canvas);
|
|
||||||
});
|
|
||||||
|
|
||||||
modal.addEventListener('hidden.bs.modal', () => {
|
|
||||||
if (chartInstance) { chartInstance.destroy(); chartInstance = null; }
|
|
||||||
allHistory = [];
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener('shown.bs.tab', (e) => {
|
|
||||||
const target = e.target?.getAttribute('data-bs-target');
|
|
||||||
const conditionMap = {
|
|
||||||
'#nav-nm': 'Near Mint',
|
|
||||||
'#nav-lp': 'Lightly Played',
|
|
||||||
'#nav-mp': 'Moderately Played',
|
|
||||||
'#nav-hp': 'Heavily Played',
|
|
||||||
'#nav-dmg': 'Damaged',
|
|
||||||
};
|
|
||||||
if (target && conditionMap[target]) {
|
|
||||||
activeCondition = conditionMap[target];
|
|
||||||
updateChart();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener('click', (e) => {
|
|
||||||
const btn = e.target?.closest('.price-range-btn');
|
|
||||||
if (!btn) return;
|
|
||||||
document.querySelectorAll('.price-range-btn').forEach(b => b.classList.remove('active'));
|
|
||||||
btn.classList.add('active');
|
|
||||||
activeRange = btn.dataset.range ?? '1m';
|
|
||||||
updateChart();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
setupListeners();
|
|
||||||
</script>
|
|
||||||
@@ -8,7 +8,6 @@ export const prerender = false;
|
|||||||
export const GET: APIRoute = async ({ url }) => {
|
export const GET: APIRoute = async ({ url }) => {
|
||||||
const cardId = Number(url.searchParams.get('cardId')) || 0;
|
const cardId = Number(url.searchParams.get('cardId')) || 0;
|
||||||
|
|
||||||
// Get all skus for this card
|
|
||||||
const cardSkus = await db
|
const cardSkus = await db
|
||||||
.select()
|
.select()
|
||||||
.from(skus)
|
.from(skus)
|
||||||
@@ -20,8 +19,7 @@ export const GET: APIRoute = async ({ url }) => {
|
|||||||
|
|
||||||
const skuIds = cardSkus.map(s => s.skuId);
|
const skuIds = cardSkus.map(s => s.skuId);
|
||||||
|
|
||||||
// Fetch price history for all skus
|
const historyRows = await db
|
||||||
const history = await db
|
|
||||||
.select({
|
.select({
|
||||||
skuId: priceHistory.skuId,
|
skuId: priceHistory.skuId,
|
||||||
calculatedAt: priceHistory.calculatedAt,
|
calculatedAt: priceHistory.calculatedAt,
|
||||||
@@ -33,7 +31,41 @@ export const GET: APIRoute = async ({ url }) => {
|
|||||||
.where(inArray(priceHistory.skuId, skuIds))
|
.where(inArray(priceHistory.skuId, skuIds))
|
||||||
.orderBy(priceHistory.calculatedAt);
|
.orderBy(priceHistory.calculatedAt);
|
||||||
|
|
||||||
return new Response(JSON.stringify(history), {
|
// Rolling 30-day cutoff for volatility
|
||||||
|
const thirtyDaysAgo = new Date(Date.now() - 30 * 86_400_000);
|
||||||
|
|
||||||
|
const byCondition: Record<string, number[]> = {};
|
||||||
|
for (const row of historyRows) {
|
||||||
|
if (row.marketPrice == null) continue;
|
||||||
|
if (!row.calculatedAt) continue;
|
||||||
|
if (new Date(row.calculatedAt) < thirtyDaysAgo) continue;
|
||||||
|
const price = Number(row.marketPrice);
|
||||||
|
if (price <= 0) continue;
|
||||||
|
if (!byCondition[row.condition]) byCondition[row.condition] = [];
|
||||||
|
byCondition[row.condition].push(price);
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeVolatility(prices: number[]): { label: string; monthlyVol: number } {
|
||||||
|
if (prices.length < 2) return { label: '—', monthlyVol: 0 };
|
||||||
|
const returns: number[] = [];
|
||||||
|
for (let i = 1; i < prices.length; i++) {
|
||||||
|
returns.push(Math.log(prices[i] / prices[i - 1]));
|
||||||
|
}
|
||||||
|
const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
|
||||||
|
const variance = returns.reduce((sum, r) => sum + (r - mean) ** 2, 0) / (returns.length - 1);
|
||||||
|
const monthlyVol = Math.sqrt(variance) * Math.sqrt(30);
|
||||||
|
const label = monthlyVol >= 0.30 ? 'High'
|
||||||
|
: monthlyVol >= 0.15 ? 'Medium'
|
||||||
|
: 'Low';
|
||||||
|
return { label, monthlyVol: Math.round(monthlyVol * 100) / 100 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const volatilityByCondition: Record<string, { label: string; monthlyVol: number }> = {};
|
||||||
|
for (const [condition, prices] of Object.entries(byCondition)) {
|
||||||
|
volatilityByCondition[condition] = computeVolatility(prices);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ history: historyRows, volatilityByCondition }), {
|
||||||
headers: { 'Content-Type': 'application/json' }
|
headers: { 'Content-Type': 'application/json' }
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
Reference in New Issue
Block a user