'use strict'; const PUBLIC_CHART_COLORS = ['--accent', '--info', '--warning', '--purple', '--danger', '--teal', '--orange', '--blue']; const $ = selector => document.querySelector(selector); const clamp = (value, min, max) => Math.min(max, Math.max(min, value)); function basePathFromScript() { const src = document.currentScript?.src || ''; try { const path = new URL(src, location.href).pathname; const slash = path.lastIndexOf('/'); return path.slice(0, slash).replace(/\/$/, ''); } catch (_) { return ''; } } const PUBLIC_BASE = basePathFromScript(); const withBase = path => `${PUBLIC_BASE}${path.startsWith('/') ? path : `/${path}`}`; function cssColor(name, fallback) { const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim(); return value || fallback; } function localeFor(lang) { return lang === 'pl' ? 'pl-PL' : 'en-GB'; } function timeLabel(timestamp, hours, locale) { const options = Number(hours) > 48 ? { day: '2-digit', month: '2-digit', hour: '2-digit' } : { hour: '2-digit', minute: '2-digit' }; return new Date(timestamp).toLocaleString(locale, options); } function preciseTime(timestamp, locale) { return new Intl.DateTimeFormat(locale, { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).format(new Date(timestamp)); } function prepareCanvas(canvas, height = 520) { const wrap = canvas.parentElement; const width = Math.max(720, Math.floor(wrap?.clientWidth || canvas.getBoundingClientRect().width || 720)); const actualHeight = Math.max(320, Math.floor(wrap?.clientHeight || height)); const dpr = window.devicePixelRatio || 1; canvas.width = Math.floor(width * dpr); canvas.height = Math.floor(actualHeight * dpr); canvas.style.width = `${width}px`; canvas.style.height = `${actualHeight}px`; const ctx = canvas.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, width, actualHeight); return { ctx, width, height: actualHeight }; } function renderLegend(series) { const host = $('#publicCustomChartLegend'); host.innerHTML = series.map((item, index) => { const color = cssColor(PUBLIC_CHART_COLORS[index % PUBLIC_CHART_COLORS.length], '#3ecf8e'); const dashed = item.dashed ? ' is-dashed' : ''; return `${escapeHtml(item.label)}`; }).join(''); } function escapeHtml(value) { return String(value ?? '').replace(/[&<>'"]/g, char => ({ '&': '&', '<': '<', '>': '>', "'": ''', '"': '"' }[char])); } function drawEmpty(canvas, message) { const { ctx, width, height } = prepareCanvas(canvas); ctx.fillStyle = cssColor('--muted', '#888'); ctx.font = '13px system-ui'; ctx.textAlign = 'center'; ctx.fillText(message, width / 2, height / 2); } function nearestPoint(points, targetTs) { if (!points.length) return null; let lo = 0, hi = points.length - 1; while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (points[mid].ts < targetTs) lo = mid + 1; else hi = mid; } const after = points[lo]; const before = lo > 0 ? points[lo - 1] : null; if (!before) return after; return Math.abs(before.ts - targetTs) <= Math.abs(after.ts - targetTs) ? before : after; } function bindTooltip(canvas, series, geometry, locale) { const wrap = canvas.parentElement; const tooltip = wrap.querySelector('.chart-tooltip'); const line = wrap.querySelector('.chart-hover-line'); const { pad, width, height, firstTs, lastTs } = geometry; const plotWidth = width - pad.left - pad.right; const timestamps = [...new Set(series.flatMap(item => item.points.map(point => new Date(point.timestamp).getTime())).filter(Number.isFinite))].sort((a, b) => a - b); const timestampPoints = timestamps.map(ts => ({ ts })); const seriesPoints = series.map((item, index) => ({ item, color: cssColor(PUBLIC_CHART_COLORS[index % PUBLIC_CHART_COLORS.length], '#3ecf8e'), points: item.points.map(point => ({ ts: new Date(point.timestamp).getTime(), value: Number(point.value) })) .filter(point => Number.isFinite(point.ts) && Number.isFinite(point.value)) .sort((a, b) => a.ts - b.ts) })); const hide = () => { tooltip.hidden = true; line.hidden = true; }; const showAt = clientX => { if (!timestamps.length) return hide(); const rect = canvas.getBoundingClientRect(); const localX = clamp(clientX - rect.left, pad.left, width - pad.right); const targetTs = firstTs + ((localX - pad.left) / Math.max(1, plotWidth)) * (lastTs - firstTs); const snapped = nearestPoint(timestampPoints, targetTs)?.ts; if (!Number.isFinite(snapped)) return hide(); const values = seriesPoints.map(entry => ({ ...entry, point: nearestPoint(entry.points, snapped) })).filter(entry => entry.point); if (!values.length) return hide(); const px = pad.left + (snapped - firstTs) / Math.max(1, lastTs - firstTs) * plotWidth; tooltip.innerHTML = `${escapeHtml(preciseTime(snapped, locale))}
${values.map(({ item, point, color }) => `
${escapeHtml(item.label)}${Number(point.value).toLocaleString(locale, { minimumFractionDigits: 1, maximumFractionDigits: 2 })} °C
`).join('')}
`; tooltip.hidden = false; line.hidden = false; line.style.left = `${px}px`; line.style.top = `${pad.top}px`; line.style.height = `${Math.max(0, height - pad.top - pad.bottom)}px`; const minLeft = wrap.scrollLeft + 8; const maxLeft = wrap.scrollLeft + wrap.clientWidth - tooltip.offsetWidth - 8; let tooltipLeft = px + 12; if (tooltipLeft + tooltip.offsetWidth > wrap.scrollLeft + wrap.clientWidth - 8) tooltipLeft = px - tooltip.offsetWidth - 12; tooltip.style.left = `${Math.max(minLeft, Math.min(tooltipLeft, Math.max(minLeft, maxLeft)))}px`; tooltip.style.top = `${pad.top + 8}px`; }; canvas.onpointermove = event => { if (event.pointerType !== 'touch') showAt(event.clientX); }; canvas.onpointerleave = event => { if (event.pointerType !== 'touch') hide(); }; } function drawChart(canvas, payload, locale) { const series = (payload.series || []).map((item, index) => ({ ...item, color: cssColor(PUBLIC_CHART_COLORS[index % PUBLIC_CHART_COLORS.length], '#3ecf8e'), points: Array.isArray(item.points) ? item.points : [] })); renderLegend(series); const allPoints = series.flatMap(item => item.points.map(point => ({ ...point, value: Number(point.value) }))) .filter(point => Number.isFinite(point.value) && Number.isFinite(new Date(point.timestamp).getTime())); if (!allPoints.length) return drawEmpty(canvas, payload.no_data_label || 'No data'); const { ctx, width, height } = prepareCanvas(canvas); const text = cssColor('--muted', '#888'); const grid = cssColor('--grid', '#333'); const compact = width < 520; const pad = compact ? { left: 43, right: 12, top: 16, bottom: 34 } : { left: 54, right: 20, top: 20, bottom: 42 }; const values = allPoints.map(point => point.value); let min = Math.floor(Math.min(...values) - 1); let max = Math.ceil(Math.max(...values) + 1); if (max - min < 2) { min -= 1; max += 1; } const firstTs = Math.min(...allPoints.map(point => new Date(point.timestamp).getTime())); const lastTs = Math.max(...allPoints.map(point => new Date(point.timestamp).getTime())); const span = Math.max(1, lastTs - firstTs); const x = ts => pad.left + (ts - firstTs) / span * (width - pad.left - pad.right); const y = value => pad.top + (max - value) / (max - min) * (height - pad.top - pad.bottom); ctx.font = '10px system-ui'; ctx.fillStyle = text; ctx.strokeStyle = grid; ctx.lineWidth = 1; for (let i = 0; i <= 5; i += 1) { const value = min + (max - min) * i / 5; const py = y(value); ctx.beginPath(); ctx.moveTo(pad.left, py); ctx.lineTo(width - pad.right, py); ctx.stroke(); ctx.textAlign = 'right'; ctx.fillText(`${value.toFixed(1)}°`, pad.left - 8, py + 3); } const ticks = width < 420 ? 2 : width < 620 ? 3 : 5; for (let i = 0; i <= ticks; i += 1) { const ts = firstTs + (span * i / ticks); const px = x(ts); ctx.textAlign = 'center'; ctx.fillText(timeLabel(ts, payload.hours, locale), px, height - 14); } series.forEach(item => { const points = item.points.map(point => ({ ts: new Date(point.timestamp).getTime(), value: Number(point.value) })) .filter(point => Number.isFinite(point.ts) && Number.isFinite(point.value)) .sort((a, b) => a.ts - b.ts); if (!points.length) return; ctx.beginPath(); ctx.strokeStyle = item.color; ctx.lineWidth = 2; ctx.setLineDash(item.dashed ? [6, 4] : []); points.forEach((point, index) => { const px = x(point.ts), py = y(point.value); if (index === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); }); ctx.stroke(); ctx.setLineDash([]); }); bindTooltip(canvas, series, { pad, width, height, firstTs, lastTs }, locale); } async function loadPublicChart() { const token = decodeURIComponent(location.pathname.split('/').filter(Boolean).pop() || ''); const title = $('#publicChartTitle'); const hint = $('#publicChartHint'); const error = $('#publicChartError'); const canvas = $('#publicCustomChart'); if (!token.startsWith('chart_')) { title.textContent = 'Custom chart'; hint.textContent = ''; error.hidden = false; error.textContent = 'Invalid chart link.'; drawEmpty(canvas, error.textContent); return; } const response = await fetch(withBase(`/api/public/charts/custom/${encodeURIComponent(token)}`), { headers: { Accept: 'application/json' }, cache: 'no-store' }); if (!response.ok) { let message = `${response.status}`; try { message = (await response.json()).error || message; } catch (_) { } throw new Error(message); } const payload = await response.json(); const lang = payload.lang === 'pl' ? 'pl' : 'en'; const locale = localeFor(lang); document.documentElement.lang = payload.lang || lang; title.textContent = payload.title || (lang === 'pl' ? 'Wykres niestandardowy' : 'Custom chart'); hint.textContent = payload.hint || ''; canvas.setAttribute('aria-label', title.textContent); drawChart(canvas, payload, locale); window.addEventListener('resize', () => drawChart(canvas, payload, locale)); } loadPublicChart().catch(error => { const host = $('#publicChartError'); host.hidden = false; host.textContent = `Unable to load chart: ${error.message}`; $('#publicChartHint').textContent = ''; drawEmpty($('#publicCustomChart'), host.textContent); });