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

View File

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

View File

@ -206,12 +206,13 @@ export class HCesiumSatelliteManager {
ellipse: { ellipse: {
semiMajorAxis: coverageRadius, semiMajorAxis: coverageRadius,
semiMinorAxis: coverageRadius, semiMinorAxis: coverageRadius,
material: baseColor.withAlpha(0.2), // 半透明填充
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
outline: true,
outlineColor: baseColor.withAlpha(0.5), // 轮廓
outlineWidth: 1,
granularity: Cesium.Math.toRadians(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 { addOrUpdateStation(options: I站点): undefined {
const existingEntity = this.currentStationEntities.get(options.id); const existingEntity = this.currentStationEntities.get(options.id);

View File

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

View File

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

View File

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

View File

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