Files
web-at-transit-mock/ui/i18n.js
T
Bkk1234 750b4a2ea8 mock: three search tabs - stop code, place name, near me
- busStop.html: added the third tab (data-mode=near) and its own panel with
  the location button, hint and result area; removed the near button from the
  toolbar and deleted the old on-screen numpad markup
- busStop.search.js: MODE_NEAR in setMode, disables the other panels, hides
  the stop list while ranked results are shown, skips filtering in that mode,
  and removed the dead initNumpad code
- security gate: the tab is revealed only when isSecureContext and
  navigator.geolocation exist; otherwise it stays hidden and the mode is
  refused
- map.js: re-enable the button after a successful lookup
- i18n: stops.modeNear / nearCta / nearHint
- bump SW version to 2026.09.27.98

Verified on localhost:8090 - three tabs, near mode shows a map with 8 ranked
stops, button re-enables and works again, switching back restores the list;
with isSecureContext forced false the tab is hidden and unselectable.
2026-10-24 00:11:56 +07:00

149 lines
6.9 KiB
JavaScript

/* ============================================================
Atroute — ระบบหลายภาษา (i18n)
------------------------------------------------------------
คำแปลแยกเป็นไฟล์ต่อภาษา: ui/locales/<รหัสภาษา>.json (แบน: "key": "ข้อความ")
เพิ่มภาษาใหม่ = วางไฟล์ + เพิ่มรหัสใน SUPPORTED (ไม่ต้องแก้โค้ดอื่น)
วิธีใช้:
1. ข้อความใน HTML: <span data-i18n="nav.home">หน้าแรก</span>
(ข้อความในแท็ก = fallback ถ้าโหลดไฟล์ภาษาไม่สำเร็จ)
2. attribute: data-i18n-attr="placeholder:search.ph,aria-label:search.ph"
ใส่ html: data-i18n-attr="html:key" (ระวัง — เป็น innerHTML)
ตัวเลขในข้อความ: data-i18n-n="3" + คำแปลมี {n}
3. ใน JS: I18N.t('key') · I18N.t('key', { n: 3 })
4. ปุ่มสลับภาษา: <button data-i18n-switch="en">EN</button>
ลำดับการโหลด: รอ I18N.ready ก่อนวาดหน้าแรก (router ทำให้แล้ว)
ถ้าโหลดไม่สำเร็จ: คงข้อความ fallback ใน HTML ไว้ (ไม่เขียนทับด้วย key)
============================================================ */
(function () {
'use strict';
var LS_KEY = 'at_lang';
var SUPPORTED = ['th', 'en'];
var BASE = 'th'; /* ภาษาตั้งต้น — ใช้เมื่อคีย์ขาดในภาษาปัจจุบัน */
var DIR = './locales/';
var CACHE = {}; /* lang -> dict */
var current = detect();
var resolveReady;
var ready = new Promise(function (r) { resolveReady = r; });
/* ---------- ตรวจจับภาษาเริ่มต้น ---------- */
function detect() {
try {
var saved = localStorage.getItem(LS_KEY);
if (saved && SUPPORTED.indexOf(saved) !== -1) return saved;
} catch (e) { /* localStorage ไม่พร้อมใช้งาน */ }
var nav = (navigator.language || BASE).toLowerCase();
return nav.indexOf('en') === 0 ? 'en' : BASE;
}
/* ---------- โหลดไฟล์ภาษา (cache ต่อภาษา · ล้มเหลว = {} ไม่ให้พัง) ---------- */
function dict(lang) {
if (CACHE[lang]) return Promise.resolve(CACHE[lang]);
return fetch(DIR + lang + '.json', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : {}; })
.then(function (d) { CACHE[lang] = d || {}; return CACHE[lang]; })
.catch(function () { CACHE[lang] = {}; return CACHE[lang]; });
}
function loaded() { return !!(CACHE[current] || CACHE[BASE]); }
/* ---------- แปลข้อความ ---------- */
function t(key, vars) {
var cur = CACHE[current], bak = CACHE[BASE];
var val = (cur && cur[key] !== undefined) ? cur[key]
: (bak && bak[key] !== undefined) ? bak[key] : undefined;
if (val === undefined) return key;
if (vars) {
Object.keys(vars).forEach(function (k) {
val = val.split('{' + k + '}').join(vars[k]);
});
}
return val;
}
/* ---------- ใช้คำแปลกับ element ---------- */
function apply(root) {
if (!loaded()) return; /* ยังไม่มีคำแปล → คงข้อความ fallback ใน HTML */
var scope = root || document;
scope.querySelectorAll('[data-i18n]').forEach(function (el) {
var vars = null;
var n = el.getAttribute('data-i18n-n');
if (n !== null) vars = { n: n };
el.textContent = t(el.getAttribute('data-i18n'), vars);
});
scope.querySelectorAll('[data-i18n-attr]').forEach(function (el) {
var avars = null;
var an = el.getAttribute('data-i18n-n');
if (an !== null) avars = { n: an };
el.getAttribute('data-i18n-attr').split(',').forEach(function (pair) {
var parts = pair.split(':');
if (parts.length === 2) {
var attr = parts[0].trim();
var key = parts[1].trim();
if (attr === 'html') {
el.innerHTML = t(key, avars);
} else {
el.setAttribute(attr, t(key, avars));
}
}
});
});
document.documentElement.lang = current;
/* ไฮไลต์ปุ่มภาษาที่ active */
document.querySelectorAll('[data-i18n-switch]').forEach(function (btn) {
btn.classList.toggle('active', btn.getAttribute('data-i18n-switch') === current);
});
}
/* ---------- สลับภาษา (โหลดไฟล์ภาษาก่อน แล้วค่อยบอกให้หน้าวาดใหม่) ---------- */
function setLang(lang) {
if (SUPPORTED.indexOf(lang) === -1) lang = BASE;
if (lang === current) return Promise.resolve(current);
current = lang;
try { localStorage.setItem(LS_KEY, lang); } catch (e) {}
return dict(current).then(function () {
window.dispatchEvent(new CustomEvent('langchange', { detail: lang }));
return lang;
});
}
/* เลือกชื่อเฉพาะตามภาษา: ชื่อฟิลด์ฐาน เช่น 'province_name' → province_name_en / province_name_th
ไม่มีคำแปล = ถอยไปใช้ภาษาไทย (ชื่อเฉพาะไม่บังคับต้องแปล) */
function name(obj, base) {
if (!obj) return '';
var v = obj[base + '_' + current];
if (v != null && v !== '') return v;
var b = obj[base + '_' + BASE];
if (b != null && b !== '') return b;
return obj[base] != null ? obj[base] : '';
}
window.I18N = {
t: t,
name: name,
apply: apply,
setLang: setLang,
getLang: function () { return current; },
langs: SUPPORTED,
default: BASE, /* ภาษาที่ใช้เมื่อคีย์ขาด */
ready: ready, /* Promise — รอคำแปลโหลดเสร็จก่อนวาดหน้าแรก */
};
/* ปุ่มสลับภาษา [data-i18n-switch] — ฟังคลิกทั่วทั้งหน้า */
document.addEventListener('click', function (e) {
var btn = e.target.closest('[data-i18n-switch]');
if (btn) setLang(btn.getAttribute('data-i18n-switch'));
});
/* โหลดภาษาปัจจุบัน (+ ภาษาตั้งต้นสำหรับ fallback) แล้วจึงพร้อมใช้งาน */
Promise.all([dict(BASE), dict(current)]).then(function () {
apply();
resolveReady();
});
})();