|
| 1 | +function getCalloutText(dateString, phrase) { |
| 2 | + if (!dateString) return phrase |
| 3 | + |
| 4 | + const date = new Date(dateString) |
| 5 | + const now = new Date() |
| 6 | + const tomorrow = new Date(now) |
| 7 | + tomorrow.setDate(now.getDate() + 1) |
| 8 | + |
| 9 | + if (isSameDay(date, now)) { |
| 10 | + return `${phrase} today` |
| 11 | + } |
| 12 | + |
| 13 | + if (isSameDay(date, tomorrow)) { |
| 14 | + return `${phrase} tomorrow` |
| 15 | + } |
| 16 | + |
| 17 | + if (date > now) { |
| 18 | + return `${phrase} ${getRelativeTimePhrase(date)}` |
| 19 | + } |
| 20 | + |
| 21 | + return phrase |
| 22 | +} |
| 23 | + |
| 24 | +function isSameDay(date1, date2) { |
| 25 | + return ( |
| 26 | + date1.getFullYear() === date2.getFullYear() && |
| 27 | + date1.getMonth() === date2.getMonth() && |
| 28 | + date1.getDate() === date2.getDate() |
| 29 | + ) |
| 30 | +} |
| 31 | + |
| 32 | +function getRelativeTimePhrase(date) { |
| 33 | + const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' }) |
| 34 | + const diffDays = Math.ceil((date - new Date()) / (1000 * 60 * 60 * 24)) |
| 35 | + |
| 36 | + if (Math.abs(diffDays) < 7) { |
| 37 | + return rtf.format(diffDays, 'day') |
| 38 | + } |
| 39 | + |
| 40 | + if (Math.abs(diffDays) < 30) { |
| 41 | + return rtf.format(Math.floor(diffDays / 7), 'week') |
| 42 | + } |
| 43 | + |
| 44 | + if (Math.abs(diffDays) < 365) { |
| 45 | + return rtf.format(Math.floor(diffDays / 30), 'month') |
| 46 | + } |
| 47 | + |
| 48 | + return rtf.format(Math.floor(diffDays / 365), 'year') |
| 49 | +} |
| 50 | + |
| 51 | +function updateCallouts() { |
| 52 | + document.querySelectorAll('[data-phrase]').forEach(element => { |
| 53 | + const { date, phrase } = element.dataset |
| 54 | + const calloutText = getCalloutText(date, phrase) |
| 55 | + |
| 56 | + if (calloutText !== phrase) { |
| 57 | + element.textContent = calloutText |
| 58 | + } else { |
| 59 | + element.remove() |
| 60 | + } |
| 61 | + }) |
| 62 | +} |
| 63 | + |
| 64 | +document.addEventListener('DOMContentLoaded', updateCallouts) |
0 commit comments