-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathoverlay.ts
More file actions
616 lines (525 loc) · 19.6 KB
/
overlay.ts
File metadata and controls
616 lines (525 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
import type {
ProfileOverlay,
ProfileOverlay_Create,
TileJSON
} from '../types.ts';
import { DrawToolMode } from '../stores/modules/draw.ts';
import type { FeatureCollection } from 'geojson';
import { bbox } from '@turf/bbox'
import type { LngLatBoundsLike, LayerSpecification, VectorTileSource, RasterTileSource, GeoJSONSource } from 'maplibre-gl'
import cotStyles from './utils/styles.ts'
import { std, stdurl } from '../std.js';
import { useMapStore } from '../stores/map.js';
import ProfileConfig from './profile.ts';
/**
* @class
*/
export default class Overlay {
_destroyed: boolean;
_internal: boolean;
_timer: ReturnType<typeof setInterval> | null;
_clickable: Array<{ id: string; type: string }>;
_error?: Error;
_loaded: boolean;
loading: boolean;
id: number;
name: string;
active: boolean;
username?: string;
frequency: number | null;
iconset: string | null;
created: string;
updated: string;
pos: number;
type: string;
opacity: number;
visible: boolean;
mode: string;
mode_id: string | null;
actions: ProfileOverlay["actions"];
url?: string;
styles: Array<LayerSpecification>;
token: string | null;
static async create(
body: ProfileOverlay | ProfileOverlay_Create,
opts: {
internal?: boolean;
skipSave?: boolean;
clickable?: Array<{ id: string; type: string }>;
before?: string;
skipLayers?: boolean;
} = {}
): Promise<Overlay> {
if (opts.skipSave !== true) {
let ov = await std('/api/profile/overlay', {
method: 'POST',
body
}) as ProfileOverlay;
if (ov.styles && ov.styles.length) {
for (const layer of ov.styles) {
const l = layer as LayerSpecification;
l.id = `${ov.id}-${l.id}`;
// @ts-expect-error Special case Background Layer type
l.source = String(ov.id);
}
}
ov = await std(`/api/profile/overlay/${ov.id}`, {
method: 'PATCH',
body: ov
}) as ProfileOverlay;
const overlay = new Overlay(ov, {
internal: opts.internal
});
await overlay.init(opts);
return overlay;
} else {
const overlay = new Overlay(body as ProfileOverlay, {
internal: opts.internal
});
await overlay.init(opts);
return overlay;
}
}
static async internal(
body: {
id: number;
type: string;
name: string;
styles?: Array<LayerSpecification>;
clickable?: Array<{ id: string; type: string }>;
}
): Promise<Overlay> {
const overlay = await Overlay.create({
...body,
visible: true,
opacity: 1,
username: 'internal',
url: '',
frequency: null,
iconset: null,
created: new Date().toISOString(),
updated: new Date().toISOString(),
token: undefined,
mode: 'internal',
mode_id: undefined,
styles: body.styles || [],
pos: 3,
}, {
skipSave: true,
clickable: body.clickable,
internal: true
});
return overlay;
}
static async load(id: number): Promise<Overlay> {
const remote = await std(`/api/profile/overlay/${id}`) as ProfileOverlay;
const ov = await Overlay.create(remote, {
skipSave: true
});
return ov;
}
constructor(
overlay: ProfileOverlay,
opts: {
internal?: boolean;
} = {}
) {
this._destroyed = false;
this._internal = opts.internal || false;
this._clickable = [];
this._loaded = false;
this.loading = false;
this.id = overlay.id;
this.name = overlay.name;
this.active = overlay.active;
this.username = overlay.username;
this.frequency = overlay.frequency;
this.iconset = overlay.iconset;
this.created = overlay.created;
this.updated = overlay.updated;
this.actions = overlay.actions || {
feature: []
};
this.pos = overlay.pos;
this.type = overlay.type;
this.opacity = overlay.opacity;
this.visible = overlay.visible;
this.mode = overlay.mode;
this.mode_id = overlay.mode_id || null;
this.url = overlay.url;
this.styles = overlay.styles as Array<LayerSpecification>;
this.token = overlay.token;
if (this.frequency) {
this._timer = setInterval(async () => {
const mapStore = useMapStore();
try {
mapStore.map.refreshTiles(String(this.id));
} catch (err) {
console.error('Error refreshing tiles for overlay', this.id, err);
}
}, this.frequency * 1000);
} else {
this._timer = null;
}
}
healthy(): boolean {
return !this._error;
}
hasBounds(): boolean {
const mapStore = useMapStore();
const source = mapStore.map.getSource(String(this.id))
if (!source) return false;
if (source.type === 'vector') {
return !!(source as VectorTileSource).bounds;
} else if (source.type === 'raster') {
return !!(source as RasterTileSource).bounds;
} else if (source.type === 'geojson') {
return true;
} else {
return false
}
}
async zoomTo(): Promise<void> {
const mapStore = useMapStore();
const source = mapStore.map.getSource(String(this.id))
if (!source) return;
if (source.type === 'vector') {
mapStore.map.fitBounds((source as VectorTileSource).bounds);
} else if (source.type === 'raster') {
mapStore.map.fitBounds((source as RasterTileSource).bounds);
} else if (source.type === 'geojson') {
const geojson = await (source as GeoJSONSource).getData();
mapStore.map.fitBounds(bbox(geojson) as LngLatBoundsLike);
}
}
async addLayers(before?: string): Promise<void> {
const mapStore = useMapStore();
// If init() failed to register the source (e.g. a /tiles fetch
// 404'd), skip layer registration. addLayer would otherwise throw
// "source ... not found" and break the rest of map setup.
if (this._error || !mapStore.map.getSource(String(this.id))) {
return;
}
for (const l of this.styles) {
if (before) {
mapStore.map.addLayer(l, before);
} else {
mapStore.map.addLayer(l)
}
}
// The above doesn't set vis/opacity initially - apply directly
// without round-tripping through update()/save() which would PATCH
// the server with unchanged values.
for (const l of this.styles) {
if (this.type === 'raster') {
mapStore.map.setPaintProperty(l.id, 'raster-opacity', Number(this.opacity));
}
mapStore.map.setLayoutProperty(l.id, 'visibility', this.visible ? 'visible' : 'none');
}
// Update attribution if this is a basemap
if (this.mode === 'basemap') {
await mapStore.updateAttribution();
}
for (const click of this._clickable) {
const hoverIds = new Set<string>();
mapStore.map.on('mouseenter', click.id, () => {
if (mapStore.draw.mode !== DrawToolMode.STATIC) return;
mapStore.map.getCanvas().style.cursor = 'pointer';
})
mapStore.map.on('mousemove', click.id, (e) => {
if (mapStore.draw.mode !== DrawToolMode.STATIC) return;
if (this.type === 'vector' && e.features) {
const newIds = e.features.map(f => String(f.id));
for (const id of hoverIds) {
if (newIds.includes(id)) continue;
mapStore.map.setFeatureState({
id: id,
source: String(this.id),
sourceLayer: 'out'
}, { hover: false });
hoverIds.delete(id);
}
for (const id of newIds) {
mapStore.map.setFeatureState({
id: id,
source: String(this.id),
sourceLayer: 'out'
}, { hover: true });
hoverIds.add(id);
}
}
});
mapStore.map.on('mouseleave', click.id, () => {
if (mapStore.draw.mode !== DrawToolMode.STATIC) return;
mapStore.map.getCanvas().style.cursor = '';
if (this.type === 'vector') {
for (const id of hoverIds) {
mapStore.map.setFeatureState({
id: id,
source: String(this.id),
sourceLayer: 'out'
}, { hover: false });
}
hoverIds.clear()
}
})
}
}
async init(opts: {
clickable?: Array<{ id: string; type: string }>;
before?: string;
skipLayers?: boolean;
} = {}) {
const mapStore = useMapStore();
if (this.type === 'raster' && this.url) {
const url = stdurl(this.url);
url.searchParams.set('token', localStorage.token);
// A failed /tiles lookup (network blip, expired token, deleted
// basemap upstream, etc.) must NOT abort map initialization or
// every other overlay disappears with it. Capture the error on
// the overlay so MenuOverlays.vue surfaces an "Issue" badge,
// and skip addSource so addLayers later no-ops cleanly.
try {
const tileJSON = await std(url.toString()) as TileJSON
if (!mapStore.map.getSource(String(this.id))) {
mapStore.map.addSource(String(this.id), {
...tileJSON,
type: 'raster',
});
}
} catch (err) {
this._error = err instanceof Error ? err : new Error(String(err));
console.error(`Failed to load raster tiles for overlay ${this.id} (${this.name}):`, err);
}
} else if (this.type === 'vector' && this.url) {
const url = stdurl(this.url);
url.searchParams.set('token', localStorage.token);
if (!mapStore.map.getSource(String(this.id))) {
// MapLibre resolves the vector TileJSON lazily on first tile
// request, so addSource itself does not throw on a bad URL.
// Still wrap defensively for parity with the raster branch.
try {
mapStore.map.addSource(String(this.id), {
type: 'vector',
url: String(url)
});
} catch (err) {
this._error = err instanceof Error ? err : new Error(String(err));
console.error(`Failed to add vector source for overlay ${this.id} (${this.name}):`, err);
}
}
} else if (this.type === 'geojson') {
if (!mapStore.map.getSource(String(this.id))) {
const data: FeatureCollection = { type: 'FeatureCollection', features: [] };
mapStore.map.addSource(String(this.id), {
type: 'geojson',
cluster: false,
data
})
}
}
const display_text = (await ProfileConfig.get('display_text'))?.value;
const display_icon_rotation = (await ProfileConfig.get('display_icon_rotation'))?.value;
let size = 8
if (display_text === 'Small') size = 4;
if (display_text === 'Large') size = 16;
if (!this.styles.length && this.type === 'raster') {
this.styles = [{
'id': String(this.id),
'type': 'raster',
'source': String(this.id)
}]
} else if (!this.styles.length && this.type === 'vector') {
this.styles = cotStyles(String(this.id), {
sourceLayer: 'out',
group: false,
icons: !!this.iconset,
labels: { size }
});
} else if (!this.styles.length && this.type === 'geojson') {
this.styles = cotStyles(String(this.id), {
group: this.mode !== "mission",
icons: true,
course: true,
rotateIcons: display_icon_rotation,
labels: { size }
});
} else if (!this.styles.length) {
this.styles = [];
}
if (this.iconset) {
mapStore.icons.addIconset(this.iconset).catch((err: unknown) => {
console.error('Error adding iconset', this.iconset, err);
});
}
if (this.type === 'vector' && this. mode !== 'basemap' && opts.clickable === undefined) {
opts.clickable = this.styles.map((l) => {
return { id: l.id, type: 'feat' };
});
} else if (this.type === 'geojson' && opts.clickable === undefined) {
opts.clickable = this.styles.map((l) => {
if (this.mode === 'mission') {
return { id: l.id, type: 'cot' };
} else {
return { id: l.id, type: this.id === -1 ? 'cot' : 'feat' };
}
});
}
if (!opts.clickable) {
opts.clickable = [];
}
this._clickable = opts.clickable;
if (!opts.skipLayers) {
await this.addLayers(opts.before);
}
this._loaded = true;
}
remove() {
const mapStore = useMapStore();
for (const l of this.styles) {
mapStore.map.removeLayer(String(l.id));
}
if (this.iconset) {
mapStore.icons.removeIconset(this.iconset).catch((err: unknown) => {
console.error('Error removing iconset', this.iconset, err);
});
}
if (mapStore.map.getStyle().sources[String(this.id)]) {
// Don't crash the map if it already removed
mapStore.map.removeSource(String(this.id));
}
}
async replace(
overlay: {
name?: string
active?: boolean;
username?: string
actions?: ProfileOverlay["actions"];
type?: string;
opacity?: number;
visible?: boolean;
mode?: string;
mode_id?: string;
url?: string;
token?: string;
styles?: Array<LayerSpecification>;
},
opts: {
before?: string;
} = {}
): Promise<void> {
this.remove();
const oldType = this.type;
if (overlay.name) this.name = overlay.name;
if (overlay.active !== undefined) this.active = overlay.active;
if (overlay.username) this.username = overlay.username;
if (overlay.actions) this.actions = overlay.actions || { feature: [] };
if (overlay.type) this.type = overlay.type;
if (this.type === 'raster' && oldType !== 'raster' && !overlay.styles) {
this.styles = [];
}
if (overlay.opacity !== undefined) this.opacity = overlay.opacity;
if (overlay.visible !== undefined) this.visible = overlay.visible;
if (overlay.mode) this.mode = overlay.mode;
if (overlay.mode_id) this.mode_id = overlay.mode_id || null;
if (overlay.url) this.url = overlay.url;
if (overlay.token) this.token = overlay.token;
if (overlay.styles) {
if (overlay.styles && overlay.styles.length) {
for (const layer of overlay.styles) {
const l = layer as LayerSpecification;
l.id = `${this.id}-${l.id}`;
// @ts-expect-error Special case Background Layer type
l.source = String(this.id);
}
}
this.styles = overlay.styles as Array<LayerSpecification>;
}
await this.init({
clickable: this._clickable,
before: opts.before
});
await this.save();
// Update attribution if this is a basemap
if (this.mode === 'basemap') {
const mapStore = useMapStore();
await mapStore.updateAttribution();
}
}
async delete(): Promise<void> {
this._destroyed = true;
const wasBasemap = this.mode === 'basemap';
if (this._timer) {
clearInterval(this._timer);
this._timer = null;
}
this.remove();
if (this._internal) return;
if (this.id) {
await std(`/api/profile/overlay?id=${this.id}`, {
method: 'DELETE'
});
}
// Update attribution if this was a basemap
if (wasBasemap) {
const mapStore = useMapStore();
await mapStore.updateAttribution();
}
}
async update(body: {
pos?: number;
visible?: boolean;
opacity?: number;
}): Promise<void> {
const mapStore = useMapStore();
let changed = false;
if (body.opacity !== undefined && body.opacity !== this.opacity) {
this.opacity = body.opacity;
for (const l of this.styles) {
if (this.type === 'raster') {
mapStore.map.setPaintProperty(l.id, 'raster-opacity', Number(this.opacity))
}
}
changed = true;
}
if (body.visible !== undefined && body.visible !== this.visible) {
this.visible = body.visible;
for (const l of this.styles) {
mapStore.map.setLayoutProperty(l.id, 'visibility', this.visible ? 'visible' : 'none');
}
changed = true;
}
// Update attribution if this is a basemap
if (this.mode === 'basemap') {
await mapStore.updateAttribution();
}
if (body.pos !== undefined && body.pos !== this.pos) {
this.pos = body.pos;
changed = true;
}
if (changed) {
await this.save();
}
}
async save(): Promise<void> {
if (this._destroyed) throw new Error('Cannot save a destroyed layer');
if (this._internal) return;
// We want to just use the default style every time for things like missions
// We only want to save the style on custom datasources
const dropStyles = ['mission', 'internal'].includes(this.mode);
await std(`/api/profile/overlay/${this.id}`, {
method: 'PATCH',
body: {
pos: this.pos,
name: this.name,
type: this.type,
active: this.active,
opacity: this.opacity,
mode_id: this.mode_id,
url: this.url,
visible: this.visible,
styles: dropStyles ? [] : this.styles
}
})
}
}