-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
462 lines (410 loc) · 12.9 KB
/
Copy pathscript.js
File metadata and controls
462 lines (410 loc) · 12.9 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
let airportData = {};
const defaultSuggestions = ['JFK', 'LHR', 'LAX', 'ATL'];
const maxSuggestions = 8;
let searchIndex = null;
let activeIndex = -1;
const RECENTS_KEY = 'simpleskies-recents';
const MAX_RECENTS = 5;
const airportInput = document.getElementById('airportInput');
const recentsRoot = document.getElementById('recentSearches');
const suggestionsRoot = document.getElementById('suggestions');
const randomAirportButton = document.getElementById('randomAirport');
const airportInfo = document.getElementById('airportInfo');
const findInfoButton = document.getElementById('findInfo');
const lookupForm = document.getElementById('lookupForm');
const themeToggle = document.getElementById('themeToggle');
function safeText(value) {
return value === undefined || value === null || value === '' ? 'N/A' : String(value);
}
function formatElevation(value) {
const text = safeText(value);
return text === 'N/A' ? text : `${text} ft`;
}
function setMessage(message, isError = false) {
const messageElement = document.createElement('span');
messageElement.textContent = message;
if (isError) {
messageElement.className = 'error-message';
}
airportInfo.replaceChildren(messageElement);
}
function createSuggestionItem(code, info) {
const item = document.createElement('div');
item.className = 'suggestion-item';
const title = document.createElement('span');
title.className = 'suggestion-title';
title.appendChild(document.createElement('strong'));
title.firstChild.textContent = code;
title.appendChild(document.createTextNode(` — ${safeText(info.name)}`));
const subtitle = document.createElement('span');
subtitle.className = 'suggestion-sub';
subtitle.textContent = safeText(info.location);
item.appendChild(title);
item.appendChild(subtitle);
item.id = `suggestion-${code}`;
item.setAttribute('role', 'option');
item.setAttribute('aria-selected', 'false');
item.dataset.code = code;
item.addEventListener('click', () => selectSuggestion(code));
item.addEventListener('mouseenter', () => {
setActive(optionElements().indexOf(item));
});
return item;
}
function optionElements() {
return Array.from(suggestionsRoot.querySelectorAll('.suggestion-item'));
}
function setActive(index) {
const options = optionElements();
if (options.length === 0) {
activeIndex = -1;
airportInput.removeAttribute('aria-activedescendant');
return;
}
activeIndex = Math.min(Math.max(index, 0), options.length - 1);
options.forEach((option, i) => {
option.classList.toggle('active', i === activeIndex);
option.setAttribute('aria-selected', i === activeIndex ? 'true' : 'false');
});
airportInput.setAttribute('aria-activedescendant', options[activeIndex].id);
}
function searchAirports(rawQuery) {
if (!searchIndex || !rawQuery || !rawQuery.trim()) {
return [];
}
const query = rawQuery.trim();
const upper = query.toUpperCase();
const lower = query.toLowerCase();
const seen = new Set();
const results = [];
const addMatch = (code) => {
if (!seen.has(code) && results.length < maxSuggestions) {
seen.add(code);
results.push(code);
}
};
const exhausted = () => results.length === maxSuggestions;
// 1. Codes beginning with the query (JFK -> JFK…).
for (const entry of searchIndex) {
if (entry.code.startsWith(upper)) {
addMatch(entry.code);
if (exhausted()) {
return results;
}
}
}
// 2. Short queries that begin with a full code (Denver -> DEN, Dallas -> DAL).
// Capped to short queries so long words like "heathrow" don't surface
// unrelated codes that merely prefix them (e.g. HEA = Herat).
if (query.length <= 6) {
const codePrefixMatches = searchIndex
.filter(entry => upper.startsWith(entry.code))
.sort((a, b) => b.code.length - a.code.length);
for (const entry of codePrefixMatches) {
addMatch(entry.code);
if (exhausted()) {
return results;
}
}
}
// 3. Word-boundary hits (e.g. "lon" -> "London Heathrow").
for (const entry of searchIndex) {
if (entry.hay.includes(` ${lower}`)) {
addMatch(entry.code);
if (exhausted()) {
return results;
}
}
}
// 4. Any substring hit anywhere in code, name, or location.
for (const entry of searchIndex) {
if (entry.hay.includes(lower)) {
addMatch(entry.code);
if (exhausted()) {
break;
}
}
}
return results;
}
function buildSearchIndex() {
searchIndex = Object.keys(airportData).map(code => ({
code,
hay: `${code} ${safeText(airportData[code].name)} ${safeText(airportData[code].location)}`.toLowerCase()
}));
}
function showSuggestions(inputValue = '') {
suggestionsRoot.replaceChildren();
const normalizedInput = inputValue.trim().toUpperCase();
if (!normalizedInput) {
renderRecents();
}
const codes = normalizedInput
? searchAirports(inputValue)
: defaultSuggestions.filter((code, index, list) => (
list.indexOf(code) === index && airportData[code]
));
if (codes.length === 0) {
return;
}
const suggestions = document.createElement('div');
suggestions.className = 'suggestions-container';
codes.forEach(code => suggestions.appendChild(createSuggestionItem(code, airportData[code])));
suggestionsRoot.appendChild(suggestions);
activeIndex = -1;
airportInput.setAttribute('aria-expanded', 'true');
}
function findAirportInfo() {
const query = airportInput.value.trim();
const airportCode = query.toUpperCase();
if (!airportCode) {
setMessage('Enter a 3-letter airport code.', true);
hideSuggestions();
return;
}
if (airportCode.length === 3 && airportData[airportCode]) {
showAirport(airportCode);
hideSuggestions();
renderRecents();
return;
}
const matches = searchAirports(query);
if (matches.length > 0) {
showSuggestions(query);
return;
}
setMessage('Airport code not found in our database.', true);
hideSuggestions();
}
let copyResetTimeout = null;
function airportPlainText(info) {
return [
`Name: ${safeText(info.name)}`,
`Location: ${safeText(info.location)}`,
`Elevation: ${formatElevation(info.elevation)}`,
`ICAO: ${safeText(info.icao)}`,
`IATA: ${safeText(info.iata)}`,
`Timezone: ${safeText(info.timezone)}`
].join('\n');
}
function flashCopyState(button, text) {
button.textContent = text;
clearTimeout(copyResetTimeout);
copyResetTimeout = setTimeout(() => {
button.textContent = 'Copy';
copyResetTimeout = null;
}, 1500);
}
function execCommandCopy(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
let succeeded = false;
try {
succeeded = document.execCommand('copy');
} catch (error) {
succeeded = false;
}
textarea.remove();
return succeeded;
}
async function copyAirportDetails(button, info) {
const text = airportPlainText(info);
try {
if (!(navigator.clipboard && navigator.clipboard.writeText)) {
throw new Error('Clipboard API unavailable');
}
await navigator.clipboard.writeText(text);
flashCopyState(button, 'Copied ✓');
} catch (error) {
flashCopyState(button, execCommandCopy(text) ? 'Copied ✓' : 'Copy failed');
}
}
function showAirport(code) {
airportInput.value = code;
const info = airportData[code];
saveRecent(code);
const fields = [
['Name', info.name],
['Location', info.location],
['Elevation', formatElevation(info.elevation)],
['ICAO Code', info.icao],
['IATA Code', info.iata],
['Timezone', info.timezone]
];
const details = document.createDocumentFragment();
fields.forEach(([label, value]) => {
const labelElement = document.createElement('strong');
labelElement.textContent = `${label}:`;
details.appendChild(labelElement);
details.append(` ${safeText(value)}`);
details.appendChild(document.createElement('br'));
});
const copyButton = document.createElement('button');
copyButton.type = 'button';
copyButton.className = 'secondary-button copy-button';
copyButton.textContent = 'Copy';
copyButton.addEventListener('click', () => {
copyAirportDetails(copyButton, info);
});
const header = document.createElement('div');
header.className = 'info-header';
header.appendChild(copyButton);
const card = document.createDocumentFragment();
card.appendChild(header);
card.appendChild(details);
airportInfo.replaceChildren(card);
updateHash(code);
}
function updateHash(code) {
try {
history.replaceState(null, '', `#${code}`);
} catch (error) {
// History API unavailable (e.g. sandboxed frame): lookup still works.
}
}
function applyHash() {
const code = window.location.hash.slice(1).toUpperCase();
if (code && airportData[code]) {
showAirport(code);
return true;
}
return false;
}
function loadRecents() {
try {
const raw = localStorage.getItem(RECENTS_KEY);
const parsed = raw ? JSON.parse(raw) : [];
if (!Array.isArray(parsed)) {
return [];
}
return parsed.filter(code => typeof code === 'string' && airportData[code]).slice(0, MAX_RECENTS);
} catch (error) {
return [];
}
}
function saveRecent(code) {
try {
const next = [code, ...loadRecents().filter(entry => entry !== code)].slice(0, MAX_RECENTS);
localStorage.setItem(RECENTS_KEY, JSON.stringify(next));
} catch (error) {
// Storage unavailable (e.g. private mode): recents stay session-only.
}
}
function renderRecents() {
recentsRoot.replaceChildren();
if (airportInput.value.trim()) {
return;
}
const recents = loadRecents();
if (recents.length === 0) {
return;
}
const label = document.createElement('span');
label.className = 'recent-label';
label.textContent = 'Recent:';
recentsRoot.appendChild(label);
recents.forEach(code => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'recent-chip';
chip.textContent = code;
chip.addEventListener('click', () => selectSuggestion(code));
recentsRoot.appendChild(chip);
});
const clear = document.createElement('button');
clear.type = 'button';
clear.className = 'recent-chip recent-clear';
clear.textContent = 'Clear';
clear.addEventListener('click', () => {
try {
localStorage.removeItem(RECENTS_KEY);
} catch (error) {
// Storage unavailable: still clear the visible chips.
}
renderRecents();
});
recentsRoot.appendChild(clear);
}
function hideSuggestions() {
suggestionsRoot.replaceChildren();
activeIndex = -1;
airportInput.setAttribute('aria-expanded', 'false');
airportInput.removeAttribute('aria-activedescendant');
}
function selectSuggestion(value) {
showAirport(value);
hideSuggestions();
}
function toggleMode() {
const nextTheme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = nextTheme;
try {
localStorage.setItem('simpleskies-theme', nextTheme);
} catch (error) {
// Storage unavailable (e.g. private mode): choice applies to this visit only.
}
}
function loadAirportData() {
if (window.AIRPORT_DATA && typeof window.AIRPORT_DATA === 'object') {
airportData = window.AIRPORT_DATA;
buildSearchIndex();
applyHash();
showSuggestions();
return;
}
fetch('data.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.then(data => {
airportData = data;
buildSearchIndex();
applyHash();
showSuggestions();
})
.catch(error => {
console.error('Error loading airport data:', error);
setMessage('Airport data could not be loaded. Keep data.js in the same folder as index.html.', true);
});
}
airportInput.addEventListener('input', () => showSuggestions(airportInput.value));
airportInput.addEventListener('keydown', (event) => {
const options = optionElements();
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
if (options.length === 0) {
return;
}
event.preventDefault();
const delta = event.key === 'ArrowDown' ? 1 : -1;
setActive(Math.min(Math.max(activeIndex + delta, 0), options.length - 1));
} else if (event.key === 'Enter') {
if (activeIndex >= 0 && options[activeIndex]) {
event.preventDefault();
selectSuggestion(options[activeIndex].dataset.code);
}
} else if (event.key === 'Escape') {
hideSuggestions();
}
});
findInfoButton.addEventListener('click', findAirportInfo);
lookupForm.addEventListener('submit', (event) => {
event.preventDefault();
findAirportInfo();
});
themeToggle.addEventListener('click', toggleMode);
loadAirportData();
window.addEventListener('hashchange', applyHash);
randomAirportButton.addEventListener('click', () => {
const codes = Object.keys(airportData);
const code = codes[Math.floor(Math.random() * codes.length)];
showAirport(code);
hideSuggestions();
});