forked from inexorabletash/travellermap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.js
2004 lines (1695 loc) · 61.9 KB
/
map.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
/*global Traveller */ // for lint and IDEs
// ======================================================================
// Exported Functionality
// ======================================================================
// NOTE: Used by other scripts
const Util = {
makeURL: (base, params) => {
'use strict';
base = String(base).replace(/\?.*/, '');
if (!params) return base;
const keys = Object.keys(params);
let args = '';
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
let value = params[key];
if (value === undefined || value === null) continue;
if (!Array.isArray(value))
value = [value];
value.forEach(value => {
args += (args ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
});
}
return args ? base + '?' + args : base;
},
// Replace with URL/searchParams
parseURLQuery: url => {
'use strict';
const o = Object.create(null);
if (url.search && url.search.length > 1) {
url.search.substring(1).split('&').forEach(pair => {
if (!pair) return;
const kv = pair.split('=', 2);
if (kv.length === 2)
o[kv[0]] = decodeURIComponent(kv[1].replace(/\+/g, ' '));
else
o[kv[0]] = true;
});
}
return o;
},
escapeHTML: s => {
'use strict';
return String(s).replace(/[&<>"']/g, c => {
switch (c) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '"': return '"';
case "'": return ''';
default: return c;
}
});
},
once: func => {
let run = false;
return function() {
if (run) return;
run = true;
func.apply(this, arguments);
};
},
debounce: (func, delay, immediate) => {
let timeoutId = 0;
if (immediate) {
return function() {
if (timeoutId)
clearTimeout(timeoutId);
else
func.apply(this, arguments);
timeoutId = setTimeout(() => { timeoutId = 0; }, delay);
};
} else {
return function() {
const $this = this, $arguments = arguments;
if (timeoutId)
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply($this, $arguments);
timeoutId = 0;
}, delay);
};
}
},
memoize: f => {
const cache = Object.create(null);
return function() {
const key = JSON.stringify([].slice.call(arguments));
return (key in cache) ? cache[key] : cache[key] = f.apply(this, arguments);
};
},
// p = ignorable(other_promise);
// p.then(...);
// p.ignore(); // p will neither resolve nor reject
// WARNING: p = ignorable(...).then(...); p.ignore(); will fail
// (Promise subclassing is not used)
ignorable: p => {
let ignored = false;
const q = new Promise((resolve, reject) => {
p.then(r => { if (!ignored) resolve(r); },
r => { if (!ignored) reject(r); });
});
q.ignore = () => { ignored = true; };
return q;
},
fetchImage: (url, img) => {
return new Promise((resolve, reject) => {
img = img || document.createElement('img');
img.src = url;
img.onload = () => { resolve(img); };
img.onerror = () => { reject(Error('Image failed to load')); };
});
},
parseCookies: () => {
const cookies = {};
document.cookie.split(/; +/g).forEach(pair => {
const i = pair.indexOf('=');
if (i === -1) cookies[''] = pair;
else cookies[pair.substring(0, i)] = pair.substring(i+1);
});
return cookies;
},
copyTextToClipboard: text => {
const ta = document.createElement('textarea');
ta.value = text;
document.body.append(ta);
if (navigator.userAgent.match(/iPad|iPhone|iPod/)) {
ta.contentEditable = true;
ta.readOnly = true;
const range = document.createRange();
range.selectNodeContents(ta);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
ta.setSelectionRange(0, text.length);
} else {
ta.select();
}
document.execCommand('copy');
ta.remove();
}
};
(global => {
'use strict';
//----------------------------------------------------------------------
// General Traveller stuff
//----------------------------------------------------------------------
const SERVICE_BASE = ((l) => {
'use strict';
if ((l.hostname === 'localhost' && l.pathname.indexOf('~') !== -1) ||
(l.protocol === 'file:'))
return 'https://travellermap.com';
return '';
})(window.location);
const LEGACY_STYLES = true;
function fromHex(c) {
return '0123456789ABCDEFGHJKLMNPQRSTUVW'.indexOf(c.toUpperCase());
}
//----------------------------------------------------------------------
// Enumerated types
//----------------------------------------------------------------------
const MapOptions = {
SectorGrid: 0x0001,
SubsectorGrid: 0x0002,
GridMask: 0x0003,
SectorsSelected: 0x0004,
SectorsAll: 0x0008,
SectorsMask: 0x000c,
BordersMajor: 0x0010,
BordersMinor: 0x0020,
BordersMask: 0x0030,
NamesMajor: 0x0040,
NamesMinor: 0x0080,
NamesMask: 0x00c0,
WorldsCapitals: 0x0100,
WorldsHomeworlds: 0x0200,
WorldsMask: 0x0300,
RoutesSelectedDeprecated: 0x0400,
PrintStyleDeprecated: 0x0800,
CandyStyleDeprecated: 0x1000,
StyleMaskDeprecated: 0x1800,
ForceHexes: 0x2000,
WorldColors: 0x4000,
FilledBorders: 0x8000,
Mask: 0xffff
};
const Styles = {
Poster: 'poster',
Atlas: 'atlas',
Print: 'print',
Candy: 'candy',
Draft: 'draft',
FASA: 'fasa'
};
//----------------------------------------------------------------------
// Astrometric Constants
//----------------------------------------------------------------------
const Astrometrics = {
ParsecScaleX: Math.cos(Math.PI / 6), // cos(30)
ParsecScaleY: 1.0,
SectorWidth: 32,
SectorHeight: 40,
ReferenceHexX: 1, // Reference is at Core 0140
ReferenceHexY: 40,
TileWidth: 256,
TileHeight: 256,
MinScale: 0.0078125,
MaxScale: 512,
HexEdge: Math.tan(Math.PI / 6) / 4 / Math.cos(Math.PI / 6),
// World-space: Hex coordinate, centered on Reference
sectorHexToWorld: (sx, sy, hx, hy) => {
return {
x: (sx * Astrometrics.SectorWidth) + hx - Astrometrics.ReferenceHexX,
y: (sy * Astrometrics.SectorHeight) + hy - Astrometrics.ReferenceHexY
};
},
worldToSectorHex: (x, y) => {
x += Astrometrics.ReferenceHexX - 1;
y += Astrometrics.ReferenceHexY - 1;
const sx = Math.floor(x / Astrometrics.SectorWidth);
const sy = Math.floor(y / Astrometrics.SectorHeight);
const hx = (x - (sx * Astrometrics.SectorWidth) + 1);
const hy = (y - (sy * Astrometrics.SectorHeight) + 1);
return {sx:sx, sy:sy, hx:hx, hy:hy};
},
// Map-space: Cartesian coordinates, centered on Reference
sectorHexToMap: (sx, sy, hx, hy) => {
const world = Astrometrics.sectorHexToWorld(sx, sy, hx, hy);
return Astrometrics.worldToMap(world.x, world.y);
},
worldToMap: (wx, wy) => {
let x = wx;
let y = wy;
// Offset from the "corner" of the hex
x -= 0.5;
y -= ((wx % 2) !== 0) ? 0 : 0.5;
// Scale to non-homogenous coordinates
x *= Astrometrics.ParsecScaleX;
y *= -Astrometrics.ParsecScaleY;
// Drop precision (avoid animations, etc)
x = Math.round(x * 1000) / 1000;
y = Math.round(y * 1000) / 1000;
return {x, y};
},
mapToWorld: (x, y) => {
const wx = Math.round((x / Astrometrics.ParsecScaleX) + 0.5);
const wy = Math.round((-y / Astrometrics.ParsecScaleY) + ((wx % 2 === 0) ? 0.5 : 0));
return {x: wx, y: wy};
},
// World-space Coordinates (Reference is 0,0)
hexDistance: (ax, ay, bx, by) => {
function even(x) { return (x % 2) == 0; }
function odd (x) { return (x % 2) != 0; }
const dx = bx - ax;
const dy = by - ay;
let adx = Math.abs(dx);
let ody = dy + Math.floor(adx / 2);
if (even(ax) && odd(bx))
ody += 1;
return Math.max(adx - ody, ody, adx);
}
};
const Defaults = {
options:
MapOptions.SectorGrid | MapOptions.SubsectorGrid |
MapOptions.SectorsSelected |
MapOptions.BordersMajor | MapOptions.BordersMinor |
MapOptions.NamesMajor |
MapOptions.WorldsCapitals | MapOptions.WorldsHomeworlds,
scale: 2,
style: Styles.Poster
};
const styleLookup = (() => {
const sheets = {};
const base = {
overlay_color: '#8080ff',
route_color: '#048104',
main_s_color: 'pink',
main_m_color: '#FFCC00',
main_l_color: 'cyan',
main_opacity: 0.25,
ew_color: '#FFCC00',
you_are_here_url: 'res/ui/youarehere.svg'
};
sheets[Styles.Poster] = base;
sheets[Styles.Candy] = base;
sheets[Styles.Draft] = base;
sheets[Styles.Atlas] = Object.assign({}, base, {
overlay_color: '#808080',
you_are_here_url: 'res/ui/youarehere-gray.svg'
});
sheets[Styles.FASA] = sheets[Styles.Print] =
Object.assign({}, base, {
you_are_here_url: 'res/ui/youarehere-gray.svg'
});
return (style, property) => {
const sheet = sheets[style] || sheets[Defaults.style];
return sheet[property];
};
})();
// ======================================================================
// Data Services
// ======================================================================
const MapService = (() => {
async function service(url, contentType, method) {
const response = await fetch(url, {method: method || 'GET',
headers: {Accept: contentType}});
if (!response.ok)
throw new Error(response.statusText);
return (contentType === 'application/json') ?
await response.json() : await response.text();
}
function url(path, options) {
return Util.makeURL(SERVICE_BASE + path, options);
}
return {
makeURL: (path, options) => {
return url(path, options);
},
coordinates: (sector, hex, options) => {
options = Object.assign({}, options, {sector, hex});
return service(url('/api/coordinates', options),
options.accept || 'application/json');
},
credits: (worldX, worldY, options) => {
options = Object.assign({}, options, {x: worldX, y: worldY});
return service(url('/api/credits', options),
options.accept || 'application/json');
},
search: (query, options, method) => {
options = Object.assign({}, options, {q: query});
return service(url('/api/search', options),
options.accept || 'application/json', method);
},
sectorData: (sector, options) => {
options = Object.assign({}, options, {sector});
return service(url('/api/sec', options),
options.accept || 'text/plain');
},
sectorDataTabDelimited: (sector, options) => {
options = Object.assign({}, options, {sector, type: 'TabDelimited'});
return service(url('/api/sec', options),
options.accept || 'text/plain');
},
sectorMetaData: (sector, options) => {
options = Object.assign({}, options, {sector});
return service(url('/api/metadata', options),
options.accept || 'application/json');
},
MSEC: (sector, options) => {
options = Object.assign({}, options, {sector});
return service(url('/api/msec', options),
options.accept || 'text/plain');
},
universe: (options) => {
options = Object.assign({}, options);
return service(url('/api/universe', options),
options.accept || 'application/json');
}
};
})();
// ======================================================================
// Least-Recently-Used Cache
// ======================================================================
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.map = {};
this.queue = [];
}
ensureCapacity(capacity) {
if (this.capacity < capacity)
this.capacity = capacity;
}
clear() {
this.map = {};
this.queue = [];
}
fetch(key) {
key = '$' + key;
const value = this.map[key];
if (value === undefined)
return undefined;
const index = this.queue.indexOf(key);
if (index !== -1)
this.queue.splice(index, 1);
this.queue.push(key);
return value;
}
insert(key, value) {
key = '$' + key;
// Remove previous instances
const index = this.queue.indexOf(key);
if (index !== -1)
this.queue.splice(index, 1);
this.map[key] = value;
this.queue.push(key);
while (this.queue.length > this.capacity) {
key = this.queue.shift();
delete this.map[key];
}
}
}
// ======================================================================
// Image Stash
// ======================================================================
class ImageStash {
constructor() {
this.map = new Map();
}
get(url, callback) {
if (this.map.has(url))
return this.map.get(url);
this.map.set(url, undefined);
Util.fetchImage(url).then(img => {
this.map.set(url, img);
callback(img);
});
return undefined;
}
}
const stash = new ImageStash();
// ======================================================================
// Animation Utilities
// ======================================================================
function isCallable(o) {
return typeof o === 'function';
}
class Animation {
// dur = total duration (seconds)
// smooth = optional smoothing function
// set onanimate to function called with animation position (0.0 ... 1.0)
constructor(dur, smooth) {
const start = Date.now();
this.onanimate = null;
this.oncancel = null;
this.oncomplete = null;
const tickFunc = () => {
const f = (Date.now() - start) / 1000 / dur;
if (f < 1.0)
this.timerid = requestAnimationFrame(tickFunc);
let p = f;
if (isCallable(smooth))
p = smooth(p);
if (isCallable(this.onanimate))
this.onanimate(p);
if (f >= 1.0 && isCallable(this.oncomplete))
this.oncomplete();
};
this.timerid = requestAnimationFrame(tickFunc);
}
cancel() {
if (this.timerid) {
cancelAnimationFrame(this.timerid);
if (isCallable(this.oncancel))
this.oncancel();
}
}
}
Animation.interpolate = (a, b, p) => {
return a * (1.0 - p) + b * p;
};
// Time smoothing function - input time is t within duration dur.
// Acceleration period is a, deceleration period is d.
//
// Example: t_filtered = smooth( t, 1.0, 0.25, 0.25 );
//
// Reference: http://www.w3.org/TR/2005/REC-SMIL2-20050107/smil-timemanip.html
Animation.smooth = (t, dur, a, d) => {
const dacc = dur * a;
const ddec = dur * d;
const r = 1 / (1 - a / 2 - d / 2);
let r_t, tdec, pd;
if (t < dacc) {
r_t = r * (t / dacc);
return t * r_t / 2;
} else if (t <= (dur - ddec)) {
return r * (t - dacc / 2);
} else {
tdec = t - (dur - ddec);
pd = tdec / ddec;
return r * (dur - dacc / 2 - ddec + tdec * (2 - pd) / 2);
}
};
// ======================================================================
// Observable name/value map
// ======================================================================
class NamedOptions {
constructor(notify) {
this._options = {};
this._notify = notify;
}
keys() { return Object.keys(this._options); }
get(key) { return this._options[key]; }
set(key, value) { this._options[key] = value; this._notify(key); }
delete(key) { delete this._options[key]; this._notify(key); }
forEach(fn, thisArg) {
const keys = Object.keys(this._options);
for (let i = 0; i < keys.length; ++i) {
const k = keys[i];
fn.call(thisArg, this._options[k], k, i);
}
}
}
//----------------------------------------------------------------------
//
// Usage:
//
// let map = new Map( document.getElementById('YourMapDiv') );
//
// map.OnPositionChanged = () => { update permalink }
// map.OnScaleChanged = () => { update scale indicator }
// map.OnStyleChanged = () => { update control panel }
// map.OnOptionsChanged = () => { update control panel }
//
// map.OnHover = ( {x, y} ) => { show data }
// map.OnClick = ( {x, y} ) => { show data }
// map.OnDoubleClick = ( {x, y} ) => { show data }
//
// Read-Only:
// map.worldX
// map.worldY
//
// Read/Write:
// map.x
// map.y
// map.position ~= [map.x, map.y]
// map.scale
// map.style
// map.options
//
// map.namedOptions
// .keys()
// .get(k)
// .set(k, v)
// .delete(k)
// .forEach((value, key, index) => { ... });
//
// map.CenterAtSectorHex( sx, sy, hx, hy, {scale, immediate} );
// map.Scroll( dx, dy, fAnimate );
// map.ZoomIn();
// map.ZoomOut();
//
// map.ApplyURLParameters()
//
// map.SetRoute()
// map.AddMarker(id, x, y, opt_url); // should have CSS style for .marker#<id>
// map.AddOverlay({type:'rectangle', x, y, w, h}); // should have CSS style for .overlay
// map.AddOverlay({type:'circle', x, y, r}); // should have CSS style for .overlay
//
//----------------------------------------------------------------------
function fireEvent(target, event, data) {
if (typeof target['On' + event] !== 'function') return;
setTimeout(() => { target['On' + event](data); }, 0);
}
// ======================================================================
// Slippy Map using Tiles
// ======================================================================
function log2(v) { return Math.log(v) / Math.LN2; }
function pow2(v) { return Math.pow(2, v); }
function dist(x, y) { return Math.sqrt(x*x + y*y); }
const SINK_OFFSET = 1000;
const INT_OPTIONS = [
'routes', 'rifts', 'dimunofficial',
'sscoords', 'allhexes',
'dw', 'an', 'mh', 'po', 'im', 'cp', 'stellar'
];
const STRING_OPTIONS = [
'ew', 'qz', 'hw', 'milieu'
];
const ZOOM_DELTA = 0.5;
function roundScale(s) {
return Math.round(s / ZOOM_DELTA) * ZOOM_DELTA;
}
class TravellerMap {
constructor (container, boundingElement) {
this.container = container;
this.rect = boundingElement.getBoundingClientRect();
this.min_scale = -5;
this.max_scale = 10;
// Exposed via getters/setters
this._options = Defaults.options;
this._style = Defaults.style;
this._logScale = 1;
this._tx = 0;
this._ty = 0;
this.tilesize = 256;
this.cache = new LRUCache(64);
this.namedOptions = new NamedOptions(Util.debounce((key) => {
this.invalidate();
fireEvent(this, 'OptionsChanged', this.options);
}, 1));
this.namedOptions.NAMES = INT_OPTIONS.concat(STRING_OPTIONS);
this.loading = new Set();
this.defer_loading = true;
const CLICK_SCALE_DELTA = -0.5;
const SCROLL_SCALE_DELTA = -0.15;
const KEY_SCROLL_DELTA = 15;
container.style.position = 'relative';
// Event target, so it doesn't change during refreshes
const sink = document.createElement('div');
sink.style.position = 'absolute';
sink.style.left = sink.style.top = sink.style.right = sink.style.bottom = (-SINK_OFFSET) + 'px';
sink.style.zIndex = 1000;
container.appendChild(sink);
this.canvas = document.createElement('canvas');
this.canvas.style.position = 'absolute';
this.canvas.style.zIndex = 0;
container.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
this.markers = [];
this.overlays = [];
this.route = null;
this.main = null;
// ======================================================================
// Event Handlers
// ======================================================================
// ----------------------------------------------------------------------
// Mouse
// ----------------------------------------------------------------------
let dragging, drag_coords, was_dragged, previous_focus;
container.addEventListener('mousedown', event => {
if (event.button !== 0) return;
this.cancelAnimation();
previous_focus = document.activeElement;
container.focus();
dragging = true;
was_dragged = false;
drag_coords = this.eventCoords(event);
container.classList.add('dragging');
event.preventDefault();
event.stopPropagation();
}, true);
let hover_coords;
container.addEventListener('mousemove', event => {
const coords = this.eventCoords(event);
// Ignore mousemove immediately following mousedown with same coords.
if (dragging && coords.x === drag_coords.x && coords.y === drag_coords.y)
return;
if (dragging) {
was_dragged = true;
this._offset(drag_coords.x - coords.x, drag_coords.y - coords.y);
drag_coords = coords;
event.preventDefault();
event.stopPropagation();
}
const wc = this.eventToWorldCoords(event);
// Throttle the events
if (hover_coords && hover_coords.x === wc.x && hover_coords.y === wc.y)
return;
hover_coords = wc;
fireEvent(this, 'Hover', hover_coords);
}, true);
document.addEventListener('mouseup', event => {
if (event.button !== 0) return;
if (dragging) {
dragging = false;
container.classList.remove('dragging');
event.preventDefault();
event.stopPropagation();
}
});
container.addEventListener('click', event => {
event.preventDefault();
event.stopPropagation();
if (!was_dragged) {
fireEvent(this, 'Click',
Object.assign({}, this.eventToWorldCoords(event), {activeElement: previous_focus}));
}
});
container.addEventListener('dblclick', event => {
event.preventDefault();
event.stopPropagation();
this.cancelAnimation();
const MAX_DOUBLECLICK_SCALE = 9;
if (this._logScale < MAX_DOUBLECLICK_SCALE) {
let newscale = this._logScale + CLICK_SCALE_DELTA * (event.altKey ? 1 : -1);
newscale = Math.min(newscale, MAX_DOUBLECLICK_SCALE);
const coords = this.eventCoords(event);
this._setScale(newscale, coords.x, coords.y);
}
fireEvent(this, 'DoubleClick', this.eventToWorldCoords(event));
});
container.addEventListener('wheel', event => {
this.cancelAnimation();
const newscale = this._logScale + SCROLL_SCALE_DELTA * Math.sign(event.deltaY);
const coords = this.eventCoords(event);
this._setScale(newscale, coords.x, coords.y);
event.preventDefault();
event.stopPropagation();
});
// ----------------------------------------------------------------------
// Resize
// ----------------------------------------------------------------------
window.addEventListener('resize', () => {
// Timeout to work around iOS Safari giving incorrect sizes while 'resize'
// dispatched.
setTimeout(() => {
const rect = boundingElement.getBoundingClientRect();
if (rect.left === this.rect.left &&
rect.top === this.rect.top &&
rect.width === this.rect.width &&
rect.height === this.rect.height) return;
this.rect = rect;
this.resetCanvas();
}, 150);
});
// ----------------------------------------------------------------------
// Touch
// ----------------------------------------------------------------------
let pinch1, pinch2;
let touch_coords, touch_wx, touch_wc, was_touch_dragged;
container.addEventListener('touchmove', event => {
if (event.touches.length === 1) {
const coords = this.eventCoords(event.touches[0]);
if (touch_coords.x !== coords.x || touch_coords.y !== coords.y) {
was_touch_dragged = true;
this._offset(touch_coords.x - coords.x, touch_coords.y - coords.y);
touch_coords = coords;
touch_wc = this.eventToWorldCoords(event.touches[0]);
}
} else if (event.touches.length === 2) {
was_touch_dragged = true;
const od = dist(pinch2.x - pinch1.x, pinch2.y - pinch1.y),
ocx = (pinch1.x + pinch2.x) / 2,
ocy = (pinch1.y + pinch2.y) / 2;
pinch1 = this.eventCoords(event.touches[0]);
pinch2 = this.eventCoords(event.touches[1]);
const nd = dist(pinch2.x - pinch1.x, pinch2.y - pinch1.y),
ncx = (pinch1.x + pinch2.x) / 2,
ncy = (pinch1.y + pinch2.y) / 2;
this._offset(ocx - ncx, ocy - ncy);
const newscale = this._logScale + log2(nd / od);
this._setScale(newscale, ncx, ncy);
}
event.preventDefault();
event.stopPropagation();
}, true);
container.addEventListener('touchend', event => {
if (event.touches.length < 2) {
this.defer_loading = false;
this.invalidate();
}
if (event.touches.length === 1)
touch_coords = this.eventCoords(event.touches[0]);
if (event.touches.length === 0 && !was_touch_dragged) {
fireEvent(this, 'Click',
Object.assign({}, touch_wc, {activeElement: previous_focus}));
}
event.preventDefault();
event.stopPropagation();
}, true);
container.addEventListener('touchstart', event => {
was_touch_dragged = false;
previous_focus = document.activeElement;
if (event.touches.length === 1) {
touch_coords = this.eventCoords(event.touches[0]);
touch_wc = this.eventToWorldCoords(event.touches[0]);
} else if (event.touches.length === 2) {
this.defer_loading = true;
pinch1 = this.eventCoords(event.touches[0]);
pinch2 = this.eventCoords(event.touches[1]);
}
event.preventDefault();
event.stopPropagation();
}, true);
// ----------------------------------------------------------------------
// Keyboard
// ----------------------------------------------------------------------
// Scrolling - track key down/up state and scroll with RAF.
const key_state = {};
let keyscroll_timerid;
const keyScroll = () => {
let dx = 0, dy = 0;
if (key_state['ArrowUp'] || key_state['i'])
dy -= KEY_SCROLL_DELTA;
if (key_state['ArrowDown'] || key_state['k'])
dy += KEY_SCROLL_DELTA;
if (key_state['ArrowLeft'] || key_state['j'])
dx -= KEY_SCROLL_DELTA;
if (key_state['ArrowRight'] || key_state['l'])
dx += KEY_SCROLL_DELTA;
if (dx || dy) {
this.Scroll(dx, dy);
requestAnimationFrame(keyScroll);
} else {
keyscroll_timerid = 0;
}
};
container.addEventListener('keydown', event => {
if (event.ctrlKey || event.altKey || event.metaKey)
return;
key_state[event.key] = true;
if (!keyscroll_timerid)
keyscroll_timerid = requestAnimationFrame(keyScroll);
});
container.addEventListener('keyup', event => {
key_state[event.key] = false;
if (!keyscroll_timerid)
keyscroll_timerid = requestAnimationFrame(keyScroll);
});
container.addEventListener('keydown', event => {
if (event.ctrlKey || event.altKey || event.metaKey)
return;
switch (event.key) {
case '-': this.ZoomOut(); break;
case '=': this.ZoomIn(); break;
default: return;
}
event.preventDefault();
event.stopPropagation();
});
// Final initialization.
this.resetCanvas();
this.defer_loading = false;
this.invalidate();
if (window == window.top) // == for IE
container.focus();
}
// ======================================================================
// Internal Methods
// ======================================================================
_offset(dx, dy) {
this.position = [this.x + dx / this.scale, this.y - dy / this.scale];
}
_setScale(newscale, px, py) {
newscale = Math.max(Math.min(newscale, this.max_scale), this.min_scale);
if (newscale === this._logScale)
return;
const cw = this.rect.width,
ch = this.rect.height;
// Mathmagic to preserve hover coordinates
let hx, hy;
if (arguments.length >= 3) {
hx = (this.x + (px - cw / 2) / this.scale) / this.tilesize;
hy = (-this.y + (py - ch / 2) / this.scale) / this.tilesize;
}
this._logScale = newscale;
if (arguments.length >= 3) {