refactor: reduce duplication via helpers

This commit is contained in:
Kiyomichi Kosaka 2025-06-20 16:05:51 +02:00
parent da56bfce7a
commit 8f570ca4d3

307
script.js
View File

@ -44,41 +44,46 @@ let updateInterval;
let lastRenderedEonstrip = null; let lastRenderedEonstrip = null;
let currentDetailCob = null; let currentDetailCob = null;
function hexToRgba(hex, alpha) { // ── Utility color helpers ────────────────────────────────────────────────
if (!hex) return ''; function parseColor(hex) {
if (!hex) return [255, 255, 255];
let c = hex.replace('#', ''); let c = hex.replace('#', '');
if (c.length === 3) { if (c.length === 3) c = c.split('').map(x => x + x).join('');
c = c.split('').map(x => x + x).join(''); const num = parseInt(c, 16);
} return [(num >> 16) & 255, (num >> 8) & 255, num & 255];
const r = parseInt(c.substring(0,2),16);
const g = parseInt(c.substring(2,4),16);
const b = parseInt(c.substring(4,6),16);
return `rgba(${r},${g},${b},${alpha})`;
} }
function getContrastColor(hex) { const toHex = v => v.toString(16).padStart(2, '0');
if (!hex) return '#fff';
let c = hex.replace('#',''); const hexToRgba = (hex, a = 1) => {
if (c.length === 3) c = c.split('').map(x=>x+x).join(''); const [r, g, b] = parseColor(hex);
const r = parseInt(c.substr(0,2),16); return `rgba(${r},${g},${b},${a})`;
const g = parseInt(c.substr(2,2),16); };
const b = parseInt(c.substr(4,2),16);
const yiq = (r*299 + g*587 + b*114) / 1000; const getContrastColor = hex => {
const [r, g, b] = parseColor(hex);
const yiq = (r * 299 + g * 587 + b * 114) / 1000;
return yiq >= 128 ? '#000' : '#fff'; return yiq >= 128 ? '#000' : '#fff';
} };
function lightenColor(hex, percent) { const lightenColor = (hex, p) => {
if (!hex) return '#fff'; const [r, g, b] = parseColor(hex).map(v =>
let c = hex.replace('#',''); Math.min(255, Math.round(v + (255 - v) * p))
if (c.length === 3) c = c.split('').map(x=>x+x).join(''); );
let r = parseInt(c.substr(0,2),16); return '#' + [r, g, b].map(toHex).join('');
let g = parseInt(c.substr(2,2),16); };
let b = parseInt(c.substr(4,2),16);
r = Math.min(255, Math.round(r + (255 - r) * percent)); const dateOptions = (long = true) => ({
g = Math.min(255, Math.round(g + (255 - g) * percent)); timeZone: currentTimezone === 'TAI' ? 'UTC' : currentTimezone,
b = Math.min(255, Math.round(b + (255 - b) * percent)); weekday: 'long',
return '#' + [r,g,b].map(x=>x.toString(16).padStart(2,'0')).join(''); year: 'numeric',
} month: long ? 'long' : 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
function applyEventColors(elem, color, alpha) { function applyEventColors(elem, color, alpha) {
if (!color || !elem) return; if (!color || !elem) return;
@ -188,7 +193,46 @@ function getHumanDiff(d1, d2) {
let minutes = Math.floor(diffMs / 60e3); diffMs -= minutes * 60e3; let minutes = Math.floor(diffMs / 60e3); diffMs -= minutes * 60e3;
let seconds = Math.floor(diffMs / 1e3); let seconds = Math.floor(diffMs / 1e3);
return { years, months, days, hours, minutes, seconds }; return { years, months, days, hours, minutes, seconds };
}
// ── Event utilities ──────────────────────────────────────────────────────
const normalizeEvent = ev => {
const baseStart = parseCobiets(ev.start || ev.cobie);
if (baseStart === null) return null;
const tzShift = ev.shiftWithTimezone ?
getTimezoneOffsetSeconds(fromCobiets(baseStart)) : 0;
const startCob = baseStart - tzShift;
const endCob = ev.end ? parseCobiets(ev.end) - tzShift : Number.POSITIVE_INFINITY;
const unitVal = COBIE_UNITS[ev.unit] || COBIE_UNITS.cosmocycle;
const interval = (ev.interval || 1) * unitVal;
let duration = 0;
if (typeof ev.duration === 'string') {
const d = parseCobiets(ev.duration);
if (d !== null) duration = d;
} else if (typeof ev.duration === 'number') {
duration = ev.duration;
}
return { startCob, endCob, interval, duration };
};
function collectEventOccurrences(start, end, predicate = () => true) {
const out = [];
if (!Array.isArray(window.SPECIAL_EVENTS)) return out;
window.SPECIAL_EVENTS.forEach(ev => {
if (!predicate(ev)) return;
const meta = normalizeEvent(ev);
if (!meta || start > meta.endCob) return;
let n = Math.floor((start - meta.startCob) / meta.interval);
if (n < 0) n = 0;
let occ = meta.startCob + n * meta.interval;
if (occ + meta.duration <= start) occ += meta.interval;
while (occ < end && occ <= meta.endCob) {
out.push({ event: ev, meta, occ });
occ += meta.interval;
}
});
return out;
} }
// getTAIOffsetAt, toCobiets, fromCobiets, breakdownNonNeg and // getTAIOffsetAt, toCobiets, fromCobiets, breakdownNonNeg and
@ -206,17 +250,7 @@ function updateCurrentTime() {
const cobieElem = document.getElementById('cobieTime'); const cobieElem = document.getElementById('cobieTime');
if (cobieElem) cobieElem.textContent = formatCobieTimestamp(cobiets); if (cobieElem) cobieElem.textContent = formatCobieTimestamp(cobiets);
const options = { const options = dateOptions();
timeZone: currentTimezone === 'TAI' ? 'UTC' : currentTimezone,
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
const taiOffset = getTAIOffsetAt(baseDate); const taiOffset = getTAIOffsetAt(baseDate);
let displayDate = baseDate; let displayDate = baseDate;
@ -226,9 +260,9 @@ function updateCurrentTime() {
document.getElementById('regularTime').textContent = currentTimezone + ': ' + displayDate.toLocaleString('en-US', options); document.getElementById('regularTime').textContent = currentTimezone + ': ' + displayDate.toLocaleString('en-US', options);
options.timeZone = 'UTC'; const optionsUTC = { ...options, timeZone: 'UTC' };
const taiDate = new Date(baseDate.getTime() + taiOffset * 1000); const taiDate = new Date(baseDate.getTime() + taiOffset * 1000);
document.getElementById('taiTime').textContent = 'TAI UTC: ' + taiDate.toLocaleString('en-US', options) + ' (UTC + ' + taiOffset + 's)'; document.getElementById('taiTime').textContent = 'TAI UTC: ' + taiDate.toLocaleString('en-US', optionsUTC) + ' (UTC + ' + taiOffset + 's)';
const bd = breakdownNonNeg(Math.abs(cobiets)); const bd = breakdownNonNeg(Math.abs(cobiets));
@ -265,17 +299,7 @@ function updateTimeBreakdown(cobiets) {
const eosEnd = eosStart + COBIE_UNITS.eonstrip - 1; const eosEnd = eosStart + COBIE_UNITS.eonstrip - 1;
// 4) Intl formatting options // 4) Intl formatting options
const dateOptions = { const optsLong = dateOptions();
timeZone: currentTimezone === 'TAI' ? 'UTC' : currentTimezone,
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
// //
// ── Build the “core” units (always visible): Galactic Year → Second ────────────── // ── Build the “core” units (always visible): Galactic Year → Second ──────────────
@ -292,8 +316,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(gyrStart); const rawStart = fromCobiets(gyrStart);
const rawEnd = fromCobiets(gyrEnd); const rawEnd = fromCobiets(gyrEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, gyrStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, gyrStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, gyrEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, gyrEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -309,8 +333,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(ccyStart); const rawStart = fromCobiets(ccyStart);
const rawEnd = fromCobiets(ccyEnd); const rawEnd = fromCobiets(ccyEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, ccyStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, ccyStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, ccyEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, ccyEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -326,8 +350,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(mqsStart); const rawStart = fromCobiets(mqsStart);
const rawEnd = fromCobiets(mqsEnd); const rawEnd = fromCobiets(mqsEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, mqsStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, mqsStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, mqsEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, mqsEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -343,8 +367,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(eosStart); const rawStart = fromCobiets(eosStart);
const rawEnd = fromCobiets(eosEnd); const rawEnd = fromCobiets(eosEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, eosStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, eosStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, eosEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, eosEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -393,8 +417,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(startAmt); const rawStart = fromCobiets(startAmt);
const rawEnd = fromCobiets(endAmt); const rawEnd = fromCobiets(endAmt);
return ` return `
<span>Started: ${formatSafeDate(rawStart, startAmt, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, startAmt, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, endAmt, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, endAmt, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -412,8 +436,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(startAmt); const rawStart = fromCobiets(startAmt);
const rawEnd = fromCobiets(endAmt); const rawEnd = fromCobiets(endAmt);
return ` return `
<span>Started: ${formatSafeDate(rawStart, startAmt, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, startAmt, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, endAmt, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, endAmt, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -431,8 +455,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(startAmt); const rawStart = fromCobiets(startAmt);
const rawEnd = fromCobiets(endAmt); const rawEnd = fromCobiets(endAmt);
return ` return `
<span>Started: ${formatSafeDate(rawStart, startAmt, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, startAmt, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, endAmt, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, endAmt, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -450,8 +474,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(startAmt); const rawStart = fromCobiets(startAmt);
const rawEnd = fromCobiets(endAmt); const rawEnd = fromCobiets(endAmt);
return ` return `
<span>Started: ${formatSafeDate(rawStart, startAmt, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, startAmt, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, endAmt, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, endAmt, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -469,8 +493,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(startAmt); const rawStart = fromCobiets(startAmt);
const rawEnd = fromCobiets(endAmt); const rawEnd = fromCobiets(endAmt);
return ` return `
<span>Started: ${formatSafeDate(rawStart, startAmt, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, startAmt, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, endAmt, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, endAmt, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -486,8 +510,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(eocStart); const rawStart = fromCobiets(eocStart);
const rawEnd = fromCobiets(eocEnd); const rawEnd = fromCobiets(eocEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, eocStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, eocStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, eocEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, eocEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -503,8 +527,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(cerStart); const rawStart = fromCobiets(cerStart);
const rawEnd = fromCobiets(cerEnd); const rawEnd = fromCobiets(cerEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, cerStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, cerStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, cerEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, cerEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -520,8 +544,8 @@ function updateTimeBreakdown(cobiets) {
const rawStart = fromCobiets(ueoStart); const rawStart = fromCobiets(ueoStart);
const rawEnd = fromCobiets(ueoEnd); const rawEnd = fromCobiets(ueoEnd);
return ` return `
<span>Started: ${formatSafeDate(rawStart, ueoStart, dateOptions)}</span><br> <span>Started: ${formatSafeDate(rawStart, ueoStart, optsLong)}</span><br>
<span>Ends: ${formatSafeDate(rawEnd, ueoEnd, dateOptions)}</span> <span>Ends: ${formatSafeDate(rawEnd, ueoEnd, optsLong)}</span>
`; `;
})()} })()}
</div> </div>
@ -638,12 +662,7 @@ function updateCalendar() {
grid.innerHTML = ''; grid.innerHTML = '';
// reuse the same dateOpts you use elsewhere: // reuse the same dateOpts you use elsewhere:
const dateOpts = { const dateOpts = dateOptions(false);
timeZone: currentTimezone==='TAI' ? 'UTC' : currentTimezone,
year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
};
for (let i = 0; i < 16; i++) { for (let i = 0; i < 16; i++) {
const cellCob = baseCob + i * COBIE_UNITS.eonstrip; const cellCob = baseCob + i * COBIE_UNITS.eonstrip;
@ -664,43 +683,16 @@ function updateCalendar() {
${startDate.toLocaleDateString('en-US', dateOpts)} ${startDate.toLocaleDateString('en-US', dateOpts)}
</div>`; </div>`;
if (Array.isArray(window.SPECIAL_EVENTS)) { collectEventOccurrences(
const cellStart = cellCob; cellCob,
const cellEnd = cellCob + COBIE_UNITS.eonstrip; cellCob + COBIE_UNITS.eonstrip,
window.SPECIAL_EVENTS.forEach(ev => { ev => ev.showMega !== false
if (ev.showMega === false) return; ).forEach(({ event }) => {
const baseStart = parseCobiets(ev.start || ev.cobie); const tag = document.createElement('div');
if (baseStart === null) return; tag.className = 'event-tag';
const tzShift = ev.shiftWithTimezone ? getTimezoneOffsetSeconds(fromCobiets(baseStart)) : 0; tag.textContent = event.label;
const startCob = baseStart - tzShift; card.appendChild(tag);
const endCob = ev.end ? parseCobiets(ev.end) - tzShift : Number.POSITIVE_INFINITY; });
const unitVal = COBIE_UNITS[ev.unit] || COBIE_UNITS.cosmocycle;
const interval = (ev.interval || 1) * unitVal;
let duration = 0;
if (typeof ev.duration === 'string') {
const d = parseCobiets(ev.duration);
if (d !== null) duration = d;
} else if (typeof ev.duration === 'number') {
duration = ev.duration;
}
if (cellStart > endCob) return;
let n = Math.floor((cellStart - startCob) / interval);
if (n < 0) n = 0;
let occ = startCob + n * interval;
if (occ + duration <= cellStart) {
occ += interval;
}
if (occ < cellEnd && occ + duration > cellStart && occ <= endCob) {
const tag = document.createElement('div');
tag.className = 'event-tag';
tag.textContent = ev.label;
card.appendChild(tag);
}
});
}
const tooltip = document.createElement('div'); const tooltip = document.createElement('div');
tooltip.className = 'tooltip'; tooltip.className = 'tooltip';
tooltip.innerHTML = showEonstripDetails(i, cellCob, dateOpts); tooltip.innerHTML = showEonstripDetails(i, cellCob, dateOpts);
@ -719,17 +711,7 @@ function showEonstripDetails(index, startCobiets, opts) {
const startDate = fromCobiets(startCobiets); const startDate = fromCobiets(startCobiets);
const endDate = fromCobiets(startCobiets + COBIE_UNITS.eonstrip - 1); const endDate = fromCobiets(startCobiets + COBIE_UNITS.eonstrip - 1);
const options = opts || { const options = opts || dateOptions();
timeZone: currentTimezone === 'TAI' ? 'UTC' : currentTimezone,
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
return ` return `
<strong>${EONSTRIP_NAMES[index]} (0x${index.toString(16).toUpperCase()})</strong><br> <strong>${EONSTRIP_NAMES[index]} (0x${index.toString(16).toUpperCase()})</strong><br>
@ -773,49 +755,19 @@ function showEonstripDetail(index, startCob) {
updateDetailCurrentTime(); updateDetailCurrentTime();
if (Array.isArray(window.SPECIAL_EVENTS)) { if (Array.isArray(window.SPECIAL_EVENTS)) {
const events = [];
const start = startCob; const start = startCob;
const end = startCob + COBIE_UNITS.eonstrip; const end = startCob + COBIE_UNITS.eonstrip;
window.SPECIAL_EVENTS.forEach(ev => { const events = collectEventOccurrences(start, end, ev => ev.showDetail !== false)
if (ev.showDetail === false) return; .map(({ event, meta, occ }) => ({
const baseStart = parseCobiets(ev.start || ev.cobie); label: event.label,
if (baseStart === null) return; color: event.color,
const tzShift = ev.shiftWithTimezone ? getTimezoneOffsetSeconds(fromCobiets(baseStart)) : 0; start: (occ - start) / COBIE_UNITS.eonstrip,
const startCobEv = baseStart - tzShift; end: (occ + meta.duration - start) / COBIE_UNITS.eonstrip,
const endCobEv = ev.end ? parseCobiets(ev.end) - tzShift : Number.POSITIVE_INFINITY; cobStart: occ,
const unitVal = COBIE_UNITS[ev.unit] || COBIE_UNITS.cosmocycle; cobEnd: occ + meta.duration,
const interval = (ev.interval || 1) * unitVal; seriesStart: meta.startCob,
let duration = 0; seriesEnd: meta.endCob
if (typeof ev.duration === 'string') { }));
const d = parseCobiets(ev.duration);
if (d !== null) duration = d;
} else if (typeof ev.duration === 'number') {
duration = ev.duration;
}
if (start > endCobEv) return;
let n = Math.floor((start - startCobEv) / interval);
if (n < 0) n = 0;
let occ = startCobEv + n * interval;
if (occ + duration <= start) occ += interval;
while (occ < end && occ <= endCobEv) {
const relStart = (occ - start) / COBIE_UNITS.eonstrip;
const relEnd = (occ + duration - start) / COBIE_UNITS.eonstrip;
events.push({
label: ev.label,
color: ev.color,
start: relStart,
end: relEnd,
cobStart: occ,
cobEnd: occ + duration,
seriesStart: startCobEv,
seriesEnd: endCobEv
});
occ += interval;
}
});
events.sort((a,b)=>a.start-b.start); events.sort((a,b)=>a.start-b.start);
const groups = []; const groups = [];
@ -877,12 +829,7 @@ function showEonstripDetail(index, startCob) {
const tooltip = document.createElement('div'); const tooltip = document.createElement('div');
tooltip.className = 'tooltip'; tooltip.className = 'tooltip';
const optsShort = { const optsShort = dateOptions(false);
timeZone: currentTimezone === 'TAI' ? 'UTC' : currentTimezone,
year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit',
hour12: false
};
const startStr = formatCobieTimestamp(ev.cobStart); const startStr = formatCobieTimestamp(ev.cobStart);
const endStr = formatCobieTimestamp(ev.cobEnd); const endStr = formatCobieTimestamp(ev.cobEnd);