-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
404 lines (341 loc) · 13.3 KB
/
Copy pathscript.js
File metadata and controls
404 lines (341 loc) · 13.3 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
document.addEventListener('DOMContentLoaded', function() {
const mapsInput = document.getElementById('mapsInput');
const convertBtn = document.getElementById('convertBtn');
const resultContainer = document.getElementById('result');
const errorContainer = document.getElementById('error');
const coordinatesEl = document.getElementById('coordinates');
const wazeUrlEl = document.getElementById('wazeUrl');
const errorMessageEl = errorContainer.querySelector('.error-message');
const resultTitleEl = document.getElementById('resultTitle');
const singleResultEl = document.getElementById('singleResult');
const routeResultEl = document.getElementById('routeResult');
const routeStepsEl = document.getElementById('routeSteps');
const routeFullLinkEl = document.getElementById('routeFullLink');
const googleMapsUrlEl = document.getElementById('googleMapsUrl');
const routeGoogleMapsUrlEl = document.getElementById('routeGoogleMapsUrl');
const shareBtn = document.getElementById('shareBtn');
const shareModal = document.getElementById('shareModal');
const modalClose = document.getElementById('modalClose');
const shareUrlInput = document.getElementById('shareUrl');
const copyBtn = document.getElementById('copyBtn');
const shareTelegramEl = document.getElementById('shareTelegram');
const shareWhatsappEl = document.getElementById('shareWhatsapp');
const shareViberEl = document.getElementById('shareViber');
let lastResult = null;
let focusBeforeModal = null;
const shortUrlCache = new Map();
const SHORTENER_ENDPOINT = 'https://s.gbitcode.com/api/shorten?source=gmaps_2_waze';
const SHORTENER_TIMEOUT_MS = 7000;
// --- URL safety ---
function safeHref(url) {
if (typeof url !== 'string') return '#';
try {
const parsed = new URL(url);
return (parsed.protocol === 'http:' || parsed.protocol === 'https:') ? url : '#';
} catch {
return '#';
}
}
// --- Encode / decode for shareable hash ---
function encodeResult(data) {
const b64 = btoa(unescape(encodeURIComponent(JSON.stringify(data))));
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
function decodeResult(encoded) {
try {
const b64 = encoded.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - b64.length % 4) % 4);
return JSON.parse(decodeURIComponent(escape(atob(padded))));
} catch {
return null;
}
}
// --- URL shortener ---
function normalizeShortUrl(raw) {
if (typeof raw !== 'string' || !raw) return null;
return raw.startsWith('http') ? raw : `https://${raw}`;
}
async function fetchShortUrl(longUrl) {
const controller = new AbortController();
const timerId = setTimeout(() => controller.abort(), SHORTENER_TIMEOUT_MS);
try {
const res = await fetch(SHORTENER_ENDPOINT, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ url: longUrl }),
signal: controller.signal
});
const json = await res.json();
return normalizeShortUrl(json.short_url);
} catch {
return null;
} finally {
clearTimeout(timerId);
}
}
// --- Modal share link helpers ---
const channelEls = [shareTelegramEl, shareWhatsappEl, shareViberEl];
function applyShareLinks(url) {
const enc = encodeURIComponent(url);
shareUrlInput.value = url;
copyBtn.disabled = false;
shareTelegramEl.href = `https://t.me/share/url?url=${enc}`;
shareWhatsappEl.href = `https://wa.me/?text=${enc}`;
shareViberEl.href = `viber://forward?text=${enc}`;
channelEls.forEach(el => {
el.removeAttribute('aria-disabled');
el.style.opacity = '';
el.style.pointerEvents = '';
});
}
function setModalLoading(loading) {
if (loading) {
shareUrlInput.value = 'Shortening…';
copyBtn.disabled = true;
channelEls.forEach(el => {
el.setAttribute('aria-disabled', 'true');
el.style.opacity = '0.5';
el.style.pointerEvents = 'none';
});
} else {
copyBtn.disabled = false;
channelEls.forEach(el => {
el.removeAttribute('aria-disabled');
el.style.opacity = '';
el.style.pointerEvents = '';
});
}
}
// --- Modal ---
function openModal() {
focusBeforeModal = document.activeElement;
shareModal.hidden = false;
modalClose.focus();
document.addEventListener('keydown', handleModalKeydown);
}
function closeModal() {
shareModal.hidden = true;
document.removeEventListener('keydown', handleModalKeydown);
if (focusBeforeModal) focusBeforeModal.focus();
}
function handleModalKeydown(e) {
if (e.key === 'Escape') {
closeModal();
return;
}
if (e.key !== 'Tab') return;
const focusable = Array.from(shareModal.querySelectorAll('button, input, a[href]'));
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey) {
if (document.activeElement === first) {
e.preventDefault();
last.focus();
}
} else {
if (document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
}
shareModal.addEventListener('click', function(e) {
if (e.target === shareModal) closeModal();
});
modalClose.addEventListener('click', closeModal);
copyBtn.addEventListener('click', async function() {
const url = shareUrlInput.value;
try {
await navigator.clipboard.writeText(url);
showCopied();
} catch {
shareUrlInput.select();
try {
document.execCommand('copy');
showCopied();
} catch {
// URL is visible — user can copy manually
}
}
});
function showCopied() {
copyBtn.textContent = 'Copied!';
setTimeout(() => { copyBtn.textContent = 'Copy link'; }, 2000);
}
shareBtn.addEventListener('click', async function() {
const encoded = encodeResult(lastResult);
const longUrl = `${location.origin}${location.pathname}#r=${encoded}`;
if (typeof gtag !== 'undefined') {
gtag('event', 'result_shared', {
'event_category': 'share',
'event_label': 'web_converter'
});
}
if (shortUrlCache.has(longUrl)) {
applyShareLinks(shortUrlCache.get(longUrl));
openModal();
return;
}
setModalLoading(true);
openModal();
const shortUrl = await fetchShortUrl(longUrl);
if (shortUrl) shortUrlCache.set(longUrl, shortUrl);
applyShareLinks(shortUrl || longUrl);
setModalLoading(false);
});
function trackChannelShare(channel) {
if (typeof gtag !== 'undefined') {
gtag('event', 'result_shared_channel', {
'event_category': 'share',
'event_label': channel
});
}
}
shareTelegramEl.addEventListener('click', () => trackChannelShare('telegram'));
shareWhatsappEl.addEventListener('click', () => trackChannelShare('whatsapp'));
shareViberEl.addEventListener('click', () => trackChannelShare('viber'));
// --- Conversion ---
convertBtn.addEventListener('click', async function() {
const mapsLink = mapsInput.value.trim();
if (!mapsLink) {
showError('Please enter a Google Maps link');
return;
}
hideMessages();
convertBtn.disabled = true;
convertBtn.textContent = 'Converting...';
try {
const response = await fetch('https://faas-fra1-afec6ce7.doserverless.co/api/v1/web/fn-2147b526-aa08-4de1-a083-670d2a13332a/default/gmap2waze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: {
chat: {
id: -1
},
text: mapsLink
}
})
});
const data = await response.json();
if (data.ok && data.coordinates && data.wazeUrl) {
showResult(data);
} else {
showError('Failed to convert the link. Please check if the URL is valid.');
}
} catch (error) {
showError('An error occurred while converting the link. Please try again.');
console.error('Error:', error);
} finally {
convertBtn.disabled = false;
convertBtn.textContent = 'Convert';
}
});
mapsInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
convertBtn.click();
}
});
// --- Rendering ---
function isRouteData(data) {
return (data.format === 'route' || data.url_type === 'combo_route') &&
Array.isArray(data.waypoints) && data.waypoints.length > 1;
}
function showResult(data) {
lastResult = data;
if (isRouteData(data)) {
renderRoute(data);
} else {
renderSingle(data);
}
resultContainer.style.display = 'block';
errorContainer.style.display = 'none';
if (typeof gtag !== 'undefined') {
gtag('event', 'link_converted_web', {
'event_category': 'conversion',
'event_label': 'web_converter'
});
}
}
function renderSingle(data) {
const { latitude, longitude } = data.coordinates;
coordinatesEl.textContent = `${latitude}, ${longitude}`;
wazeUrlEl.href = safeHref(data.wazeUrl);
googleMapsUrlEl.href = safeHref(data.googleMapsUrl);
resultTitleEl.textContent = 'Your link!';
routeStepsEl.innerHTML = '';
singleResultEl.style.display = 'block';
routeResultEl.style.display = 'none';
}
function renderRoute(data) {
const { waypoints, wazeUrl2 } = data;
const count = waypoints.length;
resultTitleEl.textContent = `Route (${count} stops)`;
routeStepsEl.innerHTML = '';
waypoints.forEach((wp, i) => {
if (!wp || typeof wp.latitude !== 'number' || !isFinite(wp.latitude) ||
typeof wp.longitude !== 'number' || !isFinite(wp.longitude)) return;
let label;
if (i === 0) {
label = 'Start';
} else if (i === count - 1) {
label = 'Destination';
} else {
label = `Step ${i}`;
}
const lat = wp.latitude.toFixed(6);
const lng = wp.longitude.toFixed(6);
const li = document.createElement('li');
li.className = 'route-step';
const labelEl = document.createElement('span');
labelEl.className = 'route-step-label';
labelEl.textContent = label;
const coordEl = document.createElement('span');
coordEl.className = 'route-step-coords';
coordEl.textContent = `${lat}, ${lng}`;
const linkEl = document.createElement('a');
linkEl.href = safeHref(`https://waze.com/ul?ll=${lat},${lng}&navigate=yes`);
linkEl.target = '_blank';
linkEl.rel = 'noopener';
linkEl.className = 'waze-link route-step-link';
linkEl.textContent = 'Open in Waze';
li.appendChild(labelEl);
li.appendChild(coordEl);
li.appendChild(linkEl);
routeStepsEl.appendChild(li);
});
routeFullLinkEl.href = safeHref(wazeUrl2);
routeGoogleMapsUrlEl.href = safeHref(data.googleMapsUrl);
singleResultEl.style.display = 'none';
routeResultEl.style.display = 'block';
}
function showError(message) {
errorMessageEl.textContent = message;
errorContainer.style.display = 'block';
resultContainer.style.display = 'none';
if (typeof gtag !== 'undefined') {
gtag('event', 'web_conversion_failed', {
'event_category': 'conversion',
'event_label': 'web_converter_error'
});
}
}
function hideMessages() {
resultContainer.style.display = 'none';
errorContainer.style.display = 'none';
}
// --- Hash-based shared result (runs on page load) ---
const hash = location.hash;
if (hash.startsWith('#r=')) {
const data = decodeResult(hash.slice(3));
if (data === null) {
// malformed base64/JSON — silently ignore, show converter form
} else if (data.ok && data.coordinates && data.wazeUrl) {
showResult(data);
} else {
showError('This share link appears to be invalid or incomplete.');
}
}
});