vesium 1.0.1-beta.51 → 1.0.1-beta.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,9 @@
1
- import { computedAsync, promiseTimeout, refThrottled, tryOnScopeDispose, useElementBounding, useElementSize, useMutationObserver, watchImmediate, watchThrottled } from "@vueuse/core";
2
- import { CallbackProperty, Cartesian2, Cartesian3, Cartographic, ConstantProperty, Ellipsoid, EllipsoidGeodesic, Material, Math as Math$1, ScreenSpaceEventHandler, ScreenSpaceEventType, Viewer, defined } from "cesium";
1
+ import { computedAsync, refThrottled, tryOnScopeDispose, useElementBounding, useElementSize, useMutationObserver, watchImmediate, watchThrottled } from "@vueuse/core";
2
+ import { Cartesian2, EllipsoidGeodesic, ScreenSpaceEventHandler, ScreenSpaceEventType, Viewer } from "cesium";
3
3
  import { computed, getCurrentScope, inject, markRaw, nextTick, provide, readonly, ref, shallowReactive, shallowReadonly, shallowRef, toRaw, toRef, toValue, watch, watchEffect } from "vue";
4
+ import { cartesianToCanvasCoord, isDef, isFunction, isPromise, resolvePick, throttle, toCartesian3, tryRun } from "@vesium/shared";
5
+
6
+ export * from "@vesium/shared"
4
7
 
5
8
  //#region createViewer/index.ts
6
9
  /**
@@ -11,6 +14,8 @@ const CREATE_VIEWER_INJECTION_KEY = Symbol("CREATE_VIEWER_INJECTION_KEY");
11
14
  * @internal
12
15
  */
13
16
  const CREATE_VIEWER_COLLECTION = /* @__PURE__ */ new WeakMap();
17
+ /**
18
+ */
14
19
  function createViewer(...args) {
15
20
  const viewer = shallowRef();
16
21
  const readonlyViewer = shallowReadonly(viewer);
@@ -29,9 +34,7 @@ function createViewer(...args) {
29
34
  const value = toRaw(toValue(arg1));
30
35
  if (value instanceof Viewer) viewer.value = markRaw(value);
31
36
  else if (value) {
32
- const element = value;
33
- const options = arg2;
34
- viewer.value = new Viewer(element, options);
37
+ viewer.value = new Viewer(value, arg2);
35
38
  onCleanup(() => !viewer.value?.isDestroyed() && viewer.value?.destroy());
36
39
  } else viewer.value = void 0;
37
40
  });
@@ -43,530 +46,6 @@ function createViewer(...args) {
43
46
  });
44
47
  }
45
48
 
46
- //#endregion
47
- //#region utils/arrayDiff.ts
48
- /**
49
- * 计算两个数组的差异,返回新增和删除的元素
50
- */
51
- function arrayDiff(list, oldList) {
52
- const oldListSet = new Set(oldList);
53
- const added = list.filter((obj) => !oldListSet.has(obj));
54
- const newListSet = new Set(list);
55
- const removed = oldList?.filter((obj) => !newListSet.has(obj)) ?? [];
56
- return {
57
- added,
58
- removed
59
- };
60
- }
61
-
62
- //#endregion
63
- //#region utils/canvasCoordToCartesian.ts
64
- /**
65
- * Convert canvas coordinates to Cartesian coordinates
66
- *
67
- * @param canvasCoord Canvas coordinates
68
- * @param scene Cesium.Scene instance
69
- * @param mode optional values are 'pickPosition' | 'globePick' | 'auto' | 'noHeight' @default 'auto'
70
- *
71
- * `pickPosition`: Use scene.pickPosition for conversion, which can be used for picking models, oblique photography, etc.
72
- * However, if depth detection is not enabled (globe.depthTestAgainstTerrain=false), picking terrain or inaccurate issues may occur
73
- *
74
- * `globePick`: Use camera.getPickRay for conversion, which cannot be used for picking models or oblique photography,
75
- * but can be used for picking terrain. If terrain does not exist, the picked elevation is 0
76
- *
77
- * `auto`: Automatically determine which picking content to return
78
- *
79
- * Calculation speed comparison: globePick > auto >= pickPosition
80
- */
81
- function canvasCoordToCartesian(canvasCoord, scene, mode = "auto") {
82
- if (mode === "pickPosition") return scene.pickPosition(canvasCoord);
83
- else if (mode === "globePick") {
84
- const ray = scene.camera.getPickRay(canvasCoord);
85
- return ray && scene.globe.pick(ray, scene);
86
- } else {
87
- if (scene.globe.depthTestAgainstTerrain) return scene.pickPosition(canvasCoord);
88
- const position1 = scene.pickPosition(canvasCoord);
89
- const ray = scene.camera.getPickRay(canvasCoord);
90
- const position2 = ray && scene.globe.pick(ray, scene);
91
- if (!position1) return position2;
92
- const height1 = (position1 && Ellipsoid.WGS84.cartesianToCartographic(position1).height) ?? 0;
93
- const height2 = (position2 && Ellipsoid.WGS84.cartesianToCartographic(position2).height) ?? 0;
94
- return height1 < height2 ? position1 : position2;
95
- }
96
- }
97
-
98
- //#endregion
99
- //#region utils/cartesianToCanvasCoord.ts
100
- /**
101
- * Convert Cartesian coordinates to canvas coordinates
102
- *
103
- * @param position Cartesian coordinates
104
- * @param scene Cesium.Scene instance
105
- */
106
- function cartesianToCanvasCoord(position, scene) {
107
- return scene.cartesianToCanvasCoordinates(position);
108
- }
109
-
110
- //#endregion
111
- //#region utils/is.ts
112
- const toString = Object.prototype.toString;
113
- function isDef(val) {
114
- return typeof val !== "undefined";
115
- }
116
- function isBoolean(val) {
117
- return typeof val === "boolean";
118
- }
119
- function isFunction(val) {
120
- return typeof val === "function";
121
- }
122
- function isNumber(val) {
123
- return typeof val === "number";
124
- }
125
- function isString(val) {
126
- return typeof val === "string";
127
- }
128
- function isObject(val) {
129
- return toString.call(val) === "[object Object]";
130
- }
131
- function isWindow(val) {
132
- return typeof window !== "undefined" && toString.call(val) === "[object Window]";
133
- }
134
- function isPromise(val) {
135
- return !!val && (typeof val === "object" || typeof val === "function") && typeof val.then === "function";
136
- }
137
- function isElement(val) {
138
- return !!(val && val.nodeName && val.nodeType === 1);
139
- }
140
- const isArray = Array.isArray;
141
- function isBase64(val) {
142
- const reg = /^\s*data:([a-z]+\/[\d+.a-z-]+(;[a-z-]+=[\da-z-]+)?)?(;base64)?,([\s\w!$%&'()*+,./:;=?@~-]*?)\s*$/i;
143
- return reg.test(val);
144
- }
145
- function assertError(condition, error) {
146
- if (condition) throw new Error(error);
147
- }
148
-
149
- //#endregion
150
- //#region utils/cesiumEquals.ts
151
- /**
152
- * Determines if two Cesium objects are equal.
153
- *
154
- * This function not only judges whether the instances are equal,
155
- * but also judges the equals method in the example.
156
- *
157
- * @param left The first Cesium object
158
- * @param right The second Cesium object
159
- * @returns Returns true if the two Cesium objects are equal, otherwise false
160
- */
161
- function cesiumEquals(left, right) {
162
- return left === right || isFunction(left?.equals) && left.equals(right) || isFunction(right?.equals) && right.equals(left);
163
- }
164
-
165
- //#endregion
166
- //#region utils/toCoord.ts
167
- /**
168
- * Converts coordinates to an array or object in the specified format.
169
- *
170
- * @param position The coordinate to be converted, which can be a Cartesian3, Cartographic, array, or object.
171
- * @param options Conversion options, including conversion type and whether to include altitude information.
172
- * @returns The converted coordinate, which may be an array or object. If the input position is empty, undefined is returned.
173
- *
174
- * @template T Conversion type, optional values are 'Array' or 'Object', @default 'Array'.
175
- * @template Alt Whether to include altitude information, default is false
176
- */
177
- function toCoord(position, options = {}) {
178
- if (!position) return void 0;
179
- const { type = "Array", alt = false } = options;
180
- let longitude, latitude, height;
181
- if (position instanceof Cartesian3) {
182
- const cartographic = Ellipsoid.WGS84.cartesianToCartographic(position);
183
- longitude = Math$1.toDegrees(cartographic.longitude);
184
- latitude = Math$1.toDegrees(cartographic.latitude);
185
- height = cartographic.height;
186
- } else if (position instanceof Cartographic) {
187
- const cartographic = position;
188
- longitude = Math$1.toDegrees(cartographic.longitude);
189
- latitude = Math$1.toDegrees(cartographic.latitude);
190
- height = cartographic.height;
191
- } else if (Array.isArray(position)) {
192
- longitude = Math$1.toDegrees(position[0]);
193
- latitude = Math$1.toDegrees(position[1]);
194
- height = position[2];
195
- } else {
196
- longitude = position.longitude;
197
- latitude = position.latitude;
198
- height = position.height;
199
- }
200
- if (type === "Array") return alt ? [
201
- longitude,
202
- latitude,
203
- height
204
- ] : [longitude, latitude];
205
- else return alt ? {
206
- longitude,
207
- latitude,
208
- height
209
- } : {
210
- longitude,
211
- latitude
212
- };
213
- }
214
-
215
- //#endregion
216
- //#region utils/convertDMS.ts
217
- /**
218
- * Convert degrees to DMS (Degrees Minutes Seconds) format string
219
- *
220
- * @param degrees The angle value
221
- * @param precision The number of decimal places to retain for the seconds, defaults to 3
222
- * @returns A DMS formatted string in the format: degrees° minutes′ seconds″
223
- */
224
- function dmsEncode(degrees, precision = 3) {
225
- const str = `${degrees}`;
226
- let i = str.indexOf(".");
227
- const d = i < 0 ? str : str.slice(0, Math.max(0, i));
228
- let m = "0";
229
- let s = "0";
230
- if (i > 0) {
231
- m = `0${str.slice(Math.max(0, i))}`;
232
- m = `${+m * 60}`;
233
- i = m.indexOf(".");
234
- if (i > 0) {
235
- s = `0${m.slice(Math.max(0, i))}`;
236
- m = m.slice(0, Math.max(0, i));
237
- s = `${+s * 60}`;
238
- i = s.indexOf(".");
239
- s = s.slice(0, Math.max(0, i + 4));
240
- s = (+s).toFixed(precision);
241
- }
242
- }
243
- return `${Math.abs(+d)}°${+m}′${+s}″`;
244
- }
245
- /**
246
- * Decode a DMS (Degrees Minutes Seconds) formatted string to a decimal angle value
247
- *
248
- * @param dmsCode DMS formatted string, e.g. "120°30′45″N"
249
- * @returns The decoded decimal angle value, or 0 if decoding fails
250
- */
251
- function dmsDecode(dmsCode) {
252
- const [dd, msStr] = dmsCode.split("°") ?? [];
253
- const [mm, sStr] = msStr?.split("′") ?? [];
254
- const ss = sStr?.split("″")[0];
255
- const d = Number(dd) || 0;
256
- const m = (Number(mm) || 0) / 60;
257
- const s = (Number(ss) || 0) / 60 / 60;
258
- const degrees = d + m + s;
259
- if (degrees === 0) return 0;
260
- else {
261
- let res = degrees;
262
- if ([
263
- "W",
264
- "w",
265
- "S",
266
- "s"
267
- ].includes(dmsCode[dmsCode.length - 1])) res = -res;
268
- return res;
269
- }
270
- }
271
- /**
272
- * Convert latitude and longitude coordinates to degrees-minutes-seconds format
273
- *
274
- * @param position The latitude and longitude coordinates
275
- * @param precision The number of decimal places to retain for 'seconds', default is 3
276
- * @returns Returns the coordinates in degrees-minutes-seconds format, or undefined if the conversion fails
277
- */
278
- function degreesToDms(position, precision = 3) {
279
- const coord = toCoord(position, { alt: true });
280
- if (!coord) return;
281
- const [longitude, latitude, height] = coord;
282
- const x = dmsEncode(longitude, precision);
283
- const y = dmsEncode(latitude, precision);
284
- return [
285
- `${x}${longitude > 0 ? "E" : "W"}`,
286
- `${y}${latitude > 0 ? "N" : "S"}`,
287
- height
288
- ];
289
- }
290
- /**
291
- * Convert DMS (Degrees Minutes Seconds) format to decimal degrees for latitude and longitude coordinates
292
- *
293
- * @param dms The latitude or longitude coordinate in DMS format
294
- * @returns Returns the coordinate in decimal degrees format, or undefined if the conversion fails
295
- */
296
- function dmsToDegrees(dms) {
297
- const [x, y, height] = dms;
298
- const longitude = dmsDecode(x);
299
- const latitude = dmsDecode(y);
300
- return [
301
- longitude,
302
- latitude,
303
- Number(height) || 0
304
- ];
305
- }
306
-
307
- //#endregion
308
- //#region utils/isCesiumConstant.ts
309
- /**
310
- * Determines if the Cesium property is a constant.
311
- *
312
- * @param value Cesium property
313
- */
314
- function isCesiumConstant(value) {
315
- return !defined(value) || !!value.isConstant;
316
- }
317
-
318
- //#endregion
319
- //#region utils/material.ts
320
- /**
321
- * Only as a type fix for `Cesium.Material`
322
- */
323
- var CesiumMaterial = class extends Material {
324
- constructor(options) {
325
- super(options);
326
- }
327
- };
328
- /**
329
- * Get material from cache, alias of `Material._materialCache.getMaterial`
330
- */
331
- function getMaterialCache(type) {
332
- return Material._materialCache.getMaterial(type);
333
- }
334
- /**
335
- * Add material to Cesium's material cache, alias of `Material._materialCache.addMaterial`
336
- */
337
- function addMaterialCache(type, material) {
338
- return Material._materialCache.addMaterial(type, material);
339
- }
340
-
341
- //#endregion
342
- //#region utils/pick.ts
343
- /**
344
- * Analyze the result of Cesium's `scene.pick` and convert it to an array format
345
- */
346
- function resolvePick(pick = {}) {
347
- const { primitive, id, primitiveCollection, collection } = pick;
348
- const entityCollection = id && id.entityCollection || null;
349
- const dataSource = entityCollection && entityCollection.owner || null;
350
- const ids = Array.isArray(id) ? id : [id].filter(Boolean);
351
- return [
352
- ...ids,
353
- primitive,
354
- primitiveCollection,
355
- collection,
356
- entityCollection,
357
- dataSource
358
- ].filter((e) => !!e);
359
- }
360
- /**
361
- * Determine if the given array of graphics is hit by Cesium's `scene.pick`
362
- *
363
- * @param pick The `scene.pick` object used for matching
364
- * @param graphic An array of graphics to check for hits
365
- */
366
- function pickHitGraphic(pick, graphic) {
367
- if (!Array.isArray(graphic) || !graphic.length) return false;
368
- const elements = resolvePick(pick);
369
- if (!elements.length) return false;
370
- return elements.some((element) => graphic.includes(element));
371
- }
372
-
373
- //#endregion
374
- //#region utils/property.ts
375
- /**
376
- * Is Cesium.Property
377
- * @param value - The target object
378
- */
379
- function isProperty(value) {
380
- return value && isFunction(value.getValue);
381
- }
382
- /**
383
- * Converts a value that may be a Property into its target value, @see {toProperty} for the reverse operation
384
- * ```typescript
385
- * toPropertyValue('val') //=> 'val'
386
- * toPropertyValue(new ConstantProperty('val')) //=> 'val'
387
- * toPropertyValue(new CallbackProperty(()=>'val')) //=> 'val'
388
- * ```
389
- *
390
- * @param value - The value to convert
391
- */
392
- function toPropertyValue(value, time) {
393
- return isProperty(value) ? value.getValue(time) : value;
394
- }
395
- /**
396
- * Converts a value that may be a Property into a Property object, @see {toPropertyValue} for the reverse operation
397
- *
398
- * @param value - The property value or getter to convert, can be undefined or null
399
- * @param isConstant - The second parameter for converting to CallbackProperty
400
- * @returns Returns the converted Property object, if value is undefined or null, returns undefined
401
- */
402
- function toProperty(value, isConstant = false) {
403
- return isProperty(value) ? value : isFunction(value) ? new CallbackProperty(value, isConstant) : new ConstantProperty(value);
404
- }
405
- /**
406
- * Create a Cesium property key
407
- *
408
- * @param scope The host object
409
- * @param field The property name
410
- * @param maybeProperty Optional property or getter
411
- * @param readonly Whether the property is read-only
412
- */
413
- function createPropertyField(scope, field, maybeProperty, readonly$1) {
414
- let removeOwnerListener;
415
- const ownerBinding = (value) => {
416
- removeOwnerListener?.();
417
- if (defined(value?.definitionChanged)) removeOwnerListener = value?.definitionChanged?.addEventListener(() => {
418
- scope.definitionChanged.raiseEvent(scope, field, value, value);
419
- });
420
- };
421
- const privateField = `_${field}`;
422
- const property = toProperty(maybeProperty);
423
- scope[privateField] = property;
424
- ownerBinding(property);
425
- if (readonly$1) Object.defineProperty(scope, field, { get() {
426
- return scope[privateField];
427
- } });
428
- else Object.defineProperty(scope, field, {
429
- get() {
430
- return scope[privateField];
431
- },
432
- set(value) {
433
- const previous = scope[privateField];
434
- if (scope[privateField] !== value) {
435
- scope[privateField] = value;
436
- ownerBinding(value);
437
- if (defined(scope.definitionChanged)) scope.definitionChanged.raiseEvent(scope, field, value, previous);
438
- }
439
- }
440
- });
441
- }
442
- function createCesiumAttribute(scope, key, value, options = {}) {
443
- const allowToProperty = !!options.toProperty;
444
- const shallowClone = !!options.shallowClone;
445
- const changedEventKey = options.changedEventKey || "definitionChanged";
446
- const changedEvent = Reflect.get(scope, changedEventKey);
447
- const privateKey = `_${String(key)}`;
448
- const attribute = allowToProperty ? toProperty(value) : value;
449
- Reflect.set(scope, privateKey, attribute);
450
- const obj = { get() {
451
- const value$1 = Reflect.get(scope, privateKey);
452
- if (shallowClone) return Array.isArray(value$1) ? [...value$1] : { ...value$1 };
453
- else return value$1;
454
- } };
455
- let previousListener;
456
- const serial = (property, previous) => {
457
- previousListener?.();
458
- previousListener = property?.definitionChanged?.addEventListener(() => {
459
- changedEvent?.raiseEvent.bind(changedEvent)(scope, key, property, previous);
460
- });
461
- };
462
- if (!options.readonly) {
463
- if (allowToProperty && isProperty(value)) serial(value);
464
- obj.set = (value$1) => {
465
- if (allowToProperty && !isProperty(value$1)) throw new Error(`The value of ${String(key)} must be a Cesium.Property object`);
466
- const previous = Reflect.get(scope, privateKey);
467
- if (previous !== value$1) {
468
- Reflect.set(scope, privateKey, value$1);
469
- changedEvent?.raiseEvent.bind(changedEvent)(scope, key, value$1, previous);
470
- if (allowToProperty) serial(value$1);
471
- }
472
- };
473
- }
474
- Object.defineProperty(scope, key, obj);
475
- }
476
- function createCesiumProperty(scope, key, value, options = {}) {
477
- return createCesiumAttribute(scope, key, value, {
478
- ...options,
479
- toProperty: true
480
- });
481
- }
482
-
483
- //#endregion
484
- //#region utils/throttle.ts
485
- /**
486
- * Throttle function, which limits the frequency of execution of the function
487
- *
488
- * @param callback raw function
489
- * @param delay Throttled delay duration (ms)
490
- * @param trailing Trigger callback function after last call @default true
491
- * @param leading Trigger the callback function immediately on the first call @default false
492
- * @returns Throttle function
493
- */
494
- function throttle(callback, delay = 100, trailing = true, leading = false) {
495
- const restList = [];
496
- let tracked = false;
497
- const trigger = async () => {
498
- await promiseTimeout(delay);
499
- tracked = false;
500
- if (leading) try {
501
- callback(...restList[0]);
502
- } catch (error) {
503
- console.error(error);
504
- }
505
- if (trailing && (!leading || restList.length > 1)) try {
506
- callback(...restList[restList.length - 1]);
507
- } catch (error) {
508
- console.error(error);
509
- }
510
- restList.length = 0;
511
- };
512
- return (...rest) => {
513
- if (restList.length < 2) restList.push(rest);
514
- else restList[1] = rest;
515
- if (!tracked) {
516
- tracked = true;
517
- trigger();
518
- }
519
- };
520
- }
521
-
522
- //#endregion
523
- //#region utils/toCartesian3.ts
524
- /**
525
- * Converts position to a coordinate point in the Cartesian coordinate system
526
- *
527
- * @param position Position information, which can be a Cartesian coordinate point (Cartesian3), a geographic coordinate point (Cartographic), an array, or an object containing WGS84 latitude, longitude, and height information
528
- * @returns The converted Cartesian coordinate point. If the input parameter is invalid, undefined is returned
529
- */
530
- function toCartesian3(position) {
531
- if (!position) return void 0;
532
- if (position instanceof Cartesian3) return position.clone();
533
- else if (position instanceof Cartographic) return Ellipsoid.WGS84.cartographicToCartesian(position);
534
- else if (Array.isArray(position)) return Cartesian3.fromDegrees(position[0], position[1], position[2]);
535
- else return Cartesian3.fromDegrees(position.longitude, position.latitude, position.height);
536
- }
537
-
538
- //#endregion
539
- //#region utils/toCartographic.ts
540
- /**
541
- * Converts a position to a Cartographic coordinate point
542
- *
543
- * @param position Position information, which can be a Cartesian3 coordinate point, a Cartographic coordinate point, an array, or an object containing WGS84 longitude, latitude, and height information
544
- * @returns The converted Cartographic coordinate point, or undefined if the input parameter is invalid
545
- */
546
- function toCartographic(position) {
547
- if (!position) return void 0;
548
- if (position instanceof Cartesian3) return Ellipsoid.WGS84.cartesianToCartographic(position);
549
- else if (position instanceof Cartographic) return position.clone();
550
- else if (Array.isArray(position)) return Cartographic.fromDegrees(position[0], position[1], position[2]);
551
- else return Cartographic.fromDegrees(position.longitude, position.latitude, position.height);
552
- }
553
-
554
- //#endregion
555
- //#region utils/tryRun.ts
556
- /**
557
- * Safely execute the provided function without throwing errors,
558
- * essentially a simple wrapper around a `try...catch...` block
559
- */
560
- function tryRun(fn) {
561
- return (...args) => {
562
- try {
563
- return fn?.(...args);
564
- } catch (error) {
565
- console.error(error);
566
- }
567
- };
568
- }
569
-
570
49
  //#endregion
571
50
  //#region toPromiseValue/index.ts
572
51
  /**
@@ -576,6 +55,7 @@ function tryRun(fn) {
576
55
  *
577
56
  * @param source The source value, which can be a reactive reference or an asynchronous getter.
578
57
  * @param options Conversion options
58
+ * @returns The converted value.
579
59
  *
580
60
  * @example
581
61
  * ```ts
@@ -608,6 +88,11 @@ async function toPromiseValue(source, options = {}) {
608
88
  * Easily use the `addEventListener` in `Cesium.Event` instances,
609
89
  * when the dependent data changes or the component is unmounted,
610
90
  * the listener function will automatically reload or destroy.
91
+ *
92
+ * @param event The Cesium.Event instance
93
+ * @param listener The listener function
94
+ * @param options additional options
95
+ * @returns A function that can be called to remove the event listener
611
96
  */
612
97
  function useCesiumEventListener(event, listener, options = {}) {
613
98
  const isActive = toRef(options.isActive ?? true);
@@ -652,6 +137,8 @@ function useViewer() {
652
137
  //#region useCameraState/index.ts
653
138
  /**
654
139
  * Reactive Cesium Camera state
140
+ * @param options options
141
+ * @returns Reactive camera states
655
142
  */
656
143
  function useCameraState(options = {}) {
657
144
  let getCamera = options.camera;
@@ -703,6 +190,8 @@ function computeLevel(height) {
703
190
  //#region useCesiumFps/index.ts
704
191
  /**
705
192
  * Reactive get the frame rate of Cesium
193
+ * @param options options
194
+ * @returns Reactive fps states
706
195
  */
707
196
  function useCesiumFps(options = {}) {
708
197
  const { delay = 100 } = options;
@@ -727,14 +216,13 @@ function useCesiumFps(options = {}) {
727
216
  /**
728
217
  * Scope the SideEffects of Cesium-related `Collection` and automatically remove them when unmounted.
729
218
  * - note: This is a basic function that is intended to be called by other lower-level function
730
- * @param addFn - add SideEffect function. eg.`entites.add`
731
- * @param removeFn - Clean SideEffect function. eg.`entities.remove`
732
- * @param removeScopeArgs - The parameters to pass for `removeScope` triggered when the component is unmounted
219
+ * @returns Contains side effect addition and removal functions
733
220
  */
734
- function useCollectionScope(addFn, removeFn, removeScopeArgs) {
221
+ function useCollectionScope(options) {
222
+ const { addEffect, removeEffect, removeScopeArgs } = options;
735
223
  const scope = shallowReactive(/* @__PURE__ */ new Set());
736
224
  const add = (instance, ...args) => {
737
- const result = addFn(instance, ...args);
225
+ const result = addEffect(instance, ...args);
738
226
  if (isPromise(result)) return new Promise((resolve, reject) => {
739
227
  result.then((i) => {
740
228
  scope.add(i);
@@ -748,7 +236,7 @@ function useCollectionScope(addFn, removeFn, removeScopeArgs) {
748
236
  };
749
237
  const remove = (instance, ...args) => {
750
238
  scope.delete(instance);
751
- return removeFn(instance, ...args);
239
+ return removeEffect(instance, ...args);
752
240
  };
753
241
  const removeWhere = (predicate, ...args) => {
754
242
  scope.forEach((instance) => {
@@ -777,8 +265,7 @@ function useDataSource(dataSources, options = {}) {
777
265
  const result = computedAsync(() => toPromiseValue(dataSources), void 0, { evaluating });
778
266
  const viewer = useViewer();
779
267
  watchEffect((onCleanup) => {
780
- const _isActive = toValue(isActive);
781
- if (_isActive) {
268
+ if (toValue(isActive)) {
782
269
  const list = Array.isArray(result.value) ? [...result.value] : [result.value];
783
270
  const _collection = collection ?? viewer.value?.dataSources;
784
271
  list.forEach((item) => item && _collection?.add(item));
@@ -794,7 +281,7 @@ function useDataSource(dataSources, options = {}) {
794
281
  //#endregion
795
282
  //#region useDataSourceScope/index.ts
796
283
  /**
797
- * // Scope the SideEffects of `DataSourceCollection` operations and automatically remove them when unmounted
284
+ * Scope the SideEffects of `DataSourceCollection` operations and automatically remove them when unmounted
798
285
  */
799
286
  function useDataSourceScope(options = {}) {
800
287
  const { collection: _collection, destroyOnRemove } = options;
@@ -802,21 +289,25 @@ function useDataSourceScope(options = {}) {
802
289
  const collection = computed(() => {
803
290
  return toValue(_collection) ?? viewer.value?.dataSources;
804
291
  });
805
- const addFn = (dataSource) => {
806
- if (!collection.value) throw new Error("collection is not defined");
807
- return collection.value.add(dataSource);
808
- };
809
- const removeFn = (dataSource, destroy) => {
810
- return !!collection.value?.remove(dataSource, destroy);
811
- };
812
- const { scope, add, remove, removeWhere, removeScope } = useCollectionScope(addFn, removeFn, [destroyOnRemove]);
813
- return {
814
- scope,
815
- add,
816
- remove,
817
- removeWhere,
818
- removeScope
819
- };
292
+ return useCollectionScope({
293
+ addEffect(instance) {
294
+ if (!collection.value) throw new Error("collection is not defined");
295
+ if (isPromise(instance)) return new Promise((resolve, reject) => {
296
+ instance.then((i) => {
297
+ collection.value.add(i);
298
+ resolve(i);
299
+ }).catch((error) => reject(error));
300
+ });
301
+ else {
302
+ collection.value.add(instance);
303
+ return instance;
304
+ }
305
+ },
306
+ removeEffect(instance, destroy) {
307
+ return !!collection.value?.remove(instance, destroy);
308
+ },
309
+ removeScopeArgs: [destroyOnRemove]
310
+ });
820
311
  }
821
312
 
822
313
  //#endregion
@@ -836,8 +327,8 @@ function useElementOverlay(target, position, options = {}) {
836
327
  if (!viewer.value?.scene) return;
837
328
  if (!cartesian3.value) coord.value = void 0;
838
329
  else {
839
- const reslut = cartesianToCanvasCoord(cartesian3.value, viewer.value.scene);
840
- coord.value = !Cartesian2.equals(reslut, coord.value) ? reslut : coord.value;
330
+ const result = cartesianToCanvasCoord(cartesian3.value, viewer.value.scene);
331
+ coord.value = !Cartesian2.equals(result, coord.value) ? result : coord.value;
841
332
  }
842
333
  });
843
334
  const canvasBounding = useElementBounding(() => viewer.value?.canvas.parentElement);
@@ -898,8 +389,7 @@ function useEntity(data, options = {}) {
898
389
  const result = computedAsync(() => toPromiseValue(data), [], { evaluating });
899
390
  const viewer = useViewer();
900
391
  watchEffect((onCleanup) => {
901
- const _isActive = toValue(isActive);
902
- if (_isActive) {
392
+ if (toValue(isActive)) {
903
393
  const list = Array.isArray(result.value) ? [...result.value] : [result.value];
904
394
  const _collection = collection ?? viewer.value?.entities;
905
395
  list.forEach((item) => item && _collection?.add(item));
@@ -923,22 +413,25 @@ function useEntityScope(options = {}) {
923
413
  const collection = computed(() => {
924
414
  return toValue(_collection) ?? viewer.value?.entities;
925
415
  });
926
- const addFn = (entity) => {
927
- if (!collection.value) throw new Error("collection is not defined");
928
- if (!collection.value.contains(entity)) collection.value.add(entity);
929
- return entity;
930
- };
931
- const removeFn = (entity) => {
932
- return !!collection.value?.remove(entity);
933
- };
934
- const { scope, add, remove, removeWhere, removeScope } = useCollectionScope(addFn, removeFn, []);
935
- return {
936
- scope,
937
- add,
938
- remove,
939
- removeWhere,
940
- removeScope
941
- };
416
+ return useCollectionScope({
417
+ addEffect(instance) {
418
+ if (!collection.value) throw new Error("collection is not defined");
419
+ if (isPromise(instance)) return new Promise((resolve, reject) => {
420
+ instance.then((i) => {
421
+ collection.value.add(i);
422
+ resolve(i);
423
+ }).catch((error) => reject(error));
424
+ });
425
+ else {
426
+ collection.value.add(instance);
427
+ return instance;
428
+ }
429
+ },
430
+ removeEffect(instance) {
431
+ return !!collection.value?.remove(instance);
432
+ },
433
+ removeScopeArgs: []
434
+ });
942
435
  }
943
436
 
944
437
  //#endregion
@@ -1161,7 +654,7 @@ function useGraphicEvent() {
1161
654
  const collection = /* @__PURE__ */ new WeakMap();
1162
655
  const cursorCollection = /* @__PURE__ */ new WeakMap();
1163
656
  const dragCursorCollection = /* @__PURE__ */ new WeakMap();
1164
- const removeGraphicEvent = (graphic, type, listener) => {
657
+ const remove = (graphic, type, listener) => {
1165
658
  const _graphic = graphic === "global" ? GLOBAL_GRAPHIC_SYMBOL : graphic;
1166
659
  collection?.get(_graphic)?.get(type)?.delete(listener);
1167
660
  cursorCollection?.get(_graphic)?.get(type)?.delete(listener);
@@ -1174,13 +667,12 @@ function useGraphicEvent() {
1174
667
  if (dragCursorCollection?.get(_graphic)?.get(type)?.size === 0) dragCursorCollection?.get(_graphic)?.delete(type);
1175
668
  if (dragCursorCollection?.get(_graphic)?.size === 0) dragCursorCollection?.delete(_graphic);
1176
669
  };
1177
- const addGraphicEvent = (graphic, type, listener, options = {}) => {
670
+ const add = (graphic, type, listener, options = {}) => {
1178
671
  const _graphic = graphic === "global" ? GLOBAL_GRAPHIC_SYMBOL : graphic;
1179
672
  collection.get(_graphic) ?? collection.set(_graphic, /* @__PURE__ */ new Map());
1180
673
  const eventTypeMap = collection.get(_graphic);
1181
674
  eventTypeMap.get(type) ?? eventTypeMap.set(type, /* @__PURE__ */ new Set());
1182
- const listeners = eventTypeMap.get(type);
1183
- listeners.add(listener);
675
+ eventTypeMap.get(type).add(listener);
1184
676
  let { cursor = "pointer", dragCursor } = options;
1185
677
  if (isDef(cursor)) {
1186
678
  const _cursor = isFunction(cursor) ? cursor : () => cursor;
@@ -1188,16 +680,16 @@ function useGraphicEvent() {
1188
680
  cursorCollection.get(_graphic).get(type) ?? cursorCollection.get(_graphic).set(type, /* @__PURE__ */ new Map());
1189
681
  cursorCollection.get(_graphic).get(type).set(listener, _cursor);
1190
682
  }
1191
- if (type === "DRAG") dragCursor ??= (event) => event?.dragging ? "crosshair" : void 0;
683
+ if (type === "DRAG") dragCursor ??= ((event) => event?.dragging ? "crosshair" : void 0);
1192
684
  if (isDef(dragCursor)) {
1193
685
  const _dragCursor = isFunction(dragCursor) ? dragCursor : () => dragCursor;
1194
686
  dragCursorCollection.get(_graphic) ?? dragCursorCollection.set(_graphic, /* @__PURE__ */ new Map());
1195
687
  dragCursorCollection.get(_graphic).get(type) ?? dragCursorCollection.get(_graphic).set(type, /* @__PURE__ */ new Map());
1196
688
  dragCursorCollection.get(_graphic).get(type).set(listener, _dragCursor);
1197
689
  }
1198
- return () => removeGraphicEvent(graphic, type, listener);
690
+ return () => remove(graphic, type, listener);
1199
691
  };
1200
- const clearGraphicEvent = (graphic, type) => {
692
+ const clear = (graphic, type) => {
1201
693
  const _graphic = graphic === "global" ? GLOBAL_GRAPHIC_SYMBOL : graphic;
1202
694
  if (type === "all") {
1203
695
  collection.delete(_graphic);
@@ -1213,16 +705,14 @@ function useGraphicEvent() {
1213
705
  if (dragCursorCollection?.get(_graphic)?.size === 0) dragCursorCollection?.delete(_graphic);
1214
706
  };
1215
707
  for (const type of POSITIONED_EVENT_TYPES) usePositioned(type, (event) => {
1216
- const graphics = resolvePick(event.pick);
1217
- graphics.concat(GLOBAL_GRAPHIC_SYMBOL).forEach((graphic) => {
708
+ resolvePick(event.pick).concat(GLOBAL_GRAPHIC_SYMBOL).forEach((graphic) => {
1218
709
  collection.get(graphic)?.get(type)?.forEach((fn) => tryRun(fn)?.(event));
1219
710
  });
1220
711
  });
1221
712
  const dragging = ref(false);
1222
713
  const viewer = useViewer();
1223
714
  useHover((event) => {
1224
- const graphics = resolvePick(event.pick).concat(GLOBAL_GRAPHIC_SYMBOL);
1225
- graphics.forEach((graphic) => {
715
+ resolvePick(event.pick).concat(GLOBAL_GRAPHIC_SYMBOL).forEach((graphic) => {
1226
716
  collection.get(graphic)?.get("HOVER")?.forEach((fn) => tryRun(fn)?.(event));
1227
717
  if (!dragging.value) cursorCollection.get(graphic)?.forEach((map) => {
1228
718
  map.forEach((fn) => {
@@ -1246,9 +736,9 @@ function useGraphicEvent() {
1246
736
  });
1247
737
  });
1248
738
  return {
1249
- addGraphicEvent,
1250
- removeGraphicEvent,
1251
- clearGraphicEvent
739
+ add,
740
+ remove,
741
+ clear
1252
742
  };
1253
743
  }
1254
744
 
@@ -1259,8 +749,7 @@ function useImageryLayer(data, options = {}) {
1259
749
  const result = computedAsync(() => toPromiseValue(data), [], { evaluating });
1260
750
  const viewer = useViewer();
1261
751
  watchEffect((onCleanup) => {
1262
- const _isActive = toValue(isActive);
1263
- if (_isActive) {
752
+ if (toValue(isActive)) {
1264
753
  const list = Array.isArray(result.value) ? [...result.value] : [result.value];
1265
754
  const _collection = collection ?? viewer.value?.imageryLayers;
1266
755
  if (collection?.isDestroyed()) return;
@@ -1296,22 +785,25 @@ function useImageryLayerScope(options = {}) {
1296
785
  const collection = computed(() => {
1297
786
  return toValue(_collection) ?? viewer.value?.imageryLayers;
1298
787
  });
1299
- const addFn = (imageryLayer, index) => {
1300
- if (!collection.value) throw new Error("collection is not defined");
1301
- collection.value.add(imageryLayer, index);
1302
- return imageryLayer;
1303
- };
1304
- const removeFn = (imageryLayer, destroy) => {
1305
- return !!collection.value?.remove(imageryLayer, destroy);
1306
- };
1307
- const { scope, add, remove, removeWhere, removeScope } = useCollectionScope(addFn, removeFn, [destroyOnRemove]);
1308
- return {
1309
- scope,
1310
- add,
1311
- remove,
1312
- removeWhere,
1313
- removeScope
1314
- };
788
+ return useCollectionScope({
789
+ addEffect(instance, index) {
790
+ if (!collection.value) throw new Error("collection is not defined");
791
+ if (isPromise(instance)) return new Promise((resolve, reject) => {
792
+ instance.then((i) => {
793
+ collection.value.add(i, index);
794
+ resolve(i);
795
+ }).catch((error) => reject(error));
796
+ });
797
+ else {
798
+ collection.value.add(instance, index);
799
+ return instance;
800
+ }
801
+ },
802
+ removeEffect(instance, destroy) {
803
+ return !!collection.value?.remove(instance, destroy);
804
+ },
805
+ removeScopeArgs: [destroyOnRemove]
806
+ });
1315
807
  }
1316
808
 
1317
809
  //#endregion
@@ -1322,8 +814,7 @@ function usePostProcessStage(data, options = {}) {
1322
814
  const viewer = useViewer();
1323
815
  watchEffect((onCleanup) => {
1324
816
  if (!viewer.value) return;
1325
- const _isActive = toValue(isActive);
1326
- if (_isActive) {
817
+ if (toValue(isActive)) {
1327
818
  const list = Array.isArray(result.value) ? [...result.value] : [result.value];
1328
819
  const _collection = collection ?? viewer.value.scene.postProcessStages;
1329
820
  list.forEach((item) => item && _collection.add(item));
@@ -1347,21 +838,22 @@ function usePostProcessStageScope(options = {}) {
1347
838
  const collection = computed(() => {
1348
839
  return toValue(_collection) ?? viewer.value?.postProcessStages;
1349
840
  });
1350
- const addFn = (postProcessStage) => {
1351
- if (!collection.value) throw new Error("collection is not defined");
1352
- return collection.value.add(postProcessStage);
1353
- };
1354
- const removeFn = (postProcessStage) => {
1355
- return !!collection.value?.remove(postProcessStage);
1356
- };
1357
- const { scope, add, remove, removeWhere, removeScope } = useCollectionScope(addFn, removeFn, []);
1358
- return {
1359
- scope,
1360
- add,
1361
- remove,
1362
- removeWhere,
1363
- removeScope
1364
- };
841
+ return useCollectionScope({
842
+ addEffect(instance) {
843
+ if (!collection.value) throw new Error("collection is not defined");
844
+ if (isPromise(instance)) return new Promise((resolve, reject) => {
845
+ instance.then((instance$1) => {
846
+ collection.value.add(instance$1);
847
+ resolve(instance$1);
848
+ }).catch((error) => reject(error));
849
+ });
850
+ else return collection.value.add(instance);
851
+ },
852
+ removeEffect(instance, ...args) {
853
+ return !!collection.value?.remove(instance, ...args);
854
+ },
855
+ removeScopeArgs: []
856
+ });
1365
857
  }
1366
858
 
1367
859
  //#endregion
@@ -1371,8 +863,7 @@ function usePrimitive(data, options = {}) {
1371
863
  const result = computedAsync(() => toPromiseValue(data), void 0, { evaluating });
1372
864
  const viewer = useViewer();
1373
865
  watchEffect((onCleanup) => {
1374
- const _isActive = toValue(isActive);
1375
- if (_isActive) {
866
+ if (toValue(isActive)) {
1376
867
  const list = Array.isArray(result.value) ? [...result.value] : [result.value];
1377
868
  const _collection = collection === "ground" ? viewer.value?.scene.groundPrimitives : collection ?? viewer.value?.scene.primitives;
1378
869
  list.forEach((item) => item && _collection?.add(item));
@@ -1394,16 +885,22 @@ function usePrimitiveScope(options = {}) {
1394
885
  const { collection: _collection } = options;
1395
886
  const viewer = useViewer();
1396
887
  const collection = computed(() => {
1397
- return toValue(_collection) ?? viewer.value?.scene.primitives;
888
+ const value = toValue(_collection);
889
+ return value === "ground" ? viewer.value?.scene?.groundPrimitives : value || viewer.value?.scene.primitives;
890
+ });
891
+ const { scope, add, remove, removeWhere, removeScope } = useCollectionScope({
892
+ addEffect(instance, ...args) {
893
+ if (!collection.value) throw new Error("collection is not defined");
894
+ if (isPromise(instance)) return new Promise((resolve, reject) => {
895
+ instance.then((instance$1) => resolve(collection.value.add(instance$1, ...args))).catch((error) => reject(error));
896
+ });
897
+ else return collection.value.add(instance, ...args);
898
+ },
899
+ removeEffect(instance) {
900
+ return !!collection.value?.remove(instance);
901
+ },
902
+ removeScopeArgs: []
1398
903
  });
1399
- const addFn = (primitive) => {
1400
- if (!collection.value) throw new Error("collection is not defined");
1401
- return collection.value.add(primitive);
1402
- };
1403
- const removeFn = (primitive) => {
1404
- return !!collection.value?.remove(primitive);
1405
- };
1406
- const { scope, add, remove, removeWhere, removeScope } = useCollectionScope(addFn, removeFn, []);
1407
904
  return {
1408
905
  scope,
1409
906
  add,
@@ -1472,10 +969,7 @@ function useScaleBar(options = {}) {
1472
969
  const leftPosition = scene.globe.pick(left, scene);
1473
970
  const rightPosition = scene.globe.pick(right, scene);
1474
971
  if (!leftPosition || !rightPosition) return;
1475
- const leftCartographic = scene.globe.ellipsoid.cartesianToCartographic(leftPosition);
1476
- const rightCartographic = scene.globe.ellipsoid.cartesianToCartographic(rightPosition);
1477
- const geodesic = new EllipsoidGeodesic(leftCartographic, rightCartographic);
1478
- pixelDistance.value = geodesic.surfaceDistance;
972
+ pixelDistance.value = new EllipsoidGeodesic(scene.globe.ellipsoid.cartesianToCartographic(leftPosition), scene.globe.ellipsoid.cartesianToCartographic(rightPosition)).surfaceDistance;
1479
973
  };
1480
974
  watchImmediate(viewer, () => setPixelDistance());
1481
975
  useCesiumEventListener(() => viewer.value?.camera.changed, throttle(setPixelDistance, delay));
@@ -1483,10 +977,7 @@ function useScaleBar(options = {}) {
1483
977
  if (pixelDistance.value) return distances.find((item) => pixelDistance.value * maxPixelRef.value > item);
1484
978
  });
1485
979
  const width = computed(() => {
1486
- if (distance.value && pixelDistance.value) {
1487
- const value = distance.value / pixelDistance.value;
1488
- return value;
1489
- }
980
+ if (distance.value && pixelDistance.value) return distance.value / pixelDistance.value;
1490
981
  return 0;
1491
982
  });
1492
983
  const distanceText = computed(() => {
@@ -1512,12 +1003,11 @@ function useSceneDrillPick(windowPosition, options = {}) {
1512
1003
  const { width = 3, height = 3, limit, throttled = 8, isActive = true } = options;
1513
1004
  const viewer = useViewer();
1514
1005
  const position = refThrottled(computed(() => toValue(windowPosition)), throttled, false, true);
1515
- const pick = computed(() => {
1006
+ return computed(() => {
1516
1007
  if (position.value && toValue(isActive)) return viewer.value?.scene.drillPick(position.value, toValue(limit), toValue(width), toValue(height));
1517
1008
  });
1518
- return pick;
1519
1009
  }
1520
1010
 
1521
1011
  //#endregion
1522
- export { CREATE_VIEWER_COLLECTION, CREATE_VIEWER_INJECTION_KEY, CesiumMaterial, addMaterialCache, arrayDiff, assertError, canvasCoordToCartesian, cartesianToCanvasCoord, cesiumEquals, createCesiumAttribute, createCesiumProperty, createPropertyField, createViewer, degreesToDms, dmsDecode, dmsEncode, dmsToDegrees, getMaterialCache, isArray, isBase64, isBoolean, isCesiumConstant, isDef, isElement, isFunction, isNumber, isObject, isPromise, isProperty, isString, isWindow, pickHitGraphic, resolvePick, throttle, toCartesian3, toCartographic, toCoord, toPromiseValue, toProperty, toPropertyValue, tryRun, useCameraState, useCesiumEventListener, useCesiumFps, useCollectionScope, useDataSource, useDataSourceScope, useElementOverlay, useEntity, useEntityScope, useGraphicEvent, useImageryLayer, useImageryLayerScope, usePostProcessStage, usePostProcessStageScope, usePrimitive, usePrimitiveScope, useScaleBar, useSceneDrillPick, useScenePick, useScreenSpaceEventHandler, useViewer };
1012
+ export { CREATE_VIEWER_COLLECTION, CREATE_VIEWER_INJECTION_KEY, createViewer, toPromiseValue, useCameraState, useCesiumEventListener, useCesiumFps, useCollectionScope, useDataSource, useDataSourceScope, useElementOverlay, useEntity, useEntityScope, useGraphicEvent, useImageryLayer, useImageryLayerScope, usePostProcessStage, usePostProcessStageScope, usePrimitive, usePrimitiveScope, useScaleBar, useSceneDrillPick, useScenePick, useScreenSpaceEventHandler, useViewer };
1523
1013
  //# sourceMappingURL=index.mjs.map