UNPKG

humanize-time-tool

Version:

A simple and lightweight Node.js library for human-friendly time formatting and localization.

63 lines (51 loc) 1.98 kB
import { timeAgo, setupLanguages } from 'lang-time-formatter-tool'; /** * Initializes the time-ago UI inside a specified container selector. * @param {string} containerSelector CSS selector for container element (e.g. '.article') */ export function initTimeAgoUI(containerSelector) { const container = document.querySelector(containerSelector); if (!container) { console.error(`Container element not found for selector: '${containerSelector}'`); return; } const availableLanguages = [ 'sv', 'en', 'fr', 'de', 'es', 'it', 'pt', 'nl', 'pl', 'fi', 'no', 'da', 'ru', 'zh', 'ja', 'ko', 'ar', 'hi', 'he', 'tr', 'el', 'cs', 'vi', 'et', 'lv', 'lt', 'sk', 'hu', 'sr', 'hr', 'uk', 'be', 'bg', 'ro', 'th', 'sl', 'bs', 'fa', 'is' ]; const fallbackLang = 'sv'; const { getTranslations, defaultTranslations } = setupLanguages(availableLanguages, fallbackLang); // Create dropdown const dropdown = document.createElement('select'); dropdown.id = 'language-select'; availableLanguages.forEach(lang => { const option = document.createElement('option'); option.value = lang; option.textContent = lang.toUpperCase(); dropdown.appendChild(option); }); // Insert HTML structure container.innerHTML = ` <p id="time-text"></p> <label for="language-select">Select Language:</label> `; container.appendChild(dropdown); let currentLang = localStorage.getItem('selectedLang') || fallbackLang; dropdown.value = currentLang; const startTime = new Date(); function updateText() { const translations = getTranslations(currentLang) || defaultTranslations[fallbackLang]; const timeText = timeAgo(startTime, currentLang, translations); document.getElementById('time-text').textContent = timeText; localStorage.setItem('selectedLang', currentLang); } updateText(); setInterval(updateText, 10000); dropdown.addEventListener('change', e => { currentLang = e.target.value; updateText(); }); }