-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathleaflet.distortableimage.js
8417 lines (7208 loc) · 363 KB
/
leaflet.distortableimage.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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/ansi-html-community/index.js":
/*!***************************************************!*\
!*** ./node_modules/ansi-html-community/index.js ***!
\***************************************************/
/***/ (function(module) {
"use strict";
module.exports = ansiHTML
// Reference to https://github.com/sindresorhus/ansi-regex
var _regANSI = /(?:(?:\u001b\[)|\u009b)(?:(?:[0-9]{1,3})?(?:(?:;[0-9]{0,3})*)?[A-M|f-m])|\u001b[A-M]/
var _defColors = {
reset: ['fff', '000'], // [FOREGROUD_COLOR, BACKGROUND_COLOR]
black: '000',
red: 'ff0000',
green: '209805',
yellow: 'e8bf03',
blue: '0000ff',
magenta: 'ff00ff',
cyan: '00ffee',
lightgrey: 'f0f0f0',
darkgrey: '888'
}
var _styles = {
30: 'black',
31: 'red',
32: 'green',
33: 'yellow',
34: 'blue',
35: 'magenta',
36: 'cyan',
37: 'lightgrey'
}
var _openTags = {
'1': 'font-weight:bold', // bold
'2': 'opacity:0.5', // dim
'3': '<i>', // italic
'4': '<u>', // underscore
'8': 'display:none', // hidden
'9': '<del>' // delete
}
var _closeTags = {
'23': '</i>', // reset italic
'24': '</u>', // reset underscore
'29': '</del>' // reset delete
}
;[0, 21, 22, 27, 28, 39, 49].forEach(function (n) {
_closeTags[n] = '</span>'
})
/**
* Converts text with ANSI color codes to HTML markup.
* @param {String} text
* @returns {*}
*/
function ansiHTML (text) {
// Returns the text if the string has no ANSI escape code.
if (!_regANSI.test(text)) {
return text
}
// Cache opened sequence.
var ansiCodes = []
// Replace with markup.
var ret = text.replace(/\033\[(\d+)m/g, function (match, seq) {
var ot = _openTags[seq]
if (ot) {
// If current sequence has been opened, close it.
if (!!~ansiCodes.indexOf(seq)) { // eslint-disable-line no-extra-boolean-cast
ansiCodes.pop()
return '</span>'
}
// Open tag.
ansiCodes.push(seq)
return ot[0] === '<' ? ot : '<span style="' + ot + ';">'
}
var ct = _closeTags[seq]
if (ct) {
// Pop sequence
ansiCodes.pop()
return ct
}
return ''
})
// Make sure tags are closed.
var l = ansiCodes.length
;(l > 0) && (ret += Array(l + 1).join('</span>'))
return ret
}
/**
* Customize colors.
* @param {Object} colors reference to _defColors
*/
ansiHTML.setColors = function (colors) {
if (typeof colors !== 'object') {
throw new Error('`colors` parameter must be an Object.')
}
var _finalColors = {}
for (var key in _defColors) {
var hex = colors.hasOwnProperty(key) ? colors[key] : null
if (!hex) {
_finalColors[key] = _defColors[key]
continue
}
if ('reset' === key) {
if (typeof hex === 'string') {
hex = [hex]
}
if (!Array.isArray(hex) || hex.length === 0 || hex.some(function (h) {
return typeof h !== 'string'
})) {
throw new Error('The value of `' + key + '` property must be an Array and each item could only be a hex string, e.g.: FF0000')
}
var defHexColor = _defColors[key]
if (!hex[0]) {
hex[0] = defHexColor[0]
}
if (hex.length === 1 || !hex[1]) {
hex = [hex[0]]
hex.push(defHexColor[1])
}
hex = hex.slice(0, 2)
} else if (typeof hex !== 'string') {
throw new Error('The value of `' + key + '` property must be a hex string, e.g.: FF0000')
}
_finalColors[key] = hex
}
_setTags(_finalColors)
}
/**
* Reset colors.
*/
ansiHTML.reset = function () {
_setTags(_defColors)
}
/**
* Expose tags, including open and close.
* @type {Object}
*/
ansiHTML.tags = {}
if (Object.defineProperty) {
Object.defineProperty(ansiHTML.tags, 'open', {
get: function () { return _openTags }
})
Object.defineProperty(ansiHTML.tags, 'close', {
get: function () { return _closeTags }
})
} else {
ansiHTML.tags.open = _openTags
ansiHTML.tags.close = _closeTags
}
function _setTags (colors) {
// reset all
_openTags['0'] = 'font-weight:normal;opacity:1;color:#' + colors.reset[0] + ';background:#' + colors.reset[1]
// inverse
_openTags['7'] = 'color:#' + colors.reset[1] + ';background:#' + colors.reset[0]
// dark grey
_openTags['90'] = 'color:#' + colors.darkgrey
for (var code in _styles) {
var color = _styles[code]
var oriColor = colors[color] || '000'
_openTags[code] = 'color:#' + oriColor
code = parseInt(code)
_openTags[(code + 10).toString()] = 'background:#' + oriColor
}
}
ansiHTML.reset()
/***/ }),
/***/ "./src/DistortableCollection.js":
/*!**************************************!*\
!*** ./src/DistortableCollection.js ***!
\**************************************/
/***/ (function() {
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var arr = [];
L.DistortableCollection = L.FeatureGroup.extend({
options: {
editable: true,
exportOpts: {
exportStartUrl: '//export.mapknitter.org/export',
statusUrl: '//export.mapknitter.org',
exportUrl: 'http://export.mapknitter.org/'
}
},
initialize: function initialize(options) {
L.setOptions(this, options);
L.FeatureGroup.prototype.initialize.call(this, options);
L.Utils.initTranslation.call(this);
this.editable = this.options.editable;
},
onAdd: function onAdd(map) {
L.FeatureGroup.prototype.onAdd.call(this, map);
this._map = map;
if (this.editable) {
this.editing.enable();
}
/**
* although we have a DistortableCollection.Edit class that handles collection events to keep our code managable,
* events that need to be added on individual images are kept here to do so through `layeradd`.
*/
this.on('layeradd', this._addEvents, this);
this.on('layerremove', this._removeEvents, this);
},
onRemove: function onRemove() {
if (this.editing) {
this.editing.disable();
}
this.off('layeradd', this._addEvents, this);
this.off('layerremove', this._removeEvents, this);
},
_addEvents: function _addEvents(e) {
var layer = e.layer;
L.DomEvent.on(layer, {
dragstart: this._dragStartMultiple,
drag: this._dragMultiple
}, this);
L.DomEvent.on(layer.getElement(), {
mousedown: this._deselectOthers,
/* Enable longpress for multi select for touch devices. */
contextmenu: this._longPressMultiSelect
}, this);
},
_removeEvents: function _removeEvents(e) {
var layer = e.layer;
L.DomEvent.off(layer, {
dragstart: this._dragStartMultiple,
drag: this._dragMultiple
}, this);
L.DomEvent.off(layer.getElement(), {
mousedown: this._deselectOthers,
contextmenu: this._longPressMultiSelect
}, this);
},
_longPressMultiSelect: function _longPressMultiSelect(e) {
var _this = this;
if (!this.editable) {
return;
}
e.preventDefault();
this.eachLayer(function (layer) {
var edit = layer.editing;
if (layer.getElement() === e.target && edit.enabled()) {
L.DomUtil.toggleClass(layer.getElement(), 'collected');
if (_this.anyCollected()) {
layer.deselect();
_this.editing._addToolbar();
} else {
_this.editing._removeToolbar();
}
}
});
},
isCollected: function isCollected(overlay) {
return L.DomUtil.hasClass(overlay.getElement(), 'collected');
},
anyCollected: function anyCollected() {
var layerArr = this.getLayers();
return layerArr.some(this.isCollected.bind(this));
},
_toggleCollected: function _toggleCollected(e, layer) {
if (e.shiftKey) {
/* conditional prevents disabled images from flickering multi-select mode */
if (layer.editing.enabled()) {
L.DomUtil.toggleClass(e.target, 'collected'); // re-order layers by _leaflet_id to match their display order in UI
// add new layer to right position and avoid repitition
var newArr = arr.every(function (each) {
return each._leaflet_id !== layer._leaflet_id;
});
if (newArr) {
arr.push(layer);
} else {
arr.splice(arr.indexOf(layer), 1);
}
}
}
if (this.anyCollected()) {
layer.deselect();
} else {
this.editing._removeToolbar();
}
},
_deselectOthers: function _deselectOthers(e) {
var _this2 = this;
if (!this.editable) {
return;
}
this.eachLayer(function (layer) {
if (layer.getElement() !== e.target) {
layer.deselect();
} else {
_this2._toggleCollected(e, layer);
}
});
if (e) {
L.DomEvent.stopPropagation(e);
}
},
_dragStartMultiple: function _dragStartMultiple(e) {
var overlay = e.target;
var map = this._map;
var i;
if (!this.isCollected(overlay)) {
return;
}
this.eachLayer(function (layer) {
layer._dragStartPoints = {};
layer.deselect();
for (i = 0; i < 4; i++) {
var c = layer.getCorner(i);
layer._dragStartPoints[i] = map.latLngToLayerPoint(c);
}
});
},
_dragMultiple: function _dragMultiple(e) {
var overlay = e.target;
var map = this._map;
if (!this.isCollected(overlay)) {
return;
}
var topLeft = map.latLngToLayerPoint(overlay.getCorner(0));
var delta = overlay._dragStartPoints[0].subtract(topLeft);
this._updateCollectionFromPoints(delta, overlay);
},
_toRemove: function _toRemove() {
var _this3 = this;
var layerArr = this.getLayers();
return layerArr.filter(function (layer) {
var mode = layer.editing._mode;
return _this3.isCollected(layer) && mode !== 'lock';
});
},
_toMove: function _toMove(overlay) {
var _this4 = this;
var layerArr = this.getLayers();
return layerArr.filter(function (layer) {
var mode = layer.editing._mode;
return layer !== overlay && _this4.isCollected(layer) && mode !== 'lock';
});
},
_updateCollectionFromPoints: function _updateCollectionFromPoints(delta, overlay) {
var layersToMove = this._toMove(overlay);
var p = new L.Transformation(1, -delta.x, 1, -delta.y);
var i;
layersToMove.forEach(function (layer) {
var movedPoints = {};
for (i = 0; i < 4; i++) {
movedPoints[i] = p.transform(layer._dragStartPoints[i]);
}
layer.setCornersFromPoints(movedPoints);
});
},
_getAvgCmPerPixel: function _getAvgCmPerPixel(imgs) {
var reduce = imgs.reduce(function (sum, img) {
return sum + img.cm_per_pixel;
}, 0);
return reduce / imgs.length;
},
// Connects to JSON file and fetches JSON data therein from remote source
fetchRemoteJson: function fetchRemoteJson(url) {
return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var index, imgCollectionProps, response;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
index = 0;
imgCollectionProps = [];
_context.prev = 2;
_context.next = 5;
return axios.get(url);
case 5:
response = _context.sent;
if (!(response.data.images.length > 1)) {
_context.next = 9;
break;
}
response.data.images.forEach(function (data) {
imgCollectionProps[index] = data;
index++;
});
return _context.abrupt("return", {
avg_cm_per_pixel: response.data.avg_cm_per_pixel,
imgCollectionProps: imgCollectionProps
});
case 9:
imgCollectionProps[index] = response.data.images;
return _context.abrupt("return", {
avg_cm_per_pixel: response.data.avg_cm_per_pixel,
imgCollectionProps: imgCollectionProps
});
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](2);
console.log('err', _context.t0);
case 16:
case "end":
return _context.stop();
}
}
}, _callee, null, [[2, 13]]);
}))();
},
// expects url in this format: https://archive.org/download/segeotest/segeotest.json
recreateImagesFromJsonUrl: function recreateImagesFromJsonUrl(url) {
var _this5 = this;
return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var imageCollectionObj;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
imageCollectionObj = {};
if (!url) {
_context2.next = 6;
break;
}
_context2.next = 4;
return _this5.fetchRemoteJson(url);
case 4:
imageCollectionObj = _context2.sent;
return _context2.abrupt("return", imageCollectionObj);
case 6:
;
return _context2.abrupt("return", imageCollectionObj);
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))();
},
generateExportJson: function generateExportJson() {
var allImages = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var json = {};
json.images = [];
this.eachLayer(function (layer) {
if (allImages || this.isCollected(layer)) {
var sections = layer._image.src.split('/');
var filename = sections[sections.length - 1];
var zc = layer.getCorners();
var corners = [{
lat: zc[0].lat,
lon: zc[0].lng
}, {
lat: zc[1].lat,
lon: zc[1].lng
}, {
lat: zc[3].lat,
lon: zc[3].lng
}, {
lat: zc[2].lat,
lon: zc[2].lng
}];
json.images.push({
id: layer._leaflet_id,
src: layer._image.src,
width: layer._image.width,
height: layer._image.height,
image_file_name: filename,
nodes: corners,
cm_per_pixel: L.ImageUtil.getCmPerPixel(layer)
});
}
}, this);
json.images = json.images.reverse();
json.avg_cm_per_pixel = this._getAvgCmPerPixel(json.images);
return json;
}
});
L.distortableCollection = function (id, options) {
return new L.DistortableCollection(id, options);
};
/***/ }),
/***/ "./src/DistortableImageOverlay.js":
/*!****************************************!*\
!*** ./src/DistortableImageOverlay.js ***!
\****************************************/
/***/ (function() {
L.DistortableImageOverlay = L.ImageOverlay.extend({
options: {
height: 200,
crossOrigin: true,
// todo: find ideal number to prevent distortions during RotateScale, and make it dynamic (remove hardcoding)
edgeMinWidth: 50,
editable: true,
mode: 'distort',
selected: false,
interactive: true,
tooltipText: ''
},
initialize: function initialize(url, options) {
L.setOptions(this, options);
L.Utils.initTranslation.call(this);
this.edgeMinWidth = this.options.edgeMinWidth;
this.editable = this.options.editable;
this._selected = this.options.selected;
this._url = url;
this.rotation = {};
this.interactive = this.options.interactive;
this.tooltipText = this.options.tooltipText;
},
onAdd: function onAdd(map) {
var _this = this;
this._map = map;
if (!this.getElement()) {
this._initImage();
}
map.on('viewreset', this._reset, this);
if (this.options.corners) {
this._corners = this.options.corners;
if (map.options.zoomAnimation && L.Browser.any3d) {
map.on('zoomanim', this._animateZoom, this);
}
} // Have to wait for the image to load because need to access its w/h
L.DomEvent.on(this.getElement(), 'load', function () {
_this.getPane().appendChild(_this.getElement());
_this._initImageDimensions();
if (_this.options.rotation) {
var units = _this.options.rotation.deg >= 0 ? 'deg' : 'rad';
_this.setAngle(_this.options.rotation[units], units);
} else {
_this.rotation = {
deg: 0,
rad: 0
};
_this._reset();
}
/* Initialize default corners if not already set */
if (!_this._corners) {
if (map.options.zoomAnimation && L.Browser.any3d) {
map.on('zoomanim', _this._animateZoom, _this);
}
}
/** if there is a featureGroup, only its editable option matters */
var eventParents = _this._eventParents;
if (eventParents) {
_this.eP = eventParents[Object.keys(eventParents)[0]];
if (_this.eP.editable) {
_this.editing.enable();
}
} else {
if (_this.editable) {
_this.editing.enable();
}
_this.eP = null;
}
});
L.DomEvent.on(this.getElement(), 'click', this.select, this);
L.DomEvent.on(map, {
singleclickon: this._singleClickListeners,
singleclickoff: this._resetClickListeners,
singleclick: this._singleClick
}, this);
/**
* custom events fired from DoubleClickLabels.js. Used to differentiate
* single / dblclick to not deselect images on map dblclick.
*/
if (!(map.doubleClickZoom.enabled() || map.doubleClickLabels.enabled())) {
L.DomEvent.on(map, 'click', this.deselect, this);
}
this.fire('add');
L.DomEvent.on(this.getElement(), 'mousemove', this.activateTooltip, this);
L.DomEvent.on(this.getElement(), 'mouseout', this.closeTooltip, this);
},
onRemove: function onRemove(map) {
L.DomEvent.off(this.getElement(), 'click', this.select, this);
L.DomEvent.off(map, {
singleclickon: this._singleClickListeners,
singleclickoff: this._resetClickListeners,
singleclick: this._singleClick
}, this);
L.DomEvent.off(map, 'click', this.deselect, this);
if (this.editing) {
this.editing.disable();
}
this.fire('remove');
L.ImageOverlay.prototype.onRemove.call(this, map);
L.DomEvent.on(this.getElement(), 'mouseout', this.closeTooltip, this);
L.DomEvent.off(this.getElement(), 'mousemove', this.deactivateTooltip, this);
},
_initImageDimensions: function _initImageDimensions() {
var map = this._map;
var originalImageWidth = L.DomUtil.getStyle(this.getElement(), 'width');
var originalImageHeight = L.DomUtil.getStyle(this.getElement(), 'height');
var aspectRatio = parseInt(originalImageWidth) / parseInt(originalImageHeight);
var imageHeight = this.options.height;
var imageWidth = parseInt(aspectRatio * imageHeight);
var center = map.project(map.getCenter());
var offset = L.point(imageWidth, imageHeight).divideBy(2);
if (this.options.corners) {
this._corners = this.options.corners;
} else {
this._corners = [map.unproject(center.subtract(offset)), map.unproject(center.add(L.point(offset.x, -offset.y))), map.unproject(center.add(L.point(-offset.x, offset.y))), map.unproject(center.add(offset))];
}
this._initialDimensions = {
'center': center,
'offset': offset,
'zoom': map.getZoom()
};
this.setBounds(L.latLngBounds(this.getCorners()));
},
_singleClick: function _singleClick(e) {
if (e.type === 'singleclick') {
this.deselect();
} else {
return;
}
},
_singleClickListeners: function _singleClickListeners() {
var map = this._map;
L.DomEvent.off(map, 'click', this.deselect, this);
L.DomEvent.on(map, 'singleclick', this.deselect, this);
},
_resetClickListeners: function _resetClickListeners() {
var map = this._map;
L.DomEvent.on(map, 'click', this.deselect, this);
L.DomEvent.off(map, 'singleclick', this.deselect, this);
},
isSelected: function isSelected() {
return this._selected;
},
deselect: function deselect() {
var edit = this.editing;
if (!edit.enabled()) {
return;
}
edit._removeToolbar();
edit._hideMarkers();
this._selected = false;
this.fire('deselect');
return this;
},
select: function select(e) {
var edit = this.editing;
var eP = this.eP;
if (!edit.enabled()) {
return;
}
if (e) {
L.DomEvent.stopPropagation(e);
} // this ensures deselection of all other images, allowing us to keep collection group optional
this._programmaticGrouping();
this._selected = true;
edit._addToolbar();
edit._showMarkers();
this.fire('select'); // we run the selection logic 1st anyway because the collection group's _addToolbar method depends on it
if (eP && eP.anyCollected()) {
this.deselect();
return;
}
return this;
},
_programmaticGrouping: function _programmaticGrouping() {
this._map.eachLayer(function (layer) {
if (layer instanceof L.DistortableImageOverlay) {
layer.deselect();
}
});
},
setCorner: function setCorner(corner, latlng) {
var edit = this.editing;
this._corners[corner] = latlng;
this.setBounds(L.latLngBounds(this.getCorners()));
this.fire('update');
if (edit.toolbar && edit.toolbar instanceof L.DistortableImage.PopupBar) {
edit._updateToolbarPos();
}
this.edited = true;
return this;
},
_cornerExceedsMapLats: function _cornerExceedsMapLats(zoom, corner, map) {
if (map.options.crs.Simple == L.CRS.Simple) {
return false;
} else {
var exceedsTop;
var exceedsBottom;
if (zoom === 0) {
exceedsTop = map.project(corner).y < 2;
exceedsBottom = map.project(corner).y >= 255;
} else {
exceedsTop = map.project(corner).y / zoom < 2;
exceedsBottom = map.project(corner).y / Math.pow(2, zoom) >= 255;
}
return exceedsTop || exceedsBottom;
}
},
activateTooltip: function activateTooltip() {
if (!this._selected) {
this.bindTooltip(this.tooltipText, {
direction: 'top'
}).openTooltip();
}
},
closeToolTip: function closeToolTip() {
this.closeTooltip();
},
deactivateTooltip: function deactivateTooltip() {
this.unbindTooltip();
},
setCorners: function setCorners(latlngObj) {
var map = this._map;
var zoom = map.getZoom();
var edit = this.editing;
var i = 0; // this is to fix https://github.com/publiclab/Leaflet.DistortableImage/issues/402
for (var k in latlngObj) {
if (this._cornerExceedsMapLats(zoom, latlngObj[k], map)) {
// calling reset / update w/ the same corners bc it prevents a marker flicker for rotate
this.setBounds(L.latLngBounds(this.getCorners()));
this.fire('update');
return;
}
}
for (var _k in latlngObj) {
this._corners[i] = latlngObj[_k];
i += 1;
}
this.setBounds(L.latLngBounds(this.getCorners()));
this.fire('update');
if (edit.toolbar && edit.toolbar instanceof L.DistortableImage.PopupBar) {
edit._updateToolbarPos();
}
this.edited = true;
return this;
},
setCornersFromPoints: function setCornersFromPoints(pointsObj) {
var map = this._map;
var zoom = map.getZoom();
var edit = this.editing;
var i = 0;
for (var k in pointsObj) {
var corner = map.layerPointToLatLng(pointsObj[k]);
if (this._cornerExceedsMapLats(zoom, corner, map)) {
// calling reset / update w/ the same corners bc it prevents a marker flicker for rotate
this.setBounds(L.latLngBounds(this.getCorners()));
this.fire('update');
return;
}
}
for (var _k2 in pointsObj) {
this._corners[i] = map.layerPointToLatLng(pointsObj[_k2]);
i += 1;
}
this.setBounds(L.latLngBounds(this.getCorners()));
this.fire('update');
if (edit.toolbar && edit.toolbar instanceof L.DistortableImage.PopupBar) {
edit._updateToolbarPos();
}
this.edited = true;
return this;
},
scaleBy: function scaleBy(scale) {
var map = this._map;
var center = map.project(this.getCenter());
var i;
var p;
var scaledCorners = {};
if (scale === 0) {
return;
}
for (i = 0; i < 4; i++) {
p = map.project(this.getCorner(i)).subtract(center).multiplyBy(scale).add(center);
scaledCorners[i] = map.unproject(p);
}
this.setCorners(scaledCorners);
return this;
},
getAngle: function getAngle() {
var unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'deg';
var matrix = this.getElement().style[L.DomUtil.TRANSFORM].split('matrix3d')[1].slice(1, -1).split(',');
var row0x = matrix[0];
var row0y = matrix[1];
var row1x = matrix[4];
var row1y = matrix[5];
var determinant = row0x * row1y - row0y * row1x;
var angle = L.TrigUtil.calcAngle(row0x, row0y, 'rad');
if (determinant < 0) {
angle += angle < 0 ? Math.PI : -Math.PI;
}
if (angle < 0) {
angle = 2 * Math.PI + angle;
}
return unit === 'deg' ? Math.round(L.TrigUtil.radiansToDegrees(angle)) : L.Util.formatNum(angle, 2);
},
setAngle: function setAngle(angle) {
var unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'deg';
var currentAngle = this.getAngle(unit);
var angleToRotateBy = angle - currentAngle;
this.rotateBy(angleToRotateBy, unit);
return this;
},
rotateBy: function rotateBy(angle) {
var unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'deg';
var map = this._map;
var center = map.project(this.getCenter());
var corners = {};
var i;
var p;
var q;
if (unit === 'deg') {
angle = L.TrigUtil.degreesToRadians(angle);
}
for (i = 0; i < 4; i++) {
p = map.project(this.getCorner(i)).subtract(center);
q = L.point(Math.cos(angle) * p.x - Math.sin(angle) * p.y, Math.sin(angle) * p.x + Math.cos(angle) * p.y);
corners[i] = map.unproject(q.add(center));
}
this.setCorners(corners);
return this;
},
dragBy: function dragBy(formerPoint, newPoint) {
var map = this._map;
var i;
var p;
var transCorners = {};
var delta = map.project(formerPoint).subtract(map.project(newPoint));
for (i = 0; i < 4; i++) {
p = map.project(this.getCorner(i)).subtract(delta);
transCorners[i] = map.unproject(p);
}
this.setCorners(transCorners);
},
restore: function restore() {
var map = this._map;
var center = this._initialDimensions.center;
var offset = this._initialDimensions.offset;
var zoom = this._initialDimensions.zoom;
var corners = [center.subtract(offset), center.add(L.point(offset.x, -offset.y)), center.add(L.point(-offset.x, offset.y)), center.add(offset)];
for (var i = 0; i < 4; i++) {
if (!map.unproject(corners[i], zoom).equals(this.getCorner(i))) {
this.setCorner(i, map.unproject(corners[i], zoom));
}
}
this.edited = false;
this.fire('restore');
return this;
},
/* Copied from Leaflet v0.7 https://github.com/Leaflet/Leaflet/blob/66282f14bcb180ec87d9818d9f3c9f75afd01b30/src/dom/DomUtil.js#L189-L199 */
/* since L.DomUtil.getTranslateString() is deprecated in Leaflet v1.0 */
_getTranslateString: function _getTranslateString(point) {
// on WebKit browsers (Chrome/Safari/iOS Safari/Android)
// using translate3d instead of translate
// makes animation smoother as it ensures HW accel is used.
// Firefox 13 doesn't care
// (same speed either way), Opera 12 doesn't support translate3d
var is3d = L.Browser.webkit3d;
var open = 'translate' + (is3d ? '3d' : '') + '(';
var close = (is3d ? ',0' : '') + ')';
return open + point.x + 'px,' + point.y + 'px' + close;
},
_reset: function _reset() {
var map = this._map;
var image = this.getElement();
var latLngToLayerPoint = L.bind(map.latLngToLayerPoint, map);
var transformMatrix = this._calculateProjectiveTransform(latLngToLayerPoint);