ctucx.git: oeffi-web

[nimlang] oeffisearch fork that works without javascript

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
'use strict';

import { showDiv, ElementById, padZeros, isValidDate } from './helpers.js';
import { getCache, addCache, parseName, saveDataStorage, ConsoleLog, t, loadDS100 } from './app_functions.js';
import { dataStorage } from './app.js';
import { get } from './api.js';
import { go } from './router.js';
import { html, render } from './lit-html.js';
import { showAlertModal, showLoader, hideLoader} from './overlays.js';
import { showSettings } from './settingsView.js';


let currDate             = new Date();
let fromValue            = '';
let toValue              = '';
let isArrValue           = false;
let dateValue            = currDate.getFullYear()+'-'+padZeros(currDate.getMonth()+1)+'-'+padZeros(currDate.getDate());;
let timeValue            = padZeros(currDate.getHours())+':'+padZeros(currDate.getMinutes());
let suggestionsCache     = {
	from: {},
	to: {},
};

const searchTemplate = (journeysHistory) => html`
	<div id="searchView">
		<div class="inputs">
			<input type="text" id="from" value="${fromValue}" placeholder="${t('from')}" autocomplete="off" @keyup=${loadSuggestions} @focus=${startTyping} @blur=${stopTyping} @keypress=${onKeypress}>
		  <div class="suggestions" id="fromsuggestions"></div>
			<input type="text" id="to" value="${toValue}" placeholder="${t('to')}" autocomplete="off" @keyup=${loadSuggestions} @focus=${startTyping} @blur=${stopTyping} @keypress=${onKeypress}>
		  <div class="suggestions" id="tosuggestions"></div>
			<div id="datetime">
				<div id="deparr">
					<label class="switch">
						<input type="checkbox" id="isarr" ?checked=${isArrValue}>
						<span class="slider"></span>
					</label>
				</div>
				<input type="date" id="date" placeholder="${t('date')} (YYYY-MM-DD)" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" value="${dateValue}">
				<input type="time" id="time" placeholder="${t('time')} (HH:MM" pattern="[0-9]{2}:[0-9]{2}" value="${timeValue}">
			</div>
		</div>

		<div class="row">
			<div class="product_selector">
				<input type="checkbox" id="national">
				<label for="national" title="${t('longdistancetrain')}">&nbsp;</label>

				<input type="checkbox" id="regional">
				<label for="regional" title="${t('regionaltrain')}">&nbsp;</label>

				<input type="checkbox" id="suburban">
				<label for="suburban" title="${t('suburbantrain')}">&nbsp;</label>

				<input type="checkbox" id="subway">
				<label for="subway" title="${t('subway')}">&nbsp;</label>

				<input type="checkbox" id="tram">
				<label for="tram" title="${t('tram')}">&nbsp;</label>

				<input type="checkbox" id="bus">
				<label for="bus" title="${t('bus')}">&nbsp;</label>

				<input type="checkbox" id="ferry">
				<label for="ferry" title="${t('ferry')}">&nbsp;</label>

				<input type="checkbox" id="taxi"> 
				<label for="taxi" title="${t('taxi')}">&nbsp;</label>
			</div>
			<div class="button swap" id="swap" title="${t('swap')}" @click=${swapFromTo}></div>

			<a class="button settings" title="${t('settings')}" @click=${showSettings}></a>
			<div class="button search" tabindex="0" id="search" title="${t('search')}" @click=${search}></div>
		</div>

		${journeysHistory.length ? html`
			${journeysHistoryTemplate(journeysHistory)}
		` : ''}
	</div>
`;

const journeysHistoryTemplate = (journeysHistory) => html`
	<div id="journeysHistory">
		<table>
			<thead>
				<tr><th>${t('from')}</th><th>${t('to')}</th><th>${t('options')}</th></tr>
			</thead>
			<tbody id="journeysHistoryTable">
				${journeysHistory.map(element => html`
					<tr class="fromHistory" @click=${() => setFromHistory(journeysHistory.length - 1 - journeysHistory.indexOf(element))}" title="${t('setfromto')}">
						<td>${parseName(element.fromPoint)}</td>
						<td>${parseName(element.toPoint)}</td>
						<td>
							<a class="departures" href="#/${element.reqId}" title="${t('journeyoverview')}"></a>
							${element.journeyId === '' ? '' : html`
								<a class="directions" href="#/${element.reqId}/${element.journeyId}" title="${t('lastjourney')}"></a>
							`}
						</td>
					</tr>
				`)}
			</tbody>
		</table>
	</div>
`;

export const searchView = () => {
	const journeysHistory = getCache('journeysHistory').slice().reverse();	
	render(searchTemplate(journeysHistory), ElementById('content'));

	ElementById('from').focus();

	for (let product in dataStorage.settings.products) {
		if (ElementById(product) !== null) {
			ElementById(product).checked = dataStorage.settings.products[product];
		}
	};
};

export const search = async (requestId) => {
	const provider      = dataStorage.settings.provider;
	let   products      = readProductSelection();
	const accessibility = dataStorage.settings.accessibility;
	let   isDep         = !ElementById('isarr').checked;
	let   date          = ElementById('date').value;
	let   time          = ElementById('time').value;
	let   timestamp     = '';
	let   from          = '';
	let   to            = '';

	currDate   = new Date();
	fromValue  = ElementById('from').value;
	toValue    = ElementById('to').value;
	dateValue  = ElementById('date').value;
	timeValue  = ElementById('time').value;
	isArrValue = ElementById('isarr').checked;

	if (date !== '') {
		if (!isValidDate(date)) {
			showAlertModal('Ungültiges Datum!');
			return;
		}
	} else {
		date = currDate.getFullYear()+'-'+padZeros(currDate.getMonth()+1)+'-'+padZeros(currDate.getDate());
	}

	if (time !== '') {
		if (!new RegExp('([0-1][0-9]|2[0-3]):([0-5][0-9])').test(time)) {
			showAlertModal('Ungültige Zeitangabe!');
			return;
		}
	} else {
		time = padZeros(currDate.getHours())+':'+padZeros(currDate.getMinutes());
	}

	if (ElementById('from').value == "" | ElementById('to').value == "") {
		showAlertModal("Abfahrts - und Ankunftsbahnhof müssen ausgefüllt werden.");
		return;
	}

	if (Object.entries(suggestionsCache.from).length !== 0) {
		from = suggestionsCache.from;
	} else {
		let suggestions = await get("/suggestions",  {"query": ElementById('from').value, "results": 1}, true);

		if (!suggestions[0]) {
    		showAlertModal("Abfahrtsbahnof ungültig");
			return;
  		}

		from = suggestions[0]
	}

	if (Object.entries(suggestionsCache.to).length !== 0) {
		to = suggestionsCache.to;
	} else {
		let suggestions = await get("/suggestions",  {"query": ElementById('to').value, "results": 1}, true);

		if (!suggestions[0]) {
			showAlertModal("Ankunftsbahnhof ungültig");
			return;
  		}

		to = suggestions[0]
	}

	dataStorage.settings.products = products;
	saveDataStorage();


	const split_date = date.split('-');
	const split_time = time.split(':');

	timestamp = Math.round(new Date(split_date[0], split_date[1]-1, split_date[2], split_time[0], split_time[1]).getTime()/1000);

	ConsoleLog(timestamp+'///'+date+' '+time+':00');

	let params = {
			"fromPoint":     from,
			"toPoint":       to,
			"accessibility": accessibility,
			"products":      products
		}

	if (!isDep) {
		params.arrival = timestamp
	} else {
		params.departure = timestamp
	}

	const data = await get("/journeys", {"params":params});
	addCache('journeys', data);
	go('/' + data.reqId);
};

const suggestionsTemplate = (suggestions, inputId) => html`
  <div class="suggestionsbox" @mouseover=${mouseOverSuggestions} @mouseout=${stopMouseOverSuggestions}>
  	${suggestions.map(element => html`
  		<p class="suggestion" @click=${() => setSuggestion(encodeURI(JSON.stringify(element)), inputId)}>${parseName(element)}</p>
  	`)}
  </div>
`;

const loadSuggestions = async (e, input) => {
	const val = e.target.value;
	suggestionsCache[e.target.id] = {};
	const suggestions = val ? await get("/suggestions",  {"query": val}, true) : [];
	const suggestionsEl = ElementById(e.target.id+'suggestions');
	render(suggestionsTemplate(suggestions, e.target.id), suggestionsEl);
};

export const setSuggestion  = (data, inputId) => {
	if (typeof data === 'string') {
		data = JSON.parse(decodeURI(data));
	}

	suggestionsCache[inputId] = data;
	ElementById(inputId).value = parseName(data);

	if (inputId === 'from') {
	  ElementById('fromsuggestions').classList.remove('mouseover');
		ElementById('to').focus();
	} else if (inputId === 'to') {
	  ElementById('tosuggestions').classList.remove('mouseover');
    ElementById('to').blur();
  }
};

export const swapFromTo  = () => {
	suggestionsCache.from = [suggestionsCache.to, suggestionsCache.to = suggestionsCache.from][0];

	let from = ElementById('from');
	let to   = ElementById('to');

	from.value = [to.value, to.value = from.value][0];
};

export const setFromHistory  = (id) => {
	const cache = getCache('journeysHistory');

	if (cache[id] !== undefined){
		setSuggestion(cache[id].fromPoint, 'from');
		setSuggestion(cache[id].toPoint, 'to');
	}
};

export const readProductSelection  = () => {
	let products = {
			"nationalExp": false,
			"national":        false,
			"regionalExp":     false,
			"regional":        false,
			"suburban":        false,
			"bus":             false,
			"ferry":           false,
			"subway":          false,
			"tram":            false,
			"taxi":            false
		}

	if (ElementById('national').checked !== false) {
		products.nationalExp = true;
		products.national    = true;
	}

	if (ElementById('regional').checked !== false) {
		products.regionalExp = true;
		products.regional    = true;
	}

	if (ElementById('suburban').checked !== false) {
		products.suburban = true;
	}

	if (ElementById('subway').checked !== false) {
		products.subway = true;
	}

	if (ElementById('tram').checked !== false) {
		products.tram = true;
	}
	
	if (ElementById('bus').checked !== false) {
		products.bus = true; 
	}

	if (ElementById('ferry').checked !== false) {
		products.ferry = true;
	}

	if (ElementById('taxi').checked !== false) {
		products.taxi = true;
	}

	return products;
};

const startTyping = (e) => {
	ElementById(e.target.id+'suggestions').classList.add('typing');
	if (e.target.id == 'from') ElementById('tosuggestions').classList.remove('mouseover');
	if (e.target.id == 'to') ElementById('fromsuggestions').classList.remove('mouseover');
};

const stopTyping = (e) => {
	ElementById(e.target.id+'suggestions').classList.remove('typing');
};

const mouseOverSuggestions = (e) => {
  let el = e.target;
  let i = 0;
  while (i++ < 10 && el.id !== 'fromsuggestions' && el.id !== 'tosuggestions') el = el.parentElement;
	el.classList.add('mouseover');
};

const stopMouseOverSuggestions = (e) => {
  let el = e.target;
  let i = 0;
  while (i++ < 10 && el.id !== 'fromsuggestions' && el.id !== 'tosuggestions') el = el.parentElement;
	el.classList.remove('mouseover');
};

const onKeypress = (e) => {
  if (e.which == 13 || e.keyCode == 13) { // enter
    document.querySelector(`#${e.target.id}suggestions>.suggestionsbox>:first-child`).click();
    if (e.target.id === 'to') ElementById('go').click();
    return false;
  }
  return true;
};