refactor(cesium): 重构 Cesium Viewer 状态管理和 Composable
Some checks failed
/ build-and-deploy-to-vercel (push) Successful in 2m53s
/ lint-build-and-check (push) Successful in 5m9s
/ surge (push) Successful in 2m46s
/ playwright (push) Failing after 3m4s

This commit is contained in:
严浩
2025-04-07 10:00:30 +08:00
parent d7d704d120
commit 2721b4c2f3
8 changed files with 125 additions and 134 deletions

View File

@ -8,26 +8,23 @@ import { useHCesiumManagerStation } from './useHCesiumManager.站点';
import 'cesium/Build/Cesium/Widgets/widgets.css';
const props = defineProps<{
satelliteState?: HCesiumManagerSatelliteState;
stationState?: HCesiumManagerStationState;
satelliteState: HCesiumManagerSatelliteState;
stationState: HCesiumManagerStationState;
}>();
// 1. 管理 Cesium Viewer 实例生命周期
const { hCesiumViewerManager } = useHCesiumManager('cesium-container'); // 获取新的 Manager 实例
// 2. 同步地面站实体
// 将实例的 getter 和 props 的 getter 传递给组合函数
useHCesiumManagerStation(
() => hCesiumViewerManager, // 传递 Manager 实例的 getter
() => props.stationState?.stations, // 从新的 prop 中获取列表
() => props.stationState?.selectedIds, // 从新的 prop 中获取选中 ID
() => hCesiumViewerManager.value,
() => props.stationState,
);
// 3. 同步卫星实体
useHCesiumManagerSatellite(
() => hCesiumViewerManager, // 传递 Manager 实例的 getter
() => props.satelliteState?.satellites, // 传递卫星列表 getter
() => props.satelliteState?.selectedIds, // 传递选中卫星 ID getter
() => hCesiumViewerManager.value,
() => props.satelliteState,
);
</script>

View File

@ -71,6 +71,7 @@ export class HCesiumManager {
* @returns 返回添加的实体,如果 Viewer 未初始化则返回 null。
*/
addEntity(entity: Cesium.Entity): Cesium.Entity | null {
console.debug(`[HCesiumManager] 添加实体: ${entity.name}`);
if (!this.viewer) {
console.error('Viewer 未初始化,无法添加实体。');
return null;

View File

@ -206,12 +206,13 @@ export class HCesiumSatelliteManager {
ellipse: {
semiMajorAxis: coverageRadius,
semiMinorAxis: coverageRadius,
material: baseColor.withAlpha(0.2), // 半透明填充
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
outline: true,
outlineColor: baseColor.withAlpha(0.5), // 轮廓
outlineWidth: 1,
granularity: Cesium.Math.toRadians(1),
outlineWidth: 1,
material: baseColor.withAlpha(0.2),
outline: true,
outlineColor: baseColor.withAlpha(0.8),
},
});
}

View File

@ -15,8 +15,6 @@ export class HCesiumStationManager {
/**
* 向视图中添加或更新地面站实体。
* 注意:当前实现仅添加,如果已存在则警告并返回现有实体。
* @param options - 地面站的选项参数
* @returns 添加的实体对象,如果已存在或添加失败则返回 null 或现有实体。
*/
addOrUpdateStation(options: I站点): undefined {
const existingEntity = this.currentStationEntities.get(options.id);

View File

@ -4,20 +4,18 @@ import { HCesiumManager } from './managers/HCesiumManager';
* 管理 HCesiumViewerManager 实例的生命周期。
*/
export function useHCesiumManager(containerId: string) {
const hCesiumViewerManager = new HCesiumManager();
const hCesiumViewerManager = ref(new HCesiumManager());
// 可以在开发模式下暴露 manager 实例,方便调试
if ($__DEV__) Object.assign(globalThis, { hCesiumViewerManager });
onMounted(() => {
hCesiumViewerManager.init(containerId);
hCesiumViewerManager.value.init(containerId);
});
onBeforeUnmount(() => {
hCesiumViewerManager.destroy();
hCesiumViewerManager.value.destroy();
});
// 返回 Manager 实例,供其他 Composable 或组件使用
return {
hCesiumViewerManager,
};
return { hCesiumViewerManager };
}

View File

@ -2,6 +2,7 @@ import type { MaybeRefOrGetter } from 'vue';
import type { HCesiumManager } from './managers/HCesiumManager';
import type { I卫星 } from './managers/HCesiumManager.types';
import type { HCesiumManagerSatelliteState } from './useHCesiumManager.types'; // 导入状态类型
import { SatelliteCalculator } from './calculators/SatelliteCalculator'; // 导入计算器
import { HCesiumSatelliteManager } from './managers/HCesiumManager.卫星'; // 导入 Satellite Manager
@ -11,8 +12,7 @@ import { HCesiumSatelliteManager } from './managers/HCesiumManager.卫星'; //
*/
export function useHCesiumManagerSatellite(
hCesiumViewerManager: MaybeRefOrGetter<HCesiumManager | null>,
satelliteList: MaybeRefOrGetter<Array<I卫星> | undefined>,
selectedSatelliteIds: MaybeRefOrGetter<Set<string> | undefined>,
state: MaybeRefOrGetter<HCesiumManagerSatelliteState | undefined>, // 接收整个状态对象
) {
// SatelliteManager 和 Calculator 实例引用
const satelliteManager = ref<HCesiumSatelliteManager | null>(null);
@ -22,60 +22,52 @@ export function useHCesiumManagerSatellite(
// 创建一个从 ID 到卫星选项的映射,方便查找
const satelliteMap = computed(() => {
const map = new Map<string, I卫星>();
const list = toValue(satelliteList) ?? [];
const list = toValue(state)?.satellites ?? []; // 从状态对象获取列表
for (const satellite of list) {
map.set(satellite.id, satellite);
}
return map;
});
// 使用 watch 显式监听依赖项
watch(
[hCesiumViewerManager, satelliteList, selectedSatelliteIds], // 监听这些源的变化
() => {
// 回调函数
const viewerManagerInstance = toValue(hCesiumViewerManager);
// 检查 Viewer Manager 和内部 Viewer 实例是否存在
if (!viewerManagerInstance || !viewerManagerInstance.getViewer()) {
// 如果 viewer manager 或 viewer 实例尚未初始化或已销毁,则清理旧 manager 并返回
satelliteManager.value?.destroy();
satelliteManager.value = null;
return;
// 使用 watchEffect 自动追踪依赖项
watchEffect(() => {
const viewerManagerInstance = toValue(hCesiumViewerManager);
if (!viewerManagerInstance || !viewerManagerInstance.getViewer()) {
satelliteManager.value?.destroy();
satelliteManager.value = null;
return;
}
if (!satelliteManager.value) {
// 创建 SatelliteManager 时传入 ViewerManager 和 Calculator
satelliteManager.value = new HCesiumSatelliteManager(viewerManagerInstance, satelliteCalculator);
}
const manager = satelliteManager.value; // 使用 manager 实例
const selectedIdsSet = toValue(state)?.selectedIds ?? new Set<string>(); // 从状态对象获取选中 ID
const currentEntityIds = new Set(manager.getCurrentSatelliteEntities().keys()); // 从 manager 获取当前实体 ID
// 1. 移除不再选中的卫星
for (const entityId of currentEntityIds) {
if (!selectedIdsSet.has(entityId)) {
manager.removeSatellite(entityId); // 使用 manager 的移除方法
}
}
// 确保 SatelliteManager 实例存在且与当前的 ViewerManager 关联
if (!satelliteManager.value) {
// 创建 SatelliteManager 时传入 ViewerManager 和 Calculator
satelliteManager.value = new HCesiumSatelliteManager(viewerManagerInstance, satelliteCalculator);
}
const manager = satelliteManager.value; // 使用 manager 实例
const selectedIdsSet = toValue(selectedSatelliteIds) ?? new Set<string>(); // 直接获取 Set如果为 undefined 则创建空 Set
const currentEntityIds = new Set(manager.getCurrentSatelliteEntities().keys()); // 从 manager 获取当前实体 ID
// 1. 移除不再选中的卫星
for (const entityId of currentEntityIds) {
if (!selectedIdsSet.has(entityId)) {
manager.removeSatellite(entityId); // 使用 manager 的移除方法
// 2. 添加新增的选中卫星
for (const selectedId of selectedIdsSet) {
if (!currentEntityIds.has(selectedId)) {
const satelliteToAdd = satelliteMap.value.get(selectedId);
if (satelliteToAdd) {
manager.addOrUpdateSatellite(satelliteToAdd); // 使用 manager 的添加/更新方法
} else {
// 如果在 satelliteList 中找不到对应的卫星信息,发出警告
console.warn(`无法找到 ID 为 "${selectedId}" 的卫星信息,无法添加到地图。`);
}
}
// 2. 添加新增的选中卫星
for (const selectedId of selectedIdsSet) {
if (!currentEntityIds.has(selectedId)) {
const satelliteToAdd = satelliteMap.value.get(selectedId);
if (satelliteToAdd) {
manager.addOrUpdateSatellite(satelliteToAdd); // 使用 manager 的添加/更新方法
} else {
// 如果在 satelliteList 中找不到对应的卫星信息,发出警告
console.warn(`无法找到 ID 为 "${selectedId}" 的卫星信息,无法添加到地图。`);
}
}
}
},
{ immediate: true, deep: false }, // 立即执行一次,非深度监听
); // watch 结束
}
}); // watchEffect 结束
// 组件卸载时确保最终清理
onBeforeUnmount(() => {

View File

@ -3,7 +3,8 @@
import type { MaybeRefOrGetter } from 'vue';
import type { HCesiumManager } from './managers/HCesiumManager'; // 导入新的 Viewer Manager
import type { I站点 } from './managers/HCesiumManager.types'; // 类型定义保持不变
import type { I站点 } from './managers/HCesiumManager.types';
import type { HCesiumManagerStationState } from './useHCesiumManager.types'; // 从顶层类型文件导入
import { HCesiumStationManager } from './managers/HCesiumManager.站点'; // 导入 GroundStation Manager
@ -11,67 +12,67 @@ import { HCesiumStationManager } from './managers/HCesiumManager.站点'; // 导
* 管理 Cesium Viewer 中的地面站实体,根据选中的 ID 列表进行同步。
*/
export function useHCesiumManagerStation(
hCesiumViewerManager: MaybeRefOrGetter<HCesiumManager | null>, // 更新参数类型和名称
groundStationList: MaybeRefOrGetter<Array<I站点> | undefined>,
selectedStationIds: MaybeRefOrGetter<Set<string> | undefined>,
hCesiumViewerManager: MaybeRefOrGetter<HCesiumManager>,
state: MaybeRefOrGetter<HCesiumManagerStationState | undefined>, // 传递整个状态对象
) {
const stationManager = ref<HCesiumStationManager | null>(null);
// 创建一个从 ID 到站点选项的映射,方便查找
const stationMap = computed(() => {
const map = new Map<string, I站点>();
const list = toValue(groundStationList) ?? [];
const list = toValue(state)?.stations ?? []; // 从状态对象获取列表
for (const station of list) {
map.set(station.id, station);
}
return map;
});
// 使用 watch 显式监听依赖项
watch(
[hCesiumViewerManager, groundStationList, selectedStationIds], // 监听这些源的变化
() => {
// 回调函数
const viewerManagerInstance = toValue(hCesiumViewerManager);
// 检查 Viewer Manager 和内部 Viewer 实例是否存在
if (!viewerManagerInstance || !viewerManagerInstance.getViewer()) {
// 如果 viewer manager 或 viewer 实例尚未初始化或已销毁,则清理旧 manager 并返回
stationManager.value?.destroy();
stationManager.value = null;
return;
// 使用 watchEffect 自动追踪依赖项
watchEffect(() => {
console.group(`[useHCesiumManager.站点] 同步数据到Cesium...`);
const viewerManagerInstance = toValue(hCesiumViewerManager);
// 检查 Viewer Manager 和内部 Viewer 实例是否存在
if (!viewerManagerInstance || !viewerManagerInstance.getViewer()) {
// 如果 viewer manager 或 viewer 实例尚未初始化或已销毁,则清理旧 manager 并返回
stationManager.value?.destroy();
stationManager.value = null;
console.debug(`Viewer 实例未初始化。`);
console.groupEnd();
return;
}
console.debug(`同步前 Viewer 实体数量: ${viewerManagerInstance?.getViewer()?.entities.values.length}`);
if (!stationManager.value) {
stationManager.value = new HCesiumStationManager(viewerManagerInstance);
}
const manager = stationManager.value; // 使用 manager 实例
const selectedIdsSet = toValue(state)?.selectedIds ?? new Set<string>(); // 从状态对象获取选中 ID
const currentEntityIds = new Set(manager.getCurrentStationEntities().keys()); // 从 manager 获取当前实体 ID
// 1. 移除不再选中的站点
for (const entityId of currentEntityIds) {
if (!selectedIdsSet.has(entityId)) {
manager.removeStation(entityId); // 使用 manager 的移除方法
}
}
if (!stationManager.value) {
stationManager.value = new HCesiumStationManager(viewerManagerInstance);
}
const manager = stationManager.value; // 使用 manager 实例
const selectedIdsSet = toValue(selectedStationIds) ?? new Set<string>(); // 直接获取 Set如果为 undefined 则创建空 Set
const currentEntityIds = new Set(manager.getCurrentStationEntities().keys()); // 从 manager 获取当前实体 ID
// 1. 移除不再选中的站点
for (const entityId of currentEntityIds) {
if (!selectedIdsSet.has(entityId)) {
manager.removeStation(entityId); // 使用 manager 的移除方法
// 2. 添加新增的选中站点
for (const selectedId of selectedIdsSet) {
if (!currentEntityIds.has(selectedId)) {
const stationToAdd = stationMap.value.get(selectedId);
if (stationToAdd) {
manager.addOrUpdateStation(stationToAdd); // 使用 manager 的添加/更新方法
} else {
// 如果在 groundStationList 中找不到对应的站点信息,发出警告
console.warn(`无法找到 ID 为 "${selectedId}" 的站点信息,无法添加到地图。`);
}
}
// 2. 添加新增的选中站点
for (const selectedId of selectedIdsSet) {
if (!currentEntityIds.has(selectedId)) {
const stationToAdd = stationMap.value.get(selectedId);
if (stationToAdd) {
manager.addOrUpdateStation(stationToAdd); // 使用 manager 的添加/更新方法
} else {
// 如果在 groundStationList 中找不到对应的站点信息,发出警告
console.warn(`无法找到 ID 为 "${selectedId}" 的站点信息,无法添加到地图。`);
}
}
}
},
{ immediate: true, deep: false }, // 立即执行一次,非深度监听
); // watch 结束
}
console.groupEnd();
}); // watchEffect 结束
// 组件卸载时确保最终清理
onBeforeUnmount(() => {

View File

@ -10,11 +10,11 @@ import type {
} from '@/components/h-cesium-viewer/useHCesiumManager.types';
// 地面站和选中状态
const stationState = reactive<HCesiumManagerStationState>({
const 站点State = reactive<HCesiumManagerStationState>({
stations: [],
selectedIds: new Set<string>(),
});
stationState.stations = [
站点State.stations = [
{ height: 50, id: 'gs-bj', latitude: 39.9042, longitude: 116.4074, name: '北京站' },
{ height: 10, id: 'gs-sh', latitude: 31.2304, longitude: 121.4737, name: '上海站' },
{ height: 20, id: 'gs-gz', latitude: 23.1291, longitude: 113.2644, name: '广州站' },
@ -27,6 +27,9 @@ const satelliteState = reactive<HCesiumManagerSatelliteState>({
});
onMounted(async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
// setTimeout(() => {
// satelliteState.selectedIds = new Set([satelliteState.satellites[0].id]);
// }, 1500);
// 初始化卫星列表
satelliteState.satellites = [
{
@ -44,7 +47,7 @@ onMounted(async () => {
1 25544U 98067A 25091.51178241 .00016717 00000+0 30771-3 0 9997
2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391587775`,
showOrbit: false,
showCoverage: true,
showCoverage: false,
showPath: true,
},
{
@ -80,7 +83,7 @@ const selectedSatelliteIdsArray = computed({
// 计算 Checkbox Group 的 options
const stationCheckboxOptions = computed(() =>
stationState.stations.map((station) => ({ label: station.name, value: station.id })),
站点State.stations.map((station) => ({ label: station.name, value: station.id })),
);
// 添加一个随机站点
@ -89,7 +92,7 @@ const addRandomStation = () => {
const randomLon = Math.random() * 360 - 180; // -180 to 180
const randomLat = Math.random() * 180 - 90; // -90 to 90
const randomHeight = Math.random() * 1000; // 0 to 1000 meters
stationState.stations.push({
站点State.stations.push({
height: randomHeight,
id: randomId,
latitude: randomLat,
@ -97,37 +100,37 @@ const addRandomStation = () => {
name: `随机站 ${randomId.slice(-4)}`,
});
// 创建新的 Set 以触发响应式更新
stationState.selectedIds = new Set([randomId, ...stationState.selectedIds]); // ESLint: 调整顺序
consola.info('添加随机站点:', stationState.stations.at(-1)); // 使用 .at() 访问最后一个元素
站点State.selectedIds = new Set([randomId, ...站点State.selectedIds]); // ESLint: 调整顺序
consola.info('添加随机站点:', 站点State.stations.at(-1)); // 使用 .at() 访问最后一个元素
};
// 移除最后一个站点
const removeLastStation = () => {
if (stationState.stations.length > 0) {
const removedStation = stationState.stations.pop();
if (站点State.stations.length > 0) {
const removedStation = 站点State.stations.pop();
if (removedStation) {
consola.info('移除站点:', removedStation);
// 同时从选中项中移除
// 创建新的 Set 以触发响应式更新
const newSelectedIds = new Set(stationState.selectedIds);
const newSelectedIds = new Set(站点State.selectedIds);
newSelectedIds.delete(removedStation.id);
stationState.selectedIds = newSelectedIds;
站点State.selectedIds = newSelectedIds;
}
}
};
// 清空所有选中项
const clearAllStations = () => {
stationState.stations = [];
stationState.selectedIds = new Set(); // 创建新的空 Set 以触发响应式更新
站点State.stations = [];
站点State.selectedIds = new Set(); // 创建新的空 Set 以触发响应式更新
consola.info('清空所有站点');
};
// 为 a-checkbox-group 创建计算属性,处理 Set 和 Array 的转换
const selectedStationIdsArray = computed({
get: () => [...stationState.selectedIds], // 从 Set 转换为 Array
get: () => [...站点State.selectedIds], // 从 Set 转换为 Array
set: (val: string[]) => {
stationState.selectedIds = new Set(val); // 从 Array 转换回 Set
站点State.selectedIds = new Set(val); // 从 Array 转换回 Set
},
});
</script>
@ -139,17 +142,17 @@ const selectedStationIdsArray = computed({
<a-card title="地面站控制" size="small">
<div class="space-x-2">
<a-button size="small" type="primary" @click="addRandomStation">添加随机站点</a-button>
<a-button size="small" @click="removeLastStation" :disabled="stationState.stations.length === 0"
<a-button size="small" @click="removeLastStation" :disabled="站点State.stations.length === 0"
>移除最后一个</a-button
>
<a-button size="small" danger @click="clearAllStations" :disabled="stationState.stations.length === 0"
<a-button size="small" danger @click="clearAllStations" :disabled="站点State.stations.length === 0"
>清空所有</a-button
>
<span>当前站点数: {{ stationState.stations.length }}</span>
<span> | 选中站点数: {{ stationState.selectedIds.size }}</span>
<span>当前站点数: {{ 站点State.stations.length }}</span>
<span> | 选中站点数: {{ 站点State.selectedIds.size }}</span>
</div>
<!-- 站点选择 -->
<div mt-2 v-if="stationState.stations.length > 0">
<div mt-2 v-if="站点State.stations.length > 0">
<span class="mr-2">选择要显示的站点:</span>
<a-checkbox-group v-model:value="selectedStationIdsArray" :options="stationCheckboxOptions" />
</div>
@ -172,7 +175,7 @@ const selectedStationIdsArray = computed({
</div>
<div class="flex-grow w-full rounded-lg border overflow-hidden">
<!-- 将地面站和卫星状态都传递给组件 -->
<h-cesium-viewer :station-state="stationState" :satellite-state="satelliteState">
<h-cesium-viewer :station-state="站点State" :satellite-state="satelliteState">
<div class="absolute top-0 left-0 z-10 p-2 bg-black/30 rounded-br-lg">
<span class="text-white text-xs">叠加 UI 示例</span>
</div>