Dolu görünen trende yer bul.
ebilet'te uçtan uca dolu görünen seferler için ara istasyonlardaki boş koltukları birleştirir, rotaları fiyatıyla gösterir.
- Ücretsiz
- Veri tarayıcında kalır
- Klavye ve ekran okuyucuyla kullanılır
2 arama kaldı
Aynı tren, iki bilet
Sistem bir koltuğu yalnızca yolun tamamı boşsa satar. Oysa çoğu zaman yolun parçalarında yer vardır; bunları birleştirince aynı trenle gidebilirsin.
Nasıl kullanılır
İki yol var. Tampermonkey ile bir kez kurarsın, yeni sürümler kendiliğinden gelir. Yalnızca denemek için konsol yeterli.
- Aşağıdan kodu kopyala.
- ebilet.tcddtasimacilik.gov.tr sitesini aç.
- Konsolu aç: F12 ya da Mac'te ⌥ ⌘ J, sonra Console.
- Kodu yapıştır, Enter. Panel sağ altta açılır.
Chrome ilk seferde yapıştırmayı engellerse allow pasting yaz, Enter'a bas. Sayfa yenilenince kodu tekrar yapıştırman gerekir.
- Tarayıcına Tampermonkey eklentisini kur.
chrome://extensions→ Tampermonkey → Ayrıntılar → Allow User Scripts'i aç.- Scripti kur bağlantısına tıkla; Tampermonkey kurulum ekranını açar, Yükle'ye bas.
- ebilet'i yeni sekmede aç; panel kendiliğinden görünür.
Panel görünmüyorsa Tampermonkey ikonuna tıkla ve scriptin bu sitede açık olduğunu kontrol et. Yeni sürümler GitHub'dan kendiliğinden gelir.
Panelde
- ebilet'te yolculuğunu ara, örneğin Ankara Gar → Bozüyük YHT.
- Panelde ilgilendiğin kalkış saatlerine tik at.
- Panel sıradaki aramayı forma yazar; sen sadece Enter'a basarsın.
- Rotalar her aramada güncellenir: en ucuz, en erken varış, en az bilet.
Klavye, ekran okuyucu ve sesli kullanım
- Alt + Shift + K paneli açar ve klavye odağını panele getirir. Sekmeler arasında ok tuşlarıyla geçilir.
- Her aramanın sonucu ekran okuyucuya duyurulur: kaç trende yer olduğu, kaç rota bulunduğu, sıradaki arama.
- Ayarlardaki Sesli bildirim açılırsa aynı duyurular cihazındaki Türkçe sesle okunur. Metin hiçbir yere gönderilmez.
- Düğmelerin adı ekranda yazanla aynıdır; sesle kontrol (macOS Sesle Denetim, Windows Sesli Erişim, Android Voice Access) ile “Formu doldur'a dokun” gibi komutlar çalışır.
// ==UserScript==
// @name ebilet için Koltuk Bulucu (resmi değil)
// @namespace tcdd-split-seat
// @version 0.9.0
// @description Dolu görünen seferler için ara istasyonlar üzerinden tüm rotaları çıkarır: aynı trende koltuk değiştirme, istasyonda bekleyip başka trene aktarma, fiyat ve süre karşılaştırması. Sıradaki aramayı forma yazar; her aramayı siz Enter ile başlatırsınız.
// @homepageURL https://github.com/yasarcelep/bilet-bul
// @supportURL https://github.com/yasarcelep/bilet-bul/issues
// @downloadURL https://raw.githubusercontent.com/yasarcelep/bilet-bul/main/src/ebilet-koltuk-bulucu.user.js
// @updateURL https://raw.githubusercontent.com/yasarcelep/bilet-bul/main/src/ebilet-koltuk-bulucu.user.js
// @match https://ebilet.tcddtasimacilik.gov.tr/*
// @run-at document-start
// @sandbox raw
// @inject-into page
// @grant none
// ==/UserScript==
/*
* NASIL ÇALIŞIR
* -------------
* ebilet her aramayı Cloudflare Turnstile ile koruyor. Script bu korumayı aşmaz:
* siteye kendisi istek atmaz, aramayı kendisi başlatmaz. Yaptığı:
* - sizin yaptığınız aramaların yanıtlarını okumak (bir arama o iki istasyon
* arasındaki BÜTÜN trenleri kapsar),
* - bilinen parçaları birleştirip rotaları çıkarmak (aynı trende koltuk
* değiştirme + istasyonda bekleyip başka trene aktarma),
* - sıradaki aramayı forma yazıp Ara butonuna odaklanmak → siz Enter'a basın.
*
* KULLANIM
* --------
* 1. Yolculuğunuzu arayın (ör. Ankara Gar → Bozüyük YHT).
* 2. Paneldeki listede ilgilendiğiniz kalkış saatlerine tik atın.
* 3. Script sıradaki aramayı forma yazar → Enter. Her aramadan sonra rota
* listesi güncellenir. İstediğiniz an durabilirsiniz.
* 4. Rotalar: en ucuz / en erken varış / en az bilet sıralaması.
*
* ERİŞİLEBİLİRLİK
* Panel klavyeyle ve ekran okuyucuyla kullanılır: Alt+Shift+K paneli açar ve
* odaklar, sekmeler ok tuşlarıyla gezilir, arama sonuçları duyurulur. Ayarlardan
* "Sesli bildirim" açılırsa sonuçlar tarayıcının yerel Türkçe sesiyle okunur.
*
* Engelli (tekerlekli sandalye) koltukları hesaba katılmaz.
* Veriler bu tarayıcıda 6 saat saklanır (localStorage).
*/
(() => {
'use strict';
if (window.__tcddSplitLoaded) return;
window.__tcddSplitLoaded = true;
const CFG = {
searchMatch: /\/train-availability(\?|$)/i,
seatMatch: /seat|vagon|wagon|coach/i,
ignoredClassCodes: ['DSB'],
ignoredClassRe: /tekerlek|engel|wheelchair/i,
storeKey: 'tcddSplit.v6',
maxAgeMs: 6 * 3600 * 1000,
minTransferMin: 10, // farklı trene geçişte en az bekleme
maxWaitMin: 240, // bir istasyonda en çok bekleme
maxLegs: 4, // bir rotada en çok bilet
windowMin: 120, // tik atılan kalkışın ± bu kadar dakikasındaki trenler de ilk bacak olabilir
autoFill: true, // her aramadan sonra sıradakini forma yaz
staleMin: 20, // bu kadar dakikadan eski koltuk bilgisi 'eski' sayılır
speak: false, // sonuçları yerel Türkçe sesle oku
debug: false,
};
const log = (...a) => CFG.debug && console.log('[tcdd-split]', ...a);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
/* ------------------------------------------------------------------ *
* STORAGE *
* pairs: "trainId|a>b" -> { usable, disabled, per, price, cls, *
* dep, arr, ts } *
* searched: "a>b|day" -> ts (a search covers every train) *
* journey: { o, d, day, ticks:[trainId], trainStops:{id:[stops]} } *
* log: [{ ts, a, b, day, kind, n, free, status, changes }] *
* ------------------------------------------------------------------ */
function emptyStore() { return { pairs: {}, searched: {}, names: {}, journey: null, log: [] }; }
function load() {
try {
const s = Object.assign(emptyStore(), JSON.parse(localStorage.getItem(CFG.storeKey)) || {});
const now = Date.now();
for (const k of Object.keys(s.pairs)) if (now - s.pairs[k].ts > CFG.maxAgeMs) delete s.pairs[k];
for (const k of Object.keys(s.searched)) if (now - s.searched[k] > CFG.maxAgeMs) delete s.searched[k];
if (s.journey && now - (s.journey.ts || 0) > CFG.maxAgeMs) s.journey = null;
s.log = (s.log || []).filter((e) => now - e.ts <= CFG.maxAgeMs).slice(-40);
return s;
} catch (e) { return emptyStore(); }
}
function save() { try { localStorage.setItem(CFG.storeKey, JSON.stringify(store)); } catch (e) { /* ignore */ } }
const store = load();
const ui = { sort: 'price', showAll: false, fillMsg: '', lastFilledKey: null };
const state = { lastSearch: null, lastSeat: null, store };
window.__tcddSplit = state;
const pairKey = (trainId, a, b) => `${trainId}|${a}>${b}`;
const searchedKey = (a, b, day) => `${a}>${b}|${day}`;
/* ------------------------------------------------------------------ *
* CAPTURE (read-only) — XHR (site uses it) + fetch fallback *
* ------------------------------------------------------------------ */
function handle(url, method, status, bodyText, respText) {
try {
if (CFG.searchMatch.test(url) && method === 'POST') {
let body = null, resp = null;
try { body = JSON.parse(bodyText); } catch (e) { /* no body */ }
try { resp = JSON.parse(respText); } catch (e) { /* not JSON */ }
if (status === 200 && body && resp) onSearch(body, resp);
else if (body && resp && resp.code === 604) onSearch(body, { trainLegs: [] }); // "no journeys match": an empty result
else onSearchFail(status, resp, body);
} else if (status === 200 && CFG.seatMatch.test(url) && !/availability/i.test(url)) {
onSeatMap(JSON.parse(respText));
}
} catch (e) { log('parse fail', url, e); }
}
function addLog(e) {
store.log.push(Object.assign({ ts: Date.now() }, e));
if (store.log.length > 40) store.log.splice(0, store.log.length - 40);
}
function onSearchFail(status, resp, body) {
const why = resp && (resp.message || resp.error) ? ` — ${String(resp.message || resp.error).slice(0, 80)}` : '';
const route = body && (body.searchRoutes || [])[0];
if (route) {
addLog({ a: route.departureStationId, b: route.arrivalStationId, day: dayOf(route.departureDate), kind: 'error', status });
save();
}
ui.fillMsg = `Site bu aramaya yanıt vermedi (HTTP ${status}${why}). Tekrar Enter'a basın ya da "Atla"yı kullanın.`;
log('search failed', status, resp);
render();
announce(ui.fillMsg, true);
}
const xo = XMLHttpRequest.prototype.open;
const xs = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function (m, u) {
this.__ts = { m: String(m).toUpperCase(), u: String(u) };
return xo.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function (b) {
const t = this.__ts;
if (t && (CFG.searchMatch.test(t.u) || CFG.seatMatch.test(t.u))) {
this.addEventListener('load', () => {
handle(t.u, t.m, this.status, typeof b === 'string' ? b : null, this.responseText);
});
}
return xs.apply(this, arguments);
};
const nf = window.fetch;
window.fetch = async function (input, init) {
const url = typeof input === 'string' ? input : (input && input.url) || '';
const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase();
const res = await nf.apply(this, arguments);
if (CFG.searchMatch.test(url) || CFG.seatMatch.test(url)) {
const body = init && typeof init.body === 'string' ? init.body : null;
res.clone().text().then((t) => handle(url, method, res.status, body, t)).catch(() => {});
}
return res;
};
/* ------------------------------------------------------------------ *
* PARSING — matches the live schema (checked 2026-12) *
* ------------------------------------------------------------------ */
function trainsOf(resp) {
return (resp.trainLegs || []).flatMap((l) => l.trainAvailabilities || []).flatMap((a) => a.trains || []);
}
const isIgnored = (cc) => CFG.ignoredClassCodes.includes(cc.code) || CFG.ignoredClassRe.test(cc.name || '');
// Usable seats per class + cheapest price among classes that still have seats.
function availOf(t) {
const rows = [];
for (const ff of t.availableFareInfo || []) for (const c of ff.cabinClasses || []) rows.push(c);
for (const c of t.cabinClassAvailabilities || []) rows.push(c);
const best = {};
for (const r of rows) {
const cc = r.cabinClass || {};
const name = cc.name || cc.code || '?';
const n = Math.max(0, Number(r.availabilityCount) || 0);
const price = typeof r.minPrice === 'number' ? r.minPrice : null;
const b = best[name] || (best[name] = { n: 0, cc, price: null });
if (n > b.n) b.n = n;
if (price != null && n > 0 && (b.price == null || price < b.price)) b.price = price;
}
const per = {};
let usable = 0, disabled = 0, price = null, cls = null;
for (const [name, b] of Object.entries(best)) {
if (isIgnored(b.cc)) { disabled += b.n; continue; }
usable += b.n;
if (b.n > 0) {
per[name] = b.n;
if (b.price != null && (price == null || b.price < price)) { price = b.price; cls = name; }
}
}
return { usable, disabled, per, price, cls };
}
function stopsOf(t) {
const stops = [];
for (const s of t.segments || []) {
const seg = s.segment || {};
const d = seg.departureStation, a = seg.arrivalStation;
if (d) {
const ex = stops.find((x) => x.id === d.id);
if (!ex) stops.push({ id: d.id, name: d.name, dep: s.departureTime });
else if (ex.dep == null) ex.dep = s.departureTime;
}
if (a && !stops.some((x) => x.id === a.id)) stops.push({ id: a.id, name: a.name, arr: s.arrivalTime });
}
return stops;
}
const depOf = (t) => { const s = (t.segments || [])[0]; return s ? s.departureTime : null; };
const arrOf = (t) => { const s = (t.segments || []).slice(-1)[0]; return s ? s.arrivalTime : null; };
// "05-12-2026 21:00:00" is the UTC start of the Istanbul day searched.
function dayOf(apiDate) {
const m = String(apiDate || '').match(/(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2})/);
if (!m) return '?';
const ms = Date.UTC(+m[3], +m[2] - 1, +m[1], +m[4], +m[5]) + 3 * 3600 * 1000;
return new Date(ms).toLocaleDateString('tr-TR', { timeZone: 'Europe/Istanbul' });
}
const tz = { timeZone: 'Europe/Istanbul' };
const dayOf2 = (ms) => (ms == null ? '?' : new Date(ms).toLocaleDateString('tr-TR', tz));
const fmtTime = (ms) => (ms == null ? '' : new Date(ms).toLocaleTimeString('tr-TR', Object.assign({ hour: '2-digit', minute: '2-digit' }, tz)));
const fmtDay = (day) => {
const m = String(day).match(/(\d+)\.(\d+)\.(\d+)/);
if (!m) return day;
return new Date(Date.UTC(+m[3], +m[2] - 1, +m[1], 12)).toLocaleDateString('tr-TR', { day: 'numeric', month: 'long', timeZone: 'UTC' });
};
const fmtDur = (ms) => {
const min = Math.round(ms / 60000);
const h = Math.floor(min / 60), m = min % 60;
return h ? `${h} sa${m ? ' ' + m + ' dk' : ''}` : `${m} dk`;
};
const ago = (ts) => {
const m = Math.round((Date.now() - ts) / 60000);
return m < 1 ? 'az önce' : m < 60 ? `${m} dk önce` : `${Math.floor(m / 60)} sa önce`;
};
// Forget that these pairs were searched, so the panel asks for them again.
function recheck(pairs) {
const j = J();
if (!j) return;
for (const [a, b] of pairs) delete store.searched[searchedKey(a, b, j.day)];
ui.lastFilledKey = null;
ui.fillMsg = '';
save(); render();
}
const fmtPrice = (p) => (p == null ? '₺?' : '₺' + Math.round(p).toLocaleString('tr-TR'));
const nameOf = (id) => store.names[id] || String(id);
const KEEP_UPPER = new Set(['YHT']);
const title = (s) => String(s || '').split(/(\s+|\(|\))/).map((w) => {
if (KEEP_UPPER.has(w)) return w;
const l = w.toLocaleLowerCase('tr-TR');
return l.charAt(0).toLocaleUpperCase('tr-TR') + l.slice(1);
}).join('');
function onSearch(body, resp) {
const route = (body.searchRoutes || [])[0];
if (!route) return;
const a = route.departureStationId, b = route.arrivalStationId;
const day = dayOf(route.departureDate);
if (route.departureStationName) store.names[a] = route.departureStationName;
if (route.arrivalStationName) store.names[b] = route.arrivalStationName;
const trains = trainsOf(resp);
const now = Date.now();
const changes = [];
let free = 0;
for (const t of trains) {
for (const s of stopsOf(t)) store.names[s.id] = s.name;
const k = pairKey(t.id, a, b);
const prev = store.pairs[k];
const cur = Object.assign(availOf(t), { dep: depOf(t), arr: arrOf(t), ts: now });
if (prev && prev.usable !== cur.usable) changes.push({ dep: cur.dep, from: prev.usable, to: cur.usable });
if (cur.usable > 0) free++;
store.pairs[k] = cur;
}
// trains we knew on this pair that are gone now: no seats left
const seen = new Set(trains.map((t) => String(t.id)));
for (const [k, p] of Object.entries(store.pairs)) {
const m = k.match(/^(\d+)\|(\d+)>(\d+)$/);
if (!m || +m[2] !== a || +m[3] !== b || seen.has(m[1]) || p.ts >= now) continue;
if (dayOf2(p.dep) !== day) continue;
if (p.usable > 0) changes.push({ dep: p.dep, from: p.usable, to: 0 });
store.pairs[k] = Object.assign({}, p, { usable: 0, per: {}, price: null, ts: now, gone: true });
}
addLog({ a, b, day, kind: trains.length ? 'ok' : 'empty', n: trains.length, free, changes });
store.searched[searchedKey(a, b, day)] = now;
if (J() && J().day === day) J().ts = now; // still in use: keep it past maxAgeMs
save();
state.lastSearch = { a, b, day, trains };
ui.fillMsg = '';
log('search', a, '>', b, day, trains.length);
render();
announce(searchSummary(a, b, day, trains.length, free, changes));
}
// One sentence for screen readers / speech after each search.
function searchSummary(a, b, day, n, free, changes) {
let t = `${title(nameOf(a))} → ${title(nameOf(b))}: ` +
(n ? `${n} tren, ${free ? `${free} tanesinde yer var` : 'hepsi dolu'}.` : 'sefer yok.');
const opened = changes.filter((c) => c.from === 0 && c.to > 0).length;
if (opened) t += ` ${opened} seferde yer açıldı.`;
const j = J();
if (j && j.day === day && j.ticks.length) {
const m = model();
t += ` ${m.routes.length ? `${m.routes.length} rota bulundu.` : 'Henüz rota yok.'}`;
t += m.next ? ` Sıradaki arama: ${title(nameOf(m.next.a))} → ${title(nameOf(m.next.b))}.` : ' Tüm aramalar tamam.';
}
return t;
}
/* ------------------------------------------------------------------ *
* JOURNEY *
* ------------------------------------------------------------------ */
const J = () => store.journey;
const isJourneySearch = (ls) => !J() || (J().o === ls.a && J().d === ls.b && J().day === ls.day);
// Ordered station list of the journey, merged from all ticked trains.
function journeyStations() {
const j = J();
let list = [];
for (const id of j.ticks) {
const stops = j.trainStops[id] || [];
if (stops.length > list.length) list = stops.map((s) => s.id);
}
for (const id of j.ticks) {
const stops = (j.trainStops[id] || []).map((s) => s.id);
stops.forEach((sid, k) => {
if (list.includes(sid)) return;
const prev = stops.slice(0, k).reverse().find((x) => list.includes(x));
list.splice(prev == null ? 0 : list.indexOf(prev) + 1, 0, sid);
});
}
return list;
}
// Tick a train of the last search; starts the journey on the first tick.
function addTick(t) {
const ls = state.lastSearch;
if (!J()) store.journey = { o: ls.a, d: ls.b, day: ls.day, ticks: [], trainStops: {}, tickDep: {}, ts: Date.now() };
const j = J();
j.tickDep = j.tickDep || {};
j.ts = Date.now();
ui.lastFilledKey = null;
if (j.ticks.includes(t.id)) return;
j.ticks.push(t.id);
j.trainStops[t.id] = stopsOf(t).map((s) => ({ id: s.id, name: s.name }));
j.tickDep[t.id] = depOf(t);
}
// Untick; the journey ends with its last tick.
function dropTick(id) {
const j = J();
if (!j) return;
j.ticks = j.ticks.filter((x) => x !== id);
delete j.trainStops[id];
if (j.tickDep) delete j.tickDep[id];
if (!j.ticks.length) store.journey = null;
ui.lastFilledKey = null;
}
function toggleTick(t) {
if (J() && J().ticks.includes(t.id)) dropTick(t.id); else addTick(t);
save(); render();
}
/* ------------------------------------------------------------------ *
* ROUTES — all itineraries from known pairs *
* First ticket must be on a ticked departure. A train change needs *
* minTransfer..maxWait minutes; continuing on the same train is a *
* seat change at the stop (no wait). *
* ------------------------------------------------------------------ */
function buildEdges(stations) {
const idx = new Map(stations.map((s, i) => [s, i]));
const from = new Map();
for (const [k, p] of Object.entries(store.pairs)) {
if (!(p.usable > 0) || p.dep == null || p.arr == null) continue;
const m = k.match(/^(\d+)\|(\d+)>(\d+)$/);
if (!m) continue;
const train = +m[1], a = +m[2], b = +m[3];
if (!idx.has(a) || !idx.has(b) || idx.get(a) >= idx.get(b)) continue;
const e = { train, a, b, dep: p.dep, arr: p.arr, price: p.price, cls: p.cls, seats: p.usable, ts: p.ts };
if (!from.has(a)) from.set(a, []);
from.get(a).push(e);
}
return from;
}
// Departure time of a ticked train at the journey origin.
function tickDep(id) {
const j = J();
if (j.tickDep && j.tickDep[id] != null) return j.tickDep[id];
const p = Object.entries(store.pairs).find(([k]) => k.startsWith(id + '|' + j.o + '>'));
return p ? p[1].dep : null;
}
// A first leg is allowed if it leaves the origin within ±windowMin of any
// ticked departure (or is the ticked train itself).
function firstLegOk(e) {
const j = J();
if (j.ticks.includes(e.train)) return true;
const w = CFG.windowMin * 60000;
return j.ticks.some((id) => { const t0 = tickDep(id); return t0 != null && Math.abs(e.dep - t0) <= w; });
}
function findRoutes() {
const j = J();
const stations = journeyStations();
const edges = buildEdges(stations);
const routes = [];
const reached = new Set([j.o]);
const sameTrainDirect = (x, y) => {
const p = store.pairs[pairKey(x.train, x.a, y.b)];
return p && p.usable > 0;
};
const dfs = (st, arrT, last, legs) => {
if (legs.length) reached.add(st);
if (st === j.d) { routes.push(legs); return; }
if (legs.length >= CFG.maxLegs || routes.length > 400) return;
for (const e of edges.get(st) || []) {
if (!legs.length) { if (!firstLegOk(e)) continue; }
else if (e.train === last.train) {
if (e.dep < arrT - 60000) continue;
if (sameTrainDirect(last, e)) continue; // a single ticket covers it
} else {
const w = e.dep - arrT;
if (w < CFG.minTransferMin * 60000 || w > CFG.maxWaitMin * 60000) continue;
}
dfs(e.b, e.arr, e, legs.concat(e));
}
};
dfs(j.o, null, null, []);
return { stations, reached, routes: routes.map(summarize) };
}
function summarize(legs) {
const prices = legs.map((l) => l.price);
return {
legs,
dep: legs[0].dep,
arr: legs[legs.length - 1].arr,
price: prices.includes(null) ? null : prices.reduce((s, x) => s + x, 0),
tickets: legs.length,
changes: legs.filter((l, i) => i && l.train !== legs[i - 1].train).length,
seats: Math.min(...legs.map((l) => l.seats)),
checked: Math.min(...legs.map((l) => l.ts || 0)),
};
}
const SORTS = {
price: { label: 'En ucuz', fn: (x, y) => (x.price ?? 1e12) - (y.price ?? 1e12) || x.arr - y.arr },
arr: { label: 'En erken varış', fn: (x, y) => x.arr - y.arr || (x.price ?? 1e12) - (y.price ?? 1e12) },
tickets: { label: 'En az bilet', fn: (x, y) => x.tickets - y.tickets || x.changes - y.changes || (x.price ?? 1e12) - (y.price ?? 1e12) },
};
// Next search: an unsearched pair starting at a reachable station,
// earliest station first, farthest destination first.
function nextSearch(found) {
const j = J();
const st = found.stations;
const todo = [];
for (let i = 0; i < st.length - 1; i++) {
if (!found.reached.has(st[i])) continue;
for (let k = st.length - 1; k > i; k--) {
if (!store.searched[searchedKey(st[i], st[k], j.day)]) todo.push({ a: st[i], b: st[k] });
}
}
return { next: todo[0] || null, left: todo.length };
}
/* ------------------------------------------------------------------ *
* FORM PREFILL — writes from/to into the site's own form and focuses *
* its search button. Never clicks it: each search starts with your *
* own Enter/click, so the site's Turnstile check sees you. *
* ------------------------------------------------------------------ */
const normName = (s) => String(s).toLocaleUpperCase('tr-TR').replace(/\s+/g, ' ').trim();
function setInput(el, v) {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(el, v);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: 'a' }));
}
const visible = (e) => e && e.offsetParent !== null;
function findToggle(kind) {
const byId = document.getElementById(kind === 'from' ? 'fromTrainInput' : 'toTrainInput');
if (visible(byId)) return byId;
const nm = kind === 'from' ? 'Tren kalkış' : 'Tren varış';
return [...document.querySelectorAll(`input[name="${nm}"]`)].find(visible) || null;
}
function findSearchButton() {
const byId = document.getElementById('searchSeferButton');
if (visible(byId)) return byId;
return [...document.querySelectorAll('button')].find((b) => visible(b) && /^(sefer ara|ara)$/i.test(b.innerText.trim())) || null;
}
async function pickStation(kind, name) {
const toggle = findToggle(kind);
if (!toggle) return false;
if (normName(toggle.value).startsWith(normName(name) + ' ,')) return true;
const wrap = toggle.closest('.dropdown') || toggle.parentElement;
if (!wrap.classList.contains('show')) { toggle.click(); await sleep(300); }
const search = [...wrap.querySelectorAll('input')].find((e) => e !== toggle && e.type === 'text');
if (!search) return false;
setInput(search, name);
for (let i = 0; i < 25; i++) {
await sleep(150);
const btn = [...wrap.querySelectorAll('button.dropdown-item')].find((b) => {
const m = normName(b.innerText).match(/^(?:İSTASYON )?(.+?) ,/);
return m && m[1] === normName(name);
});
if (btn) { btn.click(); await sleep(300); return true; }
}
return false;
}
async function prefill(a, b, retry) {
ui.fillMsg = 'Form dolduruluyor…'; render();
const ok = (await pickStation('from', nameOf(a))) && (await pickStation('to', nameOf(b)));
const sb = ok && findSearchButton();
if (sb) {
sb.focus();
sb.style.outline = '3px solid #38d39f';
sb.style.outlineOffset = '2px';
sb.addEventListener('blur', () => { sb.style.outline = ''; }, { once: true });
}
ui.fillMsg = ok
? `Form hazır: ${title(nameOf(a))} → ${title(nameOf(b))}. Enter'a basın${J() ? ` (tarih ${fmtDay(J().day)} olmalı)` : ''}.`
: 'Form bulunamadı ya da istasyon seçilemedi — bu aramayı elle yapın.';
render();
announce(ui.fillMsg, !ok);
if (ok && !retry) {
await sleep(1500);
const f = findToggle('from'), t = findToggle('to');
const holds = (el, name) => el && normName(el.value).startsWith(normName(name) + ' ,');
if (!holds(f, nameOf(a)) || !holds(t, nameOf(b))) { log('form was reset by the site, refilling'); prefill(a, b, true); }
}
}
function maybeAutoFill(nx) {
if (!CFG.autoFill || !nx) return;
const key = `${nx.a}>${nx.b}|${J().day}`;
if (ui.lastFilledKey === key) return;
ui.lastFilledKey = key;
setTimeout(() => prefill(nx.a, nx.b), 900);
}
/* ------------------------------------------------------------------ *
* SEAT MAP — generic parse of whatever the site loads *
* ------------------------------------------------------------------ */
const SEATNUM_KEYS = ['seatNumber', 'seatNo', 'koltukNo', 'number', 'name'];
const CAR_KEYS = ['carName', 'carNo', 'carIndex', 'carNumber', 'vagonNo'];
const POS_KEYS = ['available', 'isAvailable', 'selectable', 'isSelectable', 'empty', 'isEmpty'];
const NEG_KEYS = ['reserved', 'isReserved', 'locked', 'isLocked', 'sold', 'isSold', 'occupied', 'allocated'];
const STATUS_KEYS = ['status', 'state', 'seatStatus', 'durum'];
const FREE_RE = /^(available|empty|free|bos|boş|musait|müsait)$/i;
const OCC_RE = /(reserved|sold|occupied|dolu|taken|locked|rezerve|allocated)/i;
const DIS_RE = /engel|tekerlek|wheelchair|\bdsb\b/i;
function extractSeats(resp) {
const cars = new Map(), dis = new Map();
let free = 0, disabled = 0, unknown = 0;
const cls = (o) => {
for (const k of POS_KEYS) if (o[k] === true) return 'free';
for (const k of NEG_KEYS) if (o[k] === true) return 'occ';
for (const k of POS_KEYS) if (o[k] === false) return 'occ';
for (const k of STATUS_KEYS) if (k in o) {
const v = o[k];
if (v === 0 || v === '0') return 'free';
if (typeof v === 'string') { if (FREE_RE.test(v)) return 'free'; if (OCC_RE.test(v)) return 'occ'; }
if (typeof v === 'number') return 'occ';
}
return 'unknown';
};
const looksDis = (o) => Object.entries(o).some(([k, v]) =>
(typeof v === 'string' && DIS_RE.test(v)) || (v === true && DIS_RE.test(k)) ||
(v && typeof v === 'object' && !Array.isArray(v) && Object.values(v).some((x) => typeof x === 'string' && DIS_RE.test(x))));
const walk = (o, car) => {
if (!o || typeof o !== 'object') return;
if (Array.isArray(o)) { o.forEach((x) => walk(x, car)); return; }
for (const k of CAR_KEYS) if (typeof o[k] === 'number' || typeof o[k] === 'string') { car = String(o[k]); break; }
const nk = SEATNUM_KEYS.find((k) => typeof o[k] === 'string' || typeof o[k] === 'number');
if (nk && POS_KEYS.concat(NEG_KEYS, STATUS_KEYS).some((k) => k in o)) {
const c = cls(o);
if (c === 'free') {
const m = looksDis(o) ? dis : cars;
if (m === dis) disabled++; else free++;
const key = car || '?';
if (!m.has(key)) m.set(key, []);
m.get(key).push(String(o[nk]));
} else if (c === 'unknown') unknown++;
return;
}
Object.values(o).forEach((v) => walk(v, car));
};
walk(resp, null);
return { cars, dis, free, disabled, unknown };
}
function onSeatMap(resp) {
const seats = extractSeats(resp);
if (!seats.free && !seats.disabled && !seats.unknown) return;
state.lastSeat = { seats, raw: resp, ts: Date.now() };
render();
}
/* ------------------------------------------------------------------ *
* PANEL — rendered inside a shadow root so ebilet's own CSS cannot *
* touch it. Layout: header • next-step card • tabs (Rotalar / *
* Seferler / Geçmiş) • scrollable body. Collapses to a summary pill. *
* ------------------------------------------------------------------ */
const SETTINGS_KEYS = ['windowMin', 'minTransferMin', 'maxWaitMin', 'autoFill', 'speak'];
store.settings = store.settings || {};
for (const k of SETTINGS_KEYS) if (k in store.settings) CFG[k] = store.settings[k];
const prefs = (() => { try { return JSON.parse(localStorage.getItem(CFG.storeKey + '.ui')) || {}; } catch (e) { return {}; } })();
const savePrefs = () => { try { localStorage.setItem(CFG.storeKey + '.ui', JSON.stringify({ collapsed: ui.collapsed })); } catch (e) { /* ignore */ } };
ui.collapsed = !!prefs.collapsed;
ui.tab = null; // 'routes' | 'trains' | 'log'; null = pick automatically
ui.settings = false;
const CSS = `
:host{all:initial}
*{box-sizing:border-box;min-width:0}
.sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
h2,h3,h4{margin:0;font:inherit}
.card,.pill{font:14px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#111827;-webkit-font-smoothing:antialiased}
.card{width:min(410px,calc(100vw - 24px));max-height:min(760px,calc(100vh - 24px));display:flex;flex-direction:column;background:#fff;border:1px solid #e5e7eb;border-radius:18px;box-shadow:0 20px 50px rgba(17,24,39,.22),0 2px 6px rgba(17,24,39,.08);overflow:hidden}
.pill{display:flex;align-items:center;gap:10px;background:#111827;color:#fff;border:0;border-radius:999px;padding:10px 16px 10px 12px;box-shadow:0 10px 30px rgba(17,24,39,.3);cursor:pointer;font-weight:600}
.pill small{font-weight:400;color:#d1d5db}
header{display:flex;align-items:center;gap:10px;padding:12px 12px 12px 14px;border-bottom:1px solid #f0f1f3}
header .t{flex:1}
header h2{display:block;font-size:15px;font-weight:700}
header h2:focus{outline:none}
header span{display:block;color:#6b7280;font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.icon{width:34px;height:34px;border-radius:10px;border:0;background:transparent;color:#374151;font-size:17px;cursor:pointer;display:grid;place-items:center}
.icon:hover{background:#f3f4f6}
button{font:inherit}
.btn{border:1px solid #d1d5db;background:#fff;color:#111827;border-radius:10px;padding:7px 12px;min-height:36px;font-weight:600;font-size:13.5px;cursor:pointer;white-space:nowrap}
.btn:hover{background:#f9fafb}
.btn.primary{background:#e30a17;border-color:#e30a17;color:#fff}
.btn.primary:hover{background:#c80814}
.btn.link{border:0;background:none;color:#e30a17;padding:4px 0;min-height:0}
.btn:focus-visible,.icon:focus-visible,.tab:focus-visible,.row:focus-visible,.pill:focus-visible,.seg button:focus-visible,.body:focus-visible,.set input:focus-visible{outline:2px solid #e30a17;outline-offset:2px}
.next{margin:12px 12px 0;padding:12px;border-radius:14px;background:#fef2f2;border:1px solid #fecaca}
.next.done{background:#ecfdf5;border-color:#a7f3d0}
.next .lab{font-size:12px;color:#991b1b;font-weight:600}
.next.done .lab{color:#065f46}
.next .route{font-size:16px;font-weight:700;margin:2px 0 8px}
.bar{height:6px;border-radius:3px;background:rgba(17,24,39,.08);overflow:hidden;margin-bottom:10px}
.bar i{display:block;height:100%;background:#e30a17;border-radius:3px}
.next.done .bar i{background:#0a8a4a}
.acts{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.msg{margin-top:8px;font-size:12.5px;color:#4b5563}
.msg.err{color:#b45309}
.tabs{display:flex;gap:4px;margin:12px 12px 0;padding:4px;background:#f3f4f6;border-radius:12px}
.tab{flex:1;border:0;background:transparent;border-radius:9px;padding:7px 4px;font-weight:600;font-size:13.5px;color:#4b5563;cursor:pointer}
.tab[aria-selected=true]{background:#fff;color:#111827;box-shadow:0 1px 3px rgba(0,0,0,.12)}
.tab em{font-style:normal;font-size:11.5px;background:#e30a17;color:#fff;border-radius:999px;padding:0 6px;margin-left:4px}
.body{overflow:auto;padding:12px 12px 14px;flex:1}
.sec{font-size:12px;font-weight:600;color:#6b7280;margin:4px 0 6px}
.empty{padding:22px 10px;text-align:center;color:#6b7280}
.empty b{display:block;color:#111827;font-size:15px;margin-bottom:4px}
.warnbox{padding:10px 12px;border-radius:12px;background:#fffbeb;border:1px solid #fde68a;color:#78350f;font-size:13px}
.warnbox b{display:block;margin-bottom:4px}
.target{display:flex;align-items:center;gap:10px;padding:8px 10px;border:1px solid #e5e7eb;border-radius:12px;margin-bottom:6px}
.target .tm{font-weight:700;font-size:16px;font-variant-numeric:tabular-nums}
.target .st{flex:1;font-size:13px}
.ok{color:#0a8a4a}.wait{color:#6b7280}.bad{color:#b45309}
.seg{display:flex;gap:4px;margin:12px 0 8px;flex-wrap:wrap}
.seg button{border:1px solid #e5e7eb;background:#fff;border-radius:999px;padding:5px 11px;min-height:32px;font-size:12.5px;font-weight:600;color:#374151;cursor:pointer}
.seg button[aria-pressed=true]{background:#111827;border-color:#111827;color:#fff}
.rc{border:1px solid #e5e7eb;border-radius:14px;padding:12px;margin-bottom:8px}
.rc.best{border-color:#0a8a4a;box-shadow:0 0 0 1px #0a8a4a inset}
.rh{font-weight:400;display:flex;align-items:baseline;justify-content:space-between;gap:8px}
.price{font-size:20px;font-weight:800;color:#0a8a4a;letter-spacing:-.01em}
.times{font-weight:700;font-variant-numeric:tabular-nums}
.meta{color:#6b7280;font-size:12.5px;margin:2px 0 8px}
.tl{position:relative;margin-left:6px;padding-left:16px;border-left:2px solid #e5e7eb}
.stop{position:relative;padding:3px 0;display:flex;justify-content:space-between;gap:8px;font-size:13.5px}
.stop::before{content:"";position:absolute;left:-22px;top:8px;width:10px;height:10px;border-radius:50%;background:#fff;border:2px solid #111827}
.stop .c{color:#6b7280;font-size:12.5px;white-space:nowrap}
.xfer{margin:3px 0;padding:4px 8px;border-radius:8px;font-size:12.5px;background:#fff7ed;color:#9a3412}
.xfer.same{background:#eff6ff;color:#1e40af}
.rf{display:flex;justify-content:space-between;align-items:center;margin-top:8px;font-size:12px;color:#6b7280}
.rf.stale{color:#b45309}
.row{display:flex;align-items:center;gap:10px;padding:9px 10px;border-radius:12px;cursor:pointer;border:1px solid transparent}
.row:hover{background:#f9fafb}
.row.on{background:#fef2f2;border-color:#fecaca}
.row.static{cursor:default}
.box{width:20px;height:20px;border-radius:6px;border:2px solid #d1d5db;flex:none;display:grid;place-items:center;color:#fff;font-size:13px;font-weight:800}
.row.on .box{background:#e30a17;border-color:#e30a17}
.row .tm{font-weight:700;font-variant-numeric:tabular-nums;flex:1}
.badge{font-size:12.5px;font-weight:600;border-radius:999px;padding:2px 9px;white-space:nowrap}
.badge.free{background:#ecfdf5;color:#065f46}
.badge.full{background:#f3f4f6;color:#4b5563}
.note{font-size:12px;color:#6b7280;margin:6px 2px}
.log{padding:7px 0;border-bottom:1px solid #f3f4f6;font-size:13px}
.log .w{color:#6b7280;font-variant-numeric:tabular-nums;margin-right:6px}
.chg{font-size:12.5px;padding-left:44px}
.set label{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid #f3f4f6}
.set input[type=number]{width:84px;font:inherit;font-size:16px;padding:5px 8px;border:1px solid #d1d5db;border-radius:8px;text-align:right}
.set small{display:block;color:#6b7280;font-size:12px}
.seats div{font-size:13px;padding:2px 0}
`;
// Shadow root layout: <style>, two live regions that stay put (so screen
// readers hear what is written into them), and `view`, redrawn by render().
let host, root, view, liveEl, alertEl;
function ensurePanel() {
if (host && document.body && document.body.contains(host)) return true;
if (!document.body) return false;
host = document.createElement('div');
host.id = 'tcdd-split-panel';
host.lang = 'tr';
host.style.cssText = 'position:fixed;right:12px;bottom:12px;z-index:2147483647;';
root = host.attachShadow({ mode: 'open' });
root.appendChild(h('style', null, CSS));
liveEl = h('div', 'sr');
liveEl.setAttribute('role', 'status');
liveEl.setAttribute('aria-live', 'polite');
alertEl = h('div', 'sr');
alertEl.setAttribute('role', 'alert');
view = h('div');
root.append(liveEl, alertEl, view);
document.body.appendChild(host);
return true;
}
/* ------------------------------------------------------------------ *
* ANNOUNCEMENTS — live region for screen readers; optional speech *
* with a voice that runs on this device (no text leaves the browser) *
* ------------------------------------------------------------------ */
function announce(text, urgent) {
if (!text || !ensurePanel()) return;
const el = urgent ? alertEl : liveEl;
el.textContent = '';
setTimeout(() => { el.textContent = text; }, 60); // cleared first, so a repeated message is read again
if (CFG.speak) say(text);
}
function trVoice() {
const ss = window.speechSynthesis;
if (!ss || !window.SpeechSynthesisUtterance) return null;
return ss.getVoices().find((v) => /^tr\b/i.test(v.lang) && v.localService) || null;
}
function say(text) {
const v = trVoice();
if (!v) return false;
const u = new window.SpeechSynthesisUtterance(String(text).replace(/\s*→\s*/g, ', '));
u.voice = v;
u.lang = v.lang;
window.speechSynthesis.cancel();
window.speechSynthesis.speak(u);
return true;
}
if (window.speechSynthesis && window.speechSynthesis.addEventListener) {
window.speechSynthesis.addEventListener('voiceschanged', () => { if (ui.settings) render(); });
}
// Alt+Shift+K: open the panel and put the keyboard focus in it.
document.addEventListener('keydown', (e) => {
if (!(e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && e.code === 'KeyK')) return;
e.preventDefault();
ui.collapsed = false;
savePrefs();
ui.focusKey = 'fill';
render();
}, true);
const esc = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const h = (tag, cls, html) => { const e = document.createElement(tag); if (cls) e.className = cls; if (html != null) e.innerHTML = html; return e; };
// Every button carries data-k, a key that survives a redraw, so render()
// can give the keyboard focus back to the same control.
const button = (label, cls, fn, attrs) => {
const b = h('button', cls, label);
b.type = 'button';
b.dataset.k = `${cls}:${b.textContent}`;
for (const [k, v] of Object.entries(attrs || {})) b.setAttribute(k, v);
b.addEventListener('click', (e) => { e.stopPropagation(); fn(); });
return b;
};
function model() {
const j = J();
const found = j && j.ticks.length ? findRoutes() : null;
const routes = found ? found.routes.slice().sort(SORTS[ui.sort].fn) : [];
const ns = found ? nextSearch(found) : { next: null, left: 0 };
let done = 0;
if (found) {
const st = found.stations;
for (let i = 0; i < st.length - 1; i++) for (let k = i + 1; k < st.length; k++) if (store.searched[searchedKey(st[i], st[k], j.day)]) done++;
}
return { j, found, routes, next: ns.next, left: ns.left, done };
}
function render() {
if (!ensurePanel()) { document.addEventListener('DOMContentLoaded', render, { once: true }); return; }
const m = model();
const prevBody = view.querySelector('.body');
const scroll = prevBody ? prevBody.scrollTop : 0;
// Focus is given back only if it was in the panel (or asked for): a
// redraw after a search must not pull it away from ebilet's form.
const active = root.activeElement;
const want = ui.focusKey || (active ? (active.dataset && active.dataset.k) || '-' : null);
ui.focusKey = null;
view.innerHTML = '';
const body = draw(m);
if (body) body.scrollTop = scroll;
if (want) {
const el = [...view.querySelectorAll('[data-k]')].find((e) => e.dataset.k === want) || view.querySelector('.pill, h2');
if (el) el.focus({ preventScroll: true });
}
if (!ui.collapsed && !ui.settings && m.next) maybeAutoFill(m.next);
}
function draw(m) {
if (ui.collapsed) { view.appendChild(pill(m)); return null; }
const card = h('section', 'card');
card.setAttribute('aria-label', 'Koltuk Bulucu');
card.appendChild(header(m));
view.appendChild(card);
if (ui.settings) {
const b = h('div', 'body');
b.appendChild(settingsView());
card.appendChild(b);
return b;
}
if (m.j && m.j.ticks.length) card.appendChild(nextCard(m));
const tab = ui.tab || (m.j && m.j.ticks.length ? 'routes' : 'trains');
const tabs = h('div', 'tabs');
tabs.setAttribute('role', 'tablist');
tabs.setAttribute('aria-label', 'Panel bölümleri');
const defs = [['routes', 'Rotalar', m.routes.length], ['trains', 'Seferler', 0], ['log', 'Geçmiş', 0]];
const go = (id) => { ui.tab = id; ui.focusKey = 'tab:' + id; render(); };
for (const [id, label, n] of defs) {
tabs.appendChild(button(`${label}${n ? `<em>${n}</em>` : ''}`, 'tab', () => go(id), {
role: 'tab', id: 'tcdd-tab-' + id, 'aria-selected': String(tab === id), 'aria-controls': 'tcdd-tabpanel',
tabindex: tab === id ? '0' : '-1', 'data-k': 'tab:' + id,
}));
}
// arrow keys move between tabs (WAI-ARIA tabs pattern)
tabs.addEventListener('keydown', (e) => {
const ids = defs.map((d) => d[0]);
const i = ids.indexOf(tab);
const to = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: ids.length - 1 }[e.key];
if (to == null) return;
e.preventDefault();
go(ids[(to + ids.length) % ids.length]);
});
card.appendChild(tabs);
const body = h('div', 'body');
body.id = 'tcdd-tabpanel';
body.setAttribute('role', 'tabpanel');
body.setAttribute('aria-labelledby', 'tcdd-tab-' + tab);
body.tabIndex = 0;
body.appendChild(tab === 'routes' ? routesView(m) : tab === 'trains' ? trainsView(m) : logView());
card.appendChild(body);
return body;
}
function pill(m) {
const prices = m.routes.map((r) => r.price).filter((p) => p != null);
const cheapest = prices.length ? ` · en ucuz ${fmtPrice(Math.min(...prices))}` : '';
const sub = !m.j ? 'hazır' : m.routes.length ? `${m.routes.length} rota${cheapest}` : m.next ? 'aramalar sürüyor' : 'yer yok';
return button(`Koltuk Bulucu <small>${esc(sub)}</small>`, 'pill', () => { ui.collapsed = false; savePrefs(); render(); },
{ 'aria-expanded': 'false', title: 'Koltuk Bulucu panelini aç (Alt+Shift+K)', 'data-k': 'pill' });
}
function header(m) {
const hd = h('header');
const t = h('div', 't');
const sub = m.j ? `${title(nameOf(m.j.o))} → ${title(nameOf(m.j.d))} · ${fmtDay(m.j.day)}` : 'ebilet\'te yolculuğunu ara';
t.innerHTML = `<h2 tabindex="-1">Koltuk Bulucu</h2><span>${esc(sub)}</span>`;
hd.appendChild(t);
const setLabel = ui.settings ? 'Ayarları kapat' : 'Ayarlar';
hd.appendChild(button(ui.settings ? '✕' : '⚙', 'icon', () => { ui.settings = !ui.settings; render(); },
{ 'aria-label': setLabel, title: setLabel, 'aria-expanded': String(ui.settings), 'data-k': 'settings' }));
hd.appendChild(button('–', 'icon', () => { ui.collapsed = true; savePrefs(); render(); },
{ 'aria-label': 'Küçült', title: 'Küçült', 'aria-expanded': 'true', 'data-k': 'min' }));
return hd;
}
function nextCard(m) {
const total = m.done + m.left;
const pct = total ? Math.round((m.done / total) * 100) : 100;
const c = h('div', 'next' + (m.next ? '' : ' done'));
if (m.next) {
c.innerHTML = `<div class="lab">Sıradaki arama · ${m.done + 1} / ${total}</div>` +
`<div class="route">${esc(title(nameOf(m.next.a)))} → ${esc(title(nameOf(m.next.b)))}</div>` +
`<div class="bar" role="progressbar" aria-label="Arama ilerlemesi" aria-valuemin="0" aria-valuemax="${total}" aria-valuenow="${m.done}" aria-valuetext="${m.done} / ${total} arama yapıldı"><i style="width:${pct}%"></i></div>`;
const a = h('div', 'acts');
a.appendChild(button('Formu doldur', 'btn primary', () => { ui.lastFilledKey = `${m.next.a}>${m.next.b}|${m.j.day}`; prefill(m.next.a, m.next.b); }, { 'data-k': 'fill' }));
a.appendChild(button('Atla', 'btn', () => { store.searched[searchedKey(m.next.a, m.next.b, m.j.day)] = Date.now(); ui.fillMsg = ''; save(); render(); }));
c.appendChild(a);
c.appendChild(h('div', 'msg' + (/yanıt vermedi|bulunamadı/.test(ui.fillMsg) ? ' err' : ''),
esc(ui.fillMsg || 'Form dolunca ebilet\'te Enter\'a bas; sonuç kendiliğinden okunur.')));
} else {
c.innerHTML = `<div class="lab">Tüm aramalar tamam · ${total}</div><div class="bar" aria-hidden="true"><i style="width:100%"></i></div>`;
const a = h('div', 'acts');
a.appendChild(button('Hepsini yeniden kontrol et', 'btn', recheckAll, { 'data-k': 'fill' }));
c.appendChild(a);
}
return c;
}
function recheckAll() {
const st = journeyStations();
const pairs = [];
for (let i = 0; i < st.length - 1; i++) for (let k = i + 1; k < st.length; k++) pairs.push([st[i], st[k]]);
recheck(pairs);
}
/* ---------- Rotalar ---------- */
function routesView(m) {
const v = h('div');
if (!m.j || !m.j.ticks.length) {
v.appendChild(h('div', 'empty', '<b>Henüz yolculuk seçilmedi</b>Yolculuğunu ara, sonra <b style="display:inline">Seferler</b> sekmesinde ilgilendiğin kalkış saatlerine tik at.'));
if (state.lastSearch) v.appendChild(button('Seferlere git', 'btn primary', () => { ui.tab = 'trains'; render(); }));
return v;
}
v.appendChild(h('h3', 'sec', 'Hedefler'));
const w = CFG.windowMin * 60000;
for (const id of m.j.ticks.slice().sort((x, y) => (tickDep(x) || 0) - (tickDep(y) || 0))) {
const t0 = tickDep(id);
const mine = m.routes.filter((r) => r.legs.some((l) => l.train === id) || (t0 != null && Math.abs(r.dep - t0) <= w));
let st;
if (mine.length) {
const b = mine[0];
const how = b.tickets === 1 ? 'tek bilet' : b.changes ? `${b.tickets} bilet, ${b.changes} aktarma` : `${b.tickets} bilet, aynı tren`;
st = `<span class="ok"><b>${fmtPrice(b.price)}</b> · ${b.dep !== t0 ? `kalkış ${fmtTime(b.dep)}, ` : ''}varış ${fmtTime(b.arr)}</span><br><span class="wait">${how}${mine.length > 1 ? ` · +${mine.length - 1} seçenek` : ''}</span>`;
} else if (m.next) st = '<span class="wait">aramalar sürüyor…</span>';
else st = '<span class="bad">şu an yer yok</span>';
const row = h('div', 'target', `<span class="tm">${fmtTime(t0)}</span><span class="st">${st}</span>`);
const rm = `${fmtTime(t0)} hedefini kaldır`;
row.appendChild(button('✕', 'icon', () => removeTick(id), { 'aria-label': rm, title: rm, 'data-k': 'rm:' + id }));
v.appendChild(row);
}
if (!m.routes.length) {
if (m.next) v.appendChild(h('div', 'empty', '<b>Rotalar aramalarla birlikte gelecek</b>Üstteki kutudaki aramayı yap; her sonuçtan sonra liste güncellenir.'));
else v.appendChild(h('div', 'warnbox',
'<b>Seçili saatler için şu an yer yok</b>Tüm parçalar arandı, satılabilir koltuk kalmamış. Başka saatlere tik atabilir, ' +
'ebilet\'te seferin yanındaki 🔔 zil ile TCDD\'nin boş yer bildirimini açabilir ya da bir süre sonra “Hepsini yeniden kontrol et”e basabilirsin.'));
return v;
}
const seg = h('div', 'seg');
seg.setAttribute('role', 'group');
seg.setAttribute('aria-label', 'Sıralama');
for (const [k, s] of Object.entries(SORTS)) seg.appendChild(button(s.label, '', () => { ui.sort = k; render(); }, { 'aria-pressed': String(ui.sort === k) }));
v.appendChild(seg);
const shown = ui.showAll ? m.routes : m.routes.slice(0, 5);
shown.forEach((r, i) => v.appendChild(routeCard(r, i === 0)));
if (m.routes.length > 5) v.appendChild(button(ui.showAll ? 'Daha az göster' : `Tüm rotalar (${m.routes.length})`, 'btn', () => { ui.showAll = !ui.showAll; render(); }, { 'aria-expanded': String(ui.showAll), 'data-k': 'more' }));
return v;
}
function routeCard(r, best) {
const c = h('article', 'rc' + (best ? ' best' : ''));
const kind = r.tickets === 1 ? 'tek bilet' : `${r.tickets} bilet · ${r.changes ? `${r.changes} aktarma` : 'aynı tren'}`;
c.innerHTML = `<h4 class="rh"><span class="price">${fmtPrice(r.price)}</span><span class="times">${fmtTime(r.dep)} → ${fmtTime(r.arr)}</span></h4>` +
`<div class="meta">${fmtDur(r.arr - r.dep)} · ${kind} · ${r.seats} koltuk</div>`;
const tl = h('div', 'tl');
r.legs.forEach((l, i) => {
if (i) {
const prev = r.legs[i - 1];
const where = esc(title(nameOf(l.a)));
tl.appendChild(l.train === prev.train
? h('div', 'xfer same', `${where} · aynı trende koltuk değiştir`)
: h('div', 'xfer', `${where} · ${fmtDur(l.dep - prev.arr)} bekle, sonraki trene bin`));
}
tl.appendChild(h('div', 'stop', `<span><b>${fmtTime(l.dep)}</b> ${esc(title(nameOf(l.a)))}</span><span class="c">${esc(title(l.cls || ''))} ${fmtPrice(l.price)}</span>`));
});
const last = r.legs[r.legs.length - 1];
tl.appendChild(h('div', 'stop', `<span><b>${fmtTime(last.arr)}</b> ${esc(title(nameOf(last.b)))}</span>`));
c.appendChild(tl);
const stale = Date.now() - r.checked > CFG.staleMin * 60000;
const f = h('div', 'rf' + (stale ? ' stale' : ''), `<span>${ago(r.checked)} kontrol edildi${stale ? ' · almadan önce yenile' : ''}</span>`);
f.appendChild(button('Tekrar kontrol et', 'btn link', () => recheck(r.legs.map((l) => [l.a, l.b]))));
c.appendChild(f);
return c;
}
function removeTick(id) { dropTick(id); save(); render(); }
/* ---------- Seferler ---------- */
function trainsView() {
const v = h('div');
const ls = state.lastSearch;
if (!ls) {
v.appendChild(h('div', 'empty', '<b>Arama bekleniyor</b>ebilet\'te gitmek istediğin iki istasyonu ve tarihi seçip ara. Seferler burada listelenecek.'));
return seatsBlock(v);
}
const tickable = isJourneySearch(ls);
const wrongDay = J() && J().day !== ls.day;
v.appendChild(h('h3', 'sec', `Son arama: ${esc(title(nameOf(ls.a)))} → ${esc(title(nameOf(ls.b)))} · ${esc(fmtDay(ls.day))}`));
if (wrongDay) {
v.appendChild(h('div', 'warnbox', `<b>Farklı gün</b>Bu arama ${esc(fmtDay(ls.day))} için, yolculuğun ${esc(fmtDay(J().day))}. Formdaki tarihi düzeltip tekrar ara.`));
} else if (!tickable) {
v.appendChild(h('div', 'note', 'Bu bir ara parça araması; sonuçlar rotalara eklendi.'));
}
if (!ls.trains.length) {
v.appendChild(h('div', 'warnbox', tickable && !J()
? '<b>Sefer bulunamadı</b>Bu tarihte bu iki istasyon arasında sefer yok. Başka bir gün ya da yakın bir istasyon dene.'
: '<b>Bu parçada sefer yok</b>Rota hesabında atlandı.'));
return seatsBlock(v);
}
if (tickable && !wrongDay) {
v.appendChild(h('div', 'note', 'Gitmek istediğin saatlere tik at; dolu olanlar için ara istasyonlardan rota aranır.'));
}
const ticks = new Set(J() ? J().ticks : []);
for (const t of ls.trains.slice().sort((x, y) => (depOf(x) || 0) - (depOf(y) || 0))) {
const p = store.pairs[pairKey(t.id, ls.a, ls.b)] || {};
const on = ticks.has(t.id);
const can = tickable && !wrongDay;
const row = h('div', 'row' + (on ? ' on' : '') + (can ? '' : ' static'));
if (can) {
row.setAttribute('role', 'checkbox');
row.setAttribute('aria-checked', String(on));
row.tabIndex = 0;
row.dataset.k = 'row:' + t.id;
const box = h('span', 'box', on ? '✓' : '');
box.setAttribute('aria-hidden', 'true');
row.appendChild(box);
row.addEventListener('click', () => toggleTick(t));
row.addEventListener('keydown', (e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); toggleTick(t); } });
}
row.appendChild(h('span', 'tm', `${fmtTime(depOf(t))} → ${fmtTime(arrOf(t))}`));
row.appendChild(p.usable > 0
? h('span', 'badge free', `${p.usable} boş · ${fmtPrice(p.price)}`)
: h('span', 'badge full', 'dolu'));
v.appendChild(row);
}
if (tickable && !wrongDay) {
const untick = ls.trains.filter((t) => !ticks.has(t.id));
if (untick.length) {
const a = h('div', 'acts');
a.style.marginTop = '8px';
a.appendChild(button('Dolu olanların hepsini seç', 'btn', () => {
for (const t of untick) { const p = store.pairs[pairKey(t.id, ls.a, ls.b)] || {}; if (!(p.usable > 0)) addTick(t); }
save(); render();
}));
v.appendChild(a);
}
}
return seatsBlock(v);
}
function seatsBlock(v) {
const ls = state.lastSeat;
if (!ls) return v;
const { seats } = ls;
v.appendChild(h('h3', 'sec', 'Son açılan koltuk haritası'));
const b = h('div', 'seats');
b.innerHTML = `<div class="ok"><b>Boş koltuklar (${seats.free})</b></div>` +
([...seats.cars.entries()].map(([c, l]) => `<div>Vagon ${esc(c)}: ${l.map(esc).join(', ')}</div>`).join('') || '<div>—</div>') +
(seats.disabled ? `<div class="bad">Engelli (${seats.disabled}): ${[...seats.dis.entries()].map(([c, l]) => `Vagon ${esc(c)}: ${l.map(esc).join(', ')}`).join(' · ')}</div>` : '') +
(!seats.free && seats.unknown ? `<div class="bad">${seats.unknown} koltuğun durumu çözümlenemedi.</div>` : '');
v.appendChild(b);
return v;
}
/* ---------- Geçmiş ---------- */
function logView() {
const v = h('div');
const entries = store.log.slice(-20).reverse();
if (!entries.length) {
v.appendChild(h('div', 'empty', '<b>Henüz arama yok</b>Yaptığın her arama burada görünür; aynı parçayı tekrar aradığında açılan ve dolan koltuklar da yazar.'));
return v;
}
for (const e of entries) {
let res;
if (e.kind === 'ok') res = e.free ? `${e.n} tren · <span class="ok">yer olan: ${e.free}</span>` : `${e.n} tren · <span class="wait">hepsi dolu</span>`;
else if (e.kind === 'empty') res = '<span class="bad">sefer yok</span>';
else res = `<span class="bad">hata (HTTP ${esc(e.status)})</span>`;
const other = J() && e.day !== J().day ? ` <span class="wait">· ${esc(fmtDay(e.day))}</span>` : '';
const d = h('div', 'log', `<span class="w">${fmtTime(e.ts)}</span>${esc(title(nameOf(e.a)))} → ${esc(title(nameOf(e.b)))}${other}<br><span style="padding-left:44px;display:inline-block">${res}</span>`);
for (const c of (e.changes || []).slice(0, 5)) {
const up = c.to > c.from;
d.appendChild(h('div', 'chg ' + (up ? 'ok' : 'bad'),
`${fmtTime(c.dep)} kalkış: ${c.from} → ${c.to} boş${up && c.from === 0 ? ' · yer açıldı' : !up && c.to === 0 ? ' · doldu' : ''}`));
}
v.appendChild(d);
}
return v;
}
/* ---------- Ayarlar ---------- */
function settingsView() {
const v = h('div', 'set');
v.appendChild(h('h3', 'sec', 'Ayarlar'));
const num = (key, label, hint, min, max) => {
const l = h('label', null, `<span>${label}<small>${hint}</small></span>`);
const i = document.createElement('input');
i.type = 'number'; i.min = min; i.max = max; i.step = 5; i.value = CFG[key];
i.addEventListener('change', () => {
const n = Math.max(min, Math.min(max, Math.round(Number(i.value) || 0)));
i.value = n; CFG[key] = n; store.settings[key] = n; save();
});
l.appendChild(i);
v.appendChild(l);
};
num('windowMin', 'Saat penceresi (dk)', 'Tik attığın kalkışın bu kadar öncesi/sonrası da sayılır', 0, 360);
num('minTransferMin', 'En az aktarma süresi (dk)', 'Başka trene geçerken gereken süre', 0, 120);
num('maxWaitMin', 'En çok bekleme (dk)', 'Bir istasyonda beklenebilecek en uzun süre', 15, 720);
const check = (key, label, hint, after) => {
const l = h('label', null, `<span>${label}<small>${hint}</small></span>`);
const cb = document.createElement('input');
cb.type = 'checkbox'; cb.checked = !!CFG[key];
cb.addEventListener('change', () => { CFG[key] = cb.checked; store.settings[key] = cb.checked; save(); if (after) after(cb.checked); });
l.appendChild(cb);
v.appendChild(l);
};
check('autoFill', 'Sıradaki aramayı forma yaz', 'Her aramadan sonra formu otomatik doldurur');
const voice = trVoice();
check('speak', 'Sesli bildirim', 'Arama sonuçlarını, açılan yerleri ve hataları Türkçe sesle okur',
(on) => { if (on) say('Sesli bildirim açık.'); });
if (!voice) {
v.appendChild(h('div', 'note', 'Bu tarayıcıda cihazda çalışan bir Türkçe ses bulunamadı; sesli bildirim sessiz kalır. ' +
'Ekran okuyucu kullanıyorsan duyurular yine okunur. Türkçe sesi işletim sisteminin dil ayarlarından ekleyebilirsin.'));
}
const a = h('div', 'acts');
a.style.marginTop = '14px';
a.appendChild(button('Bitti', 'btn primary', () => { ui.settings = false; render(); }));
a.appendChild(button('Tüm verileri sil', 'btn', () => {
store.pairs = {}; store.searched = {}; store.journey = null; store.log = [];
state.lastSearch = null; ui.fillMsg = ''; ui.lastFilledKey = null; ui.settings = false;
save(); render();
announce('Tüm veriler silindi.');
}));
v.appendChild(a);
v.appendChild(h('div', 'note', 'Kısayol: <b>Alt+Shift+K</b> paneli açar ve klavye odağını panele getirir. Sekmeler arasında ok tuşlarıyla geçilir.'));
v.appendChild(h('div', 'note', 'Veriler yalnızca bu tarayıcıda, 6 saat tutulur. Script siteye kendisi istek atmaz.'));
return v;
}
/* ------------------------------------------------------------------ */
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', render, { once: true });
else render();
console.info('%c[koltuk-bulucu] v0.9.0 yüklendi — siteye istek atmaz; her aramayı siz başlatırsınız. Panel: Alt+Shift+K.', 'color:#e30a17');
})();
Siteye istek atmaz
Yalnızca senin ebilet'te yaptığın aramaların yanıtlarını okur. Kendi başına arama yapmaz, Ara'ya basmaz.
Veri sende kalır
Sonuçlar sadece senin tarayıcında 6 saat saklanır, hiçbir yere gönderilmez.
Herkes için
Klavyeyle, ekran okuyucuyla ve sesle kullanılır. Sonuçlar istersen sesli okunur.
Bilet ebilet'ten
Rotayı bulduktan sonra biletleri her zamanki gibi ebilet'te alırsın. Engelli koltukları hesaba katılmaz.