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

301 lines
13 KiB
JavaScript

/* ============================================================
หน้าป้ายหยุดรถ — render จาก resource/data/busstop_list.json
------------------------------------------------------------
ข้อมูล: busstop_list.json (shape = array ตรง ๆ ไม่มี wrapper)
{
"route_code": "3064", // Highway No.
"section_code": "0100", // Control Section
"route_name": "อ่างทอง - ปากดง", // Highway Name
"kilometer": "3+000", // ★ รหัสป้าย (Survey point — แสดงผลคงรูปนี้)
"position": "ขวาทาง", // Location of the pavilion
"type": "ที่รอรถประจำทาง", // Picture / Size of the pavilion
"latitude": 14.6016517229,
"longitude": 100.4323316104,
"buses-line": [15, 101] // ★ สายรถประจำทางที่ผ่านป้ายนี้ (ว่าง = [])
}
กติกา:
- รหัสป้ายบนจอ = kilometer คงรูปเดิมเสมอ ("3+000") ตาม AGENTS.md ข้อ 9
- ชื่อไฟล์รูป = pad5(kilometer) → "3+000" = "03000" → .image/stops/03000.jpg
(ตัด "+" ออก + เติม 0 หน้าให้ครบ 5 หลัก)
- รูปหาย → ใช้ placeholder minibus-512x512.png
- KPI คำนวณจากข้อมูลจริง ไม่ hardcode
============================================================ */
(function () {
'use strict';
var DATA_URL = '../resource/data/busstop_list.json';
var ROUTES_URL = '../resource/data/routes.json'; /* ใช้ยืนยันว่าสายมีอยู่จริง ก่อนทำชิปเป็นลิงก์ */
var IMG_DIR = '../.image/stops/'; /* รูปป้ายริมทาง: pad5(กม.) เช่น 36020.jpg (ชุดเดิม) */
var STATION_IMG_DIR = '../.image/stations/'; /* รูปสถานี (ตัวอาคาร): <station_id>.jpg ตาม stations.json */
var IMG_EXTS = ['jpg', 'jpeg', 'webp', 'png']; /* ไล่ลองนามสกุล (รองรับ .jpeg) */
var PLACEHOLDER = '../.image/icons/minibus-512x512.png';
function t(key, vars) {
return window.I18N ? window.I18N.t(key, vars) : key;
}
/* "3+000" → "03000" (ตัดเครื่องหมาย + ออก แล้วเติม 0 หน้าให้ครบ 5 หลัก) */
function pad5(km) {
if (!km) return '';
return String(km)
.split('+')
.map(function (s) { return s.replace(/\D/g, ''); })
.join('')
.padStart(5, '0');
}
function fetchJSON(url) {
return fetch(url, { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.catch(function () { return null; });
}
/* ---------- รูป: รูปสถานี (<station_id>.jpg) ก่อน → รูปป้ายริมทาง (pad5 กม.) → placeholder ---------- */
function exists(url) {
return fetch(url, { method: 'HEAD', cache: 'no-store' })
.then(function (r) { return r.ok ? url : null; })
.catch(function () { return null; });
}
/* ไล่ลองนามสกุลทีละตัว (.jpg → .jpeg → .webp → .png) — ไม่มีเลย = null */
function firstExisting(base) {
var i = 0;
function next() {
if (i >= IMG_EXTS.length) return Promise.resolve(null);
var url = base + '.' + IMG_EXTS[i++];
var bu = (window.ImgURL && ImgURL.of) ? ImgURL.of(url) : url; /* ?v= กัน cache-first ของ SW */
return exists(bu).then(function (u) { return u || next(); });
}
return next();
}
function resolveImage(stop) {
var sid = stop && stop.station_id;
var code = pad5(stop && stop.kilometer);
var chain = sid ? firstExisting(STATION_IMG_DIR + sid) : Promise.resolve(null);
return chain.then(function (u) { return u ? exists(u) : null; })
.then(function (u) {
if (u) return u;
return code ? firstExisting(IMG_DIR + code) : null;
})
.then(function (u) { return u || PLACEHOLDER; });
}
/* ---------- KPI (คำนวณจากข้อมูลจริง) ---------- */
function renderKpi(stops) {
var host = document.getElementById('stops-kpi');
if (!host) return;
var routes = {};
var types = {};
var busLines = {};
stops.forEach(function (s) {
if (s.route_code) routes[s.route_code] = true;
if (s.type) types[s.type] = true;
(s['buses-line'] || []).forEach(function (n) { busLines[n] = true; });
});
// สายที่ผ่านป้ายเยอะที่สุด (นับจาก buses-line)
var countByBus = {};
stops.forEach(function (s) {
(s['buses-line'] || []).forEach(function (n) {
countByBus[n] = (countByBus[n] || 0) + 1;
});
});
var busKeys = Object.keys(countByBus);
var topBus = busKeys.sort(function (a, b) { return countByBus[b] - countByBus[a]; })[0];
var kpis = [
{ label: t('stops.kpi.total'), value: stops.length + ' ' + t('stops.unitPoints') },
{ label: t('stops.kpi.routes'), value: Object.keys(routes).length + ' ' + t('stops.unitRoutes') },
{ label: t('stops.kpi.types'), value: Object.keys(types).length + ' ' + t('stops.unitTypes') },
{ label: t('stops.kpi.buses'), value: topBus ? t('common.routePrefix', { n: topBus }) : '—' }
];
host.innerHTML = '';
kpis.forEach(function (k) {
var box = document.createElement('div');
box.className = 'mu-kpi';
var label = document.createElement('p');
label.className = 'label';
label.textContent = k.label;
var value = document.createElement('p');
value.className = 'value';
value.textContent = k.value;
box.appendChild(label);
box.appendChild(value);
host.appendChild(box);
});
}
/* ---------- การ์ดป้าย ---------- */
function buildCard(stop, imgUrl, idx, routeIds) {
var li = document.createElement('li');
li.setAttribute('data-idx', String(idx));
var img = document.createElement('img');
img.className = 'mu-stop-thumb';
img.src = imgUrl;
img.alt = stop.route_name || '';
img.loading = 'lazy';
img.decoding = 'async';
if (imgUrl === PLACEHOLDER) img.classList.add('is-placeholder');
li.appendChild(img);
var card = document.createElement('div');
card.className = 'mu-stop-card local';
var top = document.createElement('div');
top.className = 'mu-stop-top';
var left = document.createElement('div');
var pill = document.createElement('span');
pill.className = 'mu-type-pill local';
pill.textContent = stop.type || '';
left.appendChild(pill);
var title = document.createElement('h2');
title.className = 'mu-stop-title';
title.textContent = stop.place || stop.route_name || '—';
left.appendChild(title);
var loc = document.createElement('p');
loc.className = 'mu-loc';
loc.textContent = t('stops.highway') + ' ' + (stop.route_code || '—') +
' · ' + t('stops.section') + ' ' + (stop.section_code || '—');
left.appendChild(loc);
top.appendChild(left);
var codeChip = document.createElement('span');
codeChip.className = 'mu-chip count stop-code';
codeChip.textContent = stop.kilometer || '—';
top.appendChild(codeChip);
card.appendChild(top);
var row = document.createElement('div');
row.className = 'mu-chip-row';
// ★ สายรถประจำทางที่ผ่านป้ายนี้ (buses-line)
// สายที่มีใน routes.json → ทำเป็นลิงก์ไปหน้ารายละเอียดสายนั้น (#/routes/<รหัส>)
var buses = stop['buses-line'] || [];
if (buses.length) {
buses.forEach(function (n) {
var known = routeIds.indexOf(String(n)) !== -1;
var b = document.createElement(known ? 'a' : 'span');
b.className = 'mu-chip route';
if (known) {
b.href = '#/routes/' + encodeURIComponent(n);
b.title = t('stops.viewRoute', { n: n });
}
b.textContent = t('stops.busPrefix') + ' ' + n;
row.appendChild(b);
});
} else {
var nb = document.createElement('span');
nb.className = 'mu-chip';
nb.textContent = t('stops.noBusLine');
row.appendChild(nb);
}
card.appendChild(row);
var action = document.createElement('div');
action.className = 'mu-stop-action';
var note = document.createElement('p');
note.className = 'mu-stop-note';
note.textContent = stop.position || '';
action.appendChild(note);
var coords = document.createElement('span');
coords.className = 'mu-chip';
coords.textContent = (stop.latitude && stop.longitude)
? stop.latitude.toFixed(4) + ', ' + stop.longitude.toFixed(4)
: '—';
action.appendChild(coords);
card.appendChild(action);
li.appendChild(card);
return li;
}
/* ---------- สร้างการ์ดแบบทยอย (lazy) ----------
- สร้าง "ทุกใบ" เป็น <li> เปล่า (มี data-idx) เพื่อให้ตัวกรอง/นับผลทำงานถูกต้องทันที
- โหลดรูป + เนื้อหา "เฉพาะใบที่มองเห็น" → เปิดหน้าเร็ว (ไม่ยิง 154 รูปพร้อมกัน)
- ใบที่ยังไม่โหลด: ใส่ที่กันที่ว่างชั่วคราว แล้วโหลดเมื่อถูกเรียก (แสดงทั้งหมด / ค้นหาเจอ) */
var CARD_STUB = '<div class="mu-stop-card is-stub" aria-hidden="true"></div>';
function renderStops(stops, host, routeIds) {
host.innerHTML = '';
if (!stops.length) {
var empty = document.createElement('li');
empty.className = 'mu-stop-empty';
empty.textContent = t('stops.noResult');
host.appendChild(empty);
return Promise.resolve();
}
stops.forEach(function (stop, idx) {
var li = document.createElement('li');
li.setAttribute('data-idx', String(idx));
li.innerHTML = CARD_STUB;
host.appendChild(li);
});
if (window.StopsSearch && window.StopsSearch.apply) window.StopsSearch.apply(); /* ให้ตัวกรองนับ/แสดงผลทันที */
return Promise.resolve();
}
/* โหลดเนื้อหาการ์ดจริงของใบนั้น (เรียกครั้งเดียวต่อใบ) */
function hydrateCard(li, stops, routeIds) {
if (!li || li.getAttribute('data-loaded')) return Promise.resolve();
var idx = parseInt(li.getAttribute('data-idx'), 10);
if (isNaN(idx) || !stops[idx]) return Promise.resolve();
li.setAttribute('data-loaded', '1');
return resolveImage(stops[idx]).then(function (url) {
var built = buildCard(stops[idx], url, idx, routeIds); /* buildCard คืน <li> ของมันเอง */
li.innerHTML = '';
while (built.firstChild) li.appendChild(built.firstChild); /* ย้ายเนื้อหาเข้ามา — ห้ามซ้อน <li> */
});
}
var STATE = { stops: [], routeIds: [] }; /* ให้โมดูลอื่น (search) เรียก hydrateCard ได้ */
/* ---------- init ---------- */
function init() {
var host = document.getElementById('stops-list');
if (!host) return;
Promise.all([fetchJSON(DATA_URL), fetchJSON(ROUTES_URL)]).then(function (res) {
var data = res[0], routesDoc = res[1] || {};
var stops = Array.isArray(data) ? data : (data && data.stops) || [];
var routeIds = (routesDoc.routes || []).map(function (r) { return String(r.route_id); });
if (!stops.length) {
host.innerHTML = '<li class="mu-stop-empty">' + t('stops.noResult') + '</li>';
return;
}
renderKpi(stops);
STATE.stops = stops;
STATE.routeIds = routeIds;
// ผูก event ก่อน render การ์ด — กันเคสที่ render ค้างแล้วปุ่มไม่ตอบสนอง
if (window.StopsSearch) window.StopsSearch.init(stops);
renderStops(stops, host, routeIds).then(function () {
if (window.StopsSearch) window.StopsSearch.init(stops);
if (window.StopsSearch && window.StopsSearch.hydrateVisible) window.StopsSearch.hydrateVisible();
});
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// เปิดให้ search module ใช้ helper ร่วมกัน
window.StopsRender = {
pad5: pad5,
PLACEHOLDER: PLACEHOLDER,
hydrate: function (li) { return hydrateCard(li, STATE.stops, STATE.routeIds); }
};
})();