This repository has been archived by the owner on Oct 6, 2020. It is now read-only.
forked from pietervdvn/MapComplete
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
370 lines (290 loc) · 12.9 KB
/
index.ts
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
import { OsmConnection } from "./Logic/OsmConnection";
import { Changes } from "./Logic/Changes";
import { ElementStorage } from "./Logic/ElementStorage";
import { UIEventSource } from "./UI/UIEventSource";
import { UserBadge } from "./UI/UserBadge";
import { BaseLayers, Basemap } from "./Logic/Basemap";
import { PendingChanges } from "./UI/PendingChanges";
import { CenterMessageBox } from "./UI/CenterMessageBox";
import { Helpers } from "./Helpers";
import { Tag, TagUtils } from "./Logic/TagsFilter";
import { FilteredLayer } from "./Logic/FilteredLayer";
import { LayerUpdater } from "./Logic/LayerUpdater";
import { UIElement } from "./UI/UIElement";
import { FullScreenMessageBoxHandler } from "./UI/FullScreenMessageBoxHandler";
import { FeatureInfoBox } from "./UI/FeatureInfoBox";
import { GeoLocationHandler } from "./Logic/GeoLocationHandler";
import { StrayClickHandler } from "./Logic/StrayClickHandler";
import { SimpleAddUI } from "./UI/SimpleAddUI";
import { VariableUiElement } from "./UI/Base/VariableUIElement";
import { SearchAndGo } from "./UI/SearchAndGo";
import { AllKnownLayouts } from "./Customizations/AllKnownLayouts";
import { CheckBox } from "./UI/Input/CheckBox";
import Translations from "./UI/i18n/Translations";
import Locale from "./UI/i18n/Locale";
import { Layout, WelcomeMessage } from "./Customizations/Layout";
import { DropDown } from "./UI/Input/DropDown";
import { FixedUiElement } from "./UI/Base/FixedUiElement";
import { RouteLayer } from "./Logic/RouteLayer";
import { Route } from "./Logic/Route";
import { GeoOperations } from "./Logic/GeoOperations";
import { LayerSelection } from "./UI/LayerSelection";
import Combine from "./UI/Base/Combine";
import { Img } from "./UI/Img";
import { QueryParameters } from "./Logic/QueryParameters";
import { Utils } from "./Utils";
import { LocalStorageSource } from "./Logic/LocalStorageSource";
import { Playground } from './ExternalData/Playground';
import { RemarkableTree } from './ExternalData/RemarkableTree';
import { LayerDefinition } from "./Customizations/LayerDefinition";
// --------------------- Special actions based on the parameters -----------------
// @ts-ignore
if (location.href.startsWith("http://buurtnatuur.be")) {
// Reload the https version. This is important for the 'locate me' button
window.location.replace("https://buurtnatuur.be");
}
// Set to true if testing and changes should NOT be saved
const testing = QueryParameters.GetQueryParameter("test");
if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
testing.setData(testing.data ?? "true")
// If you have a testfile somewhere, enable this to spoof overpass
// This should be hosted independantly, e.g. with `cd assets; webfsd -p 8080` + a CORS plugin to disable cors rules
//Overpass.testUrl = "http://127.0.0.1:8080/streetwidths.geojson";
}
// ----------------- SELECT THE RIGHT QUESTSET -----------------
let defaultLayout = "walkbybrussels"
const path = window.location.pathname.split("/").slice(-1)[0];
if (path !== "index.html") {
defaultLayout = path.substr(0, path.length - 5);
console.log("Using", defaultLayout)
}
// Run over all questsets. If a part of the URL matches a searched-for part in the layout, it'll take that as the default
for (const k in AllKnownLayouts.allSets) {
const layout = AllKnownLayouts.allSets[k];
const possibleParts = layout.locationContains ?? [];
for (const locationMatch of possibleParts) {
if (locationMatch === "") {
continue
}
if (window.location.href.toLowerCase().indexOf(locationMatch.toLowerCase()) >= 0) {
defaultLayout = layout.name;
}
}
}
defaultLayout = QueryParameters.GetQueryParameter("layout").data ?? defaultLayout;
const layoutToUse: Layout = AllKnownLayouts.allSets[defaultLayout] ?? AllKnownLayouts["all"];
console.log("Using layout: ", layoutToUse.name);
if (layoutToUse === undefined) {
console.log("Incorrect layout")
}
// ----------------- Setup a few event sources -------------
// The message that should be shown at the center of the screen
const centerMessage = new UIEventSource<string>("");
// The countdown: if set to e.g. ten, it'll start counting down. When reaching zero, changes will be saved. NB: this is implemented later, not in the eventSource
const secondsTillChangesAreSaved = new UIEventSource<number>(0);
// const leftMessage = new UIEventSource<() => UIElement>(undefined);
// This message is shown full screen on mobile devices
const fullScreenMessage = new UIEventSource<UIElement>(undefined);
// The latest element that was selected - used to generate the right UI at the right place
const selectedElement = new UIEventSource<{ feature: any }>(undefined);
const zoom = QueryParameters.GetQueryParameter("z")
.syncWith(LocalStorageSource.Get("zoom"));
const lat = QueryParameters.GetQueryParameter("lat")
.syncWith(LocalStorageSource.Get("lat"));
const lon = QueryParameters.GetQueryParameter("lon")
.syncWith(LocalStorageSource.Get("lon"));
const locationControl = new UIEventSource<{ lat: number, lon: number, zoom: number }>({
zoom: Utils.asFloat(zoom.data) ?? layoutToUse.startzoom,
lat: Utils.asFloat(lat.data) ?? layoutToUse.startLat,
lon: Utils.asFloat(lon.data) ?? layoutToUse.startLon
});
locationControl.addCallback((latlonz) => {
zoom.setData(latlonz.zoom.toString());
lat.setData(latlonz.lat.toString().substr(0, 6));
lon.setData(latlonz.lon.toString().substr(0, 6));
})
// ----------------- Prepare the important objects -----------------
const osmConnection = new OsmConnection(
testing.data === "true"
);
Locale.language.syncWith(osmConnection.GetPreference("language"));
// @ts-ignore
window.setLanguage = function (language: string) {
Locale.language.setData(language)
}
Locale.language.addCallback((currentLanguage) => {
console.log("REsetting languate to", layoutToUse.supportedLanguages[0])
if (layoutToUse.supportedLanguages.indexOf(currentLanguage) < 0) {
// The current language is not supported -> switch to a supported one
Locale.language.setData(layoutToUse.supportedLanguages[0]);
}
}).ping()
const saveTimeout = 30000; // After this many milliseconds without changes, saves are sent of to OSM
const allElements = new ElementStorage();
const changes = new Changes(
"Beantwoorden van vragen met #MapComplete voor vragenset #" + layoutToUse.name,
osmConnection, allElements);
const bm = new Basemap("leafletDiv", locationControl, new VariableUiElement(
locationControl.map((location) => {
const mapComplete = "<a href='https://github.com/pietervdvn/MapComplete' target='_blank'>Mapcomple</a> " +
" " +
"<a href='https://github.com/pietervdvn/MapComplete/issues' target='_blank'><img src='./assets/bug.svg' alt='Report bug' class='small-userbadge-icon'></a>";
let editHere = "";
if (location !== undefined) {
editHere = " | " +
"<a href='https://www.openstreetmap.org/edit?editor=id#map=" + location.zoom + "/" + location.lat + "/" + location.lon + "' target='_blank'>" +
"<img src='./assets/pencil.svg' alt='edit here' class='small-userbadge-icon'>" +
"</a>"
}
return mapComplete + editHere;
})
));
// -------------- Setup the route -----------------------------
const route = QueryParameters.GetQueryParameter("route").map(
Route.RouteFromString,
[],
(route: Route) => {
if (route.waypoints.length == 0) {
return undefined;
}
return route?.WaypointsAsString()
}
)
new RouteLayer(route, bm);
route.ping();
// ------------- Setup the layers -------------------------------
//let playgrounds = new Playground(bm);
// let rm = new RemarkableTree(bm);
const addButtons: {
name: UIElement,
icon: string,
tags: Tag[],
layerToAddTo: FilteredLayer
}[]
= [];
const flayers: FilteredLayer[] = []
let minZoom = 0;
for (const layer of layoutToUse.layers) {
const generateInfo = function (tagsES, feature, clickLocation: { lat: number, lon: number }) {
return new FeatureInfoBox(
clickLocation,
feature,
tagsES,
layer.title,
layer.elementsToShow,
changes,
osmConnection.userDetails,
route
)
};
minZoom = Math.max(minZoom, layer.minzoom);
const flayer = FilteredLayer.fromDefinition(layer, bm, allElements, changes, osmConnection.userDetails, selectedElement, generateInfo);
const addButton = {
name: Translations.W(layer.name),
icon: layer.icon,
tags: layer.newElementTags,
layerToAddTo: flayer
}
addButtons.push(addButton);
flayers.push(flayer);
}
const layerUpdater = new LayerUpdater(bm, minZoom, flayers);
// --------------- Setting up layer selection ui --------
const closedFilterButton = `<button id="filter__button" class="filter__button shadow">${Img.closedFilterButton}</button>`;
const openFilterButton = `
<button id="filter__button" class="filter__button">${Img.openFilterButton}</button>`;
let baseLayerOptions = BaseLayers.baseLayers.map((layer) => { return { value: layer, shown: layer.name } });
const backgroundMapPicker = new Combine([new DropDown(`Background map`, baseLayerOptions, bm.CurrentLayer), openFilterButton]);
const layerSelection = new Combine([`<p class="filter__label">`, Translations.t.general.maplayers, `</p>`, new LayerSelection(flayers)]);
let layerControl = backgroundMapPicker;
if (flayers.length > 1) {
layerControl = new Combine([layerSelection, backgroundMapPicker]);
}
new CheckBox(layerControl, closedFilterButton).AttachTo("filter__selection");
// ------------------ Setup various other UI elements ------------
document.title = layoutToUse.title.InnerRender();
Locale.language.addCallback(e => {
document.title = layoutToUse.title.InnerRender();
})
new StrayClickHandler(bm, selectedElement, fullScreenMessage, () => {
return new SimpleAddUI(
bm.Location,
bm.LastClickLocation,
changes,
selectedElement,
layerUpdater.runningQuery,
osmConnection.userDetails,
route,
addButtons);
}
);
/**
* Show the questions and information for the selected element
* This is given to the div which renders fullscreen on mobile devices
*/
selectedElement.addCallback((feature) => {
const data = feature.feature.properties;
// Which is the applicable set?
for (const layer of layoutToUse.layers) {
let applicable = false;
if (!layer.data) applicable = layer.overpassFilter.matches(TagUtils.proprtiesToKV(data));
if (applicable) {
// This layer is the layer that gives the questions
const featureCenter = GeoOperations.centerpoint(feature.feature).geometry.coordinates;
const featureBox = new FeatureInfoBox(
{ lon: featureCenter[0], lat: featureCenter[1] },
feature.feature,
allElements.getElement(data.id),
layer.title,
layer.elementsToShow,
changes,
osmConnection.userDetails,
route
);
fullScreenMessage.setData(featureBox);
break;
}
}
}
);
const pendingChanges = new PendingChanges(changes, secondsTillChangesAreSaved,);
new UserBadge(osmConnection.userDetails,
pendingChanges,
Locale.CreateLanguagePicker(layoutToUse),
bm)
.AttachTo('userbadge');
new SearchAndGo(bm).AttachTo("searchbox");
const welcome = new WelcomeMessage(layoutToUse,
Locale.CreateLanguagePicker(layoutToUse, Translations.t.general.pickLanguage),
osmConnection).onClick(() => {
});
const help = new FixedUiElement(`<div class='collapse-button-img'><img src='assets/help.svg' alt='help'></div>`);
const close = new FixedUiElement(`<div class='collapse-button-img'><img src='assets/close.svg' alt='close'></div>`);
new CheckBox(
new Combine([
new Combine(["<span class='collapse-button'>", close, "</span>"]),
welcome]),
new Combine(["<span class='open-button'>", help, "</span>"])
, true
).AttachTo("messagesbox");
new FullScreenMessageBoxHandler(fullScreenMessage, () => {
selectedElement.setData(undefined)
}).update();
const welcome2 = new WelcomeMessage(layoutToUse, Locale.CreateLanguagePicker(layoutToUse, Translations.t.general.pickLanguage), osmConnection)
fullScreenMessage.setData(welcome2)
new FixedUiElement(`<div class='collapse-button-img' class="shadow"><img src='assets/help.svg' alt='help'></div>`).onClick(() => {
fullScreenMessage.setData(welcome2)
})
.AttachTo("help-button-mobile")
new CenterMessageBox(
minZoom,
centerMessage,
osmConnection,
locationControl,
layerUpdater.runningQuery)
.AttachTo("centermessage");
Helpers.SetupAutoSave(changes, secondsTillChangesAreSaved, saveTimeout);
Helpers.LastEffortSave(changes);
osmConnection.registerActivateOsmAUthenticationClass();
new GeoLocationHandler(bm).AttachTo("geolocate-button");
locationControl.ping()