ตารางเวลาคำนวณได้ + หน้ารายละเอียดป้ายขับเคลื่อนด้วยข้อมูล + แผนที่ Leaflet

Schedules — กติกา "จุดนี้ = เวลาจุดอ้างอิง ± n นาที"
- ฟิลด์ derive { from_station_id, offset_min } คำนวณที่ ui/partials/schedules.js (ท่อเดียว) รองรับอ้างจุดข้ามทิศ
- จุดย่อยของ "8 other_stop" ใช้ offsets_min จับคู่ตามลำดับ (เช่น ตลาดสามโก้ = ตลาดท่าช้าง +45 นาที)
- เครื่องมือ resource/tools/derive-times.py + ตาราง resource/data/derive-times.csv (--check / --audit ชี้จุดที่ควรตั้งกฎ)
- แยกตารางเป็นรายสาย: scheduleslist/schedules<route_id>.json และ schedules.json เป็นสารบัญ (โหลดแบบ lazy + cache)
- ตรวจจับวันทำงาน/วันหยุด + schema 3 (weekday/holiday → directions) · ไฟล์ข้อมูลเป็น CRLF ทั้งชุด
- ล้างค่าที่ไม่ใช่ HH:MM ที่ฝังใน times (ทำให้ KPI เพี้ยน) + กันค่าหลอกในตัวสรุปเวลา

UI
- หน้ารายละเอียดป้าย/ตารางเวลา ขับเคลื่อนด้วย JSON (stopDetail.init.js) · จุดขึ้นรถประจำทางอื่นๆ รองรับหลายจุดต่อสาย
- #/stops: แสดง 6 ป้ายแรก + ปุ่ม "แสดงป้ายทั้งหมด" (โหลดรูปเฉพาะที่แสดง) · ชิปสาย → #/routes/<route_id>
- หน้าแรก: ตัดตัวเลือก "ทุกสถานีในจังหวัดนี้" · ตัวกรองจังหวัด/สถานี + ปุ่มแชร์ (share URL)
- การ์ดติดต่อ: ไอคอน/ชื่อ/สีเปลี่ยนตามชนิด URL (Facebook / LINE / เว็บไซต์) + ปุ่มเปิดลิงก์จาก web_url
- รูปรองรับหลายนามสกุล (.jpg → .jpeg → .webp → .png) · ป้าย "ประมาณ" + หมายเหตุสำหรับตารางที่คำนวณ
- หน้าเครดิตเหลือ 3 หมวด · แก้ข้อความหมวดแผนที่ให้ตรงกับข้อมูลจริง
- แผนที่ Leaflet (vendor ในโปรเจกต์ ไม่ใช้ CDN): เส้นทาง + หมุด + ป๊อปอัป · แก้ CSS ที่ทำให้ SVG ยุบ 0x0

เครื่องมือและเอกสาร
- qgis-to-web.py อ่าน .shp ตรง → geojson-web (สร้างใหม่ 10 ไฟล์) + audit-geojson.py ตรวจ 3 ส่วน
- stop-km.py วัดระยะ กม. ตามเส้นจริง → stop-km.json · schedules-editor.html (แก้ทีละไฟล์ · มุมมองตารางแบบ Excel)
- AGENTS.md: กติกา derive · offsets_min · นามสกุลรูป · ชิปสาย · หน้ารายละเอียดป้ายมาจากไหน
This commit is contained in:
Bkk1234 committed 2026-09-30 03:25:18 +07:00
1 parent 88311326e6
commit 1cfaeb1526
91 files changed
+7560 -844

No files matched your search

+6 -1
View File
@@ -86,6 +86,10 @@
background: linear-gradient(135deg, #7a4cc0, #b07ce0); color: #fff;
}
.mu-contact-item .ic-wrap.tone-green { background: linear-gradient(135deg, #1f8765, #51c39c); }
.mu-contact-item .ic-wrap.tone-sky { background: linear-gradient(135deg, #1877f2, #4a9bf8); }
.mu-contact-item .ic-wrap.tone-purple { background: linear-gradient(135deg, #7a4cc0, #a583e0); }
.mu-contact-item .mu-link-go { flex: 0 0 auto; display: flex; align-items: center; color: #7a4cc0; opacity: .8; }
.mu-contact-item:hover .mu-link-go { opacity: 1; transform: translateX(2px); }
.mu-contact-item .ic-wrap svg { width: 22px; height: 22px; }
.mu-contact-item .txt { flex: 1; min-width: 0; }
.mu-contact-item .txt strong { display: block; color: #1f2a44; font-size: .98rem; margin-bottom: 2px; }
@@ -104,7 +108,8 @@
padding: 16px;
box-shadow: 0 4px 14px rgba(20, 40, 90, .06);
}
.mu-map-card svg { width: 100%; height: auto; display: block; }
/* (ตัดกฎ .mu-map-card svg เดิมออก — แผนที่ SVG นิ่งถูกแทนด้วย Leaflet
และกฎนี้ทำให้ SVG ของ Leaflet ยุบเป็น 0x0 จนเส้นทางไม่แสดง) */
.mu-summary-grid { gap: 14px; }
+41 -5
View File
@@ -84,17 +84,38 @@
}
function telHref(p) { return 'tel:' + String(p == null ? '' : p).replace(/[^\d+]/g, ''); }
/* ---------- การ์ดติดต่อ (LINE + QR + เบอร์โทรทุกเบอร์จาก routes.json) ---------- */
/* ---------- ลิงก์ติดต่อ (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 }
];
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 kind = linkKind(route.web_url);
var line = document.createElement('div');
line.className = 'mu-contact-item';
line.innerHTML =
'<span class="ic-wrap tone-green"><svg class="ic" aria-hidden="true"><use href="#ic-message-circle"/></svg></span>' +
'<div class="txt"><strong>LINE Official</strong><span id="route-line-note"></span></div>';
'<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';
@@ -120,6 +141,21 @@
'<div class="txt"><strong>' + esc(t('route.call')) + '</strong><span>' + esc(fmtPhone(p)) + '</span></div>';
host.appendChild(a);
});
/* ปุ่ม "เปิดลิงก์" แยกต่างหาก — ชัดเจนบนมือถือ (แสดงเมื่อ routes.json มี web_url) */
if (kind) {
var open = document.createElement('a');
open.className = 'mu-contact-item';
open.href = String(route.web_url).trim();
open.target = '_blank';
open.rel = 'noopener noreferrer';
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><span>' + esc(prettyUrl(route.web_url)) + '</span></div>' +
'<span class="mu-link-go"><svg class="ic" aria-hidden="true"><use href="#ic-arrow-right"/></svg></span>';
host.appendChild(open);
host.hidden = false;
}
}
/* ---------- รอบต่อวัน / รอบถัดไป จาก schedules.json ---------- */
@@ -137,8 +173,8 @@
return uniqTimes[0]; /* หมดรอบของวันนี้ → รอบแรกของวันถัดไป */
}
function loadTrips(rid) {
return fetchJSON(DATA + 'schedules.json').then(function (d) {
var recs = (d && (d.schedules || d)) || [];
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 || []);
+13 -1
View File
@@ -240,7 +240,11 @@
}
.mu-toolbar-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 12px; }
.mu-toolbar-count { margin: 10px 0 0; font-size: .84rem; color: #6f7b95; }
.mu-show-more { display: flex; justify-content: center; margin: 14px 0 4px; }
.mu-show-more .mu-btn { min-width: 220px; }
.mu-stop-card.is-stub { min-height: 120px; background: #faf8ff; border: 1px dashed #ddd2f2; box-shadow: none; }
.mu-toolbar-count { margin: 10px 0 0; font-size: .84rem; color: #6f7b95; }
.mu-toolbar-count b { color: #7a4cc0; font-variant-numeric: tabular-nums; }
/* ===== การ์ดป้าย ===== */
@@ -295,6 +299,10 @@
font-weight:700;
}
.mu-chip.route { background: #f3ecff; color:#6d28d9; border-color: #e0d6f5; }
/* ชิปสายที่เป็นลิงก์ → ไปหน้าเช็กเวลาของสายนั้น (หน้าตาเหมือนชิปเดิม + มี hover/focus) */
a.mu-chip.route { text-decoration: none; cursor: pointer; }
a.mu-chip.route:hover { background:#e9dcff; border-color:#cdb5f2; }
a.mu-chip.route:focus-visible { outline: 2px solid #7a4cc0; outline-offset: 2px; }
/* รหัสป้าย = ม่วง-ขาว แบบเดียวกับป้ายสายรถ */
.mu-chip.count.stop-code {
background: linear-gradient(135deg, #7a4cc0, #b07ce0);
@@ -449,6 +457,10 @@
<div id="near-me-result" class="mu-near-wrap" hidden></div>
<ul class="mu-stop-grid" id="stops-list"></ul>
<div class="mu-show-more">
<button type="button" class="mu-btn outline" id="stops-show-all" data-i18n="stops.showAll" hidden>แสดงป้ายทั้งหมด</button>
</div>
</div>
</main>
+78 -25
View File
@@ -25,8 +25,10 @@
'use strict';
var DATA_URL = '../resource/data/busstop_list.json';
var IMG_DIR = '../.image/stops/';
var IMG_EXT = '.jpg';
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) {
@@ -49,14 +51,32 @@
.catch(function () { return null; });
}
/* ---------- รูป: ลองรูปจริงก่อน ถ้าไม่มีค่อยใช้ placeholder ---------- */
function resolveImage(km) {
var code = pad5(km);
if (!code) return Promise.resolve(PLACEHOLDER);
var url = IMG_DIR + code + IMG_EXT;
/* ---------- รูป: รูปสถานี (<station_id>.jpg) ก่อน → รูปป้ายริมทาง (pad5 กม.) → placeholder ---------- */
function exists(url) {
return fetch(url, { method: 'HEAD', cache: 'no-store' })
.then(function (r) { return r.ok ? url : PLACEHOLDER; })
.catch(function () { return PLACEHOLDER; });
.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++];
return exists(url).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 (คำนวณจากข้อมูลจริง) ---------- */
@@ -107,7 +127,7 @@
}
/* ---------- การ์ดป้าย ---------- */
function buildCard(stop, imgUrl, idx) {
function buildCard(stop, imgUrl, idx, routeIds) {
var li = document.createElement('li');
li.setAttribute('data-idx', String(idx));
@@ -157,11 +177,17 @@
row.className = 'mu-chip-row';
// ★ สายรถประจำทางที่ผ่านป้ายนี้ (buses-line)
// สายที่มีใน routes.json → ทำเป็นลิงก์ไปหน้ารายละเอียดสายนั้น (#/routes/<รหัส>)
var buses = stop['buses-line'] || [];
if (buses.length) {
buses.forEach(function (n) {
var b = document.createElement('span');
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);
});
@@ -193,44 +219,67 @@
return li;
}
function renderStops(stops, host) {
/* ---------- สร้างการ์ดแบบทยอย (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;
return Promise.resolve();
}
// โหลดรูปทีละใบ แล้วค่อยต่อการ์ด (รักษาลำดับ)
var chain = Promise.resolve();
stops.forEach(function (stop, idx) {
chain = chain.then(function () {
return resolveImage(stop.kilometer).then(function (url) {
host.appendChild(buildCard(stop, url, idx));
});
});
var li = document.createElement('li');
li.setAttribute('data-idx', String(idx));
li.innerHTML = CARD_STUB;
host.appendChild(li);
});
return chain;
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;
fetchJSON(DATA_URL).then(function (data) {
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).then(function () {
// การ์ดพร้อมแล้ว → ให้ search module กรองซ้ำครั้งแรก
renderStops(stops, host, routeIds).then(function () {
if (window.StopsSearch) window.StopsSearch.init(stops);
if (window.StopsSearch && window.StopsSearch.hydrateVisible) window.StopsSearch.hydrateVisible();
});
});
}
@@ -242,5 +291,9 @@
}
// เปิดให้ search module ใช้ helper ร่วมกัน
window.StopsRender = { pad5: pad5, PLACEHOLDER: PLACEHOLDER };
window.StopsRender = {
pad5: pad5,
PLACEHOLDER: PLACEHOLDER,
hydrate: function (li) { return hydrateCard(li, STATE.stops, STATE.routeIds); }
};
})();
+42 -7
View File
@@ -19,6 +19,7 @@
stops: [],
codeValue: '',
placeQuery: '',
showAll: false, /* false = แสดง 6 ใบแรก · true = แสดงป้ายทั้งหมด */
bound: false
};
@@ -36,6 +37,7 @@
ช่องที่ยังไม่กรอก → ถือเป็น 0 (เช่น "3" + "_" → "03+000")
เก็บเป็น digits[] ความยาว 5 เสมอ */
var PREVIEW_LIMIT = 6; /* แสดง 6 ใบแรก (กดปุ่มเพื่อดูทั้งหมด) */
var CODE_CELLS = 5; // 2 หน้า + 3 หลัง
/* digits[] (5 หลัก) → "03+000" */
@@ -148,15 +150,19 @@
var f = currentFilter();
var filtered = state.stops.filter(function (s) { return f.fn(s, f.value); });
// อัปเดตการ์ดที่มีอยู่แล้วใน DOM (ไม่ยิง network ซ้ำ)
var cards = host.querySelectorAll('li');
/* จำกัด 6 ใบเมื่อ "ไม่ได้กรองอะไร" (เปิดหน้าปกติ) · ค้นหา/กรอง = แสดงผลทั้งหมดที่เจอ */
var searching = !!f.value;
var limit = (searching || state.showAll) ? filtered.length : PREVIEW_LIMIT;
var cards = [].filter.call(host.children, function (el) { return el.tagName === 'LI' && el.hasAttribute('data-idx'); });
var shown = 0;
Array.prototype.forEach.call(cards, function (li) {
var idx = parseInt(li.getAttribute('data-idx'), 10);
if (isNaN(idx)) return;
var visible = filtered.indexOf(state.stops[idx]) !== -1;
var pos = filtered.indexOf(state.stops[idx]);
var visible = pos !== -1 && pos < limit;
li.hidden = !visible;
if (visible) shown++;
if (visible) { shown++; if (window.StopsRender) window.StopsRender.hydrate(li); } /* โหลดรูปเฉพาะใบที่แสดง */
});
// empty state
@@ -173,12 +179,29 @@
empty.hidden = true;
}
// จำนวนผลลัพธ์
// จำนวนผลลัพธ์ + ปุ่ม "แสดงป้ายทั้งหมด"
var count = document.getElementById('stops-count');
if (count) {
count.textContent = t('stops.showing', { a: shown, b: state.stops.length });
count.textContent = searching
? t('stops.showing', { a: shown, b: filtered.length })
: t('stops.showing', { a: shown, b: state.stops.length });
count.hidden = false;
}
var more = document.getElementById('stops-show-all');
if (more) {
var left = filtered.length - shown;
more.hidden = searching || state.showAll || left <= 0; /* กรองอยู่/แสดงครบแล้ว = ไม่ต้องมีปุ่ม */
more.textContent = t('stops.showAll') + ' (' + filtered.length + ')';
}
}
/* โหลดเนื้อหาการ์ดของใบที่มองเห็น (เรียกหลัง render/กรอง) */
function hydrateVisible() {
var host = document.getElementById('stops-list');
if (!host) return;
[].forEach.call(host.children, function (li) {
if (li.tagName === 'LI' && li.hasAttribute('data-idx') && !li.hidden && window.StopsRender) window.StopsRender.hydrate(li);
});
}
/* ---------- สลับโหมด (หัวใจของการกันชน) ---------- */
@@ -389,6 +412,16 @@
// ช่องรหัส: 6-box → เด้งช่อง + เติม 0
initCodeCells();
// ปุ่ม "แสดงป้ายทั้งหมด" — กดแล้วเลิกจำกัด 6 ใบ (ไม่กรองอะไรอยู่)
var more = document.getElementById('stops-show-all');
if (more) {
more.addEventListener('click', function () {
state.showAll = true;
apply();
hydrateVisible();
});
}
// ช่องชื่อ: debounce + suggest
if (placeInput) {
var timer = null;
@@ -399,6 +432,7 @@
state.placeQuery = v;
renderSuggest();
apply();
hydrateVisible();
}, 180);
});
placeInput.addEventListener('focus', renderSuggest);
@@ -423,6 +457,7 @@
var resetBtn = document.getElementById('stops-reset-btn');
if (resetBtn) {
resetBtn.addEventListener('click', function () {
state.showAll = false; /* ล้างการค้นหา → กลับไปแสดง 6 ใบแรก */
var cells = codeCells();
Array.prototype.forEach.call(cells, function (c) { c.value = ''; });
if (placeInput) placeInput.value = '';
@@ -450,7 +485,7 @@
setMode(MODE_CODE); // เริ่มที่โหมดรหัส
}
window.StopsSearch = { init: init, setMode: setMode, formatCode: formatCode };
window.StopsSearch = { init: init, setMode: setMode, formatCode: formatCode , hydrateVisible: hydrateVisible };
// ให้ i18n เรียก render ใหม่ได้ (ไม่บังคับ)
window.addEventListener('langchange', function () {
+55 -8
View File
@@ -94,11 +94,16 @@
body.appendChild(none);
}
/* มีอย่างน้อย 1 ทิศที่มีตารางจริงไหม — ถ้ามี ห้ามขึ้น "ยังไม่มีข้อมูล" ของทิศที่ว่าง
(จุดเดียวมีได้หลายทิศ · ทิศว่างไม่ควรทำให้การ์ดที่ตารางขึ้นแล้วดูเหมือนไม่มีข้อมูล) */
var hasAny = g.recs.some(function (x) { return (x.departure_times || []).length > 0; });
g.recs.forEach(function (r) {
var times = (r.departure_times || []).slice();
/* ไม่มีเวลาเลย (เช่น สาย 999: departure_times = []) → บอกว่าไม่มีข้อมูล ไม่ต้องมีบรรทัดลอย */
/* ทิศนี้ยังไม่มีเวลา → ข้ามไปเลยถ้าทิศอื่นมีการ์ดข้อมูลอยู่แล้ว */
if (!times.length) {
if (hasAny) return;
var empty = document.createElement('p');
empty.className = 'mu-stop-sub';
empty.textContent = t('route.empty');
@@ -106,15 +111,22 @@
return;
}
/* หัวแถว = ชื่อทิศ (dir_label) → ไม่มีค่อยใช้ dir_note → ไม่มีอีกค่อยบอกว่าอยู่ที่จุดนี้
ทิศที่ไปคนละทางจากจุดเดียวกัน (ป่าโมกไปอ่างทอง / ป่าโมกไปอยุธยา) จึงแยกให้เห็นชัด */
var sub = document.createElement('p');
sub.className = 'mu-stop-sub';
sub.innerHTML = r.direction_note
? esc(r.direction_note) + ' <span class="mu-direction-tag">' + esc(t('check.direction')) + '</span>'
: esc(t('check.atStop')) + ' ' + esc(g.name);
if (r.dir_label) {
sub.innerHTML = esc(r.dir_label) +
(r.direction_note ? ' <span class="mu-direction-tag">' + esc(r.direction_note) + '</span>' : '');
} else if (r.direction_note) {
sub.innerHTML = esc(r.direction_note) + ' <span class="mu-direction-tag">' + esc(t('check.direction')) + '</span>';
} else {
sub.textContent = t('check.atStop') + ' ' + g.name;
}
body.appendChild(sub);
var grid = document.createElement('div');
grid.className = 'mu-time-grid';
grid.className = 'mu-time-grid' + (r.estimated ? ' is-est' : ''); /* เวลาที่คำนวณจากต้นทาง */
var chips = [];
times.forEach(function (tm) {
var c = document.createElement('div');
@@ -124,6 +136,18 @@
chips.push(c);
});
body.appendChild(grid);
if (r.estimated) {
var est = document.createElement('p');
est.className = 'mu-est-note';
/* มาจากกฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" → บอกจุดอ้างอิง + เตือนเรื่องการจราจร */
est.textContent = r.estimateFrom && window.Schedules.offsetLabel
? t('time.derived', {
base: r.estimateFrom.name || ('#' + r.estimateFrom.station_id),
n: Schedules.offsetLabel(r.estimateFrom.offsetMin)
})
: t('time.estimated');
body.appendChild(est);
}
sections.push({ chips: chips, times: times, station: g.name });
if (r.schedule_note) {
@@ -188,11 +212,12 @@
Promise.all([
fetchJSON(DATA + 'routes.json'),
fetchJSON(DATA + 'stations.json'),
fetchJSON(DATA + 'schedules.json')
Schedules.load().then(function (sd) { return Schedules.normSub(sd); })
]).then(function (res) {
var routes = (res[0] || {}).routes || [];
var sts = (res[1] || {}).stations || [];
var recs = (res[2] || {}).schedules || res[2] || [];
if (window.Schedules && Schedules.setStationNames) Schedules.setStationNames(sts); /* ให้ข้อความ "คำนวณจาก ..." มีชื่อจุด */
var recs = window.Schedules ? Schedules.records(res[2]) : ((res[2] || {}).schedules || res[2] || []);
if (!routes.length) return;
var route = routes.filter(function (r) { return String(r.route_id) === want; })[0] ||
@@ -225,6 +250,9 @@
/* จัดกลุ่มตามลำดับจุดจอดของสาย แล้วต่อด้วยจุดที่เหลือ (ถ้ามีข้อมูล) */
var order = (route.station_ids || []).slice();
/* schema 2: ใช้ station_order ที่ตรวจทิศทางมาแล้วจากไฟล์ (ถ้ามี) */
var sched = window.Schedules ? Schedules.route(res[2], rid) : null;
if (sched && sched.station_order.length) order = sched.station_order.slice();
recs.forEach(function (r) {
if (String(r.route_id) === rid && order.indexOf(r.station_id) === -1) order.push(r.station_id);
});
@@ -249,9 +277,28 @@
var desc = $('check-zone-desc');
if (desc) {
var names = groups.map(function (g) { return g.name; });
/* บอกว่า "ตารางวันนี้" เป็นของวันไหน — เฉพาะสายที่มีการแยกตารางตามวัน (service) เท่านั้น
สายอื่นข้อความเหมือนเดิมทุกตัวอักษร */
/* ป้ายบอกว่า "ตารางที่เห็นอยู่นี้เป็นของวันไหน" — ใช้ผลตรวจวันจากตัวอ่านกลาง (ไม่คำนวณเองในหน้านี้) */
var dayLine = '';
if (window.Schedules && Schedules.dayInfo && Schedules.directions) {
var di = Schedules.dayInfo();
var infos = (Schedules.directions(res[2], rid) || []).map(function (d) { return d.service || { from: 'ไม่ระบุ' }; });
var conflict = infos.some(function (x) { return x.conflict; }); /* ทิศเดียวมีทั้งวันทำงาน+วันหยุด */
var unknown = infos.some(function (x) { return x.unknown; }); /* ยังไม่ระบุวันเลย */
var selectedByDay = infos.some(function (x) { return x.from === 'service' || x.from === 'ระบุตรง' || x.from === 'คำในโน้ต'; });
if (unknown) {
dayLine = ' · ' + t('check.dayUnknown');
} else if (conflict) {
dayLine = ' · ' + t('check.dayMixed');
} else if (selectedByDay) {
dayLine = ' · ' + t(di.dayType === 'holiday' ? 'check.dayHoliday' : 'check.dayWeekday') +
' (' + t('check.dayOfWeek') + ' ' + di.weekday_th + ')';
}
}
desc.textContent = 'สาย ' + rid + ' · ' +
(names.length > 1 ? names[0] + ' \u2192 ' + names[names.length - 1] + ' · ' : '') +
groups.length + ' ' + t('check.stopsCount');
groups.length + ' ' + t('check.stopsCount') + dayLine;
}
/* KPI */
+2 -49
View File
@@ -51,57 +51,10 @@
<p class="src">ใบอนุญาต: Leaflet <a href="https://github.com/Leaflet/Leaflet/blob/main/LICENSE" rel="noopener">BSD-2-Clause</a> · ชุดแผนที่ (tiles): <a href="https://www.openstreetmap.org/copyright" rel="noopener">OpenStreetMap © ผู้มีส่วนร่วม (ODbL)</a></p>
<ul>
<li>Leaflet — ไลบรารีแผนที่แบบ open-source</li>
<li>OpenStreetMap — ข้อมูลแผนที่และภาพ tiles</li>
<li>ในเวอร์ชัน mockup นี้ใช้ภาพแผนที่จำลอง (mock map) เพื่อการแสดงผลก่อนเชื่อมต่อข้อมูลจริง</li>
<li>OpenStreetMap — ภาพ tiles และข้อมูลแผนที่ที่ใช้แสดงผล</li>
<li>เส้นทางเดินรถ จุดจอด และหมุดสถานี วาดจากข้อมูล GIS ของทีม (<code>GeoJSON</code>) ทับบนแผนที่</li>
</ul>
</section>
<section class="mu-credit-section">
<h2><span data-i18n="credits.images">รูปภาพประกอบ</span></h2>
<p class="src">โฟลเดอร์ <code>.image/</code> — ภาพตัวอย่าง (placeholder) สำหรับพัฒนา mockup</p>
<ul>
<li><strong>ภาพเส้นทาง/รถ</strong> (<code>routes/</code>) — ภาพตัวอย่างสำหรับแสดงการ์ดสายรถ รอแทนที่ด้วยภาพจริง</li>
<li><strong>ภาพจุดสังเกต</strong> (<code>landmarks/</code>) — วัด ตลาด ริมน้ำ ฯลฯ ใช้เป็นภาพตัวอย่าง</li>
<li><strong>ภาพแผนที่เครือข่าย</strong> (<code>network/overview-map.png</code>) — แผนที่ตัวอย่าง</li>
<li><strong>QR code</strong> (<code>qrcode/</code>) — รหัส QR ของสายรถแต่ละสาย</li>
<li><strong>โลโก้ minibus</strong> (<code>icons/</code>) — โลโก้และ favicon ของเว็บ</li>
<li><strong>maintheme.png</strong> — ภาพดีไซน์ต้นแบบ (theme reference) ของโปรเจกต์</li>
</ul>
</section>
<section class="mu-credit-section">
<h2><span data-i18n="credits.logos">โลโก้ผู้สนับสนุนและพาร์ทเนอร์</span></h2>
<p class="src">โฟลเดอร์ <code>.image/partners/</code> — โลโก้เป็นเครื่องหมายการค้าของบริษัทเจ้าของแต่ละราย</p>
<ul>
<li>7-Eleven, Shopee, Lazada, airasia MOVE, busonlineticket, Trip.com, truck2hand, ทีซีแอล 999 อ่างทอง, รถบัสปิ่นเกล้า</li>
<li>โลโก้เหล่านี้ใช้เพื่อแสดงรายชื่อผู้สนับสนุน/พันธมิตรเท่านั้น สิทธิ์ทั้งหมดเป็นของเจ้าของ</li>
</ul>
</section>
<section class="mu-credit-section">
<h2><span data-i18n="credits.data">ข้อมูลการเดินรถ</span></h2>
<ul>
<li>ข้อมูลเส้นทาง ตารางเวลา และจุดจอด อ้างอิงจากข้อมูลผู้ประกอบการรถโดยสารและสถานีขนส่งผู้โดยสาร (บขส.)</li>
<li>ข้อมูลใน mockup นี้เป็น <strong>ข้อมูลตัวอย่าง</strong> (<code>resource/data/*.json</code>) สำหรับการพัฒนา — ยังไม่ใช่ข้อมูลจริงที่อัปเดตล่าสุด</li>
</ul>
</section>
<section class="mu-credit-section">
<h2><span data-i18n="credits.pwa">โหมดออฟไลน์ (PWA / Service Worker)</span></h2>
<p class="src">พัฒนาโดยทีม Atroute — ไม่ใช้ไลบรารีภายนอก</p>
<ul>
<li>เว็บนี้เป็น Progressive Web App — ติดตั้งได้ (Add to Home Screen) และเปิดใช้งานได้เมื่อไม่มีอินเทอร์เน็ต</li>
<li>อัปเดตเนื้อหาอัตโนมัติ: เมื่อเปิดเว็บ ระบบจะตรวจสอบเวอร์ชันใหม่และโหลดให้เอง — ผู้ใช้ไม่ต้องล้างแคช</li>
<li>ไฟล์ที่เกี่ยวข้อง: <code>ui/sw.js</code>, <code>ui/pwa.js</code>, <code>ui/manifest.json</code></li>
</ul>
</section>
<section class="mu-credit-section">
<h2><span data-i18n="credits.notes">หมายเหตุ</span></h2>
<ul>
<li>เว็บนี้เป็นต้นแบบ (prototype) สำหรับพัฒนาเว็บข้อมูลการเดินรถของสถานีขนส่งผู้โดยสารจังหวัดอ่างทอง</li>
<li>หากใช้ทรัพยากรใดผิดข้อกำหนดของเจ้าของ กรุณาแจ้งทีมพัฒนาเพื่อแก้ไขทันที</li>
</ul>
</section>
</div>
</main>
+10 -11
View File
@@ -86,12 +86,6 @@
stationSelect.innerHTML = '';
var list = stationsFor(provinceId);
/* ตัวเลือกแรก = ทุกสถานีในจังหวัด (ค่าเริ่มต้น → แสดงทุกสาย) */
var all = document.createElement('option');
all.value = '';
all.textContent = tr('home.allStations');
stationSelect.appendChild(all);
list.forEach(function (st) {
var opt = document.createElement('option');
opt.value = st.station_code; /* ใช้รหัสสถานี = ลิงก์สั้น อ่านง่าย */
@@ -100,8 +94,11 @@
});
if (!list.length) {
all.textContent = tr('home.stationEmpty');
all.disabled = true;
var none = document.createElement('option'); /* ไม่มีสถานีในจังหวัดนี้ → บอกด้วยตัวเลือกว่าง */
none.value = '';
none.textContent = tr('home.stationEmpty');
none.disabled = true;
stationSelect.appendChild(none);
if (stationHint) stationHint.textContent = tr('home.stationEmptyHint') + ' ' + provinceName(provinceId);
} else if (stationHint) {
stationHint.innerHTML = tr('home.stationCount', { n: list.length }) + ' ' + provinceName(provinceId);
@@ -109,7 +106,9 @@
/* คืนค่าที่เลือกไว้ (จากลิงก์) ถ้ามีในจังหวัดนี้ */
if (preferredCode && list.some(function (s) { return s.station_code === preferredCode; })) {
stationSelect.value = preferredCode;
stationSelect.value = preferredCode; /* จากลิงก์แชร์ (?s=) */
} else if (list.length) {
stationSelect.value = list[0].station_code; /* ไม่มีตัวเลือก "ทุกสถานี" แล้ว → เลือกสถานีแรก */
} else {
stationSelect.value = '';
}
@@ -200,12 +199,12 @@
fetchJSON(DATA_URL.routeGroups),
fetchJSON(DATA_URL.routes),
fetchJSON(DATA_URL.routesMunicipal),
fetchJSON(DATA_URL.schedules)
(window.Schedules ? Schedules.load().then(function (sd) { return Schedules.normSub(sd); }) : fetchJSON(DATA_URL.schedules))
]).then(function (res) {
var groups = ((res[0] || {}).route_groups) || [];
var routes = ((res[1] || {}).routes) || [];
var municipal = ((res[2] || {}).routes) || [];
var recs = (res[3] || {}).schedules || res[3] || [];
var recs = window.Schedules ? Schedules.records(res[3]) : ((res[3] || {}).schedules || res[3] || []);
if (!groups.length || !routes.length) return;
/* รวมเส้นทางหมวดเทศบาลจากไฟล์แยก (ข้ามแถวที่ยังไม่ได้กรอก) */
+151
View File
@@ -0,0 +1,151 @@
/* ============================================================
otherStop.js — ตัวอ่าน '8 other_stop.json' (ใช้ร่วมทุกหน้า)
ทำไมต้องมี: จุดจอด station_id 8 คือ "จุดขึ้นรถประจำทางอื่นๆ" ซึ่งเป็นชื่อรวม ๆ
ของทุกสาย — ตัวจริงของแต่ละสายอยู่ใน '8 other_stop.json' เช่น
{ "route_id": "1101", "station_name_th": "วัดสีบัวทอง", ... } ← 1101 คือสาย 1011
ไฟล์นี้จึงต้อง "จับคู่ route id" ก่อน แล้วค่อยเอาชื่อ/พิกัดจริงของสายนั้นไปแสดง
(เช่น หน้าป้ายต้องขึ้น "จุดขึ้นรถประจำทางอื่นๆ · วัดสีบัวทอง")
API:
OtherStop.load() → Promise<entry[]> (โหลดครั้งเดียวแล้ว cache)
OtherStop.fileRouteId(entry) → รหัสสายตามที่เขียนในไฟล์
OtherStop.resolve(fileRouteId, validIds) → { id, alias } | null
OtherStop.forRoute(entries, routeId, validIds) → entry | null
OtherStop.forStation(entries, station, routeId, validIds) → entry | null
OtherStop.stopsOf(entry) → [{ name, lat, lng, hasCoord, city_th, province_th, index }]
OtherStop.firstName(entry) → ชื่อจุดแรก (ใช้เป็นชื่อย่อของสาย)
OtherStop.allStops(entries, routeId, validIds) → รายการจุดจริง "ทุกจุด" ของสายนั้น
· แต่ละจุดมี offsetMin = นาทีจากจุดแรก (ถ้าไฟล์ใส่ "offsets_min") → ใช้คำนวณเวลาของจุดนั้นได้
· ฟิลด์ในไฟล์: station_name_th[], latitude[], longitude[], offsets_min[] (จับคู่ตามลำดับ)
============================================================ */
(function () {
'use strict';
var URL = '../resource/data/8%20other_stop.json';
var cache = null;
/* โหลดครั้งเดียว — คืน promise เดิมซ้ำ (ไม่ยิง fetch ซ้ำทุกหน้า) */
function load() {
if (cache) return cache;
cache = fetch(URL, { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (d) { return (d && d.other_stop) || []; })
.catch(function () { return []; });
return cache;
}
function fileRouteId(entry) {
return String((entry && entry.route_id) != null ? entry.route_id : '');
}
/* เทียบรหัสสายแบบ "ทนรหัสเพี้ยน": 1101 → 1011 (ตัวเลขชุดเดียวกัน สลับตำแหน่ง)
ใช้เฉพาะเมื่อรหัสในไฟล์ "ไม่มีจริง" ใน routes.json และหาคู่ได้ไม่กำกวม (1 ตัวเท่านั้น) */
function sameDigits(a, b) {
var na = String(a).replace(/\D/g, ''), nb = String(b).replace(/\D/g, '');
if (!na || na.length !== nb.length) return false;
return na.split('').sort().join('') === nb.split('').sort().join('');
}
function resolve(fid, validIds) {
var want = String(fid);
var valid = (validIds || []).map(String);
if (valid.indexOf(want) !== -1) return { id: want, alias: false };
/* เทียบแบบสลับตำแหน่ง (1101 → 1011) เฉพาะรหัสยาว ≥3 หลัก
— รหัสสั้นอย่าง "51"/"15" มีโอกาสสลับกันได้จริง → ไม่เดา */
var digits = want.replace(/\D/g, '');
if (digits.length < 3) return null;
var cands = valid.filter(function (v) { return sameDigits(v, want); });
if (cands.length === 1) return { id: cands[0], alias: true };
return null; /* ไม่รู้จัก หรือกำกวม → ไม่เดา */
}
function forRoute(entries, routeId, validIds) {
var want = String(routeId);
var hit = (entries || []).filter(function (e) { return fileRouteId(e) === want; })[0];
if (hit) return hit;
/* ถ้ายังไม่เจอ → หา entry ที่รหัสในไฟล์หมายถึงสายนี้ (เช่น 1101 → 1011) */
var found = null;
(entries || []).forEach(function (e) {
if (found) return;
var r = resolve(fileRouteId(e), validIds);
if (r && r.id === want) found = e;
});
return found;
}
/* ทุก entry ที่หมายถึงสายนี้ (สายเดียวมีได้หลายจุดจริง) */
function forRouteAll(entries, routeId, validIds) {
var want = String(routeId);
return (entries || []).filter(function (e) {
if (fileRouteId(e) === want) return true;
var r = resolve(fileRouteId(e), validIds);
return !!(r && r.id === want);
});
}
/* ---------- แตก entry → รายการ "จุดจริง" ของสายนั้น ----------
กติกาข้อมูล (เจ้าของข้อมูลกำหนด):
· station_name_th เป็นได้ทั้งข้อความเดียว หรือรายการหลายชื่อ (เช่น 954 = 4 จุด)
· latitude/longitude เป็นได้ทั้งตัวเลขเดียว หรือรายการ — จับคู่กับชื่อ "ตามลำดับ"
· "พิกัดเป็นของชื่อแรก" → ถ้ามีพิกัดเดียว ชื่อที่ 2 เป็นต้นไป = ยังไม่มีพิกัด (ไม่เดา) */
function num(v) { var n = parseFloat(v); return isNaN(n) ? null : n; }
function stopsOf(entry) {
if (!entry) return [];
var names = [].concat(entry.station_name_th == null ? [] : entry.station_name_th)
.map(function (x) { return String(x == null ? '' : x).trim(); })
.filter(Boolean);
var lats = [].concat(entry.latitude == null ? [] : entry.latitude);
var lngs = [].concat(entry.longitude == null ? [] : entry.longitude);
var offs = [].concat(entry.offsets_min == null ? [] : entry.offsets_min); /* นาทีจากจุดแรก (0 = จุดแรกเอง) */
return names.map(function (name, i) {
var lat = num(lats[i]), lng = num(lngs[i]);
return {
index: i,
name: name,
/* city/province ในไฟล์อธิบาย "จุดแรก" — จุดอื่นไม่ทราบ ไม่เดา */
city_th: i === 0 ? (entry.city_th || null) : null,
province_th: i === 0 ? (entry.province_th || null) : null,
station_type: entry.station_type || null,
note: entry.note || null,
lat: lat, lng: lng,
offsetMin: num(offs[i]), /* ระยะเวลาจากจุดแรก (นาที) — ไม่ใส่ = ไม่ทราบ */
hasCoord: lat != null && lng != null,
entry: entry
};
});
}
function firstName(entry) { var st = stopsOf(entry)[0]; return st ? st.name : null; }
function allStops(entries, routeId, validIds) {
var out = [];
forRouteAll(entries, routeId, validIds).forEach(function (e) { out = out.concat(stopsOf(e)); });
return out;
}
/* ใช้กับ "สถานี 8" (จุดขึ้นรถประจำทางอื่นๆ) เท่านั้น */
function isOtherStop(station) {
if (!station) return false;
return String(station.station_code) === 'other_stop' || Number(station.station_id) === 8;
}
function forStation(entries, station, routeId, validIds) {
if (!isOtherStop(station)) return null;
return forRoute(entries, routeId, validIds);
}
window.OtherStop = {
load: load,
fileRouteId: fileRouteId,
resolve: resolve,
forRoute: forRoute,
forRouteAll: forRouteAll,
isOtherStop: isOtherStop,
forStation: forStation,
stopsOf: stopsOf,
firstName: firstName,
allStops: allStops
};
})();
+618
View File
@@ -0,0 +1,618 @@
/* ============================================================
schedules.js — ตัวอ่านข้อมูลตารางเวลา (ใช้ร่วมทุกหน้า)
***APIs นี้ไม่เปลี่ยนชื่อ/รูปเดิม*** — หน้า check/busDetail/home/stopDetail เรียกเหมือนเดิม
ที่เพิ่มเข้ามาคือ "สมองเรื่องวันทำงาน/วันหยุด" ซึ่งทำงานอยู่ในไฟล์นี้ที่เดียว
รองรับ schedules.json 2 รูปแบบ:
schema 1 (เดิม): { "schedules": [ { route_id, station_id, direction_note, departure_times[], schedule_note } ] }
schema 2 (ใหม่): { "schema": 2, "routes": [ { route_id, station_order[], directions: [
{ dir_id, dir_label, service?, stops: [ { station_id, times[], dir_note?, note?, groups? } ] } ] } ] }
── เรื่องวันทำงาน / วันหยุด (ไม่ต้องแก้โค้ดหน้าไหนเลย) ────────────────
เพิ่มฟิลด์ "ไม่บังคับ" 2 ระดับ:
1) ระดับทิศทาง: "service": "all" | "weekday" | "holiday"
- ทั้งทิศทางใช้เฉพาะวันนั้น (เช่น ทิศ 'ตารางวันหยุด' → service: "holiday")
- ไม่ใส่ = "all" (ทุกวัน) → ไฟล์เดิมไม่ต้องแก้อะไร พฤติกรรมเหมือนเดิมเป๊ะ
2) ระดับจุดจอด: "groups": [ { "label": "วันหยุด", "dayType": "holiday", "times": ["10:00"] } ]
- เวลาที่ "เพิ่มเข้ามาเฉพาะบางวัน" (ตรงกับโน้ตเดิม เช่น "10:00 มีเฉพาะวันหยุด")
- times[] ยังเป็นตารางพื้นฐานที่ใช้ทุกวัน
ค่าเริ่มต้น: ตรวจจากวันที่ของเครื่องเอง (เสาร์–อาทิตย์ = วันหยุด + วันนักขัตฤกษ์จาก holidays.json)
ความปลอดภัย: ถ้ากรองตามวันแล้วไม่เหลือทิศทางใดเลย → ถอยไปใช้ทั้งหมด + ติดธง fallback (หน้าเว็บไม่ว่าง)
API:
Schedules.records(doc, opts) → record แบน (schema เดิม) สำหรับโค้ดเดิม
Schedules.route(doc, routeId, opts) → { route_id, station_order[], directions[], entries[] }
Schedules.directions(doc, routeId, opts) → [{ dir_id, dir_label, service, dayType, fallback, stops[] }]
Schedules.times(doc, routeId, opts) → เวลาทั้งหมดของสาย (เรียงแล้ว)
Schedules.countTrips(doc, routeId, opts) → จำนวนเที่ยวของสาย
Schedules.todayType() → 'weekday' | 'holiday'
Schedules.dayInfo(date) → { dayType, label_th, date }
Schedules.ready → promise (โหลด holidays.json เสร็จ)
opts ที่รับได้: { dayType: 'all' | 'weekday' | 'holiday' } (ไม่ส่ง = ตรวจจากวันนี้)
============================================================ */
(function () {
'use strict';
var DATA_URL = '../resource/data/';
var HOLIDAYS = [];
var ALIAS = { weekend: 'holiday', 'sat-sun': 'holiday', saturday: 'holiday', sunday: 'holiday', workday: 'weekday', weekday: 'weekday', holiday: 'holiday', all: 'all' };
/* ความเร็วเฉลี่ยตั้งต้นสำหรับคำนวณเวลาจุดที่ไม่มีตาราง (ปรับต่อทิศได้ด้วย "speedKmh") */
var DEFAULT_SPEED_KMH = 40;
function pad2(n) { return (n < 10 ? '0' : '') + n; }
function toMin(hhmm) {
var a = String(hhmm).split(':');
var h = parseInt(a[0], 10), m = parseInt(a[1], 10);
return (isNaN(h) ? 0 : h) * 60 + (isNaN(m) ? 0 : m);
}
/* คำนวณเวลาของจุดที่ไม่มีตาราง จากจุดที่มีเวลาแล้วซึ่งอยู่ใกล้ที่สุดตามระยะทาง (กม.)
คืน null เมื่อคำนวณไม่ได้ (ไม่มี กม. หรือไม่มีจุดอ้างอิง) */
function computeTimes(stop, siblings, opts) {
var o = (typeof opts === 'number') ? { speedKmh: opts } : (opts || {});
var speed = Number(o.speedKmh) > 0 ? Number(o.speedKmh) : DEFAULT_SPEED_KMH;
if (!stop || typeof stop.km !== 'number') return null;
var cands = siblings.filter(function (s) {
return s !== stop && typeof s.km === 'number' && (s.times || []).length;
});
if (!cands.length) return null;
var base = null;
if (o.baseSid != null) { /* ผู้ใช้เลือกจุดอ้างอิงเอง (จากเครื่องมือแก้ไข) */
base = cands.filter(function (s) { return String(s.station_id) === String(o.baseSid); })[0] || null;
}
if (!base && o.baseEnd === 'first') { /* ใช้เวลาจริงจากจุดต้นทาง (กม. น้อยสุด) */
base = cands.reduce(function (a, b) { return a.km <= b.km ? a : b; });
} else if (!base && o.baseEnd === 'last') { /* ใช้เวลาจริงจากจุดปลายทาง (กม. มากสุด) */
base = cands.reduce(function (a, b) { return a.km >= b.km ? a : b; });
} else if (!base) { /* อัตโนมัติ: จุดที่มีเวลาซึ่งใกล้ที่สุด */
base = cands.reduce(function (a, b) { return Math.abs(b.km - stop.km) < Math.abs(a.km - stop.km) ? b : a; });
}
var delta = (stop.km - base.km) / speed * 60; /* นาที (+ ไปข้างหน้า, - ย้อนหลัง) */
return base.times.map(function (t) {
var tot = Math.round(toMin(t) + delta);
tot = ((tot % 1440) + 1440) % 1440;
return pad2(Math.floor(tot / 60)) + ':' + pad2(tot % 60);
});
}
/* ความเร็วที่ใช้จริงของทิศหนึ่ง ๆ: มาจาก travelMin (เวลาเดินทางทั้งเส้น) ถ้ามี ไม่งั้นใช้ speedKmh/ค่าตั้งต้น */
function speedOf(dir) {
if (Number(dir.travelMin) > 0) {
var kms = (dir.stops || []).map(function (s) { return s.km; }).filter(function (x) { return typeof x === 'number'; });
if (kms.length > 1) {
var span = Math.max.apply(null, kms) - Math.min.apply(null, kms);
if (span > 0) return { kmh: span / Number(dir.travelMin) * 60, span: span, source: 'travelMin' };
}
}
return { kmh: Number(dir.speedKmh) > 0 ? Number(dir.speedKmh) : DEFAULT_SPEED_KMH, span: null, source: 'speedKmh' };
}
function hasSchema2(doc) {
return !!(doc && doc.schema === 2 && Array.isArray(doc.routes));
}
function normSub(doc) { /* เตรียมไฟล์ย่อยให้อยู่ในรูป { routes: [...] } */
if (!doc) return null;
if (doc.route_id != null && !Array.isArray(doc.routes)) {
var dirs = isSchema3(doc) ? directionsFromSchema3(doc) : (doc.directions || []);
return { schema: 2, routes: [{ route_id: doc.route_id, station_order: doc.station_order || [], directions: dirs }] };
}
return doc;
}
/* ---------- schema 3: { weekday:{directions:{...}}, holiday:{directions:{...}} } ----------
โครงอ่านง่ายสำหรับเจ้าของข้อมูล (กลุ่มวัน → ทิศทาง) · แปลงเป็นทิศภายในให้ทุกหน้าใช้ต่อได้เหมือนเดิม
กติกา: จุดที่ระบุเวลามา = จุดตั้งต้นของทิศนั้น · จุดอื่นใน station_order คำนวณจาก กม.+ความเร็ว (ถ้าเปิด autoTimes) */
var DAYGROUP = { weekday: 'weekday', holiday: 'holiday' };
function isSchema3(doc) { return !!(doc && doc.schema === 3 && (doc.weekday || doc.holiday)); }
function directionsFromSchema3(doc) {
var out = [];
['weekday', 'holiday'].forEach(function (kind) {
var grp = doc[kind];
if (!grp || !grp.directions) return;
Object.keys(grp.directions).forEach(function (name) {
var src = grp.directions[name] || {};
var times = (src.departures || src.times || []).slice();
var from = (src.from_station_id != null) ? Number(src.from_station_id) : null;
var stops = [];
if (from != null && times.length) {
stops.push({ station_id: from, times: times, dir_note: grp.label || null });
} else if (from != null) {
stops.push({ station_id: from, times: [], dir_note: grp.label || null });
}
out.push({
dir_id: kind + ':' + name,
dir_label: name,
service: { day: kind, from: 'schema 3', matches: kind === todayType() },
station_order: doc.station_order || [],
stops: stops,
/* จุดตั้งต้นมีเวลาแล้ว → ให้จุดอื่นคำนวณต่อจาก กม. เฉพาะเมื่อเปิด autoTimes */
autoTimes: !!doc.autoTimes
});
});
});
return out;
}
/* ---------- ชื่อจุดจอด (สำหรับข้อความ "คำนวณจาก ...") ----------
โหลดเบื้องหลังครั้งเดียว — ถ้ายังไม่ทัน ก็ถอยไปใช้รหัสจุดในข้อความ (ไม่พัง) */
var STATION_NAMES = {};
var namesWarmed = false;
function warmStations() {
if (namesWarmed) return;
namesWarmed = true;
fetch(DATA_URL + 'stations.json', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (d) {
((d && d.stations) || []).forEach(function (st) { STATION_NAMES[String(st.station_id)] = st.station_name_th; });
})
.catch(function () {});
}
function stationNameOf(id) { return STATION_NAMES[String(id)] || null; }
/* หน้าเว็บที่โหลด stations.json อยู่แล้วส่งชื่อเข้ามาได้ → ข้อความหมายเหตุมีชื่อทันที (ไม่ต้องรอ fetch) */
function setStationNames(list) {
((list && list.stations) || list || []).forEach(function (st) {
if (st && st.station_id != null) STATION_NAMES[String(st.station_id)] = st.station_name_th;
});
}
/* เรียกทันทีตอนไฟล์ถูกโหลด — จะทันรอบเรนเดอร์แรก (ชื่อจุดอ้างอิงในข้อความ "คำนวณจาก ...") */
warmStations();
/* ---------- เลื่อนเวลาเป็นนาที (กฎ derive: จุดนี้ = เวลาจุดอ้างอิง ± offset) ----------
คืน HH:MM เรียงใหม่ · เกินเที่ยงคืน = วนกลับ (ไม่พัง) */
function shiftTimes(times, offsetMin) {
var off = Number(offsetMin) || 0;
return (times || []).map(function (t) {
var a = String(t).split(':');
var m = (parseInt(a[0], 10) || 0) * 60 + (parseInt(a[1], 10) || 0) + off;
m = ((m % 1440) + 1440) % 1440;
var hh = Math.floor(m / 60), mm = m % 60;
return (hh < 10 ? '0' : '') + hh + ':' + (mm < 10 ? '0' : '') + mm;
}).sort();
}
/* ป้ายผลต่างเวลา เช่น +30 / −15 (ใช้ในข้อความหมายเหตุ) */
function offsetLabel(min) {
var n = Number(min) || 0;
var sign = n < 0 ? '\u2212' : '+';
return sign + Math.abs(n);
}
/* ---------- เครื่องยนต์ตรวจวัน (จันทร์–อาทิตย์) ----------
ทำงานที่ท่อกลางนี้ที่เดียว → ทุกหน้าได้ผลเหมือนกัน ไม่ต้องแก้โค้ดหน้าไหน
ลำดับการตัดสิน:
1) ถ้าทิศมี "days" ระบุตรง ๆ (อา จ อ พ พฤ ศ ส) → ใช้ตามนั้น (แม่นสุด)
2) ถ้ามี service = weekday/holiday → เทียบกับวันนี้
3) ถ้าไม่มีอะไรระบุ → อ่านคำใน dir_label / dir_note / note ของสายนั้น (ตรวจคำอัตโนมัติ)
4) ตัดสินไม่ได้ → แสดงทุกวัน (ไม่ซ่อนข้อมูล) พร้อมป้ายว่า "ยังไม่ระบุวัน" */
var DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; /* ตรงกับ Date.getDay() */
var DAY_TH = { sun: 'อาทิตย์', mon: 'จันทร์', tue: 'อังคาร', wed: 'พุธ', thu: 'พฤหัสบดี', fri: 'ศุกร์', sat: 'เสาร์' };
var DAY_ABBR = { sun: 'อา', mon: 'จ', tue: 'อ', wed: 'พ', thu: 'พฤ', fri: 'ศ', sat: 'ส' };
var DAY_ALIAS = { /* รับได้หลายชื่อ */
weekday: 'weekday', workday: 'weekday', 'วันทำงาน': 'weekday', 'จ-ศ': 'weekday', 'จ–ศ': 'weekday',
holiday: 'holiday', weekend: 'holiday', 'วันหยุด': 'holiday', 'ส-อา': 'holiday', 'ส–อา': 'holiday', 'เสาร์-อาทิตย์': 'holiday',
all: 'all', ทุกวัน: 'all', daily: 'all'
};
var DAY_WORDS_HOLIDAY = ['วันหยุด', 'นักขัตฤกษ์', 'เสาร์-อาทิตย์', 'เสาร์–อาทิตย์', 'ส-อา', 'ส–อา', 'weekend', 'holiday'];
var DAY_WORDS_WEEKDAY = ['วันทำงาน', 'วันธรรมดา', 'จ-ศ', 'จ–ศ', 'จันทร์ถึงศุกร์', 'weekday', 'workday'];
function ymd(d) {
var m = d.getMonth() + 1, day = d.getDate();
return d.getFullYear() + '-' + (m < 10 ? '0' : '') + m + '-' + (day < 10 ? '0' : '') + day;
}
function dayKey(date) { return DAYS[(date || new Date()).getDay()]; }
function isHolidayDate(date, list) {
var list_ = list || HOLIDAYS;
if (list_.indexOf(ymd(date)) !== -1) return true; /* นักขัตฤกษ์ */
var wd = (date.getDay() + 6) % 7; /* 0 = จันทร์ */
return wd >= 5; /* เสาร์–อาทิตย์ = วันหยุด */
}
function dayTypeOf(date, list) { return isHolidayDate(date || new Date(), list) ? 'holiday' : 'weekday'; }
function todayType(date) { return dayTypeOf(date); }
function dayInfo(date) {
var d = date || new Date();
var t = dayTypeOf(d);
return { dayType: t, weekday: DAYS[d.getDay()], weekday_th: DAY_TH[DAYS[d.getDay()]], date: ymd(d),
label_th: t === 'holiday' ? 'วันหยุด (ส–อา/นักขัตฤกษ์)' : 'วันทำงาน (จ–ศ)' };
}
/* ตรวจคำในข้อความ (dir_label / dir_note / note) ว่าหมายถึงวันไหน */
function detectDay(text) {
var t = String(text == null ? '' : text).trim();
if (!t) return null;
var low = t.toLowerCase();
var hitH = DAY_WORDS_HOLIDAY.filter(function (w) { return low.indexOf(w.toLowerCase()) !== -1; })[0];
var hitW = DAY_WORDS_WEEKDAY.filter(function (w) { return low.indexOf(w.toLowerCase()) !== -1; })[0];
if (hitH && !hitW) return { day: 'holiday', from: 'คำ', text: t };
if (hitW && !hitH) return { day: 'weekday', from: 'คำ', text: t };
return null; /* เจอทั้งคู่/ไม่เจอ = ไม่เดา */
}
/* รวบข้อความทั้งหมดของทิศ (label + โน้ตของทุกจุด) แล้วตรวจหา "วัน" ให้สอดคล้องกันทั้งทิศ
คืน { day, from, text } หรือ null (ยังไม่ระบุ) */
function detectDayOfDir(d) {
var texts = [];
if (d && d.dir_label) texts.push(d.dir_label);
((d && d.stops) || []).forEach(function (s) {
if (s.dir_note) texts.push(s.dir_note);
if (s.note) texts.push(s.note);
});
var verdicts = [], conflicts = false, hasHol = false, hasWk = false, sample = null;
texts.forEach(function (t) {
var v = detectDay(t);
if (!v) { return; }
if (v.day === 'holiday') { hasHol = true; } else { hasWk = true; }
verdicts.push(v); if (!sample) sample = v;
});
if (!verdicts.length) return null;
if (hasHol && hasWk) { /* ทิศเดียวมีทั้งสองวัน */
return { day: 'all', from: 'ปนกัน', text: sample.text, conflict: true };
}
return { day: verdicts[0].day, from: 'คำในโน้ต', text: sample.text };
}
/* วันนี้ตรงกับทิศนี้ไหม + บอกเหตุผล (ใช้แสดงบนหน้าเว็บได้) */
function serviceOf(obj, dirForDetect) {
if (obj && obj.days && obj.days.length) { /* ระบุวันตรง ๆ มาก่อน */
return { day: 'custom', days: obj.days.map(String), from: 'ระบุตรง', matches: obj.days.map(String).indexOf(dayKey()) !== -1 };
}
var s = (obj && obj.service) ? String(obj.service).toLowerCase() : '';
var alias = DAY_ALIAS[s] || (DAY_ALIAS[String(obj && obj.service)] || '');
if (alias === 'weekday' || alias === 'holiday') {
return { day: alias, from: 'service', matches: alias === todayType() };
}
if (alias === 'all') return { day: 'all', from: 'service', matches: true };
var det = detectDayOfDir(dirForDetect || obj); /* ไม่ระบุ → ตรวจจากคำ */
if (det) {
if (det.day === 'all') return { day: 'all', from: det.from + ' (ปนกัน)', text: det.text, conflict: true, matches: true };
return { day: det.day, from: det.from, text: det.text, matches: det.day === todayType() };
}
return { day: 'all', from: 'ไม่ระบุ', unknown: true, matches: true }; /* ไม่รู้ = แสดง (ไม่ซ่อนข้อมูล) */
}
function normDay(opts) {
if (opts && opts.dayType) return DAY_ALIAS[String(opts.dayType).toLowerCase()] || 'all';
return todayType();
}
/* ตัดสินว่าทิศนี้ใช้กับวันที่กำลังดูอยู่ไหม
service = ผลจาก serviceOf() → { day, matches, conflict?, unknown? } */
function applies(info, day) {
if (!day || day === 'all') return true; /* ไม่ระบุวัน = ดูทุกวัน */
if (!info || typeof info !== 'object') return true;
if (info.unknown) return true; /* ยังไม่ระบุวัน → แสดง (ไม่ซ่อนข้อมูล) */
if (info.conflict) return true; /* ทิศเดียวมีทั้ง 2 ตาราง → ซ่อนไม่ได้ (จะหายข้อมูล) */
if (info.day === 'custom') { /* ระบุวันตรง ๆ (days[]) */
return !info.days || info.days.indexOf(dayKey(dayDate(day))) !== -1;
}
return info.day === 'all' || info.day === day; /* เทียบกับวันที่กำลังดู ไม่ใช่ค่าของวันนี้ */
}
/* 'weekday' / 'holiday' → วันที่สมมติขึ้นมา (ใช้ตรวจ days[] ให้ตรงกับวันที่ขอ) */
function dayDate(day) {
var d = new Date();
if (day === 'weekday') { var wd = (d.getDay() + 6) % 7; d.setDate(d.getDate() - wd); }
else if (day === 'holiday') { var wd2 = (d.getDay() + 6) % 7; d.setDate(d.getDate() + (5 - wd2)); }
return d;
}
function normDay(opts) {
if (opts && opts.dayType) return ALIAS[String(opts.dayType).toLowerCase()] || 'all';
return todayType(); /* ค่าเริ่มต้น: ตรวจจากวันนี้ */
}
/* เวลาของจุดจอด ณ วันหนึ่ง ๆ = times พื้นฐาน + groups ที่ตรงกับวันนั้น */
/* timesFor(stop, day) — day ที่ส่งมา (weekday/holiday) = "วันเป้าหมาย" ที่ต้องการดู
ทิศที่ผ่านการกรองวันมาแล้วจะส่ง day='all' → คืน times ตรง ๆ · ส่วนที่ยังไม่แยกวันใช้ groups แยกเอง */
function timesFor(stop, day) {
var groups = (stop && stop.groups) || [];
if (!groups.length) return (stop && stop.times ? stop.times : []).slice();
var out = ((stop && stop.times) || []).slice(); /* เวลาที่ไม่ผูกวัน = ใช้ทุกวัน */
groups.forEach(function (g) {
var gt = g.dayType ? (ALIAS[String(g.dayType).toLowerCase()] || 'all') : 'all';
if (gt !== 'all' && day && day !== 'all' && gt !== day) return;
out = out.concat(g.times || []);
});
return out;
}
/* ---------- โหลดข้อมูล: schedules.json เป็นได้ทั้ง "ไฟล์รวม" และ "สารบัญ" ----------
- สารบัญ (index: true): routes[] มี { route_id, file } → โหลดเฉพาะไฟล์ของสายที่ขอ (lazy + cache)
- ไฟล์รวม (schema 2 เดิม): มี routes[] พร้อม directions ในตัว → ใช้ได้เหมือนเดิมไม่ต้องแก้โค้ดเก่า
- schema 1 เดิม: { schedules: [...] } → ใช้ได้เหมือนเดิม */
var SUBS = {}; /* cache ไฟล์ย่อยต่อสาย */
var subsReady = null;
function loadSubs() {
if (subsReady) return subsReady;
subsReady = fetch(DATA_URL + 'schedules.json', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (d) {
if (!d || !d.index) return d; /* ไฟล์รวม → คืนทั้งไฟล์ */
var rows = d.routes || [];
return Promise.all(rows.map(function (row) {
var file = row.file || ('schedules' + row.route_id + '.json');
return fetch(DATA_URL + 'scheduleslist/' + file, { cache: 'no-store' })
.then(function (x) { return x.ok ? x.json() : null; })
.then(function (sub) {
if (!sub) return null;
var dirs = isSchema3(sub) ? directionsFromSchema3(sub) : (sub.directions || []);
SUBS[String(sub.route_id)] = { route_id: sub.route_id, station_order: sub.station_order || [],
directions: dirs, schema3: isSchema3(sub) };
return SUBS[String(sub.route_id)];
}).catch(function () { return null; });
})).then(function (list) {
var routes = list.filter(Boolean);
return { schema: 2, index: true, routes: routes };
});
})
.catch(function () { return null; });
return subsReady;
}
/* โหลดสายเดียว (เร็ว — ใช้ตอนเปิดหน้า check/routes ของสายนั้น) */
function loadRoute(rid) {
var key = String(rid);
if (SUBS[key]) return Promise.resolve({ schema: 2, routes: [SUBS[key]] });
if (!subsReady) return loadSubs().then(function () { return SUBS[key] ? { schema: 2, routes: [SUBS[key]] } : null; });
return Promise.resolve(SUBS[key] ? { schema: 2, routes: [SUBS[key]] } : null);
}
/* ---------- ระยะทาง กม. (ไฟล์แยก resource/data/stop-km.json — สร้างโดย resource/tools/stop-km.py) ----------
แยกไฟล์เพราะ schedules.json เป็นไฟล์ที่คนแก้มือ ถ้าเอาค่าคำนวณไปฝังไว้ พอบันทึกทับจากสำเนาเก่าจะหายทั้งชุด */
var KM = {};
var kmReady = null;
function loadKm() {
if (kmReady) return kmReady;
kmReady = fetch(DATA_URL + 'stop-km.json', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (d) {
KM = (d && typeof d === 'object') ? d : {};
try { window.dispatchEvent(new CustomEvent('schedules:km', { detail: { routes: Object.keys(KM).length } })); } catch (e) { }
return KM;
})
.catch(function () { KM = {}; return KM; });
return kmReady;
}
function absKm(rid, sid) {
var r = KM[String(rid)];
if (!r) return null;
var v = r[String(sid)];
return (typeof v === 'number') ? v : null;
}
/* km ของจุดในทิศนั้น — พลิกให้ "เพิ่มขึ้นตามทางที่รถวิ่ง" เพื่อให้ผลต่างมีเครื่องหมายถูกต้องเอง
(ลำดับจุดในทิศ + กม.จริงบนเส้น เป็นตัวบอกทิศ) */
function relKms(rid, stops) {
var abs = (stops || []).map(function (s, i) {
var k = (s && typeof s.km === 'number') ? s.km : (s ? absKm(rid, s.station_id) : null);
return (typeof k === 'number') ? { i: i, k: k } : null;
});
var known = abs.filter(Boolean);
if (known.length < 2) {
return (stops || []).map(function (s) {
if (s && typeof s.km === 'number') return s.km;
return s ? absKm(rid, s.station_id) : null;
});
}
var forward = known[known.length - 1].k >= known[0].k; /* ทิศนี้วิ่งจาก กม. น้อย → มาก ใช่ไหม */
var max = known.reduce(function (a, b) { return b.k > a ? b.k : a; }, known[0].k);
return abs.map(function (x) { if (!x) return null; return forward ? x.k : (max - x.k); });
}
/* โหลด holidays.json ครั้งเดียว (ถ้าไม่มีไฟล์ → ใช้กฎเสาร์–อาทิตย์) */
var ready = null;
function loadHolidays() {
if (ready) return ready;
ready = fetch(DATA_URL + 'holidays.json', { cache: 'no-store' })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (d) {
HOLIDAYS = (d && Array.isArray(d.holidays)) ? d.holidays.slice() : [];
try { window.dispatchEvent(new CustomEvent('schedules:ready', { detail: { holidays: HOLIDAYS.length } })); } catch (e) { }
return HOLIDAYS;
})
.catch(function () { HOLIDAYS = []; return HOLIDAYS; });
return ready;
}
/* ---------- ทิศทางของสาย (กรองตามวัน + ถอยกลับถ้าว่าง) ---------- */
function directions(doc, routeId, opts) {
var rid = String(routeId);
var list = [];
if (hasSchema2(doc)) {
var r = (doc.routes || []).filter(function (x) { return String(x.route_id) === rid; })[0];
if (!r) return [];
list = (r.directions || []).map(function (d) {
return {
dir_id: d.dir_id,
dir_label: d.dir_label,
days: Array.isArray(d.days) ? d.days.map(String) : null, /* ระบุวันตรง ๆ (อา จ อ พ พฤ ศ ส) */
service: serviceOf(d, d), /* ตรวจวัน + เหตุผล (จากคำ/service/days) */
autoTimes: !!d.autoTimes, /* true = คำนวณจุดที่ไม่มีตารางให้ */
autoFor: Array.isArray(d.autoFor) ? d.autoFor.slice() : null, /* จำกัดเฉพาะจุดเหล่านี้ (ไม่ใส่ = ทุกจุดที่ว่าง) */
travelMin: Number(d.travelMin) > 0 ? Number(d.travelMin) : null, /* เวลาเดินทางทั้งเส้น (นาที) */
baseEnd: (d.baseEnd === 'first' || d.baseEnd === 'last') ? d.baseEnd : null, /* มีเวลาจริงที่ปลายไหน */
baseSid: (d.baseSid != null ? d.baseSid : null), /* หรือระบุจุดอ้างอิงตรง ๆ */
speedKmh: Number(d.speedKmh) > 0 ? Number(d.speedKmh) : DEFAULT_SPEED_KMH,
stops: (d.stops || []).map(function (s) {
return {
station_id: s.station_id,
times: s.times || [],
km: (typeof s.km === 'number') ? s.km : null, /* กม. จากต้นทาง (วัดโดย resource/tools/stop-km.py) */
dir_note: s.dir_note || null,
note: s.note || null,
groups: s.groups || null,
derive: s.derive || null /* กฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" */
};
})
};
});
} else {
/* schema 1 → ยังใช้ได้เหมือนเดิม (ไม่แยกวัน) */
list = [{ dir_id: 'all', dir_label: null, service: 'all', stops: (doc && doc.schedules ? doc.schedules : []).filter(function (r) {
return String(r.route_id) === rid;
}).map(function (r) {
return { station_id: r.station_id, times: r.departure_times || [], dir_note: r.direction_note || null, note: r.schedule_note || null, groups: null };
}) }];
}
var day = normDay(opts);
var kept = list.filter(function (d) { return applies(d.service, day); }); /* service = ผลตรวจวันของทิศนั้น */
var fallback = false;
if (!kept.length && list.length) { kept = list.slice(); fallback = true; } /* ห้ามปล่อยว่าง */
warmStations(); /* เพื่อให้ข้อความ "คำนวณจาก ..." มีชื่อจุด */
/* เวลาจริงรายจุดของ "ทั้งสาย" — กฎ derive อ้างจุดข้ามทิศได้ (เช่น 902: จุด 15 ← จุด 6 คนละทิศ) */
var realByStation = {};
(kept.length ? kept : list).forEach(function (d) {
(d.stops || []).forEach(function (s) {
var t0 = timesFor(s, day === 'all' ? 'all' : day);
if (t0.length && !realByStation[String(s.station_id)]) realByStation[String(s.station_id)] = t0;
});
});
return kept.map(function (d) {
var kms = relKms(rid, d.stops); /* km ตามทางที่รถวิ่ง (จากไฟล์ stop-km.json) */
/* ใส่ km ให้ "ทุกจุด" ก่อน — ต้องมีครบทั้งชุด ระบบหาจุดอ้างอิง/คำนวณความเร็วถึงจะทำงานได้ */
var withKm = d.stops.map(function (s, si) {
var c = {};
for (var k in s) c[k] = s[k];
if (typeof c.km !== 'number' && typeof kms[si] === 'number') c.km = kms[si];
return c;
});
var speed = speedOf({ travelMin: d.travelMin, speedKmh: d.speedKmh, stops: withKm });
var stops = withKm.map(function (s) {
var t = timesFor(s, day === 'all' ? 'all' : day);
var est = false;
var estFrom = null; /* ถ้าเป็นเวลาที่คำนวณ → ข้อมูลจุดอ้างอิง */
/* ★ กฎของเจ้าของข้อมูล: "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" (เขียนครั้งเดียวในไฟล์สาย) */
if (s.derive && s.derive.from_station_id != null) {
var src = realByStation[String(s.derive.from_station_id)];
if (src && src.length) {
t = shiftTimes(src, s.derive.offset_min);
est = true;
estFrom = { station_id: Number(s.derive.from_station_id),
name: stationNameOf(s.derive.from_station_id),
offsetMin: Number(s.derive.offset_min) || 0,
overrode: (timesFor(s, 'all').length > 0) };
}
}
if (!est && d.autoTimes && !t.length) { /* ไม่มีตารางจริง → คำนวณจากจุดที่มีเวลา + กม. */
var only = d.autoFor && d.autoFor.length
? d.autoFor.map(String).indexOf(String(s.station_id)) !== -1
: true; /* ไม่ระบุ autoFor = ทุกจุดที่ว่าง */
if (only) {
var calc = computeTimes(s, withKm, { speedKmh: speed.kmh, baseEnd: d.baseEnd, baseSid: d.baseSid });
if (calc && calc.length) { t = calc; est = true; }
}
}
return { station_id: s.station_id, times: t, km: s.km, dir_note: s.dir_note, note: s.note,
groups: s.groups, estimated: est, estimateFrom: estFrom, derive: s.derive || null };
});
return { dir_id: d.dir_id, dir_label: d.dir_label, service: d.service, days: d.days, autoTimes: d.autoTimes,
travelMin: d.travelMin, baseEnd: d.baseEnd, baseSid: d.baseSid, autoFor: d.autoFor,
speedKmh: Math.round(speed.kmh * 10) / 10,
speedFrom: speed.source, dayType: day, fallback: fallback, stops: stops };
});
}
/* ---------- schema 2 → record แบน (คง API เดิม) ---------- */
function records(doc, opts) {
if (!doc) return [];
if (!hasSchema2(doc)) return doc.schedules || (Array.isArray(doc) ? doc : []);
var out = [];
(doc.routes || []).forEach(function (r) {
directions(doc, r.route_id, opts).forEach(function (d) {
(d.stops || []).forEach(function (s) {
out.push({
route_id: r.route_id,
station_id: s.station_id,
direction_note: s.dir_note || null,
dir_label: d.dir_label || null, /* ชื่อทิศ (ป่าโมกไปอยุธยา ฯลฯ) — ใช้เป็นหัวแถว */
departure_times: s.times || [],
schedule_note: s.note || null,
estimated: !!s.estimated, /* true = เวลาคำนวณ ไม่ใช่ตารางจริง */
estimateFrom: s.estimateFrom || null, /* { station_id, name, offsetMin } เมื่อคำนวณ */
km: s.km,
dir_id: d.dir_id,
service: d.service,
days: d.days,
dayType: d.dayType,
fallback: d.fallback
});
});
});
});
return out;
}
/* ---------- ข้อมูลของสายเดียว ---------- */
function route(doc, routeId, opts) {
var rid = String(routeId);
var entries = records(doc, opts).filter(function (r) { return String(r.route_id) === rid; });
var dirs = directions(doc, rid, opts);
var order = [];
if (hasSchema2(doc)) {
var r = (doc.routes || []).filter(function (x) { return String(x.route_id) === rid; })[0];
if (r && r.station_order) order = r.station_order.slice();
}
if (!order.length) {
entries.forEach(function (r) { if (order.indexOf(r.station_id) === -1) order.push(r.station_id); });
order.sort(function (a, b) { return a - b; });
}
return { route_id: rid, station_order: order, directions: dirs, entries: entries };
}
/* ---------- เวลาทั้งหมดของสาย (ไม่ซ้ำ + เรียง) ---------- */
function times(doc, routeId, opts) {
var seen = {};
records(doc, opts).forEach(function (r) {
if (String(r.route_id) !== String(routeId)) return;
(r.departure_times || []).forEach(function (t) { seen[t] = true; });
});
return Object.keys(seen).sort();
}
/* ---------- จำนวนเที่ยวของสาย ---------- */
function countTrips(doc, routeId, opts) {
var n = 0;
records(doc, opts).forEach(function (r) {
if (String(r.route_id) === String(routeId)) n += (r.departure_times || []).length;
});
return n;
}
loadHolidays(); /* เริ่มโหลดทันที (ไม่บล็อกการอ่าน) */
loadKm();
window.Schedules = {
hasSchema2: hasSchema2,
load: loadSubs, /* โหลดทุกสาย (จากสารบัญหรือไฟล์รวม) */
loadRoute: loadRoute, /* โหลดสายเดียว + ไฟล์ย่อยที่ยังไม่เคยโหลด */
normSub: normSub,
get subs() { return SUBS; },
records: records,
route: route,
directions: directions,
times: times,
countTrips: countTrips,
/* ส่วนของวันทำงาน/วันหยุด */
todayType: todayType,
dayTypeOf: dayTypeOf,
dayInfo: dayInfo,
dayKey: dayKey,
DAYS: DAYS,
DAY_TH: DAY_TH,
DAY_ABBR: DAY_ABBR,
detectDay: detectDay,
detectDayOfDir: detectDayOfDir,
offsetLabel: offsetLabel,
stationNameOf: stationNameOf,
setStationNames: setStationNames,
shiftTimes: shiftTimes,
serviceOf: serviceOf,
timesFor: timesFor,
computeTimes: computeTimes,
speedOf: speedOf,
absKm: absKm,
relKms: relKms,
loadKm: loadKm,
get km() { return KM; },
DEFAULT_SPEED_KMH: DEFAULT_SPEED_KMH,
loadHolidays: loadHolidays,
get holidays() { return HOLIDAYS.slice(); },
ready: ready
};
})();
+42 -405
View File
@@ -1,4 +1,18 @@
<style>
.mu-other-stops { margin: 16px 0 6px; }
.mu-other-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.mu-other-item { display: block; padding: 10px 12px; background: #fff;
border: 1px solid #eef0f6; border-radius: 12px; min-width: 0; }
.mu-other-row { display: flex; align-items: center; gap: 10px; min-width: 0; }
.mu-other-item .mu-time-grid { margin-top: 8px; }
.mu-other-item .mu-est-note { margin-top: 4px; }
.mu-other-idx { flex: 0 0 auto; width: 24px; height: 24px; border-radius: 50%; background: #f1e9ff;
color: #7a4cc0; font-size: .78rem; font-weight: 700; display: flex; align-items: center; justify-content: center; }
.mu-other-txt { flex: 1; min-width: 0; }
.mu-other-txt strong { display: block; color: #1f2a44; font-size: .94rem; }
.mu-other-txt span { display: block; color: #6f7b95; font-size: .8rem; }
.mu-other-item .mu-chip { flex: 0 0 auto; font-family: ui-monospace, Consolas, monospace; font-size: .72rem; }
.mu-other-item .mu-chip.warn { background: #fff5e6; color: #9a6b00; border-color: #f2d9a8; }
:root {
--mu-accent: #7a4cc0;
--mu-accent-soft: #f3eafe;
@@ -55,8 +69,10 @@
.mu-stop-hero > * {
position: relative;
z-index: 1;
min-width: 0; /* กัน grid track บวมตาม min-content (ไม่งั้นเนื้อหาถูก overflow:hidden ตัดที่จอแคบ) */
}
.mu-stop-hero-title {
overflow-wrap: anywhere;
margin: 0;
font-size: 1.72rem;
color: var(--mu-ink);
@@ -68,7 +84,7 @@
font-size: .9rem;
}
.mu-meta-row { display:flex; flex-wrap:wrap; gap:8px; margin: 12px 0 0; }
.mu-meta-pill { background:linear-gradient(135deg, #ffffff, #f7f9ff); border:1px solid rgba(231, 224, 246, 0.9); color:#5b3b71; padding:6px 14px; border-radius:999px; font-size:.85rem; font-weight:600; box-shadow: 0 4px 10px rgba(122, 76, 192, 0.08); }
.mu-meta-pill { max-width: 100%; overflow-wrap: anywhere; background:linear-gradient(135deg, #ffffff, #f7f9ff); border:1px solid rgba(231, 224, 246, 0.9); color:#5b3b71; padding:6px 14px; border-radius:999px; font-size:.85rem; font-weight:600; box-shadow: 0 4px 10px rgba(122, 76, 192, 0.08); }
.mu-meta-pill.purple { background:linear-gradient(135deg, #f5eeff, #fce7f3); color:#7a4cc0; border-color:#e8d9f0; }
.mu-meta-pill.sky { background:linear-gradient(135deg, #ebf5ff, #eff6ff); color:#3071b8; border-color:#d7e7fb; }
.mu-meta-pill.mint { background:linear-gradient(135deg, #eafaf4, #ecfeff); color:#1f8765; border-color:#d1efdf; }
@@ -86,6 +102,8 @@
padding: 10px;
background: #fff;
box-shadow: 0 6px 14px rgba(122, 76, 192, 0.08);
min-width: 0;
overflow-wrap: anywhere;
}
.mu-hero-metric:nth-child(1) { background: linear-gradient(135deg, #f5efff, #fdf2f8); }
.mu-hero-metric:nth-child(2) { background: linear-gradient(135deg, #ecfeff, #eef6ff); }
@@ -338,6 +356,8 @@
}
}
@media (max-width: 640px) {
.mu-hero-metric-grid { grid-template-columns: 1fr; }
.mu-hero-metric { min-width: 0; overflow-wrap: anywhere; }
.mu-stop-summary-rail {
gap: 6px;
}
@@ -390,438 +410,55 @@
<main class="mu-page">
<div class="mu-container">
<p class="mu-breadcrumb"><a href="#/">หน้าแรก</a>/ <a href="#/stops">ป้ายหยุดรถ</a>/ บขส.อ่างทอง</p>
<p class="mu-breadcrumb" id="stop-breadcrumb"></p>
<section class="mu-stop-hero">
<div>
<h1 class="mu-stop-hero-title"><svg class="ic" aria-hidden="true"><use href="#ic-map-pin"/></svg> บขส.อ่างทอง</h1>
<p class="mu-stop-hero-sub">ศูนย์รวมรถโดยสารหลักของจังหวัดอ่างทอง พร้อมข้อมูลเวลารถแบบอ่านง่ายและหาเที่ยวถัดไปได้ทันที</p>
<div class="mu-meta-row">
<span class="mu-meta-pill purple"><span data-i18n="type.terminal">สถานีขนส่งหลัก</span></span>
<span class="mu-meta-pill sky">รหัส: at_main_terminal</span>
<span class="mu-meta-pill mint">เมืองอ่างทอง · จังหวัดอ่างทอง</span>
</div>
<div class="mu-hero-metric-grid">
<div class="mu-hero-metric">
<p class="mu-hero-metric-label">จำนวนสายรถ</p>
<p class="mu-hero-metric-value">8 สายหลัก</p>
</div>
<div class="mu-hero-metric">
<p class="mu-hero-metric-label">เวลาบริการ</p>
<p class="mu-hero-metric-value">04:30 - 21:00</p>
</div>
<div class="mu-hero-metric">
<p class="mu-hero-metric-label">เที่ยวเร็วสุดถัดไป</p>
<p class="mu-hero-metric-value">คำนวณอัตโนมัติ</p>
</div>
<div class="mu-hero-metric">
<p class="mu-hero-metric-label">สิ่งอำนวยความสะดวก</p>
<p class="mu-hero-metric-value">ห้องน้ำ · ที่พักคอย · ร้านอาหาร</p>
</div>
</div>
<h1 class="mu-stop-hero-title"><svg class="ic" aria-hidden="true"><use href="#ic-map-pin"/></svg> <span id="stop-title"></span></h1>
<p class="mu-stop-hero-sub" id="stop-sub"></p>
<div class="mu-meta-row" id="stop-meta"></div>
<div class="mu-hero-metric-grid" id="stop-metrics"></div>
</div>
<div>
<img class="mu-stop-hero-photo" src="../.image/stops/54950.jpg" alt="ผังป้าย บขส.อ่างทอง" fetchpriority="high" decoding="async">
<img class="mu-stop-hero-photo" id="stop-photo" alt="" fetchpriority="high" decoding="async" hidden>
<div class="mu-live-clock-card" id="mu-live-clock-card">
<div>
<p class="mu-live-clock-title">เวลาปัจจุบัน ณ ป้ายนี้</p>
<p class="mu-live-clock-title" data-i18n="stop.nowAtStop">เวลาปัจจุบัน ณ ป้ายนี้</p>
<p class="mu-live-clock-time" id="mu-current-time">--:--</p>
</div>
<p class="mu-live-clock-note"><span class="mu-live-dot"></span>กำลังคำนวณเที่ยวถัดไปอัตโนมัติ</p>
<p class="mu-live-clock-note"><span class="mu-live-dot"></span><span data-i18n="stop.autoNext">กำลังคำนวณเที่ยวถัดไปอัตโนมัติ</span></p>
</div>
</div>
</section>
<section class="mu-nearby" aria-label="สถานที่ใกล้เคียง">
<section class="mu-nearby" id="stop-nearby" aria-label="สถานที่ใกล้เคียง" hidden>
<h2><span data-i18n="stop.nearby">ใกล้เคียงป้าย</span></h2>
<p class="sub">สถานที่น่าสนใจและจุดแวะระหว่างรอรถได้สะดวก · เดินถึงได้ภายใน 5–10 นาที</p>
<div class="mu-nearby-grid">
<div class="mu-nearby-card"><img src="../.image/landmarks/riverbank.jpg" alt="ริมแม่น้ำเจ้าพระยา" loading="lazy" decoding="async"><p class="cap">ริมแม่น้ำเจ้าพระยา<small>จุดพักผ่อน · เดิน 6 นาที</small></p></div>
<div class="mu-nearby-card"><img src="../.image/landmarks/waterpark.png" alt="สวนน้ำอ่างทอง" loading="lazy" decoding="async"><p class="cap">สวนน้ำอ่างทอง<small>สวนสนุก · เดิน 8 นาที</small></p></div>
<div class="mu-nearby-card"><img src="../.image/landmarks/temple.png" alt="วัดใกล้สถานี" loading="lazy" decoding="async"><p class="cap">วัดสำคัญใกล้ป้าย<small>จุดแวะสักการะ · เดิน 5 นาที</small></p></div>
<div class="mu-nearby-card"><img src="../.image/landmarks/market.png" alt="ตลาดใกล้สถานี" loading="lazy" decoding="async"><p class="cap">ตลาดชุมชน<small>อาหาร · ติดป้าย</small></p></div>
</div> </section>
<div class="mu-toolbar">
<a class="mu-btn primary" href="#/routes/101&amp;origin=at_main_terminal">ดูตารางเวลาสายรถ 101</a>
<a class="mu-back-btn" href="#/stops"><span data-i18n="common.backStops">← กลับไปยังรายการป้าย</span></a>
</div>
<section class="mu-info-grid" aria-label="stop highlights">
<article class="mu-info-card" style="background:linear-gradient(135deg, #f7f1ff, #f2e8ff);">
<p class="label">จำนวนสายรถ</p>
<p class="value">8 สาย</p>
</article>
<article class="mu-info-card" style="background:linear-gradient(135deg, #edf6ff, #e8f3ff); border-color:#d7e7fb;">
<p class="label">เวลาบริการ</p>
<p class="value">04:30 - 21:00</p>
</article>
<article class="mu-info-card" style="background:linear-gradient(135deg, #eefdf6, #e7f9f1); border-color:#d1efdf;">
<p class="label">ประเภท</p>
<p class="value">สถานีหลัก</p>
</article>
<article class="mu-info-card" style="background:linear-gradient(135deg, #fff5fa, #ffeef6); border-color:#f7d6e5;">
<p class="label">สิ่งอำนวยความสะดวก</p>
<p class="value">ครบครัน</p>
</article>
<p class="sub" id="stop-nearby-sub"></p>
<div class="mu-nearby-grid" id="stop-nearby-grid"></div>
</section>
<div class="mu-toolbar" id="stop-toolbar"></div>
<section class="mu-info-grid" id="stop-info" aria-label="stop highlights"></section>
<section class="mu-layout-grid">
<div class="mu-card-panel">
<h2><span data-i18n="stop.routes">สายรถที่ผ่านจุดนี้</span></h2>
<div class="mu-route-tools">
<input id="mu-route-filter" class="mu-route-filter" type="text" placeholder="ค้นหาสายรถหรือปลายทาง" data-i18n-attr="placeholder:stop.searchRoute,aria-label:stop.searchRoute" data-i18n-attr="placeholder:stop.searchRoute,aria-label:stop.searchRoute">
<span class="mu-route-count" id="mu-route-count">แสดง 8 จาก 8 สาย</span>
<input id="mu-route-filter" class="mu-route-filter" type="text" placeholder="ค้นหาสายรถหรือปลายทาง" data-i18n-attr="placeholder:stop.searchRoute,aria-label:stop.searchRoute">
<span class="mu-route-count" id="mu-route-count"></span>
</div>
<ul class="mu-list mu-stop-list">
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">902</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>กรุงเทพ-อ่างทอง สายเอเซีย</strong>
<span class="mu-stop-summary-meta">เที่ยวกลับเข้า บขส.อ่างทอง</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">18 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">04:00</div><div class="mu-time-chip">04:30</div>
<div class="mu-time-chip">05:00</div><div class="mu-time-chip">05:30</div>
<div class="mu-time-chip">06:00</div><div class="mu-time-chip">06:30</div>
<div class="mu-time-chip">07:00</div><div class="mu-time-chip">07:30</div>
<div class="mu-time-chip">08:00</div><div class="mu-time-chip">08:30</div>
<div class="mu-time-chip">09:00</div><div class="mu-time-chip">09:30</div>
<div class="mu-time-chip">10:00</div><div class="mu-time-chip">10:30</div>
<div class="mu-time-chip">11:00</div><div class="mu-time-chip">11:30</div>
<div class="mu-time-chip">12:00</div><div class="mu-time-chip">12:30</div>
<div class="mu-time-chip">13:00</div><div class="mu-time-chip">13:30</div>
<div class="mu-time-chip">14:00</div><div class="mu-time-chip">14:30</div>
<div class="mu-time-chip">15:00</div><div class="mu-time-chip">15:30</div>
<div class="mu-time-chip">16:00</div><div class="mu-time-chip">16:30</div>
<div class="mu-time-chip">17:00</div><div class="mu-time-chip">17:30</div>
</div>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">15</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>กรุงเทพ-อ่างทอง สายใน</strong>
<span class="mu-stop-summary-meta">เที่ยวกลับเข้า บขส.อ่างทอง</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">4 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">05:00</div><div class="mu-time-chip">05:45</div>
<div class="mu-time-chip">06:30</div><div class="mu-time-chip">07:30</div>
</div>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">101</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>อ่างทอง-ป่าโมก-อยุธยา</strong>
<span class="mu-stop-summary-meta">เที่ยวออกจาก บขส.อ่างทอง</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">9 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip next">07:30</div><div class="mu-time-chip">08:20</div>
<div class="mu-time-chip">09:10</div><div class="mu-time-chip">10:00</div>
<div class="mu-time-chip">10:50</div><div class="mu-time-chip">11:50</div>
<div class="mu-time-chip">13:00</div><div class="mu-time-chip">14:00</div>
<div class="mu-time-chip">15:00</div>
</div>
<p class="mu-schedule-note">flow mock: เปิด route detail ที่ <strong>?route=101&amp;origin=at_main_terminal</strong></p>
<div class="mu-contact-row" style="margin-top:10px;">
<a href="#/routes/101&amp;origin=at_main_terminal"><span data-i18n="stop.openRoute">เปิดหน้ารายละเอียดสายรถนี้</span></a>
</div>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">464</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>สุพรรณ-อ่างทอง-สระบุรี</strong>
<span class="mu-stop-summary-meta">เที่ยวผ่านจุดนี้</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">20 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">06:30</div><div class="mu-time-chip">07:10</div>
<div class="mu-time-chip">07:50</div><div class="mu-time-chip">08:40</div>
<div class="mu-time-chip">09:30</div><div class="mu-time-chip">10:10</div>
<div class="mu-time-chip">10:50</div><div class="mu-time-chip">11:30</div>
<div class="mu-time-chip">12:10</div><div class="mu-time-chip">12:50</div>
<div class="mu-time-chip">13:30</div><div class="mu-time-chip">14:10</div>
<div class="mu-time-chip">14:50</div><div class="mu-time-chip">15:30</div>
<div class="mu-time-chip">16:10</div><div class="mu-time-chip">16:50</div>
<div class="mu-time-chip">17:30</div><div class="mu-time-chip">18:10</div>
<div class="mu-time-chip">18:50</div><div class="mu-time-chip">19:30</div>
</div>
<p class="mu-schedule-note"><svg class="ic" aria-hidden="true"><use href="#ic-triangle-alert"/></svg> เวลารถเปลี่ยนทุกวัน</p>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">641</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>อ่างทอง-บ้านแพรก-ลพบุรี</strong>
<span class="mu-stop-summary-meta">เที่ยวออกจาก บขส.อ่างทอง</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">9 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">07:00</div><div class="mu-time-chip">08:00</div>
<div class="mu-time-chip">09:00</div><div class="mu-time-chip">10:00</div>
<div class="mu-time-chip">11:00</div><div class="mu-time-chip">12:00</div>
<div class="mu-time-chip">13:30</div><div class="mu-time-chip">14:30</div>
<div class="mu-time-chip">16:30</div>
</div>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">324</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>อ่างทอง-วัดพิกุลทอง</strong>
<span class="mu-stop-summary-meta">เที่ยวผ่านจุดนี้</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">1 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">10:00</div>
</div>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">1011</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>อ่างทอง-สีบัวทอง</strong>
<span class="mu-stop-summary-meta">เที่ยวผ่านจุดนี้</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">3 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">12:00</div><div class="mu-time-chip">16:00</div>
<div class="mu-time-chip">17:00</div>
</div>
</div>
</details>
</li>
<li>
<details class="mu-stop-expander">
<summary>
<span class="mu-route-chip">2231</span>
<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> รถบัส</span>
<span class="mu-stop-summary-main">
<strong>อ่างทอง-มหานาม</strong>
<span class="mu-stop-summary-meta">เที่ยวผ่านจุดนี้</span>
</span>
<span class="mu-stop-summary-rail">
<span class="mu-status-pill info">1 รอบ/วัน</span>
<span class="mu-stop-chevron">⌄</span>
</span>
</summary>
<div class="mu-stop-expander-body">
<div class="mu-time-grid">
<div class="mu-time-chip">16:00</div>
</div>
</div>
</details>
</li>
</ul>
<ul class="mu-list mu-stop-list" id="stop-routes"></ul>
</div>
<aside class="mu-card-panel">
<h2><span data-i18n="stop.mapInfo">แผนที่และข้อมูลป้าย</span></h2>
<div class="at-map" id="stop-map" role="region" aria-label="แผนที่เส้นทางที่ผ่านป้ายนี้"></div>
<p class="at-map-caption" id="stop-map-caption"></p>
<div style="display:flex; flex-wrap:wrap; gap:8px; margin-top:14px;">
<span class="mu-chip" style="background: rgba(255,255,255,.9); border:1px solid rgba(231, 224, 246, 0.95); color:#5b3b71;">เปิด 04:30</span>
<span class="mu-chip" style="background: rgba(255,255,255,.9); border:1px solid rgba(231, 224, 246, 0.95); color:#5b3b71;">ปิด 21:00</span>
<span class="mu-chip" style="background: rgba(31, 135, 101, 0.08); color:#1f8765; border:1px solid rgba(31,135,101,.15);">มีห้องน้ำ</span>
<span class="mu-chip" style="background: rgba(31, 135, 101, 0.08); color:#1f8765; border:1px solid rgba(31,135,101,.15);">ที่พักคอย</span>
<span class="mu-chip" style="background: rgba(31, 135, 101, 0.08); color:#1f8765; border:1px solid rgba(31,135,101,.15);">ร้านอาหาร</span>
</div>
<div id="stop-chips" style="display:flex; flex-wrap:wrap; gap:8px; margin-top:14px;"></div>
</aside>
</section>
</div>
</main>
<script>
(function () {
function pad2(num) {
return String(num).padStart(2, "0");
}
function timeToMinutes(timeText) {
var match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(timeText.trim());
if (!match) {
return null;
}
return Number(match[1]) * 60 + Number(match[2]);
}
function renderCurrentTime(now) {
var currentTimeEl = document.getElementById("mu-current-time");
if (!currentTimeEl) {
return;
}
currentTimeEl.textContent = pad2(now.getHours()) + ":" + pad2(now.getMinutes());
}
function updateNextArrivalForRow(detailEl, nowMinutes) {
var chips = Array.from(detailEl.querySelectorAll(".mu-time-chip"));
if (!chips.length) {
return;
}
chips.forEach(function (chip) {
chip.classList.remove("next");
chip.classList.remove("next-live");
});
var times = chips
.map(function (chip, idx) {
return { chip: chip, idx: idx, minutes: timeToMinutes(chip.textContent) };
})
.filter(function (item) {
return item.minutes !== null;
})
.sort(function (a, b) {
return a.minutes - b.minutes;
});
if (!times.length) {
return;
}
var next = times.find(function (item) {
return item.minutes >= nowMinutes;
});
var wrapsToTomorrow = false;
if (!next) {
next = times[0];
wrapsToTomorrow = true;
}
next.chip.classList.add("next-live");
var rail = detailEl.querySelector(".mu-stop-summary-rail");
if (!rail) {
return;
}
var nextEl = rail.querySelector(".mu-next-arrival");
if (!nextEl) {
nextEl = document.createElement("span");
nextEl.className = "mu-next-arrival";
var chevron = rail.querySelector(".mu-stop-chevron");
if (chevron) {
rail.insertBefore(nextEl, chevron);
} else {
rail.appendChild(nextEl);
}
}
nextEl.textContent = (wrapsToTomorrow ? "พรุ่งนี้ " : "ถัดไป ") + next.chip.textContent.trim();
}
function setupRouteFilter() {
var inputEl = document.getElementById("mu-route-filter");
var countEl = document.getElementById("mu-route-count");
var items = Array.from(document.querySelectorAll(".mu-stop-list > li"));
if (!inputEl || !countEl || !items.length) {
return;
}
function applyFilter() {
var keyword = inputEl.value.trim().toLowerCase();
var visibleCount = 0;
items.forEach(function (li) {
var summaryText = li.textContent.toLowerCase();
var matched = !keyword || summaryText.indexOf(keyword) !== -1;
li.style.display = matched ? "block" : "none";
if (matched) {
visibleCount += 1;
}
});
countEl.textContent = "แสดง " + visibleCount + " จาก " + items.length + " สาย";
}
inputEl.addEventListener("input", applyFilter);
applyFilter();
}
function tick() {
var now = new Date();
var nowMinutes = now.getHours() * 60 + now.getMinutes();
renderCurrentTime(now);
document.querySelectorAll(".mu-stop-expander").forEach(function (detailEl) {
updateNextArrivalForRow(detailEl, nowMinutes);
});
}
tick();
setupRouteFilter();
setInterval(tick, 30000);
})();
</script>
<script>
(function () {
var r = window.__route || { params: {} };
var el = document.getElementById('stop-map');
if (el && window.ATMap && r.params.code) ATMap.forStop(el, r.params.code);
})();
</script>
<script src="./partials/stopDetail.init.js"></script>
+573
View File
@@ -0,0 +1,573 @@
/* ============================================================
stopDetail.init.js — หน้ารายละเอียดป้าย (#/stops/<รหัส>)
เดิม: ข้อมูลทุกอย่างฝังตายใน stopDetail.html (ทุกป้ายแสดงเหมือนกันหมด)
ใหม่: เรนเดอร์จาก JSON จริง 100% — เปลี่ยนข้อมูลที่ไหนก็แก้ที่ไฟล์ข้อมูล ไม่ต้องแก้ HTML
แหล่งข้อมูล:
stations.json → ชื่อ/ประเภท/รหัส/จังหวัด/พิกัด (+ ฟิลด์เสริม photo/description/landmarks/facilities ถ้าใส่ไว้)
routes.json → สายรถที่ผ่านป้ายนี้ (station_ids) + ชื่อสาย
schedules.json → เวลารถของแต่ละสายที่ป้ายนี้ (schema 2 ผ่านตัวอ่านกลาง Schedules)
.image/stations/ → รูปสถานี <station_id>.jpg (+ รูปเสริม <station_id>-2.jpg)
พารามิเตอร์ URL:
#/stops/<รหัสป้าย> → แสดงป้ายนั้น
#/stops/<รหัสป้าย>?route=<รหัสสาย> → กรอง/เปิดเฉพาะสายนั้นทันที
============================================================ */
(function () {
'use strict';
var DATA = '../resource/data/';
var PHOTO_DIR = '../.image/stations/'; /* รูปสถานี: <station_id>.<jpg|jpeg|webp|png> (ไล่ลองนามสกุลให้) */
var PHOTO_EXTS = ['jpg', 'jpeg', 'webp', 'png'];
/* ประเภทป้าย → คีย์แปล + โทนสี */
var TYPE_KEY = {
main_terminal: 'type.terminal', local_terminal: 'type.local', local_stop: 'type.busstop',
market: 'type.market', private_stop: 'type.marketOpt'
};
var TYPE_TONE = {
main_terminal: 'purple', local_terminal: 'sky', local_stop: 'mint', market: 'mint', private_stop: 'sky'
};
function $(id) { return document.getElementById(id); }
function t(k, v) { return window.I18N ? I18N.t(k, v) : k; }
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 pad2(n) { return (n < 10 ? '0' : '') + n; }
function toMin(s) {
var m = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(String(s || '').trim());
return m ? Number(m[1]) * 60 + Number(m[2]) : null;
}
function nowMin() { var d = new Date(); return d.getHours() * 60 + d.getMinutes(); }
function point(st) {
if (!st || st.latitude === '' || st.longitude === '' || st.latitude == null) return null;
return [parseFloat(st.longitude), parseFloat(st.latitude)];
}
/* ---------- หาป้ายของเรา: รหัส URL → stations.json ---------- */
function findStation(stations, code) {
var want = String(code || '').trim();
var hit = stations.filter(function (s) { return String(s.station_code) === want; })[0];
if (hit) return hit;
hit = stations.filter(function (s) { return String(s.station_code).toLowerCase() === want.toLowerCase(); })[0];
if (hit) return hit;
if (/^\d+$/.test(want)) {
hit = stations.filter(function (s) { return String(s.station_id) === want; })[0];
}
return hit || null;
}
/* ---------- สายรถที่ผ่านป้ายนี้ + เวลาที่ป้ายนี้ ---------- */
function routesAtStation(routes, sched, sid) {
var out = [];
routes.forEach(function (r) {
var ids = r.station_ids || [];
if (ids.indexOf(sid) === -1) return;
var legs = []; /* แต่ละทิศ = 1 รายการ */
Schedules.directions(sched, r.route_id).forEach(function (d) {
d.stops.forEach(function (s) {
if (s.station_id !== sid) return;
legs.push({ dir_id: d.dir_id, label: s.dir_note || d.dir_label || null, times: s.times || [], note: s.note || null, estimated: !!s.estimated, estimateFrom: s.estimateFrom || null });
});
});
var trips = legs.reduce(function (n, l) { return n + l.times.length; }, 0);
var pos = ids.indexOf(sid);
out.push({
route: r, legs: legs, trips: trips,
isOrigin: pos === 0, isTerminus: pos === ids.length - 1, index: pos, total: ids.length
});
});
/* เรียงตามลำดับใน routes.json (คงที่ — ตรงกับตัวเลือกสายในหน้าอื่น) */
return out;
}
/* ---------- รูปสถานี: .image/stations/<station_id>.jpg ----------
เลือกตาม station_id ใน stations.json · ไฟล์หาย → ไม่แสดงช่องว่าง (hero ยืดเต็ม) */
function findPhoto(station) {
if (station.photo) return station.photo; /* ระบุพาธเองได้ใน stations.json (ทับค่าเริ่มต้น) */
var n = station.__seq || 1; /* รูปเสริมของสถานีเดียวกัน: 2-2.jpg, 2-3.jpeg … */
var base = PHOTO_DIR + station.station_id + (n > 1 ? '-' + n : '');
return PHOTO_EXTS.map(function (e) { return base + '.' + e; }); /* เรียง候选ให้ renderHero ไล่ลอง */
}
/* ---------- ตัวเลขสรุป ---------- */
var HHMM = /^\d{1,2}:\d{2}$/; /* กันค่าหลอกในไฟล์ (เช่นข้อความ) ไม่ให้เพี้ยน KPI */
function summarise(rows) {
var times = [], trips = 0;
rows.forEach(function (x) {
trips += x.trips;
x.legs.forEach(function (l) {
times = times.concat((l.times || []).filter(function (t) { return HHMM.test(String(t)); }));
});
});
times.sort(function (a, b) { return toMin(a) - toMin(b); });
return { rows: rows.length, trips: trips, first: times[0] || null, last: times[times.length - 1] || null };
}
/* ---------- เรนเดอร์: หัวป้าย ---------- */
function renderHero(st, sum, photo, place) {
var baseName = st.station_name_th || ('ป้าย ' + st.station_code);
/* จุดขึ้นรถประจำทางอื่นๆ: ต่อท้ายด้วยชื่อสถานที่จริงของสายที่กำลังดูอยู่ */
var placeName = (place && window.OtherStop && OtherStop.firstName) ? OtherStop.firstName(place)
: (place && place.station_name_th) ? place.station_name_th : null;
var name = baseName + (placeName ? ' \u00b7 ' + placeName : '');
var city = (place && place.city_th) || st.city_th || '';
var prov = (place && place.province_th) || st.province_th || '';
var crumb = $('stop-breadcrumb');
if (crumb) crumb.innerHTML = '<a href="#/">' + esc(t('nav.home')) + '</a>/ <a href="#/stops">' +
esc(t('nav.stops')) + '</a>/ ' + esc(name);
var title = $('stop-title');
if (title) title.textContent = name;
var sub = $('stop-sub');
if (sub) {
sub.textContent = st.description ||
t('stop.subGeneric', { city: city || prov || t('stop.thisStop') });
}
var meta = $('stop-meta');
if (meta) {
meta.innerHTML =
'<span class="mu-meta-pill ' + (TYPE_TONE[st.station_type] || 'purple') + '">' +
esc(t(TYPE_KEY[st.station_type] || 'type.busstop')) + '</span>' +
'<span class="mu-meta-pill sky">' + esc(t('stop.code')) + ' ' + esc(st.station_code) + '</span>' +
(city || prov ? '<span class="mu-meta-pill mint">' + esc([city, prov].filter(Boolean).join(' · ')) + '</span>' : '');
}
var metrics = $('stop-metrics');
if (metrics) {
metrics.innerHTML =
'<div class="mu-hero-metric"><p class="mu-hero-metric-label">' + esc(t('stop.statRoutes')) + '</p>' +
'<p class="mu-hero-metric-value">' + sum.rows + '</p></div>' +
'<div class="mu-hero-metric"><p class="mu-hero-metric-label">' + esc(t('stop.statTrips')) + '</p>' +
'<p class="mu-hero-metric-value">' + sum.trips + '</p></div>' +
'<div class="mu-hero-metric"><p class="mu-hero-metric-label">' + esc(t('stop.statHours')) + '</p>' +
'<p class="mu-hero-metric-value">' + (sum.first ? esc(sum.first + ' - ' + sum.last) : '–') + '</p></div>' +
'<div class="mu-hero-metric"><p class="mu-hero-metric-label">' + esc(t('stop.nextArrival')) + '</p>' +
'<p class="mu-hero-metric-value" id="stop-next-trip">–</p></div>';
}
var img = $('stop-photo');
if (img) {
img.alt = name;
img.hidden = true; /* ซ่อนไว้ก่อน — รอผลตรวจว่ามีไฟล์จริง */
var cands = [].concat(photo || []).filter(Boolean); /* รองรับทั้งสตริงเดียวและรายการนามสกุล */
(function tryNext(i) {
if (i >= cands.length) return; /* ไม่มีไฟล์เลย → ไม่แสดงช่องว่าง */
var url = cands[i];
fetch(url, { method: 'HEAD', cache: 'no-store' })
.then(function (r) {
if (!r.ok) return tryNext(i + 1); /* ลองนามสกุลถัดไป (.jpg → .jpeg → .webp → .png) */
img.src = url;
img.hidden = false;
})
.catch(function () { tryNext(i + 1); });
})(0);
}
}
/* ---------- เรนเดอร์: การ์ดสรุป 4 ใบ ---------- */
function renderInfo(st, sum) {
var box = $('stop-info');
if (!box) return;
var tones = [
'background:linear-gradient(135deg, #f7f1ff, #f2e8ff);',
'background:linear-gradient(135deg, #edf6ff, #e8f3ff); border-color:#d7e7fb;',
'background:linear-gradient(135deg, #eefdf6, #e7f9f1); border-color:#d1efdf;',
'background:linear-gradient(135deg, #fff5fa, #ffeef6); border-color:#f7d6e5;'
];
var cards = [
[t('stop.statRoutes'), sum.rows ? t(sum.rows === 1 ? 'stop.nRoutes1' : 'stop.nRoutes', { n: sum.rows }) : '–'],
[t('stop.statTrips'), sum.trips ? String(sum.trips) : '–'],
[t('stop.statType'), t(TYPE_KEY[st.station_type] || 'type.busstop')],
[t('stop.statHours'), sum.first ? sum.first + ' - ' + sum.last : '–']
];
box.innerHTML = cards.map(function (c, i) {
return '<article class="mu-info-card" style="' + tones[i] + '">' +
'<p class="label">' + esc(c[0]) + '</p><p class="value">' + esc(c[1]) + '</p></article>';
}).join('');
}
/* ---------- เรนเดอร์: สายรถที่ผ่านป้ายนี้ ---------- */
function renderRoutes(rows, placeByRoute) {
placeByRoute = placeByRoute || {};
var list = $('stop-routes');
var filter = $('mu-route-filter');
if (!list) return;
if (!rows.length) {
list.innerHTML = '<li><p class="mu-stop-sub">' + esc(t('stop.noRoutes')) + '</p></li>';
if (filter) filter.disabled = true;
setCount(0, 0);
return;
}
list.innerHTML = '';
rows.forEach(function (x) {
var r = x.route;
var li = document.createElement('li');
var det = document.createElement('details');
det.className = 'mu-stop-expander';
if (x.isOrigin || x.isTerminus) det.open = true;
var posLabel = x.isOrigin ? t('route.origin') : (x.isTerminus ? t('route.destination') : t('route.pass'));
var place = placeByRoute[String(r.route_id)] || null;
/* จุดขึ้นรถประจำทางอื่นๆ → แสดง "ชื่อจุดจริง · อำเภอ" แทนคำว่าจุดจอดที่ N */
/* จุดขึ้นรถประจำทางอื่นๆ ที่มีหลายจุด → โชว์จุดแรก + "(+N จุด)" ไม่ยัดชื่อทั้งชุด */
var subs = (place && window.OtherStop && OtherStop.stopsOf) ? OtherStop.stopsOf(place) : [];
var pName = subs.length ? subs[0].name : (place && place.station_name_th) || '';
var pMore = subs.length > 1 ? ' ' + t('stop.otherMore', { n: subs.length - 1 }) : '';
var metaText = place
? pName + pMore + (place.city_th ? ' \u00b7 ' + place.city_th : '')
: posLabel + (x.total > 1 ? ' \u00b7 ' + (x.index + 1) + '/' + x.total : '');
var sum = document.createElement('summary');
sum.innerHTML =
'<span class="mu-route-chip">' + esc(r.route_id) + '</span>' +
'<span class="mu-route-type-badge"><svg class="ic" aria-hidden="true"><use href="#ic-bus-front"/></svg> ' +
esc(r.vehicle_type_th || t('type.terminal')) + '</span>' +
'<span class="mu-stop-summary-main">' +
'<strong>' + esc(r.route_name_th || ('สาย ' + r.route_id)) + '</strong>' +
'<span class="mu-stop-summary-meta">' + esc(metaText) + '</span>' +
'</span>' +
'<span class="mu-stop-summary-rail">' +
'<span class="mu-status-pill info">' + esc(t(x.trips === 1 ? 'stop.tripsPerDay1' : 'stop.tripsPerDay', { n: x.trips })) + '</span>' +
'<span class="mu-stop-chevron">\u2304</span>' +
'</span>';
det.appendChild(sum);
var body = document.createElement('div');
body.className = 'mu-stop-expander-body';
if (!x.legs.length || !x.trips) {
body.innerHTML = '<p class="mu-stop-sub">' + esc(t('stop.noTimes')) + '</p>';
} else {
x.legs.forEach(function (leg) {
/* ทิศที่ยังไม่มีเวลา → ข้าม (แถวนี้มีการแสดงตารางของทิศอื่นอยู่แล้ว) */
if (!(leg.times || []).length) return;
if (leg.label) {
var lab = document.createElement('p');
lab.className = 'mu-stop-sub';
lab.textContent = leg.label;
body.appendChild(lab);
}
var grid = document.createElement('div');
grid.className = 'mu-time-grid' + (leg.estimated ? ' is-est' : '');
leg.times.forEach(function (tm) {
var c = document.createElement('div');
c.className = 'mu-time-chip';
c.textContent = tm;
grid.appendChild(c);
});
body.appendChild(grid);
if (leg.estimated) {
var estN = document.createElement('p');
estN.className = 'mu-est-note';
/* กฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" → บอกจุดอ้างอิง + เตือนเรื่องการจราจร */
estN.textContent = leg.estimateFrom && window.Schedules.offsetLabel
? t('time.derived', {
base: leg.estimateFrom.name || ('#' + leg.estimateFrom.station_id),
n: Schedules.offsetLabel(leg.estimateFrom.offsetMin)
})
: t('time.estimated');
body.appendChild(estN);
}
if (leg.note) {
var n = document.createElement('p');
n.className = 'mu-schedule-note';
n.innerHTML = '<svg class="ic" aria-hidden="true"><use href="#ic-triangle-alert"/></svg> ' + esc(leg.note);
body.appendChild(n);
}
});
}
/* ลิงก์ไปตารางเวลาเต็มของสายนั้น */
var act = document.createElement('div');
act.className = 'mu-inline-actions';
act.innerHTML = '<a class="mu-btn ghost" href="#/check/' + encodeURIComponent(r.route_id) + '">' +
esc(t('stop.viewScheduleN', { n: r.route_id })) + '</a>';
body.appendChild(act);
det.appendChild(body);
li.appendChild(det);
list.appendChild(li);
});
setupFilter();
}
function setCount(shown, total) {
var el = $('mu-route-count');
if (el) el.textContent = total ? t('stop.showing', { a: shown, b: total }) : '';
}
/* ---------- กรองสายรถ (ค้นหา) ---------- */
function applyFilter() {
var input = $('mu-route-filter');
var items = Array.prototype.slice.call(document.querySelectorAll('#stop-routes > li'));
if (!items.length) return;
var kw = (input ? input.value : '').trim().toLowerCase();
var shown = 0;
items.forEach(function (li) {
var ok = !kw || li.textContent.toLowerCase().indexOf(kw) !== -1;
li.style.display = ok ? '' : 'none';
if (ok) shown++;
});
setCount(shown, items.length);
}
function setupFilter() {
var input = $('mu-route-filter');
if (input && !input.dataset.bound) {
input.dataset.bound = '1';
input.addEventListener('input', applyFilter);
}
}
/* ---------- ไฮไลต์เที่ยวถัดไป + นาฬิกา (เดิมอยู่ใน partial) ---------- */
function tick() {
var clock = $('mu-current-time');
var now = new Date();
if (clock) clock.textContent = pad2(now.getHours()) + ':' + pad2(now.getMinutes());
var nowm = nowMin();
var soonest = null;
document.querySelectorAll('.mu-stop-expander').forEach(function (det) {
var chips = Array.prototype.slice.call(det.querySelectorAll('.mu-time-chip'));
chips.forEach(function (c) { c.classList.remove('next-live'); });
var times = chips.map(function (c) { return { c: c, m: toMin(c.textContent) }; })
.filter(function (x) { return x.m !== null; })
.sort(function (a, b) { return a.m - b.m; });
if (!times.length) return;
var next = times.filter(function (x) { return x.m >= nowm; })[0];
var tomorrow = false;
if (!next) { next = times[0]; tomorrow = true; }
next.c.classList.add('next-live');
if (!soonest || next.m < soonest.m) soonest = { m: next.m, time: next.c.textContent.trim(), tomorrow: tomorrow };
var rail = det.querySelector('.mu-stop-summary-rail');
if (!rail) return;
var el = rail.querySelector('.mu-next-arrival');
if (!el) {
el = document.createElement('span');
el.className = 'mu-next-arrival';
var chev = rail.querySelector('.mu-stop-chevron');
chev ? rail.insertBefore(el, chev) : rail.appendChild(el);
}
var routeId = (det.querySelector('.mu-route-chip') || {}).textContent || '';
el.textContent = (tomorrow ? t('stop.tomorrow') : t('stop.nextAt')) + ' ' + next.c.textContent.trim();
el.dataset.route = routeId;
});
var hero = $('stop-next-trip');
if (hero) hero.textContent = soonest ? (soonest.tomorrow ? t('stop.tomorrow') + ' ' : '') + soonest.time : '–';
}
/* ---------- ป้ายที่ไม่พบข้อมูล ---------- */
function renderNotFound(code) {
var main = document.querySelector('#view .mu-container') || document.querySelector('#view');
if (!main) return;
main.innerHTML =
'<p class="mu-breadcrumb"><a href="#/stops">' + esc(t('common.backStops')) + '</a></p>' +
'<h1 class="mu-stop-hero-title">' + esc(t('stop.notFound')) + '</h1>' +
'<p class="mu-stop-hero-sub">' + esc(t('stop.notFoundSub', { code: code })) + '</p>';
}
/* ---------- เริ่มทำงาน ---------- */
function init() {
var route = window.__route || { params: {}, query: {} };
var code = (route.params && route.params.code) || '';
var wantRoute = (route.query && route.query.route) || '';
Promise.all([
fetchJSON(DATA + 'stations.json'),
fetchJSON(DATA + 'routes.json'),
Schedules.load().then(function (sd) { return Schedules.normSub(sd); }),
(window.OtherStop ? OtherStop.load() : Promise.resolve([]))
]).then(function (res) {
var stations = (res[0] || {}).stations || [];
if (window.Schedules && Schedules.setStationNames) Schedules.setStationNames(stations); /* ให้ข้อความ "คำนวณจาก ..." มีชื่อจุด */
var routes = (res[1] || {}).routes || [];
var sched = res[2] || {};
var others = res[3] || [];
var st = findStation(stations, code);
if (!st) { renderNotFound(code); return; }
var rows = routesAtStation(routes, sched, st.station_id);
var sum = summarise(rows);
/* สถานี 8 "จุดขึ้นรถประจำทางอื่นๆ" = ชื่อรวมของทุกสาย
→ จับคู่ route id เพื่อเอาชื่อสถานที่จริงของสายนั้น (เช่น 1011 → วัดสีบัวทอง / 1101 ในไฟล์) */
var validIds = routes.map(function (r) { return String(r.route_id); });
var isOther = !!(window.OtherStop && OtherStop.isOtherStop(st));
var placeByRoute = {};
if (isOther) {
routes.forEach(function (r) {
var e = OtherStop.forRoute(others, r.route_id, validIds);
if (e) placeByRoute[String(r.route_id)] = e;
});
}
var focusPlace = (isOther && wantRoute) ? (placeByRoute[String(wantRoute)] || null) : null;
renderOtherStops(isOther, routes, others, validIds, wantRoute, sched);
renderHero(st, sum, findPhoto(st), focusPlace);
renderInfo(st, sum);
renderToolbar(st, rows, wantRoute);
renderNearby(st);
renderChips(st, sum);
renderRoutes(rows, placeByRoute);
var filter = $('mu-route-filter');
if (filter && wantRoute) { filter.value = wantRoute; applyFilter(); }
tick();
setInterval(tick, 30000);
/* แผนที่: ใช้เส้นทางของสายที่ผ่านป้ายนี้ */
var mapEl = $('stop-map');
if (mapEl && window.ATMap) {
var mapOpts = {};
if (isOther && wantRoute) mapOpts.onlyRoutes = [String(wantRoute)];
if (focusPlace) mapOpts.focus = focusPlace;
try { ATMap.forStop(mapEl, st.station_code, mapOpts); } catch (e) { /* แผนที่พังไม่ควรทำให้หน้าเจ๊ง */ }
}
});
}
/* ---------- จุดขึ้นรถประจำทางอื่นๆ: แสดง "ทุกจุด" ของสายนั้น ----------
สายเดียวผ่านได้หลายจุด (เช่น 954 = ตลาดท่าช้าง · สามโก้ · วิเศษชัยชาญ · อ่างทอง)
จุดที่ยังไม่มีพิกัด → แสดงชื่อพร้อมป้าย "ยังไม่มีพิกัด" (ไม่ซ่อนข้อมูล) */
function renderOtherStops(isOther, routes, others, validIds, wantRoute, sched) {
var host = $('stop-other-stops');
if (!host) {
if (!isOther) return;
host = document.createElement('section');
host.className = 'mu-other-stops';
host.id = 'stop-other-stops';
var bar = $('stop-toolbar');
if (bar && bar.parentNode) bar.parentNode.insertBefore(host, bar);
else return;
}
if (!isOther) { host.hidden = true; return; }
var list = []; /* { route_id, stop } */
routes.forEach(function (r) {
if (wantRoute && String(r.route_id) !== String(wantRoute)) return;
OtherStop.allStops(others, r.route_id, validIds).forEach(function (st) {
list.push({ route_id: String(r.route_id), stop: st });
});
});
if (!list.length) { host.hidden = true; return; }
var one = !!wantRoute && routes.filter(function (r) { return String(r.route_id) === String(wantRoute); }).length === 1;
/* เวลาของ "จุดแรก" ของแต่ละสาย (แถว station 8 ในตารางเวลา) = ฐานสำหรับคำนวณจุดถัดไป
offsets_min ใน 8 other_stop.json บอกว่าแต่ละจุดห่างจากจุดแรกกี่นาที */
var baseByRoute = {};
if (window.Schedules && sched && Schedules.records) {
(Schedules.records(sched) || []).forEach(function (r) {
if (String(r.station_id) !== '8') return;
var rid = String(r.route_id), t2 = r.departure_times || [];
if (t2.length && (!baseByRoute[rid] || t2.length > baseByRoute[rid].length)) baseByRoute[rid] = t2;
});
}
var canShift = !!(window.Schedules && Schedules.shiftTimes && Schedules.offsetLabel);
host.hidden = false;
host.innerHTML =
'<h2 class="sect">' + esc(one
? t('stop.otherStopsTitle', { n: wantRoute, m: list.length })
: t('stop.otherStopsAll', { m: list.length })) + '</h2>' +
'<ul class="mu-list mu-other-list">' + list.map(function (x) {
var st = x.stop;
var where = [st.city_th, st.province_th].filter(Boolean).join(' · ');
var base = baseByRoute[String(x.route_id)] || null;
var hasOff = (st.offsetMin != null);
var times = (hasOff && base && canShift) ? Schedules.shiftTimes(base, st.offsetMin) : null;
var first = (hasOff && base) ? list.filter(function (y) { return String(y.route_id) === String(x.route_id); })[0] : null;
return '<li class="mu-other-item">' +
'<div class="mu-other-row">' +
'<span class="mu-other-idx">' + (st.index + 1) + '</span>' +
'<div class="mu-other-txt"><strong>' + esc(st.name) + '</strong>' +
(where ? '<span>' + esc(where) + '</span>' : '') +
(one ? '' : '<span>' + esc(t('stops.busPrefix')) + ' ' + esc(x.route_id) + '</span>') +
'</div>' +
'<span class="mu-chip ' + (st.hasCoord ? 'count' : 'warn') + '">' +
esc(st.hasCoord ? (Number(st.lat).toFixed(4) + ', ' + Number(st.lng).toFixed(4)) : t('stop.noCoord')) +
'</span>' +
'</div>' +
(times && times.length
? '<div class="mu-time-grid is-est">' + times.map(function (tm) {
return '<div class="mu-time-chip">' + esc(tm) + '</div>';
}).join('') + '</div>' +
(st.offsetMin !== 0 && first
? '<p class="mu-est-note">' + esc(t('time.derived', {
base: first.stop.name, n: Schedules.offsetLabel(st.offsetMin)
})) + '</p>'
: '')
: '') +
'</li>';
}).join('') + '</ul>';
}
/* ---------- ปุ่ม/ทางลัด ---------- */
function renderToolbar(st, rows, preferRoute) {
var bar = $('stop-toolbar');
if (!bar || !rows.length) return;
/* ถ้ามี ?route= ให้ปุ่มอ้างสายนั้นก่อน ไม่งั้นใช้สายแรก */
var top = rows[0].route;
if (preferRoute) {
var hit = rows.filter(function (x) { return String(x.route.route_id) === String(preferRoute); })[0];
if (hit) top = hit.route;
}
bar.innerHTML =
'<a class="mu-btn primary" href="#/check/' + encodeURIComponent(top.route_id) + '">' +
esc(t('stop.viewScheduleN', { n: top.route_id })) + '</a>' +
'<a class="mu-back-btn" href="#/stops">' + esc(t('common.backStops')) + '</a>';
}
/* ---------- สถานที่ใกล้เคียง (ต้องมีข้อมูลใน stations.json → landmarks[]) ---------- */
function renderNearby(st) {
var sec = $('stop-nearby');
var grid = $('stop-nearby-grid');
if (!sec || !grid) return;
var marks = st.landmarks || [];
if (!marks.length) { sec.hidden = true; return; }
sec.hidden = false;
var sub = $('stop-nearby-sub');
if (sub) sub.textContent = st.landmarks_note || t('stop.nearbySub');
grid.innerHTML = marks.map(function (m) {
return '<div class="mu-nearby-card">' +
'<img src="' + esc(m.img || '') + '" alt="' + esc(m.caption || '') + '" loading="lazy" decoding="async">' +
'<p class="cap">' + esc(m.caption || '') + (m.sub ? '<small>' + esc(m.sub) + '</small>' : '') + '</p></div>';
}).join('');
}
/* ---------- ชิป: เวลาเปิด–ปิด + สิ่งอำนวยความสะดวก (ถ้ามีใน stations.json) ---------- */
function renderChips(st, sum) {
var box = $('stop-chips');
if (!box) return;
var html = '';
if (sum.first) html += '<span class="mu-chip">' + esc(t('stop.open')) + ' ' + esc(sum.first) + '</span>';
if (sum.last) html += '<span class="mu-chip">' + esc(t('stop.close')) + ' ' + esc(sum.last) + '</span>';
(st.facilities || []).forEach(function (f) {
html += '<span class="mu-chip ok">' + esc(f) + '</span>';
});
box.innerHTML = html;
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();