forked from SignalK/freeboard-sk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.facade.ts
More file actions
1409 lines (1298 loc) · 42.2 KB
/
Copy pathapp.facade.ts
File metadata and controls
1409 lines (1298 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
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
/** Application Information Service **
* perform version checking etc. here
* ************************************/
import { effect, inject, Injectable, isDevMode, signal } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { MatIconRegistry } from '@angular/material/icon';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Subject } from 'rxjs';
import { InfoService, IndexedDB, AppInfoDef } from './lib/services';
import { isTrackShown, toggleTrackSelection } from './lib/vessel-track';
import {
AlertDialog,
ConfirmDialog,
WelcomeDialog,
MessageBarComponent,
MsgBox
} from './lib/components/dialogs';
import { ErrorListDialog } from './lib/components/dialogs/errorlist-dialog';
import { Convert, SI_BASE_UNIT, TARGET_UNIT } from './lib/convert';
import { SignalKClient } from 'signalk-client-angular';
import { SKWorkerService } from './modules';
// Package version — single source of truth is package.json, bumped by `npm version`
import { version as PACKAGE_VERSION } from '../../package.json';
import {
Position,
ErrorList,
IAppConfig,
LineString,
SKServerUnitPrefs,
SKPathDisplayUnits,
TemperatureUnitDef,
DepthUnitDef,
SpeedUnitDef,
DistanceUnitDef,
LengthUnitDef
} from './types';
import {
defaultConfig,
validateConfig,
cleanConfig,
initData
} from './app.config';
import { WELCOME_MESSAGES } from './app.messages';
import { getSvgList } from './modules/icons';
import { HttpErrorResponse } from '@angular/common/http';
import { Extent } from 'ol/extent';
import { GeoUtils } from './lib/geoutils';
import { S57Service } from './modules/map/ol';
import {
LineStyleDash,
LineStyleDef
} from './modules/settings/components/linestyle-select.component';
/** Parent Window message */
interface ParentMessage {
settings?: {
autoNightMode?: boolean;
};
commands?: {
nightModeEnable?: boolean;
};
}
// App details
const FSK: AppInfoDef = {
id: 'freeboard',
name: 'Freeboard-SK',
description: `Signal K Chart Plotter.`,
version: PACKAGE_VERSION,
url: 'https://github.com/signalk/freeboard-sk',
logo: './assets/img/app_logo.png'
};
const SERVER_APPDATA_VERSION = '1.0.0';
// Development SK server host details
const DEV_SERVER = {
host: 'localhost', // host name || ip address
port: 3000, // port number
ssl: false
};
@Injectable({ providedIn: 'root' })
export class AppFacade extends InfoService {
// Signal K API version to use
public skApiVersion = 2;
/**Host server details */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public hostDef: any = {
name: undefined,
port: undefined,
ssl: false,
url: undefined,
params: {}
};
public readonly STANDARD_RESOURCES = [
'routes',
'waypoints',
'regions',
'notes',
'charts'
];
public readonly CUSTOM_RESOURCES = [
{
name: 'tracks',
description: 'Freeboard GPX track imports.',
featureKey: 'resourceTracks'
},
{
name: 'infolayers',
description: 'Freeboard map overlays.',
featureKey: 'infoLayers'
},
{
name: 'groups',
description: 'Freeboard resource groups.',
featureKey: 'resourceGroups'
}
];
public get IGNORE_RESOURCES() {
return this.STANDARD_RESOURCES.concat(
this.CUSTOM_RESOURCES.map((i) => i.name),
['buddies']
);
}
public serverConfig = {
unitPreferences: signal<SKServerUnitPrefs>(undefined),
// Per-path display-unit overrides keyed by Signal K path (server
// `meta.displayUnits`). Populated from path metadata; consumed by
// formatValueForDisplay() when a path is supplied.
pathDisplayUnits: signal<Record<string, SKPathDisplayUnits>>({})
};
// controls map zoom limits
public MAP_ZOOM_EXTENT = {
min: 2,
max: 28
};
private AudioContext =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
window.AudioContext || (window as any).webkitAudioContext;
public audio = { context: new AudioContext() };
public db: AppDB;
public watchingSKLogin: number; // watch interval timer
// signals
kioskMode = signal<boolean>(false); // kiosk mode flag
hasAuthToken = signal<boolean>(false); // auth token has been presented
isLoggedIn = signal<boolean>(false); // logged in to SK Server
instrumentPanelAvailable = signal<boolean>(true); // show instrument panel button
skAuthChange = signal<string | undefined>(undefined); // Signal K cookie change event
sIsFetching = signal<boolean>(false); // show progress for fetching data from server
sTrueMagChoice = signal<string>(''); // preferred path True / Magnetic
instrumentPanel = signal<{
open: boolean;
activate: boolean;
}>({
open: false,
activate: false
});
// non-persisted UIstate attributes
uiCtrl = signal<{
alertList: boolean; // display AlertList
autopilotConsole: boolean; // display AutopilotConsole
radarLayer: boolean; // display Radar map Layer
routeBuilder: boolean; // display BuildRoute
suppressContextMenu: boolean; // prevent display of context menu
forceNightMode: boolean; // force setting of night mode
}>({
alertList: false,
autopilotConsole: false,
radarLayer: false,
routeBuilder: false,
suppressContextMenu: false,
forceNightMode: false
});
// persisted UI configuration items
uiConfig = signal<{
mapNorthUp: boolean; // map North / Heading Up
mapMove: boolean; // move map mode
mapConstrainZoom: boolean; // constrain zoom to chart min/max
toolbarButtons: boolean; // show toolbar buttons (both left & right)
invertColor: boolean; // invert feature label text color (for dark backgrounds)
showCourseData: boolean; // show/hide course data
showAisTargets: boolean; // show/hide AIS targets
showNotes: boolean; // show/hide Notes
autoNightMode: boolean;
}>({
mapNorthUp: true,
mapMove: false,
mapConstrainZoom: false,
toolbarButtons: false,
invertColor: false,
showCourseData: true,
showAisTargets: true,
showNotes: true,
autoNightMode: false
});
// Signal K server feature flags
featureFlags = signal<{
anchorApi: boolean;
autopilotApi: boolean;
weatherApi: boolean;
radarApi: boolean;
notificationApi: boolean;
resourceGroups: boolean;
resourceTracks: boolean;
infoLayers: boolean;
buddyList: boolean;
tidalApi: boolean;
}>({
anchorApi: true, // default true until API is available
autopilotApi: false,
weatherApi: false,
radarApi: false,
notificationApi: false,
resourceGroups: false, // ability to store resource groups
resourceTracks: false, // ability to store track resources
infoLayers: false, // ability to store map information overlays
buddyList: false,
tidalApi: false
});
selfLines = signal<{ cog: LineStyleDef; heading: LineStyleDef }>({
cog: {
fill: { color: 'rgba(204, 12, 225, 0.7)' },
stroke: {
color: 'rgba(204, 12, 225, 0.7)',
width: 1,
lineDash: null
}
},
heading: {
fill: { color: 'rgba(221, 99, 0, 0.5)' },
stroke: {
color: 'rgba(221, 99, 0, 0.5)',
width: 4,
lineDash: null
}
}
});
selfTrail = signal<LineString>([]); // vessel trail from indexedDB
selfTrailFromServer = signal<LineString>([]); // vessel trail from server
mapExtent = signal<Extent>([]); // map viewport extent
mapViewTopCenter = signal<Position>([0, 0]); // top-centre of viewport (rotation-aware)
mapViewRightCenter = signal<Position>([0, 0]); // right-centre of viewport (rotation-aware)
mapViewRotation = signal<number>(0); // OL view rotation in radians (CCW positive)
// programmatic map move request (e.g. from a plotter extension). A new
// object reference each time so the consuming effect always reacts.
mapMoveRequest = signal<{ center: Position; zoom?: number } | null>(null);
protected signalk = inject(SignalKClient);
private worker = inject(SKWorkerService);
private dialog = inject(MatDialog);
private snackbar = inject(MatSnackBar);
private iconReg = inject(MatIconRegistry);
private dom = inject(DomSanitizer);
private s57 = inject(S57Service);
constructor() {
/** Initialise and apply defaults */
super(FSK);
this.config = defaultConfig();
this.data = initData();
this.suppressPersist = true; //suppress persisting of config until doPostConfigLoad() is complete
/** initialise IndexedDB and subscribe to events */
this.db = new AppDB();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.db.dbUpdate$.subscribe((res: { action: string; value: any }) => {
if (res.action) {
switch (res.action) {
case 'db_init':
if (res.value) {
if (this.config.vessels.trail) {
this.db.getTrail().then((t) => {
this.selfTrail.update(() => (t && t.value ? t.value : []));
});
}
}
break;
case 'trail_save':
if (!res.value) {
this.debug('app.trail.save.error', 'warn');
}
break;
}
}
});
/** Signal K server App config attributes */
this.signalk.setAppId(FSK.id); // server stored config appId
this.signalk.setAppVersion(SERVER_APPDATA_VERSION); // server stored app data version
/** Initialise IconRegistry */
this.initAppIcons();
/** sets hostDef, kiosk flag and persists token */
this.parseLaunchUrl();
/** test for launch within iframe */
this.instrumentPanelAvailable.update(() => this.isTopWindow());
if (!this.isTopWindow()) {
// listen for messages from parent
window.addEventListener('message', (event) => {
this.parseMessageFromParent(event);
});
}
/** check for internet connection */
this.testForInternet();
/** Load persisted configuration */
this.loadConfig();
this.parseLocalConfig();
// respond to signals
effect(() => {
this.uiConfig();
this.debug(`AppFacade.effect().uiConfig`, this.uiConfig());
this.config.ui = this.uiConfig();
this.saveConfigDebounced();
});
effect(() => {
this.alignUnitPrefs(this.serverConfig.unitPreferences());
});
}
/**
* Detemine whether InfoPanel is used to display resource details based
* on the device screen width.
*/
public useInfoPanel(): boolean {
const mediaQuery = window.matchMedia('(max-width: 760px)');
return (
!mediaQuery.matches &&
!this.instrumentPanel().open &&
this.config.display.preferInfoPanel
);
}
/**
* Retrieve unit preferences from the signal k server
* Sets serverConfig.unitPreferences signal
*/
public fetchUnitPrefsFromSKServer() {
this.signalk.get('/signalk/v1/unitpreferences/active').subscribe({
next: (res: SKServerUnitPrefs) => {
this.serverConfig.unitPreferences.set(res);
this.refreshPathDisplayUnits();
},
error: () => {
this.debug('No server unit preferences...using fallback!');
}
});
}
/**
* Paths whose per-path display-unit override (`meta.displayUnits`) Freeboard
* honors so they can display in a different unit than their category preset.
* Currently wind speed only (see issue #304): the true-wind path is the user's
* preferred TWS path.
*/
/**
* True-wind path used as the per-path display-unit cache key and lookup. Shared
* with display consumers (e.g. the vessel popover) so the key always matches.
*/
public twsDisplayUnitPath(): string {
return this.config.units.preferredPaths.tws ?? 'environment.wind.speedTrue';
}
private displayUnitPaths(): string[] {
return [this.twsDisplayUnitPath(), 'environment.wind.speedApparent'];
}
/**
* Refresh the per-path display-unit cache from the server. Only applied when
* the user has opted into server unit preferences; otherwise the cache is
* cleared so display falls back to the category preset.
*/
public refreshPathDisplayUnits() {
if (!this.config.units.useServerPrefs) {
this.serverConfig.pathDisplayUnits.set({});
return;
}
this.displayUnitPaths().forEach((path) => this.fetchPathDisplayUnits(path));
}
/**
* Fetch a path's per-path display-unit override (`meta.displayUnits`) from the
* server and cache it. Paths with no published override are left uncached and
* fall back to the category preset.
*/
public fetchPathDisplayUnits(path: string) {
const p = path.split('.').join('/');
this.signalk.get(`/signalk/v1/api/vessels/self/${p}/meta`).subscribe({
next: (meta: { displayUnits?: SKPathDisplayUnits }) => {
// Re-check useServerPrefs: it may have been turned off while this
// request was in flight (a stale response must not re-add an override).
if (
this.config.units.useServerPrefs &&
meta?.displayUnits?.targetUnit
) {
this.setPathDisplayUnits(path, meta.displayUnits);
} else {
this.clearPathDisplayUnits(path);
}
},
error: () => {
this.debug(`No display units for path: ${path}`);
this.clearPathDisplayUnits(path);
}
});
}
/**
* Process message from parent window to respond to configuration
* requests
* @param data MessageEvent data from parent
*/
parseMessageFromParent(event: MessageEvent<ParentMessage>) {
if (isDevMode() || event.origin === this.hostDef.url) {
this.debug('parseMessageFromParent()', event.origin, event.data);
const { settings, commands } = event.data;
if (!settings && !commands) {
this.debug('parseMessageFromParent() - invalid data!');
return;
}
if (typeof settings?.autoNightMode === 'boolean') {
// set auto night mode
this.config.display.nightMode = settings.autoNightMode;
this.uiConfig.update((current) => {
return Object.assign({}, current, {
autoNightMode: this.config.display.nightMode
});
});
}
if (typeof commands?.nightModeEnable === 'boolean') {
// force dimming the display
this.uiCtrl.update((current) => {
return Object.assign({}, current, {
forceNightMode: commands.nightModeEnable
});
});
}
} else {
// We don't trust the sender of this message?
this.debug('parseMessageFromParent() - untrusted origin!', event.origin);
return;
}
}
/** Parse, clean loaded config */
private parseLocalConfig() {
cleanConfig(this.config, this.hostDef.params);
this.s57.init(this.config.map.s57Options);
this.doPostConfigLoad();
}
// line dash style helpers
get lineDashMap() {
return new Map([
['none', 'none'],
['short', '2 2'],
['medium', '4 4'],
['long', '8 4'],
['alt', '8 4 2 4']
]);
}
// line dash style format helpers
formatLineDashArray(value: LineStyleDash): number[] | null {
return value === 'none'
? null
: Array.from(this.lineDashMap.get(value))
.filter((i) => i !== ' ')
.map((i) => Number(i));
}
/** Initialise and raise "settings$.load" event */
private doPostConfigLoad() {
// initialise signals
this.uiConfig.update(() => this.config.ui);
if (this.config.vessels.fixedLocationMode) {
this.data.vessels.self.position = [
...this.config.vessels.fixedPosition
] as Position;
this.data.vessels.showSelf = true;
this.config.map.center = [...this.config.vessels.fixedPosition];
}
this.selfLines.update((current) => {
const c = {
cog: {
fill: { color: this.config.vessels.selfLines.cog.color },
stroke: {
color: this.config.vessels.selfLines.cog.color,
width: this.config.vessels.selfLines.cog.weight,
lineDash: this.formatLineDashArray(
this.config.vessels.selfLines.cog.dash
)
}
},
heading: {
fill: { color: this.config.vessels.selfLines.heading.color },
stroke: {
color: this.config.vessels.selfLines.heading.color,
width: this.config.vessels.selfLines.heading.weight,
lineDash: this.formatLineDashArray(
this.config.vessels.selfLines.heading.dash
)
}
}
};
return c;
});
this.sTrueMagChoice.set(this.config.units.headingAttribute);
this.s57.setOptions(this.config.map.s57Options);
// emit settings$.ready
this.debug(`doPostConfigLoad(): emit config$.ready`);
this.emitConfigEvent('ready');
this.suppressPersist = false; // allow persisting of config.
}
/** Retrieve and apply saved config from server */
public async loadUserConfigfromServer(): Promise<boolean> {
return new Promise((resolve) => {
this.signalk.isLoggedIn().subscribe({
next: (r: boolean) => {
this.isLoggedIn.set(r);
if (r) {
this.debug(
'loadUserConfigfromServer(): Is authenticated. Fetching config from SK Server...'
);
this.signalk.appDataGet('/').subscribe({
next: (serverSettings: IAppConfig) => {
if (Object.keys(serverSettings).length === 0) {
resolve(false);
}
cleanConfig(serverSettings, this.hostDef.params);
if (validateConfig(serverSettings)) {
this.config = serverSettings;
this.doPostConfigLoad();
this.alignCustomResourcesPaths();
this.alignUnitPrefs(this.serverConfig.unitPreferences());
this.saveConfig();
}
resolve(true);
},
error: () => {
console.info(
'applicationData: Unable to retrieve settings from server!'
);
resolve(false);
}
});
} else {
this.debug(
'loadUserConfigfromServer(): Not authenticated to SK Server!'
);
return resolve(false);
}
},
error: () => {
this.isLoggedIn.set(false);
this.debug('loadUserConfigfromServer(): Error fetching loginStatus!');
resolve(false);
}
});
});
}
/**
* Returns the per-path display-unit override for a Signal K path, or undefined
* when the server has published none for it.
*/
public getPathDisplayUnits(path: string): SKPathDisplayUnits | undefined {
return this.serverConfig.pathDisplayUnits()[path];
}
/**
* Store the per-path display-unit override for a Signal K path (from the path's
* `meta.displayUnits`).
*/
public setPathDisplayUnits(path: string, displayUnits: SKPathDisplayUnits) {
this.serverConfig.pathDisplayUnits.update((m) => ({
...m,
[path]: displayUnits
}));
}
/**
* Remove the cached per-path display-unit override for a Signal K path, so it
* reverts to the category preset.
*/
public clearPathDisplayUnits(path: string) {
this.serverConfig.pathDisplayUnits.update((m) => {
if (!(path in m)) return m;
const next = { ...m };
delete next[path];
return next;
});
}
/**
* Align server unit prefernce settings with FB units config.
*/
public alignUnitPrefs(units: SKServerUnitPrefs) {
if (!this.config.units.useServerPrefs) return;
this.debug('Aligning Unit preferences from server:', units);
if (!units?.categories) {
this.debug('No Unit preferences available!');
return;
}
if (units.categories.speed) {
this.config.units.speed = ['kn', 'm/s', 'km/h', 'mph'].includes(
units.categories.speed.targetUnit
)
? (units.categories.speed.targetUnit as SpeedUnitDef)
: this.config.units.speed;
Convert.setSymbol(
units.categories.speed.targetUnit as TARGET_UNIT,
units.categories.speed.symbol
);
}
if (units.categories.temperature) {
this.config.units.temperature = ['C', 'F'].includes(
units.categories.temperature.targetUnit
)
? (units.categories.temperature.targetUnit as TemperatureUnitDef)
: this.config.units.temperature;
Convert.setSymbol(
units.categories.temperature.targetUnit as TARGET_UNIT,
units.categories.temperature.symbol
);
}
if (units.categories.distance) {
this.config.units.distance = ['kilometer', 'naut-mile'].includes(
units.categories.distance.targetUnit
)
? (units.categories.distance.targetUnit as DistanceUnitDef)
: this.config.units.distance;
Convert.setSymbol(
units.categories.distance.targetUnit as TARGET_UNIT,
units.categories.distance.symbol
);
}
if (units.categories.depth) {
this.config.units.depth = ['m', 'foot'].includes(
units.categories.depth.targetUnit
)
? (units.categories.depth.targetUnit as DepthUnitDef)
: this.config.units.depth;
Convert.setSymbol(
units.categories.depth.targetUnit as TARGET_UNIT,
units.categories.depth.symbol
);
}
if (units.categories.length) {
this.config.units.length = ['m', 'foot'].includes(
units.categories.length.targetUnit
)
? (units.categories.length.targetUnit as LengthUnitDef)
: this.config.units.length;
Convert.setSymbol(
units.categories.length.targetUnit as TARGET_UNIT,
units.categories.length.symbol
);
}
}
/** Initialises Material IconRegistry with custom icons */
private initAppIcons() {
getSvgList().forEach((s: { id: string; path: string }) => {
this.iconReg.addSvgIcon(
s.id,
this.dom.bypassSecurityTrustResourceUrl(s.path)
);
});
}
/** Parse window.location and set hostDef & kiosk flag*/
private parseLaunchUrl() {
// process url params
if (window.location.search) {
const p = window.location.search.slice(1).split('&');
p.forEach((i: string) => {
const a = i.split('=');
this.hostDef.params[a[0]] = a.length > 1 ? a[1] : null;
});
}
// host name
this.hostDef.name =
typeof this.hostDef.params?.host !== 'undefined'
? this.hostDef.params.host
: this.devMode && DEV_SERVER.host
? DEV_SERVER.host
: window.location.hostname;
this.hostDef.ssl =
window.location.protocol === 'https:' || (this.devMode && DEV_SERVER.ssl)
? true
: false;
this.hostDef.port =
typeof this.hostDef.params.port !== 'undefined'
? parseInt(this.hostDef.params.port)
: this.devMode && DEV_SERVER.port
? DEV_SERVER.port
: parseInt(window.location.port);
// if no port specified then set to 80 | 443
this.hostDef.port = isNaN(this.hostDef.port)
? this.hostDef.ssl
? 443
: 80
: this.hostDef.port;
this.hostDef.url = `${this.hostDef.ssl ? 'https:' : 'http:'}//${
this.hostDef.name
}:${this.hostDef.port}`;
// update kiosk flag
this.kioskMode.update(() => {
const k = typeof this.hostDef.params.kiosk !== 'undefined' ? true : false;
return k;
});
//** persist token from url params
if (typeof this.hostDef.params.token !== 'undefined') {
this.persistToken(this.hostDef.params.token);
}
this.debug('host:', this.hostDef);
}
/** Test for / Warn if no Internet connection */
private testForInternet() {
window
.fetch('https://tile.openstreetmap.org')
.then(() => {
console.info('Internet connection detected.');
})
.catch(() => {
console.warn('No Internet connection detected!');
const mapsel = this.config.selections.charts;
if (mapsel.includes('openstreetmap') || mapsel.includes('openseamap')) {
if (!this.kioskMode()) {
this.showAlert(
'Internet Map Service Unavailable: ',
`Unable to display Open Street / Sea Maps!\n
Please check your Internet connection or select maps from the local network.\n
`
);
}
}
});
}
/** returns true if not embedded (is top window)*/
public isTopWindow(): boolean {
try {
return window.self === window.top;
} catch (e) {
return false;
}
}
/** persist auth token for session */
persistToken(value: string) {
if (value) {
this.signalk.authToken = value;
this.worker.postMessage({
cmd: 'auth',
options: {
token: value
}
});
document.cookie = `sktoken=${value}; SameSite=Strict`;
this.hasAuthToken.set(true); // hide login menu item
} else {
this.hasAuthToken.set(false); // show login menu item
this.signalk.authToken = null;
this.isLoggedIn.set(false);
document.cookie = `sktoken=${null}; SameSite=Strict; max-age=0;`;
this.worker.postMessage({
cmd: 'auth',
options: {
token: null
}
});
}
}
/** Start watching for change in skLoginInfo cookie */
watchSKLogin() {
if (this.watchingSKLogin) return;
this.watchingSKLogin = window.setInterval(
(() => {
let lastCookie = this.getCookie(document.cookie, 'skLoginInfo');
return () => {
const currentCookie = this.getCookie(document.cookie, 'skLoginInfo');
this.skAuthChange.set(currentCookie);
};
})(),
2000
);
}
/** return FB auth token for session */
getFBToken(): string {
return this.getCookie(document.cookie, 'sktoken');
}
/** return the requested cookie */
private getCookie(cookies: string, sel: 'sktoken' | 'skLoginInfo') {
if (!cookies) {
return undefined;
}
const tk = new Map();
cookies.split(';').forEach((i) => {
const c = i.trim().split('=');
tk.set(c[0], c[1]);
});
if (tk.has(sel)) {
return tk.get(sel);
} else {
return undefined;
}
}
/** return True / Magenetic preference */
get useMagnetic(): boolean {
return this.config.units.headingAttribute === 'navigation.headingMagnetic'
? true
: false;
}
/** add point to self vessel track */
addToSelfTrail(pt: Position) {
this.selfTrail.update((current) => {
if (current.length === 0) {
return current;
}
const lastPoint = current.slice(-1)[0];
if (pt[0] === lastPoint[0] && pt[1] === lastPoint[1]) {
return current;
}
const st = [].concat(current);
st.push(pt);
return st;
});
}
/** Whether the AIS vessel's individual track is displayed (session-only) */
isVesselTrackShown(id: string): boolean {
return isTrackShown(this.data.vessels.showTrack, id);
}
/** Toggle display of an AIS vessel's individual track on the map (session-only) */
toggleVesselTrack(id: string) {
this.data.vessels.showTrack = toggleTrackSelection(
this.data.vessels.showTrack,
id
);
}
/** Calculate the position to center the map.
* Tales into account the amount of offset to apply
*/
calcMapCenter(): Position {
const cog =
this.data.vessels.active.cogTrue ?? this.data.vessels.active.headingTrue;
if (cog === null) {
return this.data.vessels.active.position;
}
// Compute the geodetic distance from the viewport centre to the screen
// edge in the exact CoG direction. This correctly handles any map rotation
// mode (north-up or heading-up) and any screen aspect ratio.
//
// In OL, a CW bearing β has projected-space direction (sin β, cos β).
// With OL view rotation rot (CCW), the screen-space components are:
// sx = sin(β + rot) (rightward) sy = cos(β + rot) (upward)
// The edge of the viewport rectangle lies at min(hw/|sx|, hh/|sy|)
// where hw = geodetic half-width, hh = geodetic half-height.
const hh = GeoUtils.distanceTo(
this.config.map.center as Position,
this.mapViewTopCenter()
);
const hw = GeoUtils.distanceTo(
this.config.map.center as Position,
this.mapViewRightCenter()
);
const rot = this.mapViewRotation();
const sx = Math.abs(Math.sin(cog + rot));
const sy = Math.abs(Math.cos(cog + rot));
const edgeDistance = Math.min(
sx > 1e-10 ? hw / sx : Infinity,
sy > 1e-10 ? hh / sy : Infinity
);
const offsetDistance = edgeDistance * (this.config.map.centerOffset ?? 0.5);
return GeoUtils.destCoordinate(
this.data.vessels.active.position,
cog,
offsetDistance
);
}
/**
* @description Align selected custom resource paths with those enabled on the server.
*/
alignCustomResourcesPaths() {
this.signalk.api
.get(this.skApiVersion, '/resources')
.subscribe((res: { [key: string]: { description: string } }) => {
const paths = Object.keys(res).filter(
(i) => !this.IGNORE_RESOURCES.includes(i)
);
this.config.resources.paths = this.config.resources.paths.filter((k) =>
paths.includes(k)
);
});
}
/** overloaded saveConfig() */
override saveConfig() {
super.saveConfig();
if (this.isLoggedIn()) {
this.signalk.appDataSet('/', this.config).subscribe({
next: () => this.debug('saveConfig: config saved to server.'),
error: () => this.debug('saveConfig: Cannot save config to server!')
});
}
}
private saveCfgTimer: ReturnType<typeof setTimeout>;
/** Debounced saveConfig — collapses a flurry of saves (e.g. repeated map
* pans or rapid UI toggles) into a single localStorage write + server PUT. */
saveConfigDebounced(ms = 1000) {
clearTimeout(this.saveCfgTimer);
this.saveCfgTimer = setTimeout(() => this.saveConfig(), ms);
}
/** show Help at specified anchor */
showHelp(anchor?: string) {
const url = `./assets/help/index.html${anchor ? '#' + anchor : ''}`;
window.open(url, 'help');
}
/** display Welcome dialog */
showWelcome(suppressFirstRun: boolean) {
let btnText = 'Get Started';
const messages = [];
let showPrefs = false;
if (
!this.kioskMode() &&
['first_run', 'major', 'minor'].includes(this.launchStatus.result)
) {
if (this.launchStatus.result === 'first_run' && !suppressFirstRun) {
messages.push(WELCOME_MESSAGES['welcome']);
if (this.data.server && this.data.server.id) {
messages.push(WELCOME_MESSAGES[this.data.server.id]);
showPrefs = true;
}
} else {
if (
WELCOME_MESSAGES['whats-new'] &&
WELCOME_MESSAGES['whats-new'].length > 0