Files
web-at-transit-mock/ui/partials/busDetail.init.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

377 lines
19 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ============================================================
busDetail.init.js — เติมข้อมูลหน้า #/routes/<รหัสสาย> จาก JSON
------------------------------------------------------------
ชื่อสาย/ตัวเลือก/เบอร์โทร resource/data/routes.json
รูปรถ/คำอธิบาย/QR resource/data/captions/caption<รหัส>.json
รอบต่อวัน/รอบถัดไป resource/data/schedules.json
แผนที่ resource/data/geojson-web/<รหัส>.geojson (ATMap)
รูปรถ: .image/routes/<รหัส>/ ตั้งชื่อไฟล์ขึ้นต้นด้วย car หรือ boat
QR: .image/qrcode/<รหัส>.png
============================================================ */
(function () {
'use strict';
var DATA = '../resource/data/';
var IMG_ROUTES = '../.image/routes/';
var IMG_QR = '../.image/qrcode/';
var CAR_NAMES = ['car', 'boat']; /* ลำดับชื่อไฟล์รูปรถที่ยอมรับ */
var CAR_EXTS = ['jpeg', 'jpg', 'webp', 'png'];
var QR_EXTS = ['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG', 'webp'];
var FALLBACK_ID = '101'; /* เข้า #/routes ตรง ๆ ไม่มีรหัสสาย */
function $(id) { return document.getElementById(id); }
function t(k, v) { return window.I18N ? I18N.t(k, v) : k; }
function nm(o, base) { return (window.I18N && I18N.name) ? I18N.name(o, base) : ((o && o[base + '_th']) || ''); }
function esc(s) {
return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function fetchJSON(u) {
return fetch(u, { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; });
}
function setText(id, s) {
var el = $(id);
if (!el) return;
var v = (s == null ? '' : String(s)).trim();
el.textContent = v;
el.hidden = !v;
}
/* ตัวเลขสรุป: ไม่มีข้อมูลให้แสดง – เพื่อให้การ์ดทั้ง 4 ช่องเท่ากัน */
function setStat(id, s) {
var el = $(id);
if (!el) return;
var v = (s == null ? '' : String(s)).trim();
el.textContent = v || '–';
el.hidden = false;
}
function uniq(a) { return a.filter(function (u, i) { return u && a.indexOf(u) === i; }); }
/* ลองโหลดรูปตามลำดับ — พลาดก็ลองตัวถัดไป ไม่มีเลยก็ซ่อน (ไม่ทิ้งไอคอนรูปแตก) */
function tryImage(img, urls, alt, onDone) {
var i = 0;
img.alt = alt || '';
img.loading = 'eager'; /* ห้าม lazy: รูปที่ซ่อนอยู่จะไม่ถูกโหลด แล้ว onload ไม่ยิง */
img.onload = function () { img.hidden = false; if (onDone) onDone(true); };
img.onerror = function () {
if (i >= urls.length) { img.hidden = true; if (onDone) onDone(false); return; }
img.src = urls[i++];
};
img.onerror();
}
/* เติม ?v=<เวอร์ชันแอป> ให้ URL รูป — bump VERSION ใน sw.js = รูปโหลดใหม่ทั้งหมด
(browser/SW แคชรูปไว้แบบ cache-first จึงต้องเปลี่ยน URL เพื่อบังคับดึงใหม่) */
function bust(u) { return (window.ImgURL && ImgURL.of) ? ImgURL.of(u) : u; }
function vehicleUrls(rid, cap) {
var base = IMG_ROUTES + encodeURIComponent(rid) + '/', out = [];
if (cap && cap.vehicle_image) out.push(bust(base + cap.vehicle_image));
CAR_NAMES.forEach(function (n) { CAR_EXTS.forEach(function (e) { out.push(bust(base + n + '.' + e)); }); });
return uniq(out);
}
function qrUrls(rid, cap) {
var out = [];
if (cap && cap.qr_image) out.push(bust(IMG_QR + cap.qr_image));
QR_EXTS.forEach(function (e) { out.push(bust(IMG_QR + encodeURIComponent(rid) + '.' + e)); });
return uniq(out);
}
/* จัดรูปแบบเบอร์ให้อ่านง่าย — รองรับทั้งมือถือ (+66xx xxx xxxx) และเบอร์บ้าน (0-xxxx-xxxx) */
function fmtPhone(p) {
var raw = String(p == null ? '' : p).trim();
var digits = raw.replace(/[^\d+]/g, '');
if (!digits) return '';
var intl = /^\+?66/.test(digits);
var nat = intl ? digits.replace(/^\+?66/, '') : digits;
if (nat.charAt(0) === '0') return nat.slice(0, 1) + ' ' + nat.slice(1, 5) + ' ' + nat.slice(5);
if (nat.length === 9) return '+66 ' + nat.slice(0, 2) + ' ' + nat.slice(2, 5) + ' ' + nat.slice(5);
if (nat.length === 8) return '+66 ' + nat.slice(0, 2) + ' ' + nat.slice(2);
return raw;
}
function telHref(p) { return 'tel:' + String(p == null ? '' : p).replace(/[^\d+]/g, ''); }
/* ---------- ลิงก์ติดต่อ (web_url ใน routes.json) — ไอคอน/ชื่อ/สี เปลี่ยนตามชนิด URL ----------
facebook → ไอคอน facebook + โทนฟ้า · line (line.me / lin.ee / linevoom) → LINE + โทนเขียว
อื่น ๆ (www) → ไอคอนลูกโลก + โทนม่วง */
var LINK_KINDS = [
{ key: 'facebook', icon: 'ic-facebook', tone: 'tone-sky', match: /facebook\.com|fb\.(me|com)/i },
{ key: 'line', icon: 'ic-message-circle', tone: 'tone-green', match: /line\.me|lin\.ee|linevoom|line\.at/i },
{ key: 'www', icon: 'ic-globe', tone: 'tone-purple', match: /^https?:/i }
];
/* routes.json เก็บ web_url ได้ 2 แบบ:
["facebook", "https://..."] ← อาร์เรย์ [ชนิดลิงก์, URL] (แบบใหม่ — ใช้ชนิดที่ระบุไว้เลย)
"https://..." ← สตริงเดี่ยว (แบบเก่า — เดาชนิดจาก URL)
คืน { kind, url } · ไม่มีข้อมูล = null */
function parseWebUrl(raw) {
var kindKey = null, url = '';
if (Array.isArray(raw)) {
raw.forEach(function (x) {
var v = String(x == null ? '' : x).trim();
if (!v) return;
if (/^https?:\/\//i.test(v)) url = v;
else if (LINK_KINDS.some(function (k) { return k.key === v.toLowerCase(); })) kindKey = v.toLowerCase();
else if (!url) url = v; /* ค่าแปลก ๆ → กันข้อมูลหาย */
});
} else {
url = String(raw == null ? '' : raw).trim();
}
if (!url && !kindKey) return null;
return { kind: kindKey ? byKind(kindKey) : linkKind(url), url: url };
}
function byKind(key) {
for (var i = 0; i < LINK_KINDS.length; i++) { if (LINK_KINDS[i].key === key) return LINK_KINDS[i]; }
return { key: 'www', icon: 'ic-globe', tone: 'tone-purple' };
}
function linkKind(url) {
var u = String(url || '').trim();
if (!u) return null;
for (var i = 0; i < LINK_KINDS.length; i++) { if (LINK_KINDS[i].match.test(u)) return LINK_KINDS[i]; }
return { key: 'www', icon: 'ic-globe', tone: 'tone-purple' };
}
function prettyUrl(url) {
return String(url || '').trim().replace(/^https?:\/\//i, '').replace(/\/+$/, '');
}
/* ---------- การ์ดติดต่อ (LINE + QR + ลิงก์ + เบอร์โทรจาก routes.json) ---------- */
function buildContact(rid, route, cap) {
var host = $('route-contact');
if (!host) return;
host.innerHTML = '';
var web = parseWebUrl(route.web_url); /* รองรับ ["kind","url"] และสตริงเดี่ยว */
var kind = web ? web.kind : null;
var webUrl = web ? web.url : '';
var line = document.createElement('div');
line.className = 'mu-contact-item';
line.innerHTML =
'<span class="ic-wrap ' + (kind ? kind.tone : 'tone-green') + '"><svg class="ic" aria-hidden="true">' +
'<use href="#' + (kind ? kind.icon : 'ic-message-circle') + '"/></svg></span>' +
'<div class="txt"><strong>' + esc(kind ? t('route.link.' + kind.key) : 'LINE Official') + '</strong>' +
'<span id="route-line-note"></span></div>';
var qr = document.createElement('img');
qr.className = 'mu-qr-img';
qr.loading = 'lazy';
qr.decoding = 'async';
qr.hidden = true;
/* กดที่ QR → ขยายลอยกลางจอให้สแกนง่าย (ปุ่มจริง เผื่อคีย์บอร์ด/อ่านหน้าจอ) */
var qrBtn = document.createElement('button');
qrBtn.type = 'button';
qrBtn.className = 'mu-qr-btn';
qrBtn.hidden = true;
qrBtn.setAttribute('aria-label', t('route.zoomQr'));
qrBtn.appendChild(qr);
line.appendChild(qrBtn);
host.appendChild(line);
var note = (cap && cap.line_note) ? String(cap.line_note).trim() : '';
setText('route-line-note', note);
var phones = (route.phone || []).filter(Boolean);
tryImage(qr, qrUrls(rid, cap), t('route.qrAlt', { n: rid }), function (ok) {
qrBtn.hidden = !ok; /* ไม่มีรูป = ไม่มีปุ่มขยาย */
if (ok) {
var label = (kind ? t('route.link.' + kind.key) : 'LINE Official');
qrBtn.addEventListener('click', function () { openQrModal(qr.src, label, webUrl); });
}
line.hidden = !ok && !note; /* ไม่มีทั้ง QR และข้อความ = ไม่ต้องแสดงแถวนี้ */
host.hidden = line.hidden && !phones.length; /* ไม่มีอะไรจะแสดงเลย */
});
phones.forEach(function (p) {
var a = document.createElement('a');
a.className = 'mu-contact-item';
a.href = telHref(p);
a.innerHTML =
'<span class="ic-wrap"><svg class="ic" aria-hidden="true"><use href="#ic-phone"/></svg></span>' +
'<div class="txt"><strong>' + esc(t('route.call')) + '</strong><span>' + esc(fmtPhone(p)) + '</span></div>';
host.appendChild(a);
});
/* ปุ่ม "เปิดลิงก์" แยกต่างหาก — ชัดเจนบนมือถือ (แสดงเมื่อ routes.json มี web_url) */
if (kind && /^https?:\/\//i.test(webUrl)) {
var open = document.createElement('a');
open.className = 'mu-contact-item';
open.href = webUrl;
open.target = '_blank';
open.rel = 'noopener noreferrer';
open.setAttribute('aria-label', t('route.openLink') + ': ' + prettyUrl(webUrl));
open.innerHTML =
'<span class="ic-wrap ' + kind.tone + '"><svg class="ic" aria-hidden="true"><use href="#' + kind.icon + '"/></svg></span>' +
'<div class="txt"><strong>' + esc(t('route.openLink')) + '</strong></div>' + /* ไม่แสดง URL — กันล้นปุ่ม */
'<span class="mu-link-go"><svg class="ic" aria-hidden="true"><use href="#ic-arrow-right"/></svg></span>';
host.appendChild(open);
host.hidden = false;
}
}
/* ---------- ขยาย QR ลอยกลางจอ (ให้สแกนง่ายจากจออื่น) ----------
ใช้ <dialog> ของเบราว์เซอร์: กด Esc ปิดได้เอง · คลิกพื้นหลังปิด · ไม่ต้องพึ่งไลบรารี
ปุ่ม "เปิดลิงก์" เปิดแท็บใหม่ (target=_blank) */
function openQrModal(src, label, url) {
if (!src) return;
var old = $('qr-modal');
if (old) old.remove();
var hasUrl = url && /^https?:\/\//i.test(String(url).trim());
var dlg = document.createElement('dialog');
dlg.id = 'qr-modal';
dlg.className = 'mu-qr-modal';
/* กดรูป QR = เปิดลิงก์ (ตามที่เจ้าของข้อมูลต้องการ) · มีปุ่ม "เปิดลิงก์" + "คัดลอกลิงก์" เป็นทางเลือกชัดเจน */
var qrImg = hasUrl
? '<a class="mu-qr-link" href="' + esc(String(url).trim()) + '" target="_blank" rel="noopener noreferrer"' +
' aria-label="' + esc(t('route.openLink')) + '"><img class="mu-qr-big" src="' + esc(src) +
'" alt="' + esc(label || 'QR') + '" decoding="async"></a>'
: '<img class="mu-qr-big" src="' + esc(src) + '" alt="' + esc(label || 'QR') + '" decoding="async">';
var acts = hasUrl
? '<div class="mu-qr-actions">' +
'<a class="mu-btn" href="' + esc(String(url).trim()) + '" target="_blank" rel="noopener noreferrer">' +
esc(t('route.openLink')) + ' <svg class="ic" aria-hidden="true"><use href="#ic-arrow-right"/></svg></a>' +
'<button type="button" class="mu-btn ghost mu-copy-link">' +
'<svg class="ic" aria-hidden="true"><use href="#ic-copy"/></svg> ' + esc(t('route.copyLink')) + '</button>' +
'</div>'
: '';
dlg.innerHTML =
'<div class="mu-qr-modal-card">' +
'<button type="button" class="mu-qr-close" aria-label="' + esc(t('common.close')) + '">' +
'<svg class="ic" aria-hidden="true"><use href="#ic-x"/></svg></button>' +
qrImg +
'<strong>' + esc(label || '') + '</strong>' +
acts +
'</div>';
document.body.appendChild(dlg);
dlg.addEventListener('click', function (e) { /* คลิกพื้นหลัง = ปิด */
if (e.target === dlg) dlg.close();
});
dlg.addEventListener('close', function () { dlg.remove(); });
dlg.querySelector('.mu-qr-close').addEventListener('click', function () { dlg.close(); });
/* คัดลอกลิงก์ — ใช้ Clipboard API ก่อน, ถ้าไม่ให้สิทธิ์ถอยไป execCommand */
var copyBtn = dlg.querySelector('.mu-copy-link');
if (copyBtn) {
copyBtn.addEventListener('click', function () {
var target = String(url).trim();
var done = function () {
copyBtn.classList.add('is-done');
var old2 = copyBtn.innerHTML;
copyBtn.textContent = t('route.copied');
setTimeout(function () { copyBtn.innerHTML = old2; copyBtn.classList.remove('is-done'); }, 1400);
};
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(target).then(done).catch(function () { legacyCopy(target); done(); });
} else { legacyCopy(target); done(); }
});
}
if (typeof dlg.showModal === 'function') dlg.showModal(); else dlg.setAttribute('open', '');
}
/* คัดลอกแบบเก่า (เบราว์เซอร์ไม่รองรับ Clipboard API / ไม่ได้ https) */
function legacyCopy(text) {
try {
var ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.top = '-1000px';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
return true;
} catch (e) { return false; }
}
/* ---------- รอบต่อวัน / รอบถัดไป จาก schedules.json ---------- */
function toMin(hhmm) {
var a = String(hhmm).split(':');
return (parseInt(a[0], 10) || 0) * 60 + (parseInt(a[1], 10) || 0);
}
function nextTrip(times) {
if (!times.length) return null;
var uniqTimes = times.slice().sort();
var now = new Date(), mins = now.getHours() * 60 + now.getMinutes();
for (var i = 0; i < uniqTimes.length; i++) {
if (toMin(uniqTimes[i]) >= mins) return uniqTimes[i];
}
return uniqTimes[0]; /* หมดรอบของวันนี้ → รอบแรกของวันถัดไป */
}
function loadTrips(rid) {
return Schedules.load().then(function (sd) { return Schedules.normSub(sd); }).then(function (d) {
var recs = window.Schedules ? Schedules.records(d) : ((d && (d.schedules || d)) || []);
var out = [];
recs.forEach(function (r) {
if (String(r.route_id) === String(rid)) out = out.concat(r.departure_times || []);
});
return out;
});
}
function fillVehicle(rid, route, cap) {
cap = cap || {};
var img = $('route-vehicle-img');
var card = $('route-vehicle-card');
if (img) {
tryImage(img, vehicleUrls(rid, cap), t('route.vehicleAlt', { n: rid }), function (ok) {
if (card) card.classList.toggle('no-photo', !ok);
});
}
setText('route-vehicle-title', cap.vehicle_title);
setText('route-vehicle-desc', cap.vehicle_desc);
buildContact(rid, route, cap);
}
function init() {
var params = (window.__route && window.__route.params) || {};
fetchJSON(DATA + 'routes.json').then(function (d) {
var list = (d && d.routes) || [];
if (!list.length) return;
var want = String(params.routeId || '');
var route = list.filter(function (r) { return String(r.route_id) === want; })[0] ||
list.filter(function (r) { return String(r.route_id) === FALLBACK_ID; })[0] || list[0];
var rid = String(route.route_id);
/* หัวเรื่อง (chip + ชื่อสาย) — สี chip เปลี่ยนตามหมวดเส้นทาง (route_group) */
setText('route-chip', rid);
var chipEl = $('route-chip');
if (chipEl) {
chipEl.className = 'mu-route-chip' + (route.route_group ? ' grp-' + route.route_group : '');
}
setText('route-title', nm(route, 'route_name'));
document.title = 'Atroute — ' + t('common.routePrefix', { n: rid }) + (nm(route, 'route_name') ? ' ' + nm(route, 'route_name') : '');
/* dropdown: เติมจาก routes.json (ลำดับตามไฟล์) + เปลี่ยนแล้วไปสายนั้น */
var sel = $('route-select');
if (sel) {
sel.innerHTML = '';
list.forEach(function (r) {
var o = document.createElement('option');
o.value = r.route_id;
o.textContent = t('common.routePrefix', { n: r.route_id }) + (nm(r, 'route_name') ? ' - ' + nm(r, 'route_name') : '');
sel.appendChild(o);
});
sel.value = rid;
sel.addEventListener('change', function () {
window.location.hash = '#/routes/' + encodeURIComponent(sel.value);
});
}
/* สรุปเส้นทาง */
setStat('stat-stops', route.station_ids ? route.station_ids.length : '');
setStat('stat-provinces', route.province_ids ? route.province_ids.length : '');
loadTrips(rid).then(function (times) {
setStat('stat-trips', times.length ? String(times.length) : '');
setStat('stat-next', nextTrip(times) || '');
});
/* รูปรถ/คำอธิบาย/QR/เบอร์โทร */
fetchJSON(DATA + 'captions/caption' + encodeURIComponent(rid) + '.json').then(function (cap) {
fillVehicle(rid, route, cap);
});
/* แผนที่เส้นทาง */
var mapEl = $('route-map');
if (mapEl && window.ATMap) ATMap.route(mapEl, rid);
});
}
init();
})();