modified layout and made it so you can switch between card modals and keep the pricing chart

This commit is contained in:
zach
2026-03-16 11:05:10 -04:00
parent 9c81a13c69
commit c4ebbfb060
4 changed files with 323 additions and 346 deletions

View File

@@ -2,7 +2,6 @@ import Chart from 'chart.js/auto';
const CONDITIONS = ["Near Mint", "Lightly Played", "Moderately Played", "Heavily Played", "Damaged"];
// Match the $tiers colors from your SCSS exactly
const CONDITION_COLORS = {
"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)' },
@@ -11,7 +10,7 @@ const CONDITION_COLORS = {
"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 allHistory = [];
@@ -24,8 +23,19 @@ function formatDate(dateStr) {
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) {
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);
@@ -40,17 +50,22 @@ function buildChartData(history, rangeKey) {
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 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.5 : 1,
pointRadius: isActive ? 3 : 0,
borderWidth: isActive ? 2 : 1,
pointRadius: isActive ? 2.5 : 0,
pointHoverRadius: isActive ? 5 : 3,
pointBackgroundColor: isActive ? colors.active : colors.muted,
tension: 0.3,
@@ -60,12 +75,20 @@ function buildChartData(history, rangeKey) {
};
});
return { labels, datasets };
return { labels, datasets, hasData: allDates.length > 0, activeConditionHasData };
}
function updateChart() {
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.datasets = datasets;
chartInstance.update('none');
@@ -85,11 +108,18 @@ function initPriceChart(canvas) {
}
if (!allHistory.length) {
console.warn('No price history data for this card');
setEmptyState(true);
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'), {
type: 'line',
@@ -151,64 +181,54 @@ function initPriceChart(canvas) {
});
}
function setupObserver() {
function initFromCanvas(canvas) {
activeCondition = "Near Mint";
activeRange = '1m';
const modal = document.getElementById('cardModal');
if (!modal) {
console.error('cardModal element not found');
return;
}
modal?.querySelectorAll('.price-range-btn').forEach(b => {
b.classList.toggle('active', b.dataset.range === '1m');
});
initPriceChart(canvas);
}
const observer = new MutationObserver(() => {
const canvas = document.getElementById('priceHistoryChart');
if (!canvas) return;
function setup() {
const modal = document.getElementById('cardModal');
if (!modal) return;
// Disconnect immediately so tab switches don't retrigger initPriceChart
observer.disconnect();
activeCondition = "Near Mint";
activeRange = '1m';
document.querySelectorAll('.price-range-btn').forEach(b => {
b.classList.toggle('active', b.dataset.range === '1m');
});
initPriceChart(canvas);
modal.addEventListener('card-modal:swapped', () => {
const canvas = modal.querySelector('#priceHistoryChart');
if (canvas) initFromCanvas(canvas);
});
observer.observe(modal, { childList: true, subtree: true });
modal.addEventListener('hidden.bs.modal', () => {
if (chartInstance) {
chartInstance.destroy();
chartInstance = null;
}
if (chartInstance) { chartInstance.destroy(); chartInstance = null; }
allHistory = [];
// Reconnect so the next card open is detected
observer.observe(modal, { childList: true, subtree: true });
});
document.addEventListener('shown.bs.tab', (e) => {
if (!modal.contains(e.target)) return;
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 || !modal.contains(btn)) return;
modal.querySelectorAll('.price-range-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
activeRange = btn.dataset.range ?? '1m';
updateChart();
});
}
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();
});
setupObserver();
setup();

View File

@@ -41,7 +41,6 @@ import BackToTop from "./BackToTop.astro"
</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">
<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"/>
@@ -58,7 +57,7 @@ import BackToTop from "./BackToTop.astro"
<script is:inline>
(function () {
// ── Global helpers (called from card-modal partial onclick) ───────────────
// ── Global helpers ────────────────────────────────────────────────────────
window.copyImage = async function(img) {
try {
const canvas = document.createElement("canvas");
@@ -67,7 +66,6 @@ import BackToTop from "./BackToTop.astro"
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
// Try modern clipboard API first (requires HTTPS + permissions)
if (navigator.clipboard && navigator.clipboard.write) {
const blob = await new Promise((resolve, reject) => {
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 })]);
showCopyToast('📋 Image copied!', '#198754');
} else {
// Fallback: copy the image URL to clipboard as text
const url = img.src;
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(url);
showCopyToast('📋 Image URL copied!', '#198754');
} else {
// Last resort: execCommand (deprecated but broadly supported)
const input = document.createElement('input');
input.value = url;
document.body.appendChild(input);
@@ -115,7 +111,7 @@ import BackToTop from "./BackToTop.astro"
}, 2000);
}
// ── State ────────────────────────────────────────────────────────────────
// ── State ────────────────────────────────────────────────────────────────
const cardIndex = [];
let currentCardId = null;
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) {
if (!cardId || isNavigating) return;
isNavigating = true;
@@ -187,16 +193,18 @@ import BackToTop from "./BackToTop.astro"
const url = `/partials/card-modal?cardId=${cardId}`;
const { idx, total } = getAdjacentIds();
if (idx >= total - 3) {
tryTriggerSentinel();
}
if (idx >= total - 3) tryTriggerSentinel();
const doSwap = async () => {
const response = await fetch(url);
const html = await response.text();
if (modal._reconnectChartObserver) modal._reconnectChartObserver();
modal.innerHTML = html;
if (typeof htmx !== 'undefined') htmx.process(modal);
updateNavButtons(modal);
initChartAfterSwap(modal);
};
if (document.startViewTransition && direction) {
@@ -210,9 +218,7 @@ import BackToTop from "./BackToTop.astro"
isNavigating = false;
const { idx: newIdx, total: newTotal } = getAdjacentIds();
if (newIdx >= newTotal - 3) {
tryTriggerSentinel();
}
if (newIdx >= newTotal - 3) tryTriggerSentinel();
}
function navigatePrev() {
@@ -255,7 +261,7 @@ import BackToTop from "./BackToTop.astro"
else navigatePrev();
}, { passive: true });
// ── Hook into HTMX card-modal opens ──────────────────────────────────────
// ── HTMX card-modal opens ─────────────────────────────────────────────────
document.body.addEventListener('htmx:beforeRequest', async (e) => {
if (e.detail.elt.getAttribute('hx-target') !== '#cardModal') return;
@@ -270,30 +276,29 @@ import BackToTop from "./BackToTop.astro"
const target = document.getElementById('cardModal');
const sourceImg = cardEl?.querySelector('img');
// ── Fetch first, THEN transition ──────────────────────────────────────
const response = await fetch(url, { headers: { 'HX-Request': 'true' } });
if (!response.ok) throw new Error(`Failed to load modal: ${response.status}`);
const html = await response.text();
// Use a unique name per transition to avoid duplicate view-transition-name conflicts
const transitionName = `card-hero-${currentCardId}`;
try {
if (sourceImg) {
sourceImg.style.viewTransitionName = transitionName;
sourceImg.style.opacity = '0'; // hide original immediately after capture
sourceImg.style.opacity = '0';
}
const transition = document.startViewTransition(async () => {
// Clear source name BEFORE setting it on the destination
if (sourceImg) sourceImg.style.viewTransitionName = '';
if (target._reconnectChartObserver) target._reconnectChartObserver();
target.innerHTML = html;
if (typeof htmx !== 'undefined') htmx.process(target);
const destImg = target.querySelector('img.card-image');
if (destImg) {
destImg.style.viewTransitionName = transitionName; // same unique name
destImg.style.viewTransitionName = transitionName;
if (!destImg.complete) {
await new Promise(resolve => {
destImg.addEventListener('load', resolve, { once: true });
@@ -305,6 +310,7 @@ import BackToTop from "./BackToTop.astro"
await transition.finished;
updateNavButtons(target);
initChartAfterSwap(target);
} catch (err) {
console.error('[card-modal] transition failed:', err);
@@ -312,17 +318,18 @@ import BackToTop from "./BackToTop.astro"
} finally {
if (sourceImg) {
sourceImg.style.viewTransitionName = '';
sourceImg.style.opacity = ''; // restore after transition
sourceImg.style.opacity = '';
}
const destImg = target.querySelector('img.card-image');
if (destImg) destImg.style.viewTransitionName = '';
}
});
// ── Show/hide nav buttons with Bootstrap modal events ────────────────────
// ── Bootstrap modal events ────────────────────────────────────────────────
const cardModal = document.getElementById('cardModal');
cardModal.addEventListener('shown.bs.modal', () => {
updateNavButtons(cardModal);
initChartAfterSwap(cardModal);
});
cardModal.addEventListener('hidden.bs.modal', () => {
currentCardId = null;

View File

@@ -4,6 +4,8 @@ import SetIcon from '../../components/SetIcon.astro';
import EnergyIcon from '../../components/EnergyIcon.astro';
import RarityIcon from '../../components/RarityIcon.astro';
import { db } from '../../db/index';
import { priceHistory, skus } from '../../db/schema';
import { eq, inArray } from 'drizzle-orm';
import FirstEditionIcon from "../../components/FirstEditionIcon.astro";
export const partial = true;
@@ -15,13 +17,7 @@ const cardId = Number(searchParams.get('cardId')) || 0;
const card = await db.query.cards.findFirst({
where: { cardId: Number(cardId) },
with: {
prices: {
with: {
history: {
orderBy: (ph, { asc }) => [asc(ph.calculatedAt)],
}
}
},
prices: true,
set: true,
}
});
@@ -53,51 +49,114 @@ const calculatedAt = (() => {
return new Date(Math.max(...dates.map(d => d.getTime())));
})();
// Flatten all price history across all skus into a single array for the chart,
// normalising calculatedAt to a YYYY-MM-DD string to avoid timezone/dedup issues
const priceHistoryForChart = (card?.prices ?? []).flatMap(sku =>
(sku.history ?? []).map(ph => ({
condition: sku.condition,
calculatedAt: ph.calculatedAt
? new Date(ph.calculatedAt).toISOString().split('T')[0]
: null,
marketPrice: ph.marketPrice,
}))
).filter(r => r.calculatedAt !== null);
// ── Fetch price history + compute volatility ──────────────────────────────
const cardSkus = card?.prices?.length
? await db.select().from(skus).where(eq(skus.cardId, cardId))
: [];
const skuIds = cardSkus.map(s => s.skuId);
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,
marketPrice: row.marketPrice,
})).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 conditionAttributes = (price: any) => {
const volatility = (() => {
const market = price?.marketPrice;
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 condition: string = price?.condition || "Near Mint";
const vol = volatilityByCondition[condition] ?? { label: '—', monthlyVol: 0 };
const volatilityClass = (() => {
switch (volatility) {
case "High": return "alert-danger";
case "Medium": return "alert-warning";
case "Low": return "alert-success";
default: return "alert-dark";
switch (vol.label) {
case "High": return "alert-danger";
case "Medium": return "alert-warning";
case "Low": return "alert-success";
default: return "alert-dark";
}
})();
const condition: string = price?.condition || "Near Mint";
const volatilityDisplay = vol.label === '—'
? '—'
: `${vol.label} (${(vol.monthlyVol * 100).toFixed(0)}%)`;
return {
"Near Mint": { label: "nav-nm", volatility, volatilityClass, class: "show active" },
"Lightly Played": { label: "nav-lp", volatility, volatilityClass },
"Moderately Played":{ label: "nav-mp", volatility, volatilityClass },
"Heavily Played": { label: "nav-hp", volatility, volatilityClass },
"Damaged": { label: "nav-dmg", volatility, volatilityClass }
"Near Mint": { label: "nav-nm", volatility: volatilityDisplay, volatilityClass, class: "show active" },
"Lightly Played": { label: "nav-lp", volatility: volatilityDisplay, volatilityClass },
"Moderately Played":{ label: "nav-mp", volatility: volatilityDisplay, volatilityClass },
"Heavily Played": { label: "nav-hp", volatility: volatilityDisplay, volatilityClass },
"Damaged": { label: "nav-dmg", volatility: volatilityDisplay, volatilityClass }
}[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">
<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">
<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>
</li>
<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">
<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>
</li>
<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">
<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>
</li>
<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">
<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>
</li>
<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">
<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>
</li>
<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">
<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>
</li>
</ul>
@@ -188,50 +247,87 @@ const altSearchUrl = (card: any) => {
const attributes = conditionAttributes(price);
return (
<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-row flex-wrap gap-1 mb-1">
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
<h6 class="mb-auto">Market Price</h6>
<p class="mb-0 mt-1">${price.marketPrice}</p>
</div>
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
<h6 class="mb-auto">Lowest Price</h6>
<p class="mb-0 mt-1">${price.lowestPrice}</p>
</div>
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-1">
<h6 class="mb-auto">Highest Price</h6>
<p class="mb-0 mt-1">${price.highestPrice}</p>
</div>
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-1 ${attributes?.volatilityClass}`}>
<h6 class="mb-auto">Volatility</h6>
<p class="mb-0 mt-1">{attributes?.volatility}</p>
<div class="d-flex flex-column gap-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>
<p class="mb-0 mt-1">${price.marketPrice}</p>
</div>
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
<h6 class="mb-auto">Lowest Price</h6>
<p class="mb-0 mt-1">${price.lowestPrice}</p>
</div>
<div class="alert alert-dark rounded p-2 flex-fill d-flex flex-column mb-0">
<h6 class="mb-auto">Highest Price</h6>
<p class="mb-0 mt-1">${price.highestPrice}</p>
</div>
<div class={`alert rounded p-2 flex-fill d-flex flex-column mb-0 ${attributes?.volatilityClass}`}>
<h6 class="mb-auto">Volatility</h6>
<p class="mb-0 mt-1">{attributes?.volatility}</p>
</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 class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0">
<div class="row g-2 mt-2"></div>
<div class="tab-pane fade" id="nav-vendor" role="tabpanel" aria-labelledby="nav-vendor" tabindex="0"></div>
</div>
<!-- Chart lives permanently outside tab-content so Bootstrap never hides it. -->
<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>
<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;">
<canvas
id="priceHistoryChart"
class="price-history-chart"
data-card-id={card?.cardId}
data-history={JSON.stringify(priceHistoryForChart)}>
</canvas>
</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">
{showRanges['1m'] && <button type="button" class="btn btn-dark price-range-btn active" data-range="1m">1M</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>
<!-- Chart lives outside tabs so it persists across condition switches -->
<div class="alert alert-dark rounded p-2 mt-2">
<h6>Market Price History</h6>
<div class="position-relative" style="height: 200px;">
<canvas
id="priceHistoryChart"
class="price-history-chart"
data-card-id={card?.cardId}
data-history={JSON.stringify(priceHistoryForChart)}>
</canvas>
</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">
<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>
</div>
</div>
</div>
<!-- External links column -->
@@ -247,182 +343,4 @@ const altSearchUrl = (card: any) => {
</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>
</div>

View File

@@ -8,7 +8,6 @@ export const prerender = false;
export const GET: APIRoute = async ({ url }) => {
const cardId = Number(url.searchParams.get('cardId')) || 0;
// Get all skus for this card
const cardSkus = await db
.select()
.from(skus)
@@ -20,8 +19,7 @@ export const GET: APIRoute = async ({ url }) => {
const skuIds = cardSkus.map(s => s.skuId);
// Fetch price history for all skus
const history = await db
const historyRows = await db
.select({
skuId: priceHistory.skuId,
calculatedAt: priceHistory.calculatedAt,
@@ -33,7 +31,41 @@ export const GET: APIRoute = async ({ url }) => {
.where(inArray(priceHistory.skuId, skuIds))
.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' }
});
};