feat: 添加 Cesium Viewer 组件及相关功能,优化项目结构和配置
All checks were successful
/ build-and-deploy-to-vercel (push) Successful in 2m45s
/ lint-build-and-check (push) Successful in 4m30s
/ surge (push) Successful in 2m57s
/ playwright (push) Successful in 6m56s

This commit is contained in:
严浩
2025-03-31 19:43:52 +08:00
parent 32bc83e16e
commit 4636f9fde4
13 changed files with 387 additions and 13 deletions

1
.clinerules Symbolic link
View File

@ -0,0 +1 @@
.github/copilot-instructions.md

View File

@ -1,5 +0,0 @@
# 项目指导
## UnoCSS 使用规范
1. **优先使用 UnoCSS 原子类**,避免手写 CSS
- 例如:`text-red-500`、`p-4`、`flex items-center`。

4
.clinerules_MD Normal file
View File

@ -0,0 +1,4 @@
```bash
ln -s .github/copilot-instructions.md .clinerules
ln -s .github/copilot-instructions.md .clinerules-code
```

View File

@ -1,5 +1,50 @@
# 项目指导
# Project Conventions and Technical Guidelines
## UnoCSS 使用规范
1. **优先使用 UnoCSS 原子类**,避免手写 CSS
- 例如:`text-red-500``p-4``flex items-center`
This document outlines the core technical choices, coding conventions, and configuration details for this project. Adhering to these guidelines ensures consistency and leverages the project's setup effectively.
## 🚀 Core Technologies & Conventions
* **Framework:** Vue 3
* **Language:** TypeScript
* **API Style:** **Strictly use the Composition API with `<script setup>` syntax.** The Options API and the standard `<script>` block with the `setup()` function are **not** used in this project.
* **Single File Component (SFC) Structure:** Follow this order within `.vue` files:
1. `<script setup lang="ts">` (Imports, logic, composables, etc.)
2. `<template>` (HTML structure)
3. `<style>` (Preferably `<style scoped>`)
* **Code Comments:** All comments within the codebase **must be written in Chinese**. (代码中的所有注释**必须使用中文**。)
## 📦 UI Libraries & Components
* **UI Libraries:** This project utilizes both **Ant Design Vue** and **PrimeVue**.
* **Component Auto-Import:** Components from Ant Design Vue, PrimeVue, and those defined in `src/components/**/*.vue` (excluding filenames starting with `__`) are **automatically imported** via `unplugin-vue-components`.
* **Ant Design Vue:** Use components directly (e.g., `<a-button>`, `<a-table>`). Icons are also resolved (e.g., `<UserOutlined />`). CSS-in-JS is used; no manual style import is needed.
* **PrimeVue:** Use components directly with their standard names (e.g., `<Button>`, `<InputText>`, `<DataTable>`).
* **Custom Components:** Local components (e.g., `<MyCustomComponent />` defined in `src/components/MyCustomComponent.vue`) should be used directly in templates without explicit imports in `<script setup>`.
* **Custom Icons:** Custom SVG icons are available via `unplugin-icons` with the prefix `icon-`. Usage: `<icon-your-svg-file-name />`.
## ✨ API Auto-Import (unplugin-auto-import)
* **Automatic API Availability:** This project leverages `unplugin-auto-import` extensively. APIs from the following libraries/modules are globally available and **SHOULD NOT be explicitly imported** in `<script setup>` blocks unless necessary for specific type augmentation or rare cases:
* `vue` (e.g., `ref`, `computed`, `watch`, `onMounted`, `defineProps`, `defineEmits`, etc.)
* `pinia` (e.g., `defineStore`, `storeToRefs`)
* `vue-router/auto` (e.g., `useRouter`, `useRoute`, `useLink`) - Provided by `unplugin-vue-router` integration.
* `@vueuse/core` (Common utility functions)
* `vue-i18n` (e.g., `useI18n`)
* `consola/browser` (Available as the `consola` global for logging)
* **Auto-Imported Directories:** All exports from files within `src/stores/**` and `src/utils/**` are also auto-imported globally. Functions, variables, or stores defined and exported in these directories can be used directly without explicit import statements.
* **Template Usage:** Auto-import functionality also applies within the `<template>` block where appropriate (e.g., accessing store state or using certain utility functions directly).
* **Important:** Rely on the auto-import mechanism for the specified libraries and directories. Explicitly importing these APIs clutters the code unnecessarily.
## ✅ Summary of Key Rules & Conventions
* **Always** use `<script setup lang="ts">`.
* Composition API is the **only** accepted style.
* Code comments **must be in Chinese**.
* Vue 3 Composition API, Pinia, Vue Router (auto), VueUse functions, `consola`, and exports from `src/stores` & `src/utils` are globally available via auto-import; **do not** import them explicitly.
* Ant Design Vue, PrimeVue, and local `src/components` components are auto-imported; use them directly in templates without explicit imports.
* Use custom SVG icons via the `<icon-name />` syntax.
* Maintain the specified SFC structure: `<script setup>`, `<template>`, `<style>`.
---
*(Further details regarding state management patterns, routing configuration, specific linting rules, testing setup, or detailed coding style guides can be added to this document as needed.)*

View File

@ -2,12 +2,15 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit",
"source.fixAll.stylelint": "explicit",
"source.organizeImports": "never",
"source.fixAll.oxc": "explicit"
"source.fixAll.oxc": "explicit",
// "source.fixAll.eslint": "never",
// "source.fixAll.stylelint": "never",
// "source.fixAll.oxc": "never",
"source.organizeImports": "never"
},
"editor.formatOnSave": true,
// "editor.formatOnSaveMode": "modificationsIfAvailable", // 只格式化修改的部分
"editor.formatOnSaveMode": "file", // 格式化修改的部分
"editor.formatOnSaveMode": "file", // 格式化整个文件
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},

View File

@ -101,6 +101,8 @@ export default defineConfigWithVueTs(
perfectionist.configs['recommended-natural'],
{
rules: {
'perfectionist/sort-classes': 'off',
'perfectionist/sort-objects': 'off',
'perfectionist/sort-imports': ['error'],
},
},

View File

@ -0,0 +1,33 @@
import type { Viewer } from 'cesium';
import * as Cesium from 'cesium';
export const VIEWER_OPTIONS_FN = (): Viewer.ConstructorOptions => {
return {
animation: true, // .cesium-viewer-animationContainer https://cesium.com/learn/ion-sdk/ref-doc/Animation.html
baseLayer: Cesium.ImageryLayer.fromProviderAsync(
Cesium.TileMapServiceImageryProvider.fromUrl(Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII')),
),
baseLayerPicker: false,
fullscreenButton: !true, // 全屏按钮
geocoder: false, // = IonGeocodeProviderType.DEFAULT] - 在使用Geocoder小部件进行搜索时使用的地理编码服务或服务。如果设置为false则不会创建Geocoder小部件。
// globe: false, // 地球
homeButton: true, // Home按钮
infoBox: false, // InfoBox小部件。
navigationHelpButton: false, // 是否显示导航帮助按钮
orderIndependentTranslucency: false, // 顺序无关透明度
projectionPicker: !true, // 投影选择器
requestRenderMode: !true, // 如果为真渲染帧将仅在场景内部发生变化时需要时发生。启用此功能可以减少应用程序的CPU/GPU使用率并在移动设备上节省更多电量但在此模式下需要使用{@link Scene#requestRender}显式渲染新帧。在API的其他部分对场景进行更改后在许多情况下都需要这样做。请参阅{@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|使用显式渲染提高性能}。
sceneModePicker: true, // 是否显示场景模式选择器(2D/3D切换)
selectionIndicator: true,
shadows: true, // Determines if shadows are cast by light sources.
/* animationContainer: !true, */
/* timelineContainer: true, */
/* bottomContainer: document.createElement('p'), // The DOM element or ID that will contain the bottomContainer. If not specified, the bottomContainer is added to the widget itself. */
shouldAnimate: !true,
showRenderLoopErrors: true, // 如果为真当发生渲染循环错误时此小部件将自动向用户显示包含错误的HTML面板。
timeline: true,
};
};

View File

@ -0,0 +1,100 @@
import * as Cesium from 'cesium';
import { VIEWER_OPTIONS_FN } from './VIEWER_OPTIONS';
export interface GroundStationOptions {
// 调整顺序以符合 ESLint 规则
color?: Cesium.Color; // 点的可选颜色
height?: number; // 可选高度默认为0
id: string; // 站点的唯一标识符
latitude: number;
longitude: number;
name: string;
pixelSize?: number; // 点的可选像素大小
}
export class HCesiumViewerCls {
viewer: Cesium.Viewer | null = null;
/**
* 初始化 Cesium Viewer
* @param container - 用于承载 Cesium Viewer 的 DOM 元素或其 ID
*/
initCesiumViewer(container: ConstructorParameters<typeof Cesium.Viewer>[0]) {
this.viewer = new Cesium.Viewer(container, VIEWER_OPTIONS_FN());
}
/**
* 向视图中添加地面站实体
* @param options - 地面站的选项参数
* @returns 添加的实体对象,如果视图未初始化则返回 undefined
*/
addGroundStation(options: GroundStationOptions): Cesium.Entity | undefined {
if (!this.viewer) {
console.error('视图未初始化。请先调用 initCesiumViewer 方法。');
return;
}
const {
// 调整解构赋值顺序
// color = Cesium.Color.RED, // 默认颜色 - 已移除,将使用随机颜色
height = 0, // 如果未提供默认高度为0
id, // 获取 id
latitude,
longitude,
name,
pixelSize = 10, // 默认像素大小
} = options;
const position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
// 生成随机颜色
const randomColor = Cesium.Color.fromRandom();
const groundStationEntity = new Cesium.Entity({
// 使用传入的 id 作为实体的唯一标识符
id: id,
label: {
font: '14pt sans-serif',
outlineWidth: 2,
pixelOffset: new Cesium.Cartesian2(0, -12), // 标签略微偏移到点的上方
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
text: name,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
},
name: name,
point: {
color: randomColor, // 使用随机颜色
outlineColor: Cesium.Color.WHITE,
outlineWidth: 2,
pixelSize,
},
position: position,
});
return this.viewer.entities.add(groundStationEntity);
}
/**
* 从视图中移除指定的地面站实体
* @param entity - 要移除的地面站实体对象 (由 addGroundStation 返回)
* @returns 如果成功移除则返回 true否则返回 false
*/
removeGroundStation(entity: Cesium.Entity): boolean {
if (!this.viewer) {
console.error('视图未初始化。无法移除地面站。');
return false;
}
return this.viewer.entities.remove(entity);
}
/**
* 销毁 Cesium Viewer 实例并清理资源
*/
destroy() {
if (this.viewer) {
this.viewer.destroy();
this.viewer = null;
}
}
}

View File

@ -0,0 +1,122 @@
<script setup lang="ts">
import 'cesium/Build/Cesium/Widgets/widgets.css';
import * as Cesium from 'cesium'; // 引入 Cesium 类型
import { type GroundStationOptions, HCesiumViewerCls } from './h-cesium-viewer-class';
// 根据项目规则vue, pinia, vue-router/auto, @vueuse/core, vue-i18n, consola/browser, src/stores, src/utils
// 的 API 是自动导入的,因此不需要显式 import { watchEffect, ref, onMounted, onBeforeUnmount, defineProps } from 'vue';
// defineProps, ref, watchEffect, onMounted, onBeforeUnmount, consola 应该可以直接使用
const props = defineProps<{
groundStationList?: Array<GroundStationOptions>;
}>();
const hCesiumViewer = new HCesiumViewerCls();
// Object.assign(globalThis, { hCesiumViewer }); // 考虑移除或替换为更标准的 Vue 依赖注入或 provide/inject
// 使用 Map 存储当前显示的站点实体,键为站点唯一标识符,值为 Cesium.Entity
// 使用 ref 包裹 Map 以便在 watchEffect 中正确跟踪其变化
const currentStationEntities = ref<Map<string, Cesium.Entity>>(new Map());
// 移除 getStationKey 函数,将使用 station.id 作为唯一标识符
onMounted(() => {
hCesiumViewer.initCesiumViewer('cesiumContainer');
// 使用 watchEffect 监听 props.groundStationList 的变化并同步 Cesium 实体
watchEffect(() => {
// 确保 viewer 已经初始化
if (!hCesiumViewer.viewer) {
consola.warn('Cesium Viewer 尚未初始化,无法更新地面站。');
// 清理可能存在的旧实体引用(以防万一 viewer 初始化延迟)
// 使用 for...of 替换 forEach
for (const entity of currentStationEntities.value.values()) {
hCesiumViewer.removeGroundStation(entity);
}
currentStationEntities.value.clear();
return;
}
const newStations = props.groundStationList ?? []; // 处理 props 可能为 undefined 的情况,默认为空数组
const newStationKeys = new Set(newStations.map((station) => station.id)); // 使用 station.id 作为键
const currentKeys = new Set(currentStationEntities.value.keys()); // 当前 Cesium 中所有站点的键集合
// 1. 移除不再存在于新列表中的站点
// 遍历当前 Cesium 中的站点键
// 使用 for...of 替换 forEach
for (const key of currentKeys) {
// 如果当前键不在新列表的键集合中,则说明该站点需要被移除
if (!newStationKeys.has(key)) {
const entityToRemove = currentStationEntities.value.get(key);
if (entityToRemove) {
// consola.debug(`移除地面站: ${key}`); // 调试日志:输出移除信息
hCesiumViewer.removeGroundStation(entityToRemove); // 从 Cesium 中移除实体
currentStationEntities.value.delete(key); // 从内部 Map 中移除引用
}
}
}
// 2. 添加新列表中的、当前尚未显示的站点
// 遍历新列表中的站点
// 使用 for...of 替换 forEach
for (const station of newStations) {
const key = station.id; // 使用 station.id 作为键
// 如果新站点的键不在当前 Cesium 的键集合中,则说明该站点是新增的
if (!currentKeys.has(key)) {
// consola.debug(`添加地面站: ${key}`); // 调试日志:输出添加信息
const newEntity = hCesiumViewer.addGroundStation(station); // 向 Cesium 添加实体
if (newEntity) {
currentStationEntities.value.set(key, newEntity); // 将新实体的引用添加到内部 Map
} else {
// 如果添加失败(例如 viewer 问题),记录错误
consola.error(`添加地面站失败: ${key}`);
}
}
// 注意:此逻辑仅处理添加和移除。如果需要更新现有站点的属性(如颜色、大小等),
// 则需要在此处添加额外的比较和更新逻辑。
// 例如:找到已存在的实体,比较 props 中的属性与实体当前属性,如有不同则调用相应方法更新实体。
}
});
});
onBeforeUnmount(() => {
// 组件卸载前,清理所有由该组件添加的地面站实体
if (hCesiumViewer.viewer) {
// consola.debug('组件卸载,清理所有地面站...'); // 调试日志
// 使用 for...of 替换 forEach
for (const entity of currentStationEntities.value.values()) {
// 确保 viewer 仍然存在,避免在销毁过程中出错
if (hCesiumViewer.viewer && hCesiumViewer.viewer.entities) {
hCesiumViewer.removeGroundStation(entity);
}
}
}
currentStationEntities.value.clear(); // 清空内部 Map
// 销毁 Cesium Viewer 实例,释放资源
hCesiumViewer.destroy();
// consola.debug('Cesium Viewer 已销毁。'); // 调试日志
});
</script>
<template>
<div id="cesiumContainer" class="h-full w-full relative inset-0 isolate">
<!-- 插槽允许父组件在 Cesium Viewer 上层叠加 UI 元素 -->
<slot />
</div>
</template>
<style scoped>
/* 为 Cesium 容器提供基本样式,确保其可见 */
#cesiumContainer {
min-height: 300px; /* 示例:设置一个最小高度,防止容器塌陷 */
background-color: #000; /* 可以设置一个背景色,直到 Cesium 加载完成 */
}
/* 确保 Cesium 的 canvas 填满容器 */
:deep(.cesium-widget),
:deep(.cesium-widget canvas) {
width: 100%;
height: 100%;
touch-action: none;
}
</style>

View File

@ -1,4 +1,4 @@
/* eslint-disable perfectionist/sort-objects */
/* prettier-ignore */
export const TOOLTIP_MAP = {
NORAD_CAT_ID_卫星编号: "5位数字如'63158'表示NORAD卫星唯一目录编号",

View File

@ -0,0 +1,67 @@
<route lang="yaml">
meta:
layout: false
</route>
<script setup lang="ts">
import type { GroundStationOptions } from '@/components/h-cesium-viewer/h-cesium-viewer-class';
// 定义地面站列表的响应式引用
const groundStations = ref<GroundStationOptions[]>([
{ 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: '广州站' },
]);
// 添加一个随机站点
const addRandomStation = () => {
const randomId = `gs-random-${Math.random().toString(36).slice(7)}`; // 使用 slice 替换 substring
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
groundStations.value.push({
// 调整属性顺序
height: randomHeight,
id: randomId,
latitude: randomLat,
longitude: randomLon,
name: `随机站 ${randomId.slice(-4)}`,
});
consola.info('添加随机站点:', groundStations.value.at(-1)); // 使用 .at() 访问最后一个元素
};
// 移除最后一个站点
const removeLastStation = () => {
if (groundStations.value.length > 0) {
const removed = groundStations.value.pop();
consola.info('移除站点:', removed);
} else {
consola.warn('没有站点可以移除');
}
};
// 清空所有站点
const clearAllStations = () => {
groundStations.value = [];
consola.info('已清空所有站点');
};
</script>
<template>
<div class="h-screen w-screen p-4 flex flex-col">
<div class="flex-shrink-0 mb-2 space-x-2">
<a-button type="primary" @click="addRandomStation">添加随机站点</a-button>
<a-button @click="removeLastStation" :disabled="groundStations.length === 0">移除最后一个</a-button>
<a-button danger @click="clearAllStations" :disabled="groundStations.length === 0">清空所有</a-button>
<span>当前站点数: {{ groundStations.length }}</span>
</div>
<div class="flex-grow w-full rounded-lg border overflow-hidden">
<!-- 将响应式列表绑定到 prop -->
<h-cesium-viewer :ground-station-list="groundStations">
<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>
</h-cesium-viewer>
</div>
</div>
</template>

View File

@ -11,6 +11,7 @@
],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"allowJs": true, // 允许编译 JavaScript 文件
"checkJs": true, // 启用 JavaScript 文件的类型检查

1
typed-router.d.ts vendored
View File

@ -20,6 +20,7 @@ declare module 'vue-router/auto-routes' {
export interface RouteNamedMap {
'Root': RouteRecordInfo<'Root', '/', Record<never, never>, Record<never, never>>,
'$Path': RouteRecordInfo<'$Path', '/:path(.*)', { path: ParamValue<true> }, { path: ParamValue<false> }>,
'CesiumViewer': RouteRecordInfo<'CesiumViewer', '/cesium-viewer', Record<never, never>, Record<never, never>>,
'DataLoadersId': RouteRecordInfo<'DataLoadersId', '/data-loaders/:id', { id: ParamValue<true> }, { id: ParamValue<false> }>,
'DataLoadersIdSub1UserId': RouteRecordInfo<'DataLoadersIdSub1UserId', '/data-loaders/:id/sub-1/:userId', { id: ParamValue<true>, userId: ParamValue<true> }, { id: ParamValue<false>, userId: ParamValue<false> }>,
'FlowbiteSidebar': RouteRecordInfo<'FlowbiteSidebar', '/FlowbiteSidebar', Record<never, never>, Record<never, never>>,