'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)); const PUBLIC_CHART_RANGES = [6, 24, 168, 720, 2160, 8760]; 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}`}`; const PUBLIC_DEFAULT_LANGUAGE = String(document.documentElement.lang || '').trim(); const PUBLIC_RANGE_KEYS = ['history.6h', 'history.24h', 'history.7d', 'history.30d', 'history.90d', 'history.1y']; let publicLanguageManifest = null; const publicLanguagePacks = new Map(); let publicChartLanguage = PUBLIC_DEFAULT_LANGUAGE; let publicChartTranslations = {}; let publicChartLocale = PUBLIC_DEFAULT_LANGUAGE; function publicCookie(name) { const row = document.cookie.split('; ').find(item => item.startsWith(`${name}=`)); return row ? decodeURIComponent(row.split('=').slice(1).join('=')) : ''; } function publicTr(key, params = {}) { const template = publicChartTranslations[key] ?? key; return String(template).replace(/\{([a-zA-Z0-9_]+)\}/g, (_, name) => params[name] ?? `{${name}}`); } async function loadPublicLanguageManifest() { if (publicLanguageManifest) return publicLanguageManifest; const response = await fetch(withBase('/lang/index.json'), { headers: { Accept: 'application/json' }, cache: 'no-store' }); if (!response.ok) throw new Error(`language index HTTP ${response.status}`); publicLanguageManifest = await response.json(); return publicLanguageManifest; } async function setPublicChartLanguage(language) { const manifest = await loadPublicLanguageManifest(); const languages = Array.isArray(manifest.languages) ? manifest.languages : []; const fallbackCode = manifest.default || PUBLIC_DEFAULT_LANGUAGE; const item = languages.find(entry => entry.code === language) || languages.find(entry => entry.code === fallbackCode) || languages[0]; if (!item) throw new Error('language pack unavailable'); let pack = publicLanguagePacks.get(item.code); if (!pack) { const response = await fetch(withBase(item.path || `/lang/${encodeURIComponent(item.code)}.json`), { headers: { Accept: 'application/json' } }); if (!response.ok) throw new Error(`language ${item.code} HTTP ${response.status}`); pack = await response.json(); publicLanguagePacks.set(item.code, pack); } publicChartLanguage = item.code; publicChartTranslations = pack.translations || {}; publicChartLocale = pack.meta?.locale || item.locale || item.code; document.documentElement.lang = item.code; document.title = `GREE Controller · ${publicTr('publicChart.title')}`; setPublicRangeLanguage(); } function cssColor(name, fallback) { const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim(); return value || fallback; } 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(180, 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 || publicTr('publicChart.noData')); 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); } let publicChartPayload = null; let publicChartResizeFrame = 0; function publicChartToken() { return decodeURIComponent(location.pathname.split('/').filter(Boolean).pop() || ''); } function requestedPublicChartHours() { const value = Number(new URLSearchParams(location.search).get('hours')); return Number.isInteger(value) && value >= 1 && value <= 87600 ? value : null; } function setPublicRangeLanguage() { const label = $('#publicChartRangeLabel'); const select = $('#publicChartHours'); if (label) label.textContent = publicTr('history.range'); if (!select) return; [...select.options].forEach((option, index) => { const key = PUBLIC_RANGE_KEYS[index]; if (key) option.textContent = publicTr(key); }); select.setAttribute('aria-label', publicTr('publicChart.rangeAria')); } function syncPublicRangeControl(hours) { const select = $('#publicChartHours'); if (!select) return; const value = String(hours); if (![...select.options].some(option => option.value === value)) { const option = document.createElement('option'); option.value = value; option.textContent = publicTr('publicChart.hoursShort', { hours: value }); select.append(option); } select.value = value; } function publicChartApiPath(token, hours) { const value = Number(hours); const hasHours = hours !== null && hours !== undefined && Number.isInteger(value) && value >= 1 && value <= 87600; const query = hasHours ? `?hours=${encodeURIComponent(String(value))}` : ''; return `/api/public/charts/custom/${encodeURIComponent(token)}${query}`; } function redrawPublicChart() { if (!publicChartPayload) return; drawChart($('#publicCustomChart'), publicChartPayload, publicChartLocale); } async function loadPublicChart(hours = requestedPublicChartHours()) { const token = publicChartToken(); const title = $('#publicChartTitle'); const hint = $('#publicChartHint'); const error = $('#publicChartError'); const canvas = $('#publicCustomChart'); const range = $('#publicChartHours'); if (!token.startsWith('chart_')) { title.textContent = publicTr('publicChart.title'); hint.textContent = ''; error.hidden = false; error.textContent = publicTr('publicChart.invalidLink'); drawEmpty(canvas, error.textContent); return; } if (range) range.disabled = true; if (hint) hint.textContent = publicTr('publicChart.loading'); error.hidden = true; const response = await fetch(withBase(publicChartApiPath(token, hours)), { 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(); await setPublicChartLanguage(payload.lang || publicChartLanguage); title.textContent = payload.title || publicTr('publicChart.title'); hint.textContent = payload.hint || publicTr('publicChart.periodHint', { hours: payload.hours }); canvas.setAttribute('aria-label', title.textContent); syncPublicRangeControl(payload.hours); const localizedSeries = (payload.series || []).map(item => ({ ...item, label: item.label_key ? `${item.label} · ${publicTr(item.label_key)}` : item.label, })); publicChartPayload = { ...payload, series: localizedSeries, no_data_label: payload.no_data_label || publicTr('publicChart.noData') }; drawChart(canvas, publicChartPayload, publicChartLocale); if (range) range.disabled = false; } $('#publicChartHours')?.addEventListener('change', async event => { const hours = Number(event.currentTarget.value); if (!Number.isInteger(hours) || hours < 1 || hours > 87600) return; const url = new URL(location.href); url.searchParams.set('hours', String(hours)); history.replaceState(null, '', url); try { await loadPublicChart(hours); } catch (error) { const host = $('#publicChartError'); host.hidden = false; host.textContent = publicTr('publicChart.loadFailed', { error: error.message }); event.currentTarget.disabled = false; } }); window.addEventListener('resize', () => { cancelAnimationFrame(publicChartResizeFrame); publicChartResizeFrame = requestAnimationFrame(redrawPublicChart); }); async function initPublicChart() { try { await setPublicChartLanguage(publicCookie('gree_controller_language') || PUBLIC_DEFAULT_LANGUAGE); } catch (error) { console.error('Public chart language initialization failed:', error); } finally { document.documentElement.classList.remove('i18n-loading'); } try { await loadPublicChart(); } catch (error) { const host = $('#publicChartError'); host.hidden = false; host.textContent = publicChartTranslations['publicChart.loadFailed'] ? publicTr('publicChart.loadFailed', { error: error.message }) : error.message; $('#publicChartHint').textContent = ''; $('#publicChartHours').disabled = false; drawEmpty($('#publicCustomChart'), host.textContent); } } initPublicChart();