-
Notifications
You must be signed in to change notification settings - Fork 353
/
Terria.ts
2231 lines (2023 loc) · 71.5 KB
/
Terria.ts
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
import i18next from "i18next";
import { action, computed, observable, runInAction, toJS, when } from "mobx";
import { createTransformer } from "mobx-utils";
import buildModuleUrl from "terriajs-cesium/Source/Core/buildModuleUrl";
import Clock from "terriajs-cesium/Source/Core/Clock";
import defaultValue from "terriajs-cesium/Source/Core/defaultValue";
import defined from "terriajs-cesium/Source/Core/defined";
import DeveloperError from "terriajs-cesium/Source/Core/DeveloperError";
import CesiumEvent from "terriajs-cesium/Source/Core/Event";
import queryToObject from "terriajs-cesium/Source/Core/queryToObject";
import RequestScheduler from "terriajs-cesium/Source/Core/RequestScheduler";
import RuntimeError from "terriajs-cesium/Source/Core/RuntimeError";
import TerrainProvider from "terriajs-cesium/Source/Core/TerrainProvider";
import Entity from "terriajs-cesium/Source/DataSources/Entity";
import SplitDirection from "terriajs-cesium/Source/Scene/SplitDirection";
import URI from "urijs";
import {
Category,
LaunchAction,
DataSourceAction
} from "../Core/AnalyticEvents/analyticEvents";
import AsyncLoader from "../Core/AsyncLoader";
import Class from "../Core/Class";
import ConsoleAnalytics from "../Core/ConsoleAnalytics";
import CorsProxy from "../Core/CorsProxy";
import ensureSuffix from "../Core/ensureSuffix";
import filterOutUndefined from "../Core/filterOutUndefined";
import getDereferencedIfExists from "../Core/getDereferencedIfExists";
import getPath from "../Core/getPath";
import GoogleAnalytics from "../Core/GoogleAnalytics";
import hashEntity from "../Core/hashEntity";
import instanceOf from "../Core/instanceOf";
import isDefined from "../Core/isDefined";
import {
isJsonBoolean,
isJsonNumber,
isJsonObject,
isJsonString,
JsonArray,
JsonObject
} from "../Core/Json";
import { isLatLonHeight } from "../Core/LatLonHeight";
import loadJson from "../Core/loadJson";
import loadJson5 from "../Core/loadJson5";
import Result from "../Core/Result";
import ServerConfig from "../Core/ServerConfig";
import TerriaError, {
TerriaErrorOverrides,
TerriaErrorSeverity
} from "../Core/TerriaError";
import { Complete } from "../Core/TypeModifiers";
import { getUriWithoutPath } from "../Core/uriHelpers";
import PickedFeatures, {
featureBelongsToCatalogItem,
isProviderCoordsMap
} from "../Map/PickedFeatures/PickedFeatures";
import CatalogMemberMixin, { getName } from "../ModelMixins/CatalogMemberMixin";
import GroupMixin from "../ModelMixins/GroupMixin";
import MappableMixin, { isDataSource } from "../ModelMixins/MappableMixin";
import ReferenceMixin from "../ModelMixins/ReferenceMixin";
import TimeVarying from "../ModelMixins/TimeVarying";
import { HelpContentItem } from "../ReactViewModels/defaultHelpContent";
import { defaultTerms, Term } from "../ReactViewModels/defaultTerms";
import NotificationState from "../ReactViewModels/NotificationState";
import { ICredit } from "../ReactViews/Credits";
import { SHARE_VERSION } from "../ReactViews/Map/Panels/SharePanel/BuildShareLink";
import { shareConvertNotification } from "../ReactViews/Notification/shareConvertNotification";
import MappableTraits from "../Traits/TraitsClasses/MappableTraits";
import MapNavigationModel from "../ViewModels/MapNavigation/MapNavigationModel";
import TerriaViewer from "../ViewModels/TerriaViewer";
import { BaseMapsModel } from "./BaseMaps/BaseMapsModel";
import CameraView from "./CameraView";
import Catalog from "./Catalog/Catalog";
import CatalogGroup from "./Catalog/CatalogGroup";
import CatalogMemberFactory from "./Catalog/CatalogMemberFactory";
import MagdaReference, {
MagdaReferenceHeaders
} from "./Catalog/CatalogReferences/MagdaReference";
import SplitItemReference from "./Catalog/CatalogReferences/SplitItemReference";
import CommonStrata from "./Definition/CommonStrata";
import hasTraits from "./Definition/hasTraits";
import { BaseModel } from "./Definition/Model";
import updateModelFromJson from "./Definition/updateModelFromJson";
import upsertModelFromJson from "./Definition/upsertModelFromJson";
import {
ErrorServiceOptions,
ErrorServiceProvider,
initializeErrorServiceProvider
} from "./ErrorServiceProviders/ErrorService";
import StubErrorServiceProvider from "./ErrorServiceProviders/StubErrorServiceProvider";
import TerriaFeature from "./Feature/Feature";
import GlobeOrMap from "./GlobeOrMap";
import IElementConfig from "./IElementConfig";
import InitSource, {
InitSourceData,
InitSourceFromData,
isInitFromData,
isInitFromDataPromise,
isInitFromOptions,
isInitFromUrl,
ShareInitSourceData,
StoryData
} from "./InitSource";
import Internationalization, {
I18nStartOptions,
LanguageConfiguration
} from "./Internationalization";
import MapInteractionMode from "./MapInteractionMode";
import NoViewer from "./NoViewer";
import { defaultRelatedMaps, RelatedMap } from "./RelatedMaps";
import CatalogIndex from "./SearchProviders/CatalogIndex";
import ShareDataService from "./ShareDataService";
import { StoryVideoSettings } from "./StoryVideoSettings";
import TimelineStack from "./TimelineStack";
import { isViewerMode, setViewerMode } from "./ViewerMode";
import Workbench from "./Workbench";
import SelectableDimensionWorkflow from "./Workflows/SelectableDimensionWorkflow";
// import overrides from "../Overrides/defaults.jsx";
interface ConfigParameters {
/**
* TerriaJS uses this name whenever it needs to display the name of the application.
*/
appName?: string;
/**
* The email address shown when things go wrong.
*/
supportEmail?: string;
/**
* The maximum number of "feature info" boxes that can be displayed when clicking a point.
*/
defaultMaximumShownFeatureInfos: number;
/**
* URL of the JSON file that contains index of catalog.
*/
catalogIndexUrl?: string;
/**
* **Deprecated** - please use regionMappingDefinitionsUrls array instead. If this is defined, it will override `regionMappingDefinitionsUrls`
*/
regionMappingDefinitionsUrl?: string | undefined;
/**
* URLs of the JSON file that defines region mapping for CSV files. First matching region will be used (in array order)
*/
regionMappingDefinitionsUrls: string[];
/**
* URL of Proj4 projection lookup service (part of TerriaJS-Server).
*/
proj4ServiceBaseUrl?: string;
/**
* URL of CORS proxy service (part of TerriaJS-Server)
*/
corsProxyBaseUrl?: string;
/**
* @deprecated
*/
proxyableDomainsUrl?: string;
serverConfigUrl?: string;
shareUrl?: string;
/**
* URL of the service used to send feedback. If not specified, the "Give Feedback" button will not appear.
*/
feedbackUrl?: string;
/**
* An array of base paths to use to try to use to resolve init fragments in the URL. For example, if this property is `[ "init/", "http://example.com/init/"]`, then a URL with `#test` will first try to load `init/test.json` and, if that fails, next try to load `http://example.com/init/test.json`.
*/
initFragmentPaths: string[];
/**
* Whether the story is enabled. If false story function button won't be available.
*/
storyEnabled: boolean;
/**
* True (the default) to intercept the browser's print feature and use a custom one accessible through the Share panel.
*/
interceptBrowserPrint?: boolean;
/**
* True to create a separate explorer panel tab for each top-level catalog group to list its items in.
*/
tabbedCatalog?: boolean;
/**
* True to use Cesium World Terrain from Cesium ion. False to use terrain from the URL specified with the `"cesiumTerrainUrl"` property. If this property is false and `"cesiumTerrainUrl"` is not specified, the 3D view will use a smooth ellipsoid instead of a terrain surface. Defaults to true.
*/
useCesiumIonTerrain?: boolean;
/**
* The URL to use for Cesium terrain in the 3D Terrain viewer, in quantized mesh format. This property is ignored if "useCesiumIonTerrain" is set to true.
*/
cesiumTerrainUrl?: string;
/**
* The Cesium Ion Asset ID to use for Cesium terrain in the 3D Terrain viewer. `cesiumIonAccessToken` will be used to authenticate. This property is ignored if "useCesiumIonTerrain" is set to true.
*/
cesiumTerrainAssetId?: number;
/**
* The access token to use with Cesium ion. If `"useCesiumIonTerrain"` is true and this property is not specified, the Cesium default Ion key will be used. It is a violation of the Ion terms of use to use the default key in a deployed application.
*/
cesiumIonAccessToken?: string;
/**
* True to use Bing Maps from Cesium ion (Cesium World Imagery). By default, Ion will be used, unless the `bingMapsKey` property is specified, in which case that will be used instead. To disable the Bing Maps layers entirely, set this property to false and set `bingMapsKey` to null.
*/
useCesiumIonBingImagery?: boolean;
/**
* A [Bing Maps API key](https://msdn.microsoft.com/en-us/library/ff428642.aspx) used for requesting Bing Maps base maps and using the Bing Maps geocoder for searching. It is your responsibility to request a key and comply with all terms and conditions.
*/
bingMapsKey?: string;
hideTerriaLogo?: boolean;
/**
* An array of strings of HTML that fill up the top left logo space (see `brandBarSmallElements` or `displayOneBrand` for small screens).
*/
brandBarElements?: string[];
/**
* An array of strings of HTML that fill up the top left logo space - used for small screens.
*/
brandBarSmallElements?: string[];
/**
* Index of which `brandBarElements` to show for mobile header. This will be used if `this.brandBarSmallElements` is undefined.
*/
displayOneBrand?: number;
/**
* True to disable the "Centre map at your current location" button.
*/
disableMyLocation?: boolean;
disableSplitter?: boolean;
disablePedestrianMode?: boolean;
experimentalFeatures?: boolean;
magdaReferenceHeaders?: MagdaReferenceHeaders;
locationSearchBoundingBox?: number[];
/**
* A Google API key for [Google Analytics](https://analytics.google.com). If specified, TerriaJS will send various events about how it's used to Google Analytics.
*/
googleAnalyticsKey?: string;
/**
* Error service provider configuration.
*/
errorService?: ErrorServiceOptions;
globalDisclaimer?: any;
/**
* True to display welcome message on startup.
*/
showWelcomeMessage?: boolean;
// TODO: make themeing TS
/** Theme overrides, this is applied in StandardUserInterface and merged in order of highest priority:
* `StandardUserInterface.jsx` `themeOverrides` prop -> `theme` config parameter (this object) -> default `terriaTheme` (see `StandardTheme.jsx`)
*/
theme?: any;
/**
* Video to show in welcome message.
*/
welcomeMessageVideo?: any;
/**
* Video to show in Story Builder.
*/
storyVideo?: StoryVideoSettings;
/**
* True to display in-app guides.
*/
showInAppGuides?: boolean;
/**
* The content to be displayed in the help panel.
*/
helpContent?: HelpContentItem[];
helpContentTerms?: Term[];
/**
*
*/
languageConfiguration?: LanguageConfiguration;
/**
* Custom concurrent request limits for domains in Cesium's RequestScheduler. Cesium's default is 6 per domain (the maximum allowed by browsers unless the server supports http2). For servers supporting http2 try 12-24 to have more parallel requests. Setting this too high will undermine Cesium's prioritised request scheduling and important data may load slower. Format is {"domain_without_protocol:port": number}.
*/
customRequestSchedulerLimits?: Record<string, number>;
/**
* Whether to load persisted viewer mode from local storage.
*/
persistViewerMode?: boolean;
/**
* Whether to open the add data explorer panel on load.
*/
openAddData?: boolean;
/**
* Text showing at the top of feedback form.
*/
feedbackPreamble?: string;
/**
* Text showing at the bottom of feedback form.
*/
feedbackPostamble?: string;
/**
* Minimum length of feedback comment.
*/
feedbackMinLength?: number;
/** If undefined, then Leaflet's default attribution will be used */
leafletAttributionPrefix?: string;
/**
* Extra links to show in the credit line at the bottom of the map (currently only the Cesium map).
*/
extraCreditLinks?: ICredit[];
/**
* Configurable discalimer that shows up in print view
*/
printDisclaimer?: { url: string; text: string };
/**
* Prefix to which `:story-id` is added to fetch JSON for stories when using /story/:story-id routes. Should end in /
*/
storyRouteUrlPrefix?: string;
/**
* For Console Analytics
*/
enableConsoleAnalytics?: boolean;
/**
* Options for Google Analytics
*/
googleAnalyticsOptions?: unknown;
relatedMaps?: RelatedMap[];
/**
* Optional plugin configuration
*/
plugins?: Record<string, any>;
aboutButtonHrefUrl?: string | null;
}
interface StartOptions {
configUrl: string;
configUrlHeaders?: {
[key: string]: string;
};
applicationUrl?: Location;
shareDataService?: ShareDataService;
/**
* i18nOptions is explicitly a separate option from `languageConfiguration`,
* as `languageConfiguration` can be serialised, but `i18nOptions` may have
* some functions that are passed in from a TerriaMap
* */
i18nOptions?: I18nStartOptions;
/**
* Hook to run before restoring app state from the share URL. This is for
* example used in terriamap/index.js for loading plugins before restoring
* app state.
*/
beforeRestoreAppState?: () => Promise<void> | void;
}
interface Analytics {
start: (
configParameters: Partial<{
enableConsoleAnalytics: boolean;
googleAnalyticsKey: any;
googleAnalyticsOptions: any;
}>
) => void;
logEvent: (
category: string,
action: string,
label?: string,
value?: string
) => void;
}
interface TerriaOptions {
/**
* Override detecting base href from document.baseURI.
* Used in specs to support routes within Karma spec automation framework
*/
appBaseHref?: string;
/**
* Base url where TerriaJS resources can be found.
* Normally "build/TerriaJS/" in any TerriaMap and "./" in specs
*/
baseUrl?: string;
/**
* Base url where Cesium static resources can be found.
*/
cesiumBaseUrl?: string;
analytics?: Analytics;
}
interface HomeCameraInit {
[key: string]: HomeCameraInit[keyof HomeCameraInit];
north: number;
east: number;
south: number;
west: number;
}
export default class Terria {
private readonly models = observable.map<string, BaseModel>();
/** Map from share key -> id */
readonly shareKeysMap = observable.map<string, string>();
/** Map from id -> share keys */
readonly modelIdShareKeysMap = observable.map<string, string[]>();
/** Base URL for the Terria app. Used for SPA routes */
readonly appBaseHref: string =
typeof document !== "undefined" ? document.baseURI : "/";
/** Base URL to Terria resources */
readonly baseUrl: string = "build/TerriaJS/";
/**
* Base URL used by Cesium to link to images and other static assets.
* This can be customized by passing `options.cesiumBaseUrl`
* Default value is constructed relative to `Terria.baseUrl`.
*/
readonly cesiumBaseUrl: string;
readonly tileLoadProgressEvent = new CesiumEvent();
readonly indeterminateTileLoadProgressEvent = new CesiumEvent();
readonly workbench = new Workbench();
readonly overlays = new Workbench();
readonly catalog = new Catalog(this);
readonly baseMapsModel = new BaseMapsModel("basemaps", this);
readonly timelineClock = new Clock({ shouldAnimate: false });
// readonly overrides: any = overrides; // TODO: add options.functionOverrides like in master
catalogIndex: CatalogIndex | undefined;
readonly elements = observable.map<string, IElementConfig>();
@observable
readonly mainViewer = new TerriaViewer(
this,
computed(() =>
filterOutUndefined(
this.overlays.items
.map((item) => (MappableMixin.isMixedInto(item) ? item : undefined))
.concat(
this.workbench.items.map((item) =>
MappableMixin.isMixedInto(item) ? item : undefined
)
)
)
)
);
appName: string = "TerriaJS App";
supportEmail: string = "info@terria.io";
/**
* Gets or sets the {@link this.corsProxy} used to determine if a URL needs to be proxied and to proxy it if necessary.
* @type {CorsProxy}
*/
corsProxy: CorsProxy = new CorsProxy();
/**
* Gets or sets the instance to which to report Google Analytics-style log events.
* If a global `ga` function is defined, this defaults to `GoogleAnalytics`. Otherwise, it defaults
* to `ConsoleAnalytics`.
*/
readonly analytics: Analytics | undefined;
/**
* Gets the stack of layers active on the timeline.
*/
readonly timelineStack = new TimelineStack(this, this.timelineClock);
@observable
readonly configParameters: Complete<ConfigParameters> = {
appName: "TerriaJS App",
supportEmail: "info@terria.io",
defaultMaximumShownFeatureInfos: 100,
catalogIndexUrl: undefined,
regionMappingDefinitionsUrl: undefined,
regionMappingDefinitionsUrls: ["build/TerriaJS/data/regionMapping.json"],
proj4ServiceBaseUrl: "proj4def/",
corsProxyBaseUrl: "proxy/",
proxyableDomainsUrl: "proxyabledomains/", // deprecated, will be determined from serverconfig
serverConfigUrl: "serverconfig/",
shareUrl: "share",
feedbackUrl: undefined,
initFragmentPaths: ["init/"],
storyEnabled: true,
interceptBrowserPrint: true,
tabbedCatalog: false,
useCesiumIonTerrain: true,
cesiumTerrainUrl: undefined,
cesiumTerrainAssetId: undefined,
cesiumIonAccessToken: undefined,
useCesiumIonBingImagery: undefined,
bingMapsKey: undefined,
hideTerriaLogo: false,
brandBarElements: undefined,
brandBarSmallElements: undefined,
displayOneBrand: 0,
disableMyLocation: undefined,
disableSplitter: undefined,
disablePedestrianMode: false,
experimentalFeatures: undefined,
magdaReferenceHeaders: undefined,
locationSearchBoundingBox: undefined,
googleAnalyticsKey: undefined,
errorService: undefined,
globalDisclaimer: undefined,
theme: {},
showWelcomeMessage: false,
welcomeMessageVideo: {
videoTitle: "Getting started with the map",
videoUrl: "https://www.youtube-nocookie.com/embed/FjSxaviSLhc",
placeholderImage:
"https://img.youtube.com/vi/FjSxaviSLhc/maxresdefault.jpg"
},
storyVideo: {
videoUrl: "https://www.youtube-nocookie.com/embed/fbiQawV8IYY"
},
showInAppGuides: false,
helpContent: [],
helpContentTerms: defaultTerms,
languageConfiguration: undefined,
customRequestSchedulerLimits: undefined,
persistViewerMode: true,
openAddData: false,
feedbackPreamble: "translate#feedback.feedbackPreamble",
feedbackPostamble: undefined,
feedbackMinLength: 0,
leafletAttributionPrefix: undefined,
extraCreditLinks: [
// Default credit links (shown at the bottom of the Cesium map)
{
text: "map.extraCreditLinks.dataAttribution",
url: "about.html#data-attribution"
},
{ text: "map.extraCreditLinks.disclaimer", url: "about.html#disclaimer" }
],
printDisclaimer: undefined,
storyRouteUrlPrefix: undefined,
enableConsoleAnalytics: undefined,
googleAnalyticsOptions: undefined,
relatedMaps: defaultRelatedMaps,
aboutButtonHrefUrl: "about.html",
plugins: undefined
};
@observable
pickedFeatures: PickedFeatures | undefined;
@observable
selectedFeature: TerriaFeature | undefined;
@observable
allowFeatureInfoRequests: boolean = true;
/**
* Gets or sets the stack of map interactions modes. The mode at the top of the stack
* (highest index) handles click interactions with the map
*/
@observable
mapInteractionModeStack: MapInteractionMode[] = [];
@observable isWorkflowPanelActive = false;
/** Gets or sets the active SelectableDimensionWorkflow, if defined, then the workflow will be displayed using `WorkflowPanel` */
@observable
selectableDimensionWorkflow?: SelectableDimensionWorkflow;
@computed
get baseMapContrastColor() {
return (
this.baseMapsModel.baseMapItems.find(
(basemap) =>
isDefined(basemap.item?.uniqueId) &&
basemap.item?.uniqueId === this.mainViewer.baseMap?.uniqueId
)?.contrastColor ?? "#ffffff"
);
}
@observable
readonly userProperties = new Map<string, any>();
@observable
readonly initSources: InitSource[] = [];
private _initSourceLoader = new AsyncLoader(
this.forceLoadInitSources.bind(this)
);
@observable serverConfig: any; // TODO
@observable shareDataService: ShareDataService | undefined;
/* Splitter controls */
@observable showSplitter = false;
@observable splitPosition = 0.5;
@observable splitPositionVertical = 0.5;
@observable terrainSplitDirection: SplitDirection = SplitDirection.NONE;
@observable depthTestAgainstTerrainEnabled = false;
@observable stories: StoryData[] = [];
@observable storyPromptShown: number = 0; // Story Prompt modal will be rendered when this property changes. See StandardUserInterface, section regarding sui.notifications. Ideally move this to ViewState.
/**
* Gets or sets the ID of the catalog member that is currently being
* previewed. This is observed in ViewState. It is used to open "Add data" if a catalog member is open in a share link.
* This should stay private - use viewState.viewCatalogMember() instead
*/
@observable private _previewedItemId: string | undefined;
get previewedItemId() {
return this._previewedItemId;
}
/**
* Base ratio for maximumScreenSpaceError
* @type {number}
*/
@observable baseMaximumScreenSpaceError = 2;
/**
* Model to use for map navigation
*/
@observable mapNavigationModel: MapNavigationModel = new MapNavigationModel(
this
);
/**
* Gets or sets whether to use the device's native resolution (sets cesium.viewer.resolutionScale to a ratio of devicePixelRatio)
* @type {boolean}
*/
@observable useNativeResolution = false;
/**
* Whether we think all references in the catalog have been loaded
* @type {boolean}
*/
@observable catalogReferencesLoaded: boolean = false;
augmentedVirtuality?: any;
readonly notificationState: NotificationState = new NotificationState();
readonly developmentEnv = process?.env?.NODE_ENV === "development";
/**
* An error service instance. The instance can be configured by setting the
* `errorService` config parameter. Here we initialize it to stub provider so
* that the `terria.errorService` always exists.
*/
errorService: ErrorServiceProvider = new StubErrorServiceProvider();
constructor(options: TerriaOptions = {}) {
if (options.appBaseHref) {
this.appBaseHref = new URL(
options.appBaseHref,
typeof document !== "undefined" ? document.baseURI : "/"
).toString();
}
if (options.baseUrl) {
this.baseUrl = ensureSuffix(options.baseUrl, "/");
}
this.cesiumBaseUrl = ensureSuffix(
options.cesiumBaseUrl ?? `${this.baseUrl}build/Cesium/build/`,
"/"
);
// Casting to `any` as `setBaseUrl` method is not part of the Cesiums' type definitions
(buildModuleUrl as any).setBaseUrl(this.cesiumBaseUrl);
this.analytics = options.analytics;
if (!defined(this.analytics)) {
if (typeof window !== "undefined" && defined((<any>window).ga)) {
this.analytics = new GoogleAnalytics();
} else {
this.analytics = new ConsoleAnalytics();
}
}
}
/** Raise error to user.
*
* This accepts same arguments as `TerriaError.from` - but also has:
*
* @param forceRaiseToUser - which can be used to force raise the error
*/
raiseErrorToUser(
error: unknown,
overrides?: TerriaErrorOverrides,
forceRaiseToUser = false
) {
const terriaError = TerriaError.from(error, overrides);
// Set shouldRaiseToUser true if forceRaiseToUser agrument is true
if (forceRaiseToUser) terriaError.overrideRaiseToUser = true;
// Log error to error service
this.errorService.error(terriaError);
// Only show error to user if `ignoreError` flag hasn't been set to "1"
// Note: this will take precedence over forceRaiseToUser/overrideRaiseToUser
if (this.userProperties.get("ignoreErrors") !== "1")
this.notificationState.addNotificationToQueue(
terriaError.toNotification()
);
terriaError.log();
}
@computed
get currentViewer(): GlobeOrMap {
return this.mainViewer.currentViewer;
}
@computed
get cesium(): import("./Cesium").default | undefined {
if (
isDefined(this.mainViewer) &&
this.mainViewer.currentViewer.type === "Cesium"
) {
return this.mainViewer.currentViewer as import("./Cesium").default;
}
}
/**
* @returns The currently active `TerrainProvider` or `undefined`.
*/
@computed
get terrainProvider(): TerrainProvider | undefined {
return this.cesium?.terrainProvider;
}
@computed
get leaflet(): import("./Leaflet").default | undefined {
if (
isDefined(this.mainViewer) &&
this.mainViewer.currentViewer.type === "Leaflet"
) {
return this.mainViewer.currentViewer as import("./Leaflet").default;
}
}
@computed get modelValues() {
return Array.from(this.models.values());
}
@computed
get modelIds() {
return Array.from(this.models.keys());
}
getModelById<T extends BaseModel>(type: Class<T>, id: string): T | undefined {
const model = this.models.get(id);
if (instanceOf(type, model)) {
return model;
}
// Model does not have the requested type.
return undefined;
}
@action
addModel(model: BaseModel, shareKeys?: string[]) {
if (model.uniqueId === undefined) {
throw new DeveloperError("A model without a `uniqueId` cannot be added.");
}
if (this.models.has(model.uniqueId)) {
throw new RuntimeError(
`A model with the specified ID already exists: \`${model.uniqueId}\``
);
}
this.models.set(model.uniqueId, model);
shareKeys?.forEach((shareKey) =>
this.addShareKey(model.uniqueId!, shareKey)
);
}
/**
* Remove references to a model from Terria.
*/
@action
removeModelReferences(model: BaseModel) {
this.removeSelectedFeaturesForModel(model);
this.workbench.remove(model);
if (model.uniqueId) {
this.models.delete(model.uniqueId);
}
}
@action
removeSelectedFeaturesForModel(model: BaseModel) {
const pickedFeatures = this.pickedFeatures;
if (pickedFeatures) {
// Remove picked features that belong to the catalog item
pickedFeatures.features.forEach((feature, i) => {
if (featureBelongsToCatalogItem(<TerriaFeature>feature, model)) {
pickedFeatures?.features.splice(i, 1);
if (this.selectedFeature === feature)
this.selectedFeature = undefined;
}
});
}
}
getModelIdByShareKey(shareKey: string): string | undefined {
return this.shareKeysMap.get(shareKey);
}
getModelByIdOrShareKey<T extends BaseModel>(
type: Class<T>,
id: string
): T | undefined {
let model = this.getModelById(type, id);
if (model) {
return model;
} else {
const idFromShareKey = this.getModelIdByShareKey(id);
return idFromShareKey !== undefined
? this.getModelById(type, idFromShareKey)
: undefined;
}
}
async getModelByIdShareKeyOrCatalogIndex(
id: string
): Promise<Result<BaseModel | undefined>> {
try {
// See if model exists by ID of sharekey
const model = this.getModelByIdOrShareKey(BaseModel, id);
// If no model exists, try to find it through Terria model sharekeys or CatalogIndex sharekeys
if (model?.uniqueId !== undefined) {
return new Result(model);
} else if (this.catalogIndex) {
try {
await this.catalogIndex.load();
} catch (e) {
throw TerriaError.from(
e,
`Failed to load CatalogIndex while trying to load model \`${id}\``
);
}
const indexModel = this.catalogIndex.getModelByIdOrShareKey(id);
if (indexModel) {
(await indexModel.loadReference()).throwIfError();
return new Result(indexModel.target);
}
}
} catch (e) {
return Result.error(e);
}
return new Result(undefined);
}
@action
addShareKey(id: string, shareKey: string) {
if (id === shareKey || this.shareKeysMap.has(shareKey)) return;
this.shareKeysMap.set(shareKey, id);
this.modelIdShareKeysMap.get(id)?.push(shareKey) ??
this.modelIdShareKeysMap.set(id, [shareKey]);
}
/**
* Initialize errorService from config parameters.
*/
setupErrorServiceProvider(errorService: ErrorServiceOptions) {
initializeErrorServiceProvider(errorService)
.then((errorService) => {
this.errorService = errorService;
})
.catch((e) => {
console.error("Failed to initialize error service", e);
});
}
setupInitializationUrls(baseUri: uri.URI, config: any) {
const initializationUrls: string[] = config?.initializationUrls || [];
const initSources: InitSource[] = initializationUrls.map((url) => ({
name: `Init URL from config ${url}`,
errorSeverity: TerriaErrorSeverity.Error,
...generateInitializationUrl(
baseUri,
this.configParameters.initFragmentPaths,
url
)
}));
// look for v7 catalogs -> push v7-v8 conversion to initSources
if (Array.isArray(config?.v7initializationUrls)) {
initSources.push(
...(config.v7initializationUrls as JsonArray)
.filter(isJsonString)
.map((v7initUrl) => ({
name: `V7 Init URL from config ${v7initUrl}`,
errorSeverity: TerriaErrorSeverity.Error,
data: (async () => {
try {
const [{ convertCatalog }, catalog] = await Promise.all([
import("catalog-converter"),
loadJson5(v7initUrl)
]);
const convert = convertCatalog(catalog, { generateIds: false });
console.log(
`WARNING: ${v7initUrl} is a v7 catalog - it has been upgraded to v8\nMessages:\n`
);
convert.messages.forEach((message) =>
console.log(`- ${message.path.join(".")}: ${message.message}`)
);
return new Result({
data: (convert.result as JsonObject | null) || {}
});
} catch (error) {
return Result.error(error, {
title: { key: "models.catalog.convertErrorTitle" },
message: {
key: "models.catalog.convertErrorMessage",
parameters: { url: v7initUrl }
}
});
}
})()
}))
);
}
this.initSources.push(...initSources);
}
async start(options: StartOptions) {
// Some hashProperties need to be set before anything else happens
const hashProperties = queryToObject(new URI(window.location).fragment());
if (isDefined(hashProperties["ignoreErrors"])) {
this.userProperties.set("ignoreErrors", hashProperties["ignoreErrors"]);
}
this.shareDataService = options.shareDataService;
// If in development environment, allow usage of #configUrl to set Terria config URL
if (this.developmentEnv) {
if (
isDefined(hashProperties["configUrl"]) &&
hashProperties["configUrl"] !== ""
)
options.configUrl = hashProperties["configUrl"];
}
const baseUri = new URI(options.configUrl).filename("");
const launchUrlForAnalytics =
options.applicationUrl?.href || getUriWithoutPath(baseUri);
try {
const config = await loadJson5(
options.configUrl,
options.configUrlHeaders
);
// If it's a magda config, we only load magda config and parameters should never be a property on the direct
// config aspect (it would be under the `terria-config` aspect)
if (isJsonObject(config) && config.aspects) {
await this.loadMagdaConfig(options.configUrl, config, baseUri);
}
runInAction(() => {
if (isJsonObject(config) && isJsonObject(config.parameters)) {
this.updateParameters(config.parameters);
}
if (this.configParameters.errorService) {
this.setupErrorServiceProvider(this.configParameters.errorService);
}
this.setupInitializationUrls(baseUri, config);
});
} catch (error) {
this.raiseErrorToUser(error, {
sender: this,
title: { key: "models.terria.loadConfigErrorTitle" },
message: `Couldn't load ${options.configUrl}`,
severity: TerriaErrorSeverity.Error
});
} finally {
if (!options.i18nOptions?.skipInit) {
await Internationalization.initLanguage(
this.configParameters.languageConfiguration,
options.i18nOptions,
this.baseUrl
);
}
}
setCustomRequestSchedulerDomainLimits(
this.configParameters.customRequestSchedulerLimits
);
this.analytics?.start(this.configParameters);
this.analytics?.logEvent(
Category.launch,
LaunchAction.url,
launchUrlForAnalytics
);