-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Layer.js
732 lines (639 loc) · 21.9 KB
/
Layer.js
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/**
* Base class for all layers for the Layer System.
*
* Basically, it's a wrapper around {@link L.FeatureGroup}. It doesn't provide all of it's methods because they're used internally in the layer system, and their usage will break it. So do NOT touch the actual FeatureGroup object.
*
* Every layer has its own menu which you can modify by using methods inherited from {@link L.ALS.Widgetable}.
*
* Usage:
*
* 1. Set {@link L.ALS.Layer#defaultName} property to the default name of your layer.
* 1. Create wizard by extending {@link L.ALS.Wizard}.
* 1. Set {@link L.ALS.Layer.wizard} to an instance of your wizard.
* 1. If you need to implement settings for your layer, extend {@link L.ALS.Settings} and set {@link L.ALS.Layer.settings} to an instance of your settings.
* 1. Implement {@link L.ALS.Layer#init} method. It's used as a constructor.
* 1. Modify layer menu by using methods inherited from {@link L.ALS.Widgetable}.
* 1. Implement your own methods or extend current ones. Basically, make it work :D
*
* Please, read the docs for each public method, you might need to (if not should) override most of them.
*
* Important notes:
*
* 1. NEVER use {@link L.LayerGroup} because it breaks layer system!
* 1. Use {@link L.ALS.Layer#addLayers} and {@link L.ALS.Layer#removeLayers} to add and remove Leaflet layers.
* 1. To hide Leaflet layers from the map, use `this.map.remove()` and `this.map.add()`.
* 1. Use {@link L.ALS.Layer#addEventListenerTo} and {@link L.ALS.Layer#removeEventListenerFrom} to add and remove event listeners from objects and map.
* 1. Use {@link L.ALS.ControlManager} methods to manage controls.
* 1. Unless your layer is super simple, you'll most likely need to implement custom serialization and deserialization mechanisms. Please, refer to the {@link L.ALS.Serializable} docs and [example project](https://github.com/matafokka/SynthFlight) for this.
*
* @param wizardResults {Object} Results compiled from the wizard. It is an object who's keys are IDs of your widgets and values are, well, their values.
* @param settings {SettingsObject} Current layer settings.
*
* @class
* @extends L.ALS.Widgetable
* @mixes L.ALS.ControlManager
*/
L.ALS.Layer = L.ALS.Widgetable.extend( /** @lends L.ALS.Layer.prototype */ {
/**
* Name to be assigned to this layer by default. Set it to locale property to localize it.
* @type {string}
* @readonly
*/
defaultName: "layerDefaultName",
/**
* Indicates whether this layer is shown or not. Do NOT modify!
* @type {boolean}
* @readonly
*/
isShown: true,
/**
* Indicates whether this layer is selected or not. Should not be modified!
* @type {boolean}
* @readonly
*/
isSelected: true, // Initially true, so when layer is added, user's code would work
/**
* Whether creation of this layer has been cancelled at {@link L.ALS.Layer#init} by calling `cancelCreation()`.
*/
creationCancelled: false,
_controlsShown: false,
/**
* Whether ALS should write an entry to the history when this layer is created or duplicated, i.e. when
* {@link L.ALS.Layer#init} is called.
*
* Setting it to `false` allows you to control when an action should be added to the history.
* Useful for things like dynamic content loading. You also may want to use {@link L.ALS.operationsWindow} to
* display loading text and animation.
*
* You should always call {@link L.ALS.Layer#writeToHistory} when you're done!
*
* You can always change the value of this property back to `true` to make ALS write to history automatically.
*
* @example Read file from a wizard asynchronously. Write to the history when file is read.
* L.ALS.MyLayer = L.ALS.Layer.extend({
* writeToHistoryOnInit: false, // Disable writing to the history on initialization
*
* init: function (wizardResults, settings) {
* // Read a file from a wizard
* let file = wizardResults["fileWidget"][0], fileReader = new FileReader();
* fileReader.addEventListener("load", (event) => {
* // File reading logic here...
*
* writeToHistory(); // File is read, time to write layer creation to the history
* });
* }
* });
*/
writeToHistoryOnInit: true,
includes: L.ALS.ControlManager.prototype,
/**
* Layer's constructor. Do NOT override it! Use {@link L.ALS.Layer#init} method instead!
* @param layerSystem {L.ALS.System} Layer system that creates this layer
* @param args {Array} Arguments to pass to {@link L.ALS.Layer#init}
* @param settings {SettingsObject} Settings to pass to {@link L.ALS.Layer#init}
* @private
*/
initialize: function (layerSystem, args, settings) {
L.ALS.Widgetable.prototype.initialize.call(this, "als-layer-menu");
L.ALS.ControlManager.prototype.initialize.call(this, layerSystem);
this.setConstructorArguments([args]);
this.serializationIgnoreList.push("_layerSystem", "_nameLabel", "_leafletLayers", "_mapEvents", "getBounds", "isSelected");
/**
* Contains event listeners bound to various objects. Looks like this:
* ```
* {
* "object_id_1": {
* "event_type_1": ["handler1", "handler2", ...],
* "event_type_2": [...],
* ...
* },
* "object_id_2": { ... },
* ...
* }
* ```
* @private
*/
this._eventsForObjects = {};
/**
* @typedef {Object} MapEvent
* @property {string} type Event type
* @property {Object} handler Handler object
* @property {Function} handlerFunction Function to call on given event
* @private
*/
/**
* Contains map events bound to this layer
* @type {MapEvent[]}
* @private
*/
this._mapEvents = [];
/**
* Layer system managing this layer. Deprecated in favor of {@link L.ALS.Layer#layerSystem}
* @type {L.ALS.System}
* @deprecated
* @private
*/
this._layerSystem = layerSystem;
/**
* Layer system managing this layer
* @type {L.ALS.System}
*/
this.layerSystem = layerSystem;
/**
* Map on which this layer is being added
* @type {L.Map}
* @protected
*/
this.map = this.layerSystem.map;
/**
* Unique ID of this layer
* @type {string}
* @readonly
*/
this.id = "ALSLayer" + L.ALS.Helpers.generateID();
/**
* Pane name for this layer
* @type {string}
*/
this.pane = "ALSPane" + this.id;
/**
* Pane element for this layer
* @type HTMLDivElement
*/
this.paneElement = this.map.createPane(this.pane);
this.paneElement.classList.add("als-pane");
/**
* Contains added Leaflet layers
* @type {L.FeatureGroup}
* @package
* @ignore
*/
this._leafletLayers = L.featureGroup([], {pane: this.pane}).addTo(this.map);
/**
* Current name of this layer
* @type {string}
* @private
*/
this._name = this.defaultName;
// Build menu
// Handle
let handle = document.createElement("i");
handle.className = "als-layer-handle ri ri-drag-move-2-line";
// Editable label containing layer's name
let label = document.createElement("p");
label.className = "als-layer-label";
label.innerHTML = this.defaultName;
// Make it editable on double click
label.addEventListener("dblclick", function () {
this.contentEditable = "true";
// noinspection JSValidateTypes
this.focus();
});
// Make it not editable when user leaves
label.addEventListener("blur", (event) => {
let target = event.target;
target.contentEditable = "false";
this.setName(target.innerHTML);
this.writeToHistory();
});
// Make it end editing when user presses Enter
label.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
event.preventDefault();
// noinspection JSValidateTypes
this.blur();
}
});
// Delete button
let deleteButton = document.createElement("i");
deleteButton.className = "ri ri-delete-bin-line als-menu-delete";
deleteButton.addEventListener("click", () => this.deleteLayer(true, true));
// Duplicate button
let duplicateButton;
if (this.layerSystem._enableDuplicateButton) {
duplicateButton = document.createElement("i");
duplicateButton.className = "ri ri-file-copy-line";
duplicateButton.addEventListener("click", () => this.layerSystem._duplicateLayer(this));
}
// Drop-down menu button
let menuButton = document.createElement("i");
menuButton.className = "ri ri-settings-3-line";
// Menu itself
L.ALS.Helpers.makeCollapsible(menuButton, this.container);
this._hideButton = document.createElement("i");
this._hideButton.className = "ri ri-eye-line";
L.ALS.Helpers.makeHideable(this._hideButton, undefined, () => {
this._hideButton.className = "ri ri-eye-off-line";
this._onHide();
this.onHide();
}, () => {
this._hideButton.className = "ri ri-eye-line";
this._onShow();
this.onShow();
}, false);
this._hideButton.setAttribute("data-hidden", "0");
let layerWidget = document.createElement("div");
layerWidget.className = "als-layer-container";
layerWidget.id = this.id;
let controlsContainer = document.createElement("div");
controlsContainer.className = "als-items-row";
let elements = [handle, label, deleteButton, duplicateButton, menuButton, this._hideButton];
for (let e of elements) {
if (e)
controlsContainer.appendChild(e);
}
if (!this.layerSystem._useOnlyOneLayer)
layerWidget.appendChild(controlsContainer);
else
this.container.classList.add("als-only-one-layer");
layerWidget.appendChild(this.container);
layerWidget.addEventListener("click", () => {
if (this.layerSystem) // It's still called when delete button has been clicked. Tis condition fixes this issue.
this.layerSystem._selectLayer(this.id);
});
this.layerSystem._layerContainer.appendChild(layerWidget);
this.layerSystem._layers[this.id] = this;
this._nameLabel = label;
this.init(args, settings, () => this.creationCancelled = true); // Initialize layer and pass all the properties
if (this.creationCancelled)
return;
// Select new layer
this.layerSystem._selectLayer(this.id);
this._onSelect();
},
/**
* Adds event listener (handler) to the object. Use it instead of `object.on()`.
*
* Note: we use object's methods as handlers to be able to save and restore them when user saves the project.
*
* @param object {Object} Object to add listener to
* @param type {string} Event type, string in format used by Leaflet
* @param handler {string} Your object's method that will handle this event
*/
addEventListenerTo: function (object, type, handler) {
// Write added event listener to the _eventsForObjects
if (object._advSysID === undefined)
object._advSysID = "advLayerSys" + L.ALS.Helpers.generateID();
if (this._eventsForObjects[object._advSysID] === undefined)
this._eventsForObjects[object._advSysID] = {};
if (this._eventsForObjects[object._advSysID][type] === undefined)
this._eventsForObjects[object._advSysID][type] = [];
let handlerFunction = (event) => {
// Always handle map events. Handle layer events only if it's selected and shown.
if (object === this.map || (this.isSelected && this.isShown))
this[handler](event);
}
let handlerObject = {
type: type,
handler: handler,
handlerFunction
}
this._eventsForObjects[object._advSysID][type].push(handlerObject);
object.on(type, handlerFunction);
if (object === this.map)
this._mapEvents.push(handlerObject);
},
/**
* Removes event listener (handler) to the specified event type from the object. Use it instead object.off().
*
* @see Layer.addEventListenerTo For more information
*
* @param object {object} - Object to remove event listener from
* @param type {string} - Event type
* @param handler {string} - Event listener (handler) to remove
*/
removeEventListenerFrom: function (object, type, handler) {
if (object._advSysID === undefined)
return;
let handlers = this._eventsForObjects[object._advSysID][type];
if (handlers === undefined)
return;
let index = -1;
for (let i = 0; i < handlers.length; i++) {
if (handlers[i].handler === handler) {
index = i;
break;
}
}
if (index === -1)
return;
let handlerObject = handlers[index];
if (object === this.map)
this._mapEvents.splice(this._mapEvents.indexOf(handlerObject), 1);
object.off(type, handlerObject.handlerFunction);
this._eventsForObjects[object._advSysID][type].splice(index, 1);
},
/**
* Removes all event listeners bounded to the map by this layer. This method is intended ONLY for internal use. Do NOT call it!
* @package
* @ignore
*/
_removeAllMapEventListeners: function () {
for (let handlerObject of this._mapEvents)
this.map.off(handlerObject.type, handlerObject.handlerFunction);
},
/**
* Shows or hides controls of this layer
* @private
*/
_toggleControls: function () {
let show = this.isShown && this.isSelected;
if ((show && this._controlsShown) || (!show && !this._controlsShown))
return;
this._controlsShown = show;
let fn = show ? "addTo" : "remove";
for (let id in this._controls)
this._controls[id][fn](this.map);
},
/**
* Called whenever layer is being showed or and object is being added.
*
* This method is for internal use only. To add behavior upon showing, override {@link L.ALS.Layer#onShow} method.
* @private
*/
_onShow: function () {
this._leafletLayers.addTo(this.map);
this.isShown = true;
this._toggleControls();
},
/**
* Called whenever layer is being hidden.
*
* This method is for internal use only. To add behavior upon hiding, override {@link L.ALS.Layer#onHide} method.
* @private
*/
_onHide: function () {
this._leafletLayers.remove();
this.isShown = false;
this._toggleControls();
},
/**
* Called whenever user selects this layer.
* @protected
*/
_onSelect: function () {
this._toggleControls();
this.paneElement.classList.remove("als-inactive-pane");
this.onSelect();
},
/**
* Called whenever user deselects this layer.
* @protected
*/
_onDeselect: function () {
this._toggleControls();
this.paneElement.classList.add("als-inactive-pane");
this.onDeselect();
},
/**
* Called whenever layer is being shown
*/
onShow: function () {
},
/**
* Called whenever layer is being hidden
*/
onHide: function () {
},
/**
* Called whenever user selects this layer.
*/
onSelect: function () {
},
/**
* Called whenever user deselects this layer.
*/
onDeselect: function () {
},
/**
* Called whenever user changes this layer's name
*/
onNameChange: function () {
},
/**
* Adds Leaflet layers to this layer.
*
* Do NOT override!
*
* @param layers {L.Layer} Layers to add
*/
addLayers: function (...layers) {
for (let layer of layers)
this._leafletLayers.addLayer(layer);
if (this.isShown)
this._onShow();
this.layerSystem._reorderLayers(); // We gotta reorder layers because Leaflet will bring lastly added layer on top.
},
/**
* Removes added Leaflet layers with its event handlers.
* @param layers {L.Layer} Layers to remove. If layer extends LayerGroup, will also remove Leaflet layers contained in it.
*/
removeLayers: function (...layers) {
for (let layer of layers) {
// Remove layers from the layer group
if (layer.eachLayer)
layer.eachLayer(lyr => this.removeLayers(lyr));
// Remove attached event listeners
if (layer._advSysID !== undefined) {
delete this._eventsForObjects[layer._advSysID];
layer.clearAllEventListeners();
}
// Remove layer from both group and map
this._leafletLayers.removeLayer(layer);
layer.remove();
}
},
/**
* Use this method instead of {@link L.ALS.Layer#initialize}
* @param wizardResults {Object} Results compiled from the wizard. It is an object who's keys are IDs of your controls and values are values of your controls.
* @param settings {SettingsObject} Current layer settings and both default and custom general settings.
* @param cancelCreation {function} A function that will safely cancel creation of this layer.
* If your initialization calls other layer methods, consider using {@link L.ALS.Layer#creationCancelled} property
* to detect whether creation has been cancelled and to avoid getting errors.
* You should call this function only in synchronous code, only at {@link L.ALS.Layer#init} and only before adding any widgets!
*/
init: function (wizardResults, settings, cancelCreation) {
},
/**
* Deletes this layer
* @param shouldAskUser {boolean} If set to true, the message asking if user wants to delete selected layer will be displayed. Otherwise, layer will be silently deleted.
* @param writeToHistory {boolean} If true, will write deletion to the history
*/
deleteLayer: function (shouldAskUser = false, writeToHistory = false) {
this.layerSystem._selectLayer(this.id);
this.layerSystem._deleteLayer(shouldAskUser, writeToHistory);
},
_onDelete: function () {
this.onDelete();
for (let id in this._controls)
this.removeControl(this._controls[id]);
},
/**
* Called upon deletion. Here you can clean up everything you've done which can't be undone by the system (i.e., layers added directly to the map or created elements on the page)
*/
onDelete: function () {
},
// Wrappers
/**
* @see FeatureGroup.setStyle
* @return {L.ALS.Layer} this
*/
setStyle: function (style) {
this._leafletLayers.setStyle(style);
return this;
},
/**
* @see FeatureGroup.getBounds
*/
getBounds: function () {
return this._leafletLayers.getBounds();
},
/**
* @see FeatureGroup.eachLayer
* @return {L.ALS.Layer} this
*/
eachLayer: function (fn, context) {
this._leafletLayers.eachLayer(fn, context);
return this;
},
/**
* Sets name of this layer
* @param name {string} Name to set
*/
setName: function (name) {
this._name = name;
this._nameLabel.innerHTML = this._name;
this.onNameChange();
},
/**
* @return {string} Name of this layer
*/
getName: function () {
return this._name;
},
/**
* Called when layer is being exported. If you want to export more than only geometry, override this method.
*
* Default implementation is:
* ```JS
* return this._leafletLayers.toGeoJSON();
* ```
*
* @see L.FeatureGroup.toGeoJSON
*/
toGeoJSON: function () {
return this._leafletLayers.toGeoJSON();
},
/**
* Copies settings to this layer as properties
* @param settings {SettingsObject} `settings` argument passed to {@link L.ALS.Layer#init}
* @protected
*/
copySettingsToThis: function (settings) {
for (let s in settings) {
if (s !== "skipSerialization" && s !== "skipDeserialization")
this[s] = settings[s];
}
},
/**
* Called whenever user updates the settings. Use it to update your layer depending on changed settings.
* @param settings {SettingsObject} Same as settings passed to {@link L.ALS.Layer#init}
*/
applyNewSettings: function (settings) {
},
/**
* Serializes some important properties. Must be called at {@link L.ALS.Layer#serialize} in any layer!
*
* Deprecated in favor of {@link L.ALS.Serializable.getObjectFromSerialized} which uses this function under-the-hood.
*
* @param serialized {Object} Your serialized object
*
* @deprecated
*/
serializeImportantProperties: function (serialized) {
let props = ["_name", "isShown", "isSelected"];
for (let prop of props)
serialized[prop] = this[prop];
serialized._isCollapsed = this.container.getAttribute("data-hidden") === "1";
},
/**
* Writes a record to the history. Call it at the end of each action.
*
* This method interferes with serialization and deserialization.
* It won't do anything, if called when serialization or deserialization hasn't finished,
* for example, when restoring from history.
*
* Basically, an alias for {@link L.ALS.System#writeToHistory}.
*/
writeToHistory: function () {
if (this.layerSystem) // There might be cases (race conditions?) when layer's not fully initialized but something
this.layerSystem.writeToHistory();
},
getObjectToSerializeTo: function (seenObjects) {
let serialized = L.ALS.Serializable.prototype.getObjectToSerializeTo.call(this, seenObjects);
serialized._widgets = this.serializeWidgets(seenObjects);
this.serializeImportantProperties(serialized);
return serialized;
},
/**
* Serializes this layer.
*
* Default implementation is:
* ```JS
* let serialized = L.ALS.Widgetable.prototype.serialize.call(this, seenObjects);
* this.serializeImportantProperties(serialized);
* return serialized;
* ```
*
* @param seenObjects {Object} Already seen objects
* @return {Object}
*/
serialize: function (seenObjects) {
let serialized = L.ALS.Widgetable.prototype.serialize.call(this, seenObjects);
this.serializeImportantProperties(serialized);
return serialized;
},
statics: {
/**
* Wizard class which gives a layer its initial properties
* @type {function(new:L.ALS.Wizard)}
* @memberOf L.ALS.Layer
*/
wizard: L.ALS.Wizard,
/**
* Settings instance
* @type {L.ALS.Settings}
* @memberOf L.ALS.Layer
*/
settings: new L.ALS.Settings(),
/**
* Deserializes some important properties. Must be called at `deserialize` in any layer!
* @param serialized {Object} Serialized object
* @param instance {L.ALS.Layer|Object} New instance of your layer
* @memberOf L.ALS.Layer
*/
deserializeImportantProperties: function (serialized, instance) {
instance.setName(serialized._name);
let props = ["isShown", "isSelected"];
for (let prop of props)
instance[prop] = serialized[prop];
if (serialized._isCollapsed)
instance.container.setAttribute("data-hidden", "1");
},
/**
* @see L.ALS.Serializable.deserialize
* @override
* @inheritDoc
* @memberOf L.ALS.Layer
*/
deserialize: function (serialized, layerSystem, settings, seenObjects) {
serialized.constructorArguments = [layerSystem, serialized.constructorArguments[0], settings];
let wasSelected = serialized.isSelected;
serialized.isSelected = true; // Initially true, so when layer is added, user's code would work
let instance = L.ALS.Widgetable.deserialize(serialized, seenObjects);
L.ALS.Layer.deserializeImportantProperties(serialized, instance);
serialized.isSelected = wasSelected;
return instance;
}
},
});