-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathcontext.js
More file actions
645 lines (532 loc) · 19.1 KB
/
context.js
File metadata and controls
645 lines (532 loc) · 19.1 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import { debounce, throttle } from 'es-toolkit/compat';
import { dispatch as d3_dispatch } from 'd3-dispatch';
import { json as d3_json } from 'd3-fetch';
import { select as d3_select } from 'd3-selection';
import packageJSON from '../../package.json';
import { t } from '../core/localizer';
import { fileFetcher } from './file_fetcher';
import { localizer } from './localizer';
import { coreHistory } from './history';
import { coreValidator } from './validator';
import { coreUploader } from './uploader';
import { geoRawMercator } from '../geo/raw_mercator';
import { modeSelect, modeSelectNote } from '../modes';
import { presetManager } from '../presets';
import { rendererBackground, rendererFeatures, rendererMap, rendererPhotos } from '../renderer';
import { services } from '../services';
import { uiInit } from '../ui/init';
import { utilKeybinding, utilRebind, utilStringQs, utilCleanOsmString } from '../util';
export function coreContext() {
const dispatch = d3_dispatch('enter', 'exit', 'change');
const context = {};
let _deferred = new Set();
context.version = packageJSON.version;
context.privacyVersion = '20201202';
// iD will alter the hash so cache the parameters intended to setup the session
context.initialHashParams = window.location.hash ? utilStringQs(window.location.hash) : {};
/* Changeset */
// An osmChangeset object. Not loaded until needed.
context.changeset = null;
let _defaultChangesetComment = context.initialHashParams.comment;
let _defaultChangesetSource = context.initialHashParams.source;
let _defaultChangesetHashtags = context.initialHashParams.hashtags;
/** @type {GetSet<iD.Context, string>} */
context.defaultChangesetComment = function(val) {
if (!arguments.length) return _defaultChangesetComment;
_defaultChangesetComment = val;
return context;
};
/** @type {GetSet<iD.Context, string>} */
context.defaultChangesetSource = function(val) {
if (!arguments.length) return _defaultChangesetSource;
_defaultChangesetSource = val;
return context;
};
/** @type {GetSet<iD.Context, string>} */
context.defaultChangesetHashtags = function(val) {
if (!arguments.length) return _defaultChangesetHashtags;
_defaultChangesetHashtags = val;
return context;
};
/* Document title */
/* (typically shown as the label for the browser window/tab) */
// If true, iD will update the title based on what the user is doing
let _setsDocumentTitle = true;
/** @type {GetSet<iD.Context, boolean>} */
context.setsDocumentTitle = function(val) {
if (!arguments.length) return _setsDocumentTitle;
_setsDocumentTitle = val;
return context;
};
// The part of the title that is always the same
let _documentTitleBase = document.title;
/** @type {GetSet<iD.Context, string>} */
context.documentTitleBase = function(val) {
if (!arguments.length) return _documentTitleBase;
_documentTitleBase = val;
return context;
};
/** User interface and keybinding @type {ReturnType<uiInit>} */
let _ui;
context.ui = () => _ui;
context.lastPointerType = () => _ui.lastPointerType();
let _keybinding = utilKeybinding('context');
context.keybinding = () => _keybinding;
d3_select(document).call(_keybinding);
/* Straight accessors. Avoid using these if you can. */
// Instantiate the connection here because it doesn't require passing in
// `context` and it's needed for pre-init calls like `preauth`
let _connection = services.osm;
/** @type {ReturnType<coreHistory>} */
let _history;
/** @type {ReturnType<coreValidator>} */
let _validator;
/** @type {ReturnType<coreUploader>} */
let _uploader;
context.connection = () => _connection;
context.history = () => _history;
context.validator = () => _validator;
context.uploader = () => _uploader;
/* Connection */
context.preauth = (options) => {
if (_connection) {
_connection.switch(options);
}
return context;
};
/** @param {string | string[]} locale */
// A string or array or locale codes to prefer over the browser's settings
context.locale = function(locale) {
if (!arguments.length) return localizer.localeCode();
localizer.preferredLocaleCodes(locale);
return context;
};
function afterLoad(cid, callback) {
return (err, result) => {
if (err) {
if (typeof callback === 'function') {
callback(err);
}
return;
} else if (_connection && _connection.getConnectionId() !== cid) {
if (typeof callback === 'function') {
callback({ message: 'Connection Switched', status: -1 });
}
return;
} else {
_history.merge(result.data, result.extent);
if (typeof callback === 'function') {
callback(err, result);
}
return;
}
};
}
context.loadTiles = (projection, callback) => {
const handle = window.requestIdleCallback(() => {
_deferred.delete(handle);
if (_connection && context.editableDataEnabled()) {
const cid = _connection.getConnectionId();
_connection.loadTiles(projection, afterLoad(cid, callback));
}
});
_deferred.add(handle);
};
context.loadTileAtLoc = (loc, callback) => {
const handle = window.requestIdleCallback(() => {
_deferred.delete(handle);
if (_connection && context.editableDataEnabled()) {
const cid = _connection.getConnectionId();
_connection.loadTileAtLoc(loc, afterLoad(cid, callback));
}
});
_deferred.add(handle);
};
// Download the full entity and its parent relations. The callback may be called multiple times.
context.loadEntity = (entityID, callback) => {
if (_connection) {
const cid = _connection.getConnectionId();
_connection.loadEntity(entityID, afterLoad(cid, callback));
// We need to fetch the parent relations separately.
_connection.loadEntityRelations(entityID, afterLoad(cid, callback));
}
};
// Download single note
context.loadNote = (entityID, callback) => {
if (_connection) {
const cid = _connection.getConnectionId();
_connection.loadEntityNote(entityID, afterLoad(cid, callback));
}
};
context.zoomToEntity = (entityID, zoomTo) => {
context.zoomToEntities([entityID], zoomTo);
};
context.zoomToEntities = (entityIDs, zoomTo) => {
// be sure to load the entity even if we're not going to zoom to it
let loadedEntities = [];
const throttledZoomTo = throttle(() => _map.zoomTo(loadedEntities), 500);
entityIDs.forEach(entityID => context.loadEntity(entityID, (err, result) => {
if (err) return;
const entity = result.data.find(e => e.id === entityID);
if (!entity) return;
loadedEntities.push(entity);
if (zoomTo !== false) {
throttledZoomTo();
}
}));
_map.on('drawn.zoomToEntity', () => {
if (!entityIDs.every(entityID => context.hasEntity(entityID))) return;
_map.on('drawn.zoomToEntity', null);
context.on('enter.zoomToEntity', null);
context.enter(modeSelect(context, entityIDs));
});
context.on('enter.zoomToEntity', () => {
if (_mode.id !== 'browse') {
_map.on('drawn.zoomToEntity', null);
context.on('enter.zoomToEntity', null);
}
});
};
context.moveToNote = (noteId, moveTo) => {
context.loadNote(noteId, (err) => {
if (err) return;
// zoom to, used note loc
const note = services.osm.getNote(noteId);
if (!note) return;
if (moveTo !== false) {
context.map().center(note.loc);
}
// open note layer
const noteLayer = context.layers().layer('notes');
noteLayer.enabled(true);
// select the note
context.enter(modeSelectNote(context, noteId));
});
};
let _minEditableZoom = 16;
context.minEditableZoom = function(val) {
if (!arguments.length) return _minEditableZoom;
_minEditableZoom = val;
if (_connection) {
_connection.tileZoom(val);
}
return context;
};
// String length limits in Unicode characters, not JavaScript UTF-16 code units
context.maxCharsForTagKey = () => 255;
context.maxCharsForTagValue = () => 255;
context.maxCharsForRelationRole = () => 255;
context.cleanTagKey = (val) => utilCleanOsmString(val, context.maxCharsForTagKey());
context.cleanTagValue = (val) => utilCleanOsmString(val, context.maxCharsForTagValue());
context.cleanRelationRole = (val) => utilCleanOsmString(val, context.maxCharsForRelationRole());
/* History */
let _inIntro = false;
context.inIntro = function(val) {
if (!arguments.length) return _inIntro;
_inIntro = val;
return context;
};
// Immediately save the user's history to localstorage, if possible
// This is called someteimes, but also on the `window.onbeforeunload` handler
context.save = () => {
// no history save, no message onbeforeunload
if (_inIntro || context.container().select('.modal').size()) return;
let canSave;
if (_mode && _mode.id === 'save') {
canSave = false;
// Attempt to prevent user from creating duplicate changes - see #5200
if (services.osm && services.osm.isChangesetInflight()) {
_history.clearSaved();
return;
}
} else {
canSave = context.selectedIDs().every(id => {
const entity = context.hasEntity(id);
return entity && !entity.isDegenerate();
});
}
if (canSave) {
_history.save();
}
if (_history.hasChanges()) {
return t('save.unsaved_changes');
}
};
// Debounce save, since it's a synchronous localStorage write,
// and history changes can happen frequently (e.g. when dragging).
context.debouncedSave = debounce(context.save, 100);
/** @template {Function} T @param {T} fn @returns {T} */
function withDebouncedSave(fn) {
return function() {
const result = fn.apply(_history, arguments);
context.debouncedSave();
return result;
};
}
/* Graph */
context.hasEntity = (id) => _history.graph().hasEntity(id);
context.entity = (id) => _history.graph().entity(id);
/* Modes */
let _mode;
context.mode = () => _mode;
context.enter = (newMode) => {
if (_mode) {
_mode.exit();
dispatch.call('exit', this, _mode);
}
_mode = newMode;
_mode.enter();
dispatch.call('enter', this, _mode);
};
/** @returns {string[]} */
context.selectedIDs = () => (_mode && _mode.selectedIDs && _mode.selectedIDs()) || [];
context.activeID = () => _mode && _mode.activeID && _mode.activeID();
let _selectedNoteID;
context.selectedNoteID = function(noteID) {
if (!arguments.length) return _selectedNoteID;
_selectedNoteID = noteID;
return context;
};
// NOTE: Don't change the name of this until UI v3 is merged
let _selectedErrorID;
context.selectedErrorID = function(errorID) {
if (!arguments.length) return _selectedErrorID;
_selectedErrorID = errorID;
return context;
};
/* Behaviors */
context.install = (behavior) => context.surface().call(behavior);
context.uninstall = (behavior) => context.surface().call(behavior.off);
/* Copy/Paste */
/** @type {iD.Graph} */
let _copyGraph;
context.copyGraph = () => _copyGraph;
/** @type {string[]} */
let _copyIDs = [];
/** @type {GetSet<iD.Context, string[]>} */
context.copyIDs = function(val) {
if (!arguments.length) return _copyIDs;
_copyIDs = val;
_copyGraph = _history.graph();
return context;
};
let _copyLonLat;
context.copyLonLat = function(val) {
if (!arguments.length) return _copyLonLat;
_copyLonLat = val;
return context;
};
/* Background */
/** @type {ReturnType<rendererBackground>} */
let _background;
context.background = () => _background;
/* Features */
/** @type {ReturnType<rendererFeatures>} */
let _features;
context.features = () => _features;
context.hasHiddenConnections = (id) => {
const graph = _history.graph();
const entity = graph.entity(id);
return _features.hasHiddenConnections(entity, graph);
};
/* Photos */
/** @type {ReturnType<rendererPhotos>} */
let _photos;
context.photos = () => _photos;
/* Map */
/** @type {ReturnType<rendererMap>} */
let _map;
context.map = () => _map;
context.layers = () => _map.layers();
context.surface = () => _map.surface;
context.editableDataEnabled = () => _map.editableDataEnabled();
context.surfaceRect = () => _map.surface.node().getBoundingClientRect();
context.editable = () => {
// don't allow editing during save
const mode = context.mode();
if (!mode || mode.id === 'save') return false;
return _map.editableDataEnabled();
};
/* Debug */
let _debugFlags = {
tile: false, // tile boundaries
collision: false, // label collision bounding boxes
imagery: false, // imagery bounding polygons
target: false, // touch targets
downloaded: false // downloaded data from osm
};
context.debugFlags = () => _debugFlags;
/** @param {keyof _debugFlags} flag */
context.getDebug = (flag) => flag && _debugFlags[flag];
/** @param {keyof _debugFlags} flag @param {boolean} val */
context.setDebug = function(flag, val) {
if (arguments.length === 1) val = true;
_debugFlags[flag] = val;
dispatch.call('change');
return context;
};
/* Container */
let _container = d3_select(null);
/** @type {'light' | 'dark'} */
let _theme;
/** @type {GetSet<iD.Context, typeof _container>} */
context.container = function(val) {
if (!arguments.length) return _container;
_container = val;
_container.classed('ideditor', true);
_container.classed('theme-dark', _theme === 'dark');
_container.classed('theme-light', _theme === 'light');
return context;
};
context.containerNode = function(val) {
if (!arguments.length) return context.container().node();
context.container(d3_select(val));
return context;
};
context.theme = function(val) {
if (!arguments.length) return _theme;
_theme = val;
context.container(_container); // refresh theme
return context;
};
let _embed;
context.embed = function(val) {
if (!arguments.length) return _embed;
_embed = val;
return context;
};
/* Assets */
let _assetPath = '';
/** @type {GetSet<iD.Context, string>} */
context.assetPath = function(val) {
if (!arguments.length) return _assetPath;
_assetPath = val;
fileFetcher.assetPath(val);
return context;
};
/** @type {Tags} */
let _assetMap = {};
/** @type {GetSet<iD.Context, Tags>} */
context.assetMap = function(val) {
if (!arguments.length) return _assetMap;
_assetMap = val;
fileFetcher.assetMap(val);
return context;
};
/** @param {string} val */
context.asset = (val) => {
if (/^http(s)?:\/\//i.test(val)) return val;
const filename = _assetPath + val;
return _assetMap[filename] || filename;
};
/** @param {string} val */
context.imagePath = (val) => context.asset(`img/${val}`);
/* reset (aka flush) */
context.reset = () => {
context.debouncedSave.cancel();
Array.from(_deferred).forEach(handle => {
window.cancelIdleCallback(handle);
_deferred.delete(handle);
});
Object.values(services).forEach(service => {
if (service && typeof service.reset === 'function') {
service.reset(context);
}
});
context.changeset = null;
_validator.reset();
_features.reset();
_history.reset();
_uploader.reset();
// don't leave stale state in the inspector
context.container().select('.inspector-wrap *').remove();
return context;
};
context.flush = context.reset;
/* Projections */
context.projection = geoRawMercator();
context.curtainProjection = geoRawMercator();
// these lines are required to define the type-definitions.
// the actual value is assigned below, in the `init` function.
context.graph = /** @type {() => iD.Graph} */ (undefined);
context.pauseChangeDispatch = /** @type {Function} */ (undefined);
context.resumeChangeDispatch = /** @type {Function} */ (undefined);
context.perform = /** @type {typeof _history.perform} */ (undefined);
context.replace = /** @type {typeof _history.replace} */ (undefined);
context.pop = /** @type {typeof _history.pop} */ (undefined);
context.overwrite = /** @type {typeof _history.overwrite} */ (undefined);
context.undo = /** @type {typeof _history.undo} */ (undefined);
context.redo = /** @type {typeof _history.redo} */ (undefined);
context.on = /** @type {any} */ (undefined);
/** @returns {typeof context} */
context.init = () => {
instantiateInternal();
initializeDependents();
return context;
// Load variables and properties. No property of `context` should be accessed
// until this is complete since load statuses are indeterminate. The order
// of instantiation shouldn't matter.
function instantiateInternal() {
_history = coreHistory(context);
context.graph = _history.graph;
context.pauseChangeDispatch = _history.pauseChangeDispatch;
context.resumeChangeDispatch = _history.resumeChangeDispatch;
context.perform = withDebouncedSave(_history.perform);
context.replace = withDebouncedSave(_history.replace);
context.pop = withDebouncedSave(_history.pop);
context.undo = withDebouncedSave(_history.undo);
context.redo = withDebouncedSave(_history.redo);
_validator = coreValidator(context);
_uploader = coreUploader(context);
_background = rendererBackground(context);
_features = rendererFeatures(context);
_map = rendererMap(context);
_photos = rendererPhotos(context);
_ui = uiInit(context);
}
// Set up objects that might need to access properties of `context`. The order
// might matter if dependents make calls to each other. Be wary of async calls.
function initializeDependents() {
if (context.initialHashParams.presets) {
presetManager.addablePresetIDs(new Set(context.initialHashParams.presets.split(',')));
}
if (context.initialHashParams.locale) {
localizer.preferredLocaleCodes(context.initialHashParams.locale);
}
if (context.initialHashParams.theme) {
context.theme(context.initialHashParams.theme);
}
// kick off some async work
localizer.ensureLoaded();
presetManager.ensureLoaded();
_background.ensureLoaded();
Object.values(services).forEach(service => {
if (service && typeof service.init === 'function') {
service.init();
}
});
_map.init();
_validator.init();
_features.init();
// Migrate history data from localStorage to IndexedDB
_history.migrateHistoryData();
if (services.maprules && context.initialHashParams.maprules) {
d3_json(context.initialHashParams.maprules)
.then(mapcss => {
services.maprules.init();
mapcss.forEach(mapcssSelector => services.maprules.addRule(mapcssSelector));
})
.catch(() => { /* ignore */ });
}
// if the container isn't available, e.g. when testing, don't load the UI
if (!context.container().empty()) {
_ui.ensureLoaded()
.then(() => {
_background.init();
_photos.init();
});
}
}
};
return utilRebind(context, dispatch, 'on');
}