const WORKER = 'https://hkb-chart.rafflespadongstephen.workers.dev/';
const AREA = false; // true = add a soft fill under the line
const RANGES = [['1D','Today'],['5D','Past 5 days'],['1M','Past month'],['6M','Past 6 months'],
['YTD','Year to date'],['1Y','Past year'],['5Y','Past 5 years'],['MAX','All time']];
const $ = id => document.getElementById(id);
const cache = {};
let chart, current = '1D';
const fmt = v => parseFloat(Number(v).toFixed(3)).toString();
const mins = s => {
const m = (s || '').match(/(\d{1,2}):(\d{2})(?::\d{2})?\s?([AP]M)/i);
if (!m) return null;
let h = (+m[1]) % 12; if (/P/i.test(m[3])) h += 12;
return h * 60 + (+m[2]);
};
const clock = v => {
const h = Math.floor(v / 60), m = v % 60;
return (h % 12 || 12) + ':' + String(m).padStart(2, '0') + ' ' + (h {
const b = document.createElement('button');
b.textContent = k; b.dataset.k = k;
b.style.cssText = 'border:0;border-radius:8px;padding:6px 14px;font-size:13px;font-weight:500;font-family:inherit;cursor:pointer;background:transparent;color:#5f6368';
b.onclick = () => load(k);
tabs.appendChild(b);
});
function markTabs() {
[...tabs.children].forEach(b => {
const on = b.dataset.k === current;
b.style.background = on ? '#d3e3fd' : 'transparent';
b.style.color = on ? '#0842a0' : '#5f6368';
});
}
async function load(w) {
current = w; markTabs();
try {
if (!cache[w]) cache[w] = await (await fetch(WORKER + '?window=' + w)).json();
if (current === w) draw(cache[w], w);
} catch (e) { $('gf-name').textContent = 'Data unavailable'; }
}
function draw({summary, graph, error}, w) {
if (!summary || !graph || !graph.length) {
$('gf-name').textContent = 'Data unavailable' + (error ? ': ' + error : '');
return;
}
const label = RANGES.find(r => r[0] === w)[1];
const pm = summary.price_movement || {};
const up = pm.movement !== 'Down';
const line = up ? '#137333' : '#c5221f';
const sign = up ? '+' : '−';
const price = summary.extracted_price ?? graph[graph.length - 1].price;
const sym = ({ MYR: 'RM', USD: '$' })[summary.currency] || (summary.currency || '');
const money = v => { const s = Number(v).toFixed(3); return sym + (s.endsWith('0') ? Number(v).toFixed(2) : s); };
const useTime = w === '1D' && graph.every(p => mins(p.date) !== null);
const prev = (useTime && pm.value != null) ? price + (up ? -pm.value : pm.value) : null;
$('gf-name').textContent = summary.title || 'HKB';
$('gf-price').textContent = money(price);
const chg = $('gf-chg'); chg.style.color = line;
chg.innerHTML = `
${up ? '↑' : '↓'}` +
`${sign}${(pm.percentage ?? 0).toFixed(2)}%` +
(pm.value != null ? ` (${sign}${pm.value.toFixed(4)})` : '') + ` ${label}`;
$('gf-sub').textContent = (summary.date || graph[graph.length - 1].date)
.replace(/(\w{3}) 0?(\d{1,2}) \d{4},/, '$1 $2,')
.replace(/UTC([+-])0?(\d{1,2}):00/, 'UTC$1$2') + (summary.currency ? ' · ' + summary.currency : '');
const pts = graph.map((p, i) => ({ x: useTime ? mins(p.date) : i, y: p.price, v: p.volume || 0, d: p.date }));
const ys = pts.map(p => p.y);
const all = prev != null ? ys.concat(prev) : ys;
const lo = Math.min(...all), hi = Math.max(...all);
const rng = (hi - lo) || Math.max(hi * 0.02, 0.01);
const yMin = lo - rng * 0.45, yMax = hi + rng * 0.15;
const maxV = Math.max(...pts.map(p => p.v), 1);
const my = new Date(Date.now() + 8 * 3600 * 1000);
const nm = my.getUTCHours() * 60 + my.getUTCMinutes();
const lunch = useTime && my.getUTCDay() >= 1 && my.getUTCDay() = 750 && nm {
if (!p.v) return;
const h = p.v / maxV * a.height * 0.16;
const px = x.getPixelForValue(p.x);
const before = i ? pts[i - 1].y : p.y;
ctx.fillStyle = p.y >= before ? 'rgba(19,115,51,.35)' : 'rgba(197,34,31,.35)';
ctx.fillRect(px - bw / 2, a.bottom - h, bw, h);
});
},
afterDatasetsDraw(c) {
const {ctx, chartArea: a, scales: {x, y}} = c;
ctx.save();
if (prev != null) {
const py = y.getPixelForValue(prev);
ctx.setLineDash([1, 3]); ctx.strokeStyle = '#80868b'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(a.left, py); ctx.lineTo(a.right, py); ctx.stroke();
ctx.setLineDash([]); ctx.fillStyle = '#5f6368'; ctx.font = '12px sans-serif'; ctx.textAlign = 'right';
ctx.fillText('Prev. close ' + money(prev), a.right, py - 6);
}
if (useTime) {
const l = pts[pts.length - 1];
const lx = x.getPixelForValue(l.x), ly = y.getPixelForValue(l.y);
ctx.setLineDash([3, 3]); ctx.strokeStyle = line; ctx.globalAlpha = 0.6; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(Math.min(a.right, lx + 40), ly); ctx.stroke();
ctx.globalAlpha = 1; ctx.setLineDash([]);
ctx.fillStyle = line; ctx.beginPath(); ctx.arc(lx, ly, 4, 0, 7); ctx.fill();
if (lunch) {
ctx.fillStyle = '#5f6368'; ctx.font = '12px sans-serif'; ctx.textAlign = 'center';
ctx.fillText('Lunch', lx, ly - 26); ctx.fillText('break', lx, ly - 12);
}
}
const t = c.tooltip;
if (t && t.opacity && t.dataPoints && t.dataPoints.length) {
const tx = t.dataPoints[0].element.x;
ctx.strokeStyle = '#5f6368'; ctx.lineWidth = 1;
ctx.beginPath(); ctx.moveTo(tx, a.top); ctx.lineTo(tx, a.bottom); ctx.stroke();
}
ctx.restore();
}
};
if (chart) chart.destroy();
chart = new Chart($('gf-c'), {
type: 'line',
plugins: [deco],
data: { datasets: [{
data: pts, borderColor: line, borderWidth: 2, tension: 0,
stepped: useTime ? 'before' : false,
pointRadius: 0, pointHoverRadius: 5, pointHoverBackgroundColor: line,
fill: AREA ? 'start' : false, backgroundColor: line + '22'
}]},
options: {
responsive: true, maintainAspectRatio: false, animation: false,
interaction: { mode: 'nearest', axis: 'x', intersect: false },
plugins: {
legend: { display: false },
tooltip: {
displayColors: false, backgroundColor: '#fff', borderColor: '#dadce0', borderWidth: 1,
titleColor: '#5f6368', bodyColor: '#202124', bodyFont: { size: 14, weight: '500' },
callbacks: { title: i => i[0].raw.d, label: i => money(i.parsed.y) }
}
},
scales: {
x: {
type: 'linear',
min: useTime ? 540 : undefined, max: useTime ? 1020 : undefined,
grid: { color: '#e3e6e9', drawTicks: false }, border: { display: false },
afterBuildTicks: useTime ? (ax => { ax.ticks = [600, 720, 840, 960].map(value => ({ value })); }) : undefined,
ticks: {
color: '#5f6368', maxRotation: 0, maxTicksLimit: 6,
callback: v => useTime ? clock(v) : (pts[Math.round(v)] ? String(pts[Math.round(v)].d).split(',')[0] : '')
}
},
y: {
position: 'left', min: yMin, max: yMax,
grid: { display: false }, border: { display: false },
ticks: { color: '#5f6368', callback: v => v < lo - 1e-9 ? '' : fmt(v) }
}
}
}
});
}
markTabs();
load('1D');