Make upload a smoother experience with some in-app UI and enable it on all platforms
[lantea.git] / js / ui.js
... / ...
CommitLineData
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5// Get the best-available indexedDB object.
6window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
7var mainDB;
8
9var gUIHideCountdown = 0;
10var gWaitCounter = 0;
11var gAction, gActionLabel;
12var gOSMAPIURL = "http://api.openstreetmap.org/";
13
14window.onload = function() {
15 gAction = document.getElementById("action");
16 gActionLabel = document.getElementById("actionlabel");
17
18 var mSel = document.getElementById("mapSelector");
19 for (var mapStyle in gMapStyles) {
20 var opt = document.createElement("option");
21 opt.value = mapStyle;
22 opt.text = gMapStyles[mapStyle].name;
23 mSel.add(opt, null);
24 }
25
26 var areas = document.getElementsByClassName('overlayArea');
27 for (var i = 0; i <= areas.length - 1; i++) {
28 areas[i].addEventListener("mouseup", uiEvHandler, false);
29 areas[i].addEventListener("mousemove", uiEvHandler, false);
30 areas[i].addEventListener("mousedown", uiEvHandler, false);
31 areas[i].addEventListener("mouseout", uiEvHandler, false);
32
33 areas[i].addEventListener("touchstart", uiEvHandler, false);
34 areas[i].addEventListener("touchmove", uiEvHandler, false);
35 areas[i].addEventListener("touchend", uiEvHandler, false);
36 areas[i].addEventListener("touchcancel", uiEvHandler, false);
37 areas[i].addEventListener("touchleave", uiEvHandler, false);
38 }
39
40 document.getElementById("body").addEventListener("keydown", uiEvHandler, false);
41
42 if (navigator.platform.length == "") {
43 // For Firefox OS, don't display the "save" button.
44 // Do this by setting the debugHide class for testing in debug mode.
45 document.getElementById("saveTrackButton").classList.add("debugHide");
46 }
47
48 // Without OAuth, the login data is useless
49 //document.getElementById("uploadSettingsArea").classList.remove("debugHide");
50 // As login data is useless for now, always enable upload button
51 document.getElementById("uploadTrackButton").disabled = false;
52
53 if (gDebug) {
54 // Note that GPX upload returns an error 500 on the dev API right now.
55 gOSMAPIURL = "http://api06.dev.openstreetmap.org/";
56 }
57
58 initDB();
59 initMap();
60
61 var loopCnt = 0;
62 var waitForInitAndDraw = function() {
63 if ((gWaitCounter <= 0) || (loopCnt > 100)) {
64 if (gWaitCounter <= 0)
65 gWaitCounter = 0;
66 else
67 console.log("Loading failed (waiting for init).");
68
69 gMapPrefsLoaded = true;
70 resizeAndDraw();
71 gActionLabel.textContent = "";
72 gAction.style.display = "none";
73 setTracking(document.getElementById("trackCheckbox"));
74 gPrefs.get(gDebug ? "osm_dev_user" : "osm_user", function(aValue) {
75 if (aValue) {
76 document.getElementById("uploadUser").value = aValue;
77 document.getElementById("uploadTrackButton").disabled = false;
78 }
79 });
80 gPrefs.get(gDebug ? "osm_dev_pwd" : "osm_pwd", function(aValue) {
81 var upwd = document.getElementById("uploadPwd");
82 if (aValue)
83 document.getElementById("uploadPwd").value = aValue;
84 });
85 }
86 else
87 setTimeout(waitForInitAndDraw, 100);
88 loopCnt++;
89 };
90 waitForInitAndDraw();
91}
92
93window.onresize = function() {
94 resizeAndDraw();
95}
96
97function initDB() {
98 // Open DB.
99 var request = window.indexedDB.open("MainDB-lantea", 2);
100 request.onerror = function(event) {
101 // Errors can be handled here. Error codes explain in:
102 // https://developer.mozilla.org/en/IndexedDB/IDBDatabaseException#Constants
103 if (gDebug)
104 console.log("error opening mainDB: " + event.target.errorCode);
105 };
106 request.onsuccess = function(event) {
107 mainDB = request.result;
108 };
109 request.onupgradeneeded = function(event) {
110 mainDB = request.result;
111 var ver = mainDB.version || 0; // version is empty string for a new DB
112 if (gDebug)
113 console.log("mainDB has version " + ver + ", upgrade needed.");
114 if (!mainDB.objectStoreNames.contains("prefs")) {
115 // Create a "prefs" objectStore.
116 var prefsStore = mainDB.createObjectStore("prefs");
117 }
118 if (!mainDB.objectStoreNames.contains("track")) {
119 // Create a "track" objectStore.
120 var trackStore = mainDB.createObjectStore("track", {autoIncrement: true});
121 }
122 if (!mainDB.objectStoreNames.contains("tilecache")) {
123 // Create a "tilecache" objectStore.
124 var tilecacheStore = mainDB.createObjectStore("tilecache");
125 }
126 mainDB.onversionchange = function(event) {
127 mainDB.close();
128 mainDB = undefined;
129 initDB();
130 };
131 };
132}
133
134function showUI() {
135 if (gUIHideCountdown <= 0) {
136 var areas = document.getElementsByClassName('overlayArea');
137 for (var i = 0; i <= areas.length - 1; i++) {
138 areas[i].classList.remove("hidden");
139 }
140 setTimeout(maybeHideUI, 1000);
141 }
142 gUIHideCountdown = 5;
143}
144
145function maybeHideUI() {
146 gUIHideCountdown--;
147 if (gUIHideCountdown <= 0) {
148 var areas = document.getElementsByClassName('overlayArea');
149 for (var i = 0; i <= areas.length - 1; i++) {
150 areas[i].classList.add("hidden");
151 }
152 }
153 else {
154 setTimeout(maybeHideUI, 1000);
155 }
156}
157
158function toggleTrackArea() {
159 var fs = document.getElementById("trackArea");
160 if (fs.style.display != "block") {
161 fs.style.display = "block";
162 showUI();
163 }
164 else {
165 fs.style.display = "none";
166 }
167}
168
169function toggleSettings() {
170 var fs = document.getElementById("settingsArea");
171 if (fs.style.display != "block") {
172 fs.style.display = "block";
173 showUI();
174 }
175 else {
176 fs.style.display = "none";
177 }
178}
179
180function toggleFullscreen() {
181 if ((document.fullScreenElement && document.fullScreenElement !== null) ||
182 (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
183 (document.webkitFullScreenElement && document.webkitFullScreenElement !== null)) {
184 if (document.cancelFullScreen) {
185 document.cancelFullScreen();
186 } else if (document.mozCancelFullScreen) {
187 document.mozCancelFullScreen();
188 } else if (document.webkitCancelFullScreen) {
189 document.webkitCancelFullScreen();
190 }
191 }
192 else {
193 var elem = document.getElementById("body");
194 if (elem.requestFullScreen) {
195 elem.requestFullScreen();
196 } else if (elem.mozRequestFullScreen) {
197 elem.mozRequestFullScreen();
198 } else if (elem.webkitRequestFullScreen) {
199 elem.webkitRequestFullScreen();
200 }
201 }
202}
203
204function showUploadDialog() {
205 var dia = document.getElementById("dialogArea");
206 var areas = dia.children;
207 for (var i = 0; i <= areas.length - 1; i++) {
208 areas[i].style.display = "none";
209 }
210 document.getElementById("uploadDialog").style.display = "block";
211 document.getElementById("uploadTrackButton").disabled = true;
212 dia.classList.remove("hidden");
213}
214
215function cancelDialog() {
216 document.getElementById("dialogArea").classList.add("hidden");
217 document.getElementById("uploadTrackButton").disabled = false;
218}
219
220var uiEvHandler = {
221 handleEvent: function(aEvent) {
222 var touchEvent = aEvent.type.indexOf('touch') != -1;
223
224 switch (aEvent.type) {
225 case "mousedown":
226 case "touchstart":
227 case "mousemove":
228 case "touchmove":
229 case "mouseup":
230 case "touchend":
231 case "keydown":
232 showUI();
233 break;
234 }
235 }
236};
237
238function setUploadField(aField) {
239 switch (aField.id) {
240 case "uploadUser":
241 gPrefs.set(gDebug ? "osm_dev_user" : "osm_user", aField.value);
242 document.getElementById("uploadTrackButton").disabled = !aField.value.length;
243 break;
244 case "uploadPwd":
245 gPrefs.set(gDebug ? "osm_dev_pwd" : "osm_pwd", aField.value);
246 break;
247 }
248}
249
250function makeISOString(aTimestamp) {
251 // ISO time format is YYYY-MM-DDTHH:mm:ssZ
252 var tsDate = new Date(aTimestamp);
253 return tsDate.getUTCFullYear() + "-" +
254 (tsDate.getUTCMonth() < 10 ? "0" : "") + tsDate.getUTCMonth() + "-" +
255 (tsDate.getUTCDate() < 10 ? "0" : "") + tsDate.getUTCDate() + "T" +
256 (tsDate.getUTCHours() < 10 ? "0" : "") + tsDate.getUTCHours() + ":" +
257 (tsDate.getUTCMinutes() < 10 ? "0" : "") + tsDate.getUTCMinutes() + ":" +
258 (tsDate.getUTCSeconds() < 10 ? "0" : "") + tsDate.getUTCSeconds() + "Z";
259}
260
261function convertTrack(aTargetFormat) {
262 var out = "";
263 switch (aTargetFormat) {
264 case "gpx":
265 out += '<?xml version="1.0" encoding="UTF-8" ?>' + "\n\n";
266 out += '<gpx version="1.0" creator="Lantea" xmlns="http://www.topografix.com/GPX/1/0">' + "\n";
267 if (gTrack.length) {
268 out += ' <trk>' + "\n";
269 out += ' <trkseg>' + "\n";
270 for (var i = 0; i < gTrack.length; i++) {
271 if (gTrack[i].beginSegment && i > 0) {
272 out += ' </trkseg>' + "\n";
273 out += ' <trkseg>' + "\n";
274 }
275 out += ' <trkpt lat="' + gTrack[i].coords.latitude + '" lon="' +
276 gTrack[i].coords.longitude + '">' + "\n";
277 if (gTrack[i].coords.altitude) {
278 out += ' <ele>' + gTrack[i].coords.altitude + '</ele>' + "\n";
279 }
280 out += ' <time>' + makeISOString(gTrack[i].time) + '</time>' + "\n";
281 out += ' </trkpt>' + "\n";
282 }
283 out += ' </trkseg>' + "\n";
284 out += ' </trk>' + "\n";
285 }
286 out += '</gpx>' + "\n";
287 break;
288 case "json":
289 out = JSON.stringify(gTrack);
290 break;
291 default:
292 break;
293 }
294 return out;
295}
296
297function saveTrack() {
298 if (gTrack.length) {
299 var outDataURI = "data:application/gpx+xml," +
300 encodeURIComponent(convertTrack("gpx"));
301 window.open(outDataURI, 'GPX Track');
302 }
303}
304
305function saveTrackDump() {
306 if (gTrack.length) {
307 var outDataURI = "data:application/json," +
308 encodeURIComponent(convertTrack("json"));
309 window.open(outDataURI, 'JSON dump');
310 }
311}
312
313function uploadTrack() {
314 var dia = document.getElementById("dialogArea");
315 var areas = dia.children;
316 for (var i = 0; i <= areas.length - 1; i++) {
317 areas[i].style.display = "none";
318 }
319 document.getElementById("uploadStatus").style.display = "block";
320
321 // See http://wiki.openstreetmap.org/wiki/Api06#Uploading_traces
322 var trackBlob = new Blob([convertTrack("gpx")],
323 { "type" : "application/gpx+xml" });
324 var formData = new FormData();
325 formData.append("file", trackBlob);
326 var desc = document.getElementById("uploadDesc").value;
327 formData.append("description",
328 desc.length ? desc : "Track recorded via Lantea Maps");
329 //formData.append("tags", "");
330 formData.append("visibility",
331 document.getElementById("uploadVisibility").value);
332 var XHR = new XMLHttpRequest();
333 XHR.onreadystatechange = function() {
334 if (XHR.readyState == 4 && XHR.status == 200) {
335 // so far so good
336 reportUploadStatus(true);
337 } else if (XHR.readyState == 4 && XHR.status != 200) {
338 // fetched the wrong page or network error...
339 reportUploadStatus(false);
340 }
341 };
342 XHR.open("POST", gOSMAPIURL + "api/0.6/gpx/create", true);
343 // Cross-Origin XHR doesn't allow username/password (HTTP Auth).
344 // So, we'll ask the user for entering credentials with rather ugly UI.
345 XHR.withCredentials = true;
346 try {
347 XHR.send(formData);
348 }
349 catch (e) {
350 reportUploadStatus(false, e);
351 }
352}
353
354function reportUploadStatus(aSuccess, aMessage) {
355 document.getElementById("uploadStatusCloseButton").disabled = false;
356 document.getElementById("uploadInProgress").style.display = "none";
357 if (aSuccess) {
358 document.getElementById("uploadSuccess").style.display = "block";
359 }
360 else if (aMessage) {
361 document.getElementById("uploadErrorMsg").textContent = aMessage;
362 document.getElementById("uploadError").style.display = "block";
363 }
364 else {
365 document.getElementById("uploadFailed").style.display = "block";
366 }
367}
368
369var gPrefs = {
370 objStore: "prefs",
371
372 get: function(aKey, aCallback) {
373 if (!mainDB)
374 return;
375 var transaction = mainDB.transaction([this.objStore]);
376 var request = transaction.objectStore(this.objStore).get(aKey);
377 request.onsuccess = function(event) {
378 aCallback(request.result, event);
379 };
380 request.onerror = function(event) {
381 // Errors can be handled here.
382 aCallback(undefined, event);
383 };
384 },
385
386 set: function(aKey, aValue, aCallback) {
387 if (!mainDB)
388 return;
389 var success = false;
390 var transaction = mainDB.transaction([this.objStore], "readwrite");
391 var objStore = transaction.objectStore(this.objStore);
392 var request = objStore.put(aValue, aKey);
393 request.onsuccess = function(event) {
394 success = true;
395 if (aCallback)
396 aCallback(success, event);
397 };
398 request.onerror = function(event) {
399 // Errors can be handled here.
400 if (aCallback)
401 aCallback(success, event);
402 };
403 },
404
405 unset: function(aKey, aCallback) {
406 if (!mainDB)
407 return;
408 var success = false;
409 var transaction = mainDB.transaction([this.objStore], "readwrite");
410 var request = transaction.objectStore(this.objStore).delete(aKey);
411 request.onsuccess = function(event) {
412 success = true;
413 if (aCallback)
414 aCallback(success, event);
415 };
416 request.onerror = function(event) {
417 // Errors can be handled here.
418 if (aCallback)
419 aCallback(success, event);
420 }
421 }
422};
423
424var gTrackStore = {
425 objStore: "track",
426
427 getList: function(aCallback) {
428 if (!mainDB)
429 return;
430 var transaction = mainDB.transaction([this.objStore]);
431 var objStore = transaction.objectStore(this.objStore);
432 if (objStore.getAll) { // currently Mozilla-specific
433 objStore.getAll().onsuccess = function(event) {
434 aCallback(event.target.result);
435 };
436 }
437 else { // Use cursor (standard method).
438 var tPoints = [];
439 objStore.openCursor().onsuccess = function(event) {
440 var cursor = event.target.result;
441 if (cursor) {
442 tPoints.push(cursor.value);
443 cursor.continue();
444 }
445 else {
446 aCallback(tPoints);
447 }
448 };
449 }
450 },
451
452 push: function(aValue, aCallback) {
453 if (!mainDB)
454 return;
455 var transaction = mainDB.transaction([this.objStore], "readwrite");
456 var objStore = transaction.objectStore(this.objStore);
457 var request = objStore.add(aValue);
458 request.onsuccess = function(event) {
459 if (aCallback)
460 aCallback(request.result, event);
461 };
462 request.onerror = function(event) {
463 // Errors can be handled here.
464 if (aCallback)
465 aCallback(false, event);
466 };
467 },
468
469 clear: function(aCallback) {
470 if (!mainDB)
471 return;
472 var success = false;
473 var transaction = mainDB.transaction([this.objStore], "readwrite");
474 var request = transaction.objectStore(this.objStore).clear();
475 request.onsuccess = function(event) {
476 success = true;
477 if (aCallback)
478 aCallback(success, event);
479 };
480 request.onerror = function(event) {
481 // Errors can be handled here.
482 if (aCallback)
483 aCallback(success, event);
484 }
485 }
486};