feat: 支持班级灵动岛云端配置与跨端同步
This commit is contained in:
1 parent
4449fbd0a1
commit
f6dd59aa25
40 files changed
+1208
-719
No files matched your search
+12
-9
@@ -5,8 +5,9 @@ description: 经典提醒、自定义常驻方案、课程与课件传输。
|
||||
|
||||
# 灵动岛
|
||||
|
||||
灵动岛是客户端的独立透明窗口,不占任务栏。设置中可选择经典 fixed 或自定义 custom,默认 fixed。
|
||||
自定义当前即常驻模式;旧 residentEnabled 字段只作兼容,不是另一个独立开关。
|
||||
灵动岛是客户端的独立透明窗口,不占任务栏。每个班的岛内方案由 Web 管理端「班级灵动岛」维护,
|
||||
教室端登录本班后自动同步;未配置的班使用经典 fixed,默认 fixed。自定义当前即常驻模式;
|
||||
旧 residentEnabled 字段只作兼容,不是另一个独立开关。
|
||||
两种布局共用一个原生窗口,切布局不会新开第二个岛。
|
||||
|
||||
## 两种消息展示
|
||||
@@ -33,19 +34,21 @@ description: 经典提醒、自定义常驻方案、课程与课件传输。
|
||||
| 展开详情 |  |
|
||||
| 紧急通知 |  |
|
||||
|
||||
## 编辑自定义方案
|
||||
## 在 Web 管理端编辑班级方案
|
||||
|
||||
“设置 → 灵动岛 → 自定义 → 编辑岛内组件”进入主窗口设置页。
|
||||
Web 管理端打开「班级与人员 → 班级灵动岛」,先选择班级,再编辑这个班独立的方案。
|
||||
页面上方排列当前组件,右上角选择配置方案;刷新图标重置当前方案,加号新建方案,文件夹菜单提供方案设置、复制、删除及 JSON 导入导出。
|
||||
下方组件库常驻显示文本、分割线、课程表、日期、时钟、天气简报、倒计时和组合容器。通知、作业和叫人通过岛内铃铛及共用消息面板展示,组件库不再提供这些消息选项;已有方案中的消息节点仍兼容。
|
||||
从组件库拖入上方的行或容器以添加,拖动已有组件调整顺序或跨行移动;也可点击组件库添加到选中的容器或当前行。
|
||||
分别编辑常态 rows 与无消息展开 expandedRows,点选组件打开内容、外观、尺寸与隐藏条件设置;行可以新增、排序、设为主要行或删除。
|
||||
“进入编辑模式”切换为实际内容预览,支持预览缩放;退出后回到组件标签排列。轮播和滚动容器在编辑时展示全部子组件,便于选择和排列。
|
||||
“预览组件外观”展示接近教室端的最终岛体,支持预览缩放;常态行固定 40px 高并保持水平、垂直居中。
|
||||
返回结构排列后继续拖拽。轮播和滚动容器在结构排列中展示全部子组件,便于选择和排列。
|
||||
倒计时可指定目标名称与日期,也可按课表倒数至上课、下课或放学。
|
||||
天气简报需填写地点名称及经纬度,使用 [Open-Meteo](https://open-meteo.com/en/docs) 的天气数据,每 15 分钟更新;断网时保留本次客户端运行中的缓存并标明“缓存”。天气提示根据天气概况生成,不提供官方气象预警。
|
||||
方案保存到本机 config.json.islandLayout,不增加服务端同步。
|
||||
编辑预览不创建额外桌面窗口;打开编辑页不自动切布局,应用后启用自定义方案。
|
||||
保存按序进行,失败可重试,主题与关怀模式沿用客户端设置。
|
||||
方案保存到班级记录,仅本班班主任或管理员可写;班级账号和教室客户端只读本班方案。
|
||||
保存后服务端广播 `class:updated`,客户端立即拉取;断线时保留本机上一次已同步方案。
|
||||
客户端设置页不再提供岛内组件编辑入口,只展示当前是否使用服务端下发方案。
|
||||
提醒阈值与指针避让仍按教室本机偏好保存,不随班级布局覆盖。
|
||||
|
||||
## 外观、位置与输入
|
||||
|
||||
@@ -54,7 +57,7 @@ description: 经典提醒、自定义常驻方案、课程与课件传输。
|
||||
强调色支持自定义、壁纸调色板、跟随系统和屏幕调色板四种来源;自定义背景与前景可分别关闭,关闭后回落当前亮/暗主题。前景色会派生 100% / 85.5% / 77.3% / 52.9% / 36.5% 五级文字 alpha。外观页的圆角滑块同步修改当前自定义方案的常态圆角,与编辑器设置一致。
|
||||
左右边距只在左/右停靠时生效,居中锚点仍在屏幕中线。
|
||||
触摸屏自动进入触摸模式,保留触摸命中和失焦宽限;鼠标模式按光标控制输入穿透。
|
||||
自定义常驻内容支持鼠标避让淡化及反转,交互入口、展开/编辑和触摸操作按实现暂停避让。
|
||||
自定义常驻内容支持鼠标避让淡化及反转,交互入口、展开和触摸操作按实现暂停避让。
|
||||
应用内动画开关决定岛动画,不能用主窗口的减少动态效果说明替代岛自身规则。
|
||||
|
||||
经典几何与配色参考见[设计令牌](../dev/winisland-design-tokens.md),实现入口见[当前实现约定](../dev/implementation.md)。
|
||||
|
||||
+13
-12
@@ -12,18 +12,19 @@ API 前缀 /api,JWT 使用 Authorization: Bearer。成功/失败结构以 `lib
|
||||
|
||||
## 身份与班级
|
||||
|
||||
| 方法与路径(省略 /api) | 行为及边界 |
|
||||
| ----------------------------------------------------------------------- | -------------------------------------------------------------- |
|
||||
| POST /auth/login、/auth/class-login | 员工/班级登录,共享登录限流;学生无账号 |
|
||||
| GET /auth/me;POST /auth/logout;PATCH /auth/password | 当前身份、退出、员工本人改密码 |
|
||||
| GET/POST /classes;GET/PATCH/DELETE /classes/:id | 班级查询/管理,读取 class:read;写入 class:manage 且仅管理员 |
|
||||
| PATCH /classes/:id/class-account、/classes/:id/head-teacher | 班级凭据 class:account + 班主任;班主任分配仅管理员 |
|
||||
| PUT /classes/:id/subject-teachers | 任课关系设置,Course 为唯一来源 |
|
||||
| GET/PATCH /classes/:id/student-grade-query | 查看/修改班级个人成绩查询开关,班级端不能修改 |
|
||||
| GET/POST /classes/:id/students;DELETE /classes/:id/students/:studentId | 本班名单及维护,受名单功能权限和班级关系约束 |
|
||||
| /students、/teachers | 名单与账号 CRUD;读/写使用不同权限键,具体角色限制读取对应模块 |
|
||||
| POST /teachers/:id/reset-password | 指定新密码或默认重置;学生无对应接口 |
|
||||
| /permissions/me、/catalog、/groups、/users | 当前有效权限、目录、组与账号分组 |
|
||||
| 方法与路径(省略 /api) | 行为及边界 |
|
||||
| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
||||
| POST /auth/login、/auth/class-login | 员工/班级登录,共享登录限流;学生无账号 |
|
||||
| GET /auth/me;POST /auth/logout;PATCH /auth/password | 当前身份、退出、员工本人改密码 |
|
||||
| GET/POST /classes;GET/PATCH/DELETE /classes/:id | 班级查询/管理,读取 class:read;写入 class:manage 且仅管理员 |
|
||||
| PATCH /classes/:id/class-account、/classes/:id/head-teacher | 班级凭据 class:account + 班主任;班主任分配仅管理员 |
|
||||
| PUT /classes/:id/subject-teachers | 任课关系设置,Course 为唯一来源 |
|
||||
| GET/PATCH /classes/:id/student-grade-query | 查看/修改班级个人成绩查询开关,班级端不能修改 |
|
||||
| GET/PATCH /classes/:id/island-layout | 班级灵动岛方案;读取 class:read,写入 class:settings + 班主任,班级端只读本班 |
|
||||
| GET/POST /classes/:id/students;DELETE /classes/:id/students/:studentId | 本班名单及维护,受名单功能权限和班级关系约束 |
|
||||
| /students、/teachers | 名单与账号 CRUD;读/写使用不同权限键,具体角色限制读取对应模块 |
|
||||
| POST /teachers/:id/reset-password | 指定新密码或默认重置;学生无对应接口 |
|
||||
| /permissions/me、/catalog、/groups、/users | 当前有效权限、目录、组与账号分组 |
|
||||
|
||||
## 教学与文件
|
||||
|
||||
|
||||
@@ -24,11 +24,16 @@ description: 课表、周次、学年、岛、设备与课件的现行实现入
|
||||
年度升级由 `term.promotionPlan`、`term.promotionAt` 和 `PromotionRun.year` 管理,先存快照;运行期到点执行,启动漏跑需管理员预览补跑。
|
||||
毕业班归档,其余升一级,新班不复制任课关系。转出学生由 `lib/students.ts` 统一过滤。
|
||||
|
||||
## 岛与本机配置
|
||||
## 岛、班级方案与本机配置
|
||||
|
||||
方案存 `config.json.islandLayout`,默认 fixed。当前 custom 即常驻,归一化将兼容字段 residentEnabled 与 custom 对齐。
|
||||
每个班的方案存 `Class.islandLayoutJson`,默认未配置时回落本机 `config.json.islandLayout` 的 fixed。
|
||||
Web 管理端「班级灵动岛」用 `class:read` 读取、`class:settings` + 班主任关系写入;班级端只能读本班。
|
||||
保存后广播 `class:updated`,客户端按登录班级拉取并写入本机配置,供离线启动沿用。
|
||||
客户端合并服务端方案时保留本机提醒阈值与指针避让;未配置的班回退经典 default,避免沿用上一个班。
|
||||
当前 custom 即常驻,归一化将兼容字段 residentEnabled 与 custom 对齐。
|
||||
`LayoutIslandApp.vue` 选择经典 `IslandApp.vue` 或 `CustomIslandRuntime.vue`,只有一个原生岛窗口。
|
||||
自定义常态行与无消息展开行独立编辑,通知列表复用 `ClassicNotifications.vue`;编辑页是主窗口设置子路由。
|
||||
自定义常态行与无消息展开行独立编辑,通知列表复用 `ClassicNotifications.vue`;
|
||||
编辑器和预览在 Web 管理端,教室客户端不再注册布局编辑路由。
|
||||
自定义模式通过铃铛提示新消息,点击查看;经典模式普通通知上课暂存、普通叫人可点开胶囊、紧急消息自动展开。
|
||||
课程提醒配置独立保存,课件传输期间由 `CoursewareTransfer.vue` 显示进度。
|
||||
|
||||
|
||||
@@ -74,15 +74,15 @@ ClassIsland 源值中的颜色采用 Avalonia `AARRGGBB`,写入 CSS 时统一
|
||||
|
||||
### 主界面对照
|
||||
|
||||
| ClassIsland 概念 | ClassHelper 实体 |
|
||||
| ----------------------- | ------------------------------------------------------------------ |
|
||||
| MainWindow | 独立 `island.html` + 主进程透明 `BrowserWindow` |
|
||||
| MainWindowLine | `CustomIslandRuntime.vue` 的 `.layout-row` 与行级 CSS 变量 |
|
||||
| ComponentPresenter | `ComponentNode.vue` 根节点的宽高、透明度、隐藏与裁剪 |
|
||||
| 日期/时钟/天气/课程组件 | `ComponentNode.vue`、`WeatherBrief.vue` 等共享组件 |
|
||||
| Fluent/Classic 主题 | `custom-runtime.css` / `custom-island.css` / `classic-island.css` |
|
||||
| 编辑模式视图 | 主窗口 `IslandEditorView.vue`、`IslandEditorNode.vue` 与右侧检查器 |
|
||||
| 提醒宿主 | `ClassicNotifications.vue`,嵌入自定义岛或经典岛 |
|
||||
| ClassIsland 概念 | ClassHelper 实体 |
|
||||
| ----------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| MainWindow | 独立 `island.html` + 主进程透明 `BrowserWindow` |
|
||||
| MainWindowLine | `CustomIslandRuntime.vue` 的 `.layout-row` 与行级 CSS 变量 |
|
||||
| ComponentPresenter | `ComponentNode.vue` 根节点的宽高、透明度、隐藏与裁剪 |
|
||||
| 日期/时钟/天气/课程组件 | `ComponentNode.vue`、`WeatherBrief.vue` 等共享组件 |
|
||||
| Fluent/Classic 主题 | `custom-runtime.css` / `custom-island.css` / `classic-island.css` |
|
||||
| 编辑与预览视图 | Web 管理端 `IslandLayoutsView.vue`、`IslandEditorNode.vue`、`IslandPreviewNode.vue` 与右侧检查器 |
|
||||
| 提醒宿主 | `ClassicNotifications.vue`,嵌入自定义岛或经典岛 |
|
||||
|
||||
## 动画与命中
|
||||
|
||||
@@ -98,6 +98,6 @@ ClassIsland 源值中的颜色采用 Avalonia `AARRGGBB`,写入 CSS 时统一
|
||||
## 修改入口
|
||||
|
||||
外观范围改 shared,经典样式改 classic-island.css,自定义样式改 custom-runtime.css 和 custom-island.css,
|
||||
原生窗口与命中改 main/island.ts。组件结构/设置改 shared/island-layout.ts 并同步编辑器和运行时。
|
||||
原生窗口与命中改 main/island.ts。组件结构/设置改 shared/island-layout.ts 并同步 Web 编辑器和运行时。
|
||||
改 token 后运行 `pnpm check:design-tokens`,它会校验亮/暗键集合、必备 token、kebab-case 与岛内裸颜色。
|
||||
展示行为见[灵动岛](../app/island.md),测试见[验收与测试](testing.md)。
|
||||
+19
-19
@@ -8,25 +8,25 @@ description: 当前功能说明、开发契约与实现入口,避免重复维
|
||||
本文为现行文档入口。功能规则在对应章节维护;源码行为发生变化时,同步修改对应章节。
|
||||
旧任务书、历史审查结论和旧构建验收数字不作为当前功能依据。
|
||||
|
||||
| 主题 | 文档 | 工作区源码入口 |
|
||||
| ------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
|
||||
| 架构与模块 | [架构总览](dev/architecture.md) | `server/src/modules/registry.ts` |
|
||||
| 日课表、作息与轮换 | [课表](app/schedules.md) | `server/src/lib/class-plan.ts`、`modules/class-plans/` |
|
||||
| 学生、教师、班级 | [班级、学生与教师](app/classes.md) | `server/src/lib/access.ts`、`modules/students/` |
|
||||
| 权限组与岗位范围 | [角色与权限](dev/permissions.md) | `shared/src/permissions.ts`、`server/src/lib/authz/`、`server/src/lib/permissions.ts` |
|
||||
| 作业 | [作业](app/homeworks.md) | `server/src/modules/homeworks/` |
|
||||
| AI 助手 | [解析与确认发布](app/assistant.md) | `server/src/modules/ai/`、`web-admin/src/views/AssistantView.vue` |
|
||||
| 通知与叫人 | [通知](app/notifications.md)、[叫人](app/calls.md) | `server/src/modules/notifications/`、`calls/` |
|
||||
| 课件 | [课件上传与传输](app/courseware.md) | 三端 `courseware` 模块与 `shared/src/courseware.ts` |
|
||||
| 成绩与隐私 | [成绩](app/grades.md) | `server/src/modules/grades/` |
|
||||
| 经典与自定义常驻岛 | [灵动岛](app/island.md) | `desktop-client/src/island/LayoutIslandApp.vue`、`CustomIslandRuntime.vue` |
|
||||
| 导入 | [表格与课表导入](app/imports.md) | `server/src/modules/imports/`、`class-plans/profile-import.service.ts` |
|
||||
| API 与实时 | [REST API](dev/api.md)、[实时事件](dev/realtime.md) | `server/src/modules/`、`realtime/`、`shared/src/constants.ts` |
|
||||
| 数据模型与迁移 | [数据模型](dev/data-model.md) | `server/prisma/schema.prisma`、`migrations/` |
|
||||
| 数据库管理 | [数据库管理](management/database.md)、[MySQL](management/mysql.md) | `server/src/lib/snapshot.ts`、`modules/database/` |
|
||||
| 安装与升级 | [生产部署](management/production.md)、[Linux](management/linux-deploy.md)、[更新](management/upgrade.md) | `deploy/`、`scripts/dist-server.mjs` |
|
||||
| 验证与发布 | [验收](dev/testing.md)、[发布](dev/release.md) | 根 `package.json`、`scripts/`、`.github/workflows/` |
|
||||
| 当前实现约定 | [实现约定](dev/implementation.md) | 课表、升级、岛、课件与设备维护的关键边界 |
|
||||
| 主题 | 文档 | 工作区源码入口 |
|
||||
| ------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
||||
| 架构与模块 | [架构总览](dev/architecture.md) | `server/src/modules/registry.ts` |
|
||||
| 日课表、作息与轮换 | [课表](app/schedules.md) | `server/src/lib/class-plan.ts`、`modules/class-plans/` |
|
||||
| 学生、教师、班级 | [班级、学生与教师](app/classes.md) | `server/src/lib/access.ts`、`modules/students/` |
|
||||
| 权限组与岗位范围 | [角色与权限](dev/permissions.md) | `shared/src/permissions.ts`、`server/src/lib/authz/`、`server/src/lib/permissions.ts` |
|
||||
| 作业 | [作业](app/homeworks.md) | `server/src/modules/homeworks/` |
|
||||
| AI 助手 | [解析与确认发布](app/assistant.md) | `server/src/modules/ai/`、`web-admin/src/views/AssistantView.vue` |
|
||||
| 通知与叫人 | [通知](app/notifications.md)、[叫人](app/calls.md) | `server/src/modules/notifications/`、`calls/` |
|
||||
| 课件 | [课件上传与传输](app/courseware.md) | 三端 `courseware` 模块与 `shared/src/courseware.ts` |
|
||||
| 成绩与隐私 | [成绩](app/grades.md) | `server/src/modules/grades/` |
|
||||
| 经典与自定义常驻岛 | [灵动岛](app/island.md) | `desktop-client/src/island/LayoutIslandApp.vue`、`CustomIslandRuntime.vue`;Web `IslandLayoutsView.vue` |
|
||||
| 导入 | [表格与课表导入](app/imports.md) | `server/src/modules/imports/`、`class-plans/profile-import.service.ts` |
|
||||
| API 与实时 | [REST API](dev/api.md)、[实时事件](dev/realtime.md) | `server/src/modules/`、`realtime/`、`shared/src/constants.ts` |
|
||||
| 数据模型与迁移 | [数据模型](dev/data-model.md) | `server/prisma/schema.prisma`、`migrations/` |
|
||||
| 数据库管理 | [数据库管理](management/database.md)、[MySQL](management/mysql.md) | `server/src/lib/snapshot.ts`、`modules/database/` |
|
||||
| 安装与升级 | [生产部署](management/production.md)、[Linux](management/linux-deploy.md)、[更新](management/upgrade.md) | `deploy/`、`scripts/dist-server.mjs` |
|
||||
| 验证与发布 | [验收](dev/testing.md)、[发布](dev/release.md) | 根 `package.json`、`scripts/`、`.github/workflows/` |
|
||||
| 当前实现约定 | [实现约定](dev/implementation.md) | 课表、升级、岛、课件与设备维护的关键边界 |
|
||||
|
||||
表中的包路径均相对仓库 `packages/`;脚本和部署目录相对仓库根。
|
||||
源码总入口:[GitHub 仓库](https://github.com/LoveChengke/ClassHelper)。
|
||||
|
||||
@@ -136,11 +136,19 @@
|
||||
justify-content: center;
|
||||
min-width: 0;
|
||||
}
|
||||
.resident-card .layout-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: var(--ci-island-height);
|
||||
min-height: var(--ci-island-height);
|
||||
}
|
||||
.resident-card .row-components {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0;
|
||||
height: var(--ci-island-height);
|
||||
min-height: var(--ci-island-height);
|
||||
}
|
||||
.resident-card .resident-compact .component-node:not(.container) {
|
||||
|
||||
@@ -226,13 +226,6 @@ if (!gotLock) {
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
});
|
||||
island.setEditLayoutHandler(() => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return;
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
mainWindow.webContents.send('island:open-editor');
|
||||
});
|
||||
// 灵动岛点"标为已读":转交主窗口渲染进程调用接口并刷新通知中心
|
||||
island.setMarkReadHandler((id) => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) return;
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
type CoursewareTransfer,
|
||||
DEFAULT_ISLAND_APPEARANCE,
|
||||
CLASSISLAND_ISLAND_METRICS,
|
||||
normalizeIslandLayouts,
|
||||
ISLAND_POSITIONS,
|
||||
ISLAND_SHADOW_PAD,
|
||||
ISLAND_SIZE_DELTA,
|
||||
@@ -27,7 +26,7 @@ import {
|
||||
type IslandLessonReminder,
|
||||
} from '@classhelper/shared';
|
||||
import { logger } from './logger.js';
|
||||
import { getConfig, saveConfig } from './config.js';
|
||||
import { getConfig } from './config.js';
|
||||
import { LessonReminderTracker } from './lesson-reminder.js';
|
||||
|
||||
/** 生产环境的灵动岛页面地址(导航白名单的精确比对用) */
|
||||
@@ -175,7 +174,6 @@ class IslandController {
|
||||
if (this.customLayout && this.lessonCue?.kind === 'ending') return false;
|
||||
return Boolean(
|
||||
this.lessonCue &&
|
||||
!this.editingLayout &&
|
||||
!this.previewId &&
|
||||
!(
|
||||
this.state.active &&
|
||||
@@ -256,7 +254,6 @@ class IslandController {
|
||||
* 只有投影所需的 10px 留白,不再吞掉桌面点击。
|
||||
*/
|
||||
private touchMode = false;
|
||||
private editingLayout = false;
|
||||
private settlingLayout = false;
|
||||
private layoutSettleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private customSize = { width: 424, height: 80 };
|
||||
@@ -280,7 +277,7 @@ class IslandController {
|
||||
if (!this.win || this.win.isDestroyed() || process.platform !== 'win32') return;
|
||||
if (this.residentShapeTimer) clearTimeout(this.residentShapeTimer);
|
||||
this.residentShapeTimer = null;
|
||||
if (!this.residentEnabled || !this.touchMode || this.editingLayout) {
|
||||
if (!this.residentEnabled || !this.touchMode) {
|
||||
if (this.residentShaped) this.win.setShape([]);
|
||||
this.residentShaped = false;
|
||||
return;
|
||||
@@ -289,15 +286,7 @@ class IslandController {
|
||||
const apply = () => {
|
||||
this.residentShapeTimer = null;
|
||||
const r = this.hitRect;
|
||||
if (
|
||||
!r ||
|
||||
!this.win ||
|
||||
this.win.isDestroyed() ||
|
||||
!this.residentEnabled ||
|
||||
!this.touchMode ||
|
||||
this.editingLayout
|
||||
)
|
||||
return;
|
||||
if (!r || !this.win || this.win.isDestroyed() || !this.residentEnabled || !this.touchMode) return;
|
||||
this.win.setShape([
|
||||
{
|
||||
x: Math.max(0, Math.floor(r.x - 8)),
|
||||
@@ -315,9 +304,6 @@ class IslandController {
|
||||
);
|
||||
} else apply();
|
||||
}
|
||||
getEditingLayout(): boolean {
|
||||
return this.editingLayout;
|
||||
}
|
||||
syncCustomLayout(): void {
|
||||
this.refreshLessonReminder();
|
||||
if (this.residentEnabled !== this.residentWasEnabled) {
|
||||
@@ -355,13 +341,6 @@ class IslandController {
|
||||
this.syncWindow();
|
||||
}, 320);
|
||||
}
|
||||
private editLayoutHandler: (() => void) | null = null;
|
||||
setEditLayoutHandler(handler: () => void): void {
|
||||
this.editLayoutHandler = handler;
|
||||
}
|
||||
editLayout(enabled = true): void {
|
||||
if (enabled) this.editLayoutHandler?.();
|
||||
}
|
||||
reportCustomSize(value: { width: number; height: number }): void {
|
||||
if (
|
||||
!this.customLayout ||
|
||||
@@ -372,7 +351,6 @@ class IslandController {
|
||||
)
|
||||
return;
|
||||
this.customDesiredSize = { ...value };
|
||||
if (this.editingLayout) return;
|
||||
if (this.residentEnabled) {
|
||||
if (this.customTimer) clearTimeout(this.customTimer);
|
||||
this.customTimer = null;
|
||||
@@ -391,7 +369,7 @@ class IslandController {
|
||||
if (this.customTimer) clearTimeout(this.customTimer);
|
||||
this.customTimer = setTimeout(() => {
|
||||
this.customTimer = null;
|
||||
if (!this.win || !this.customLayout || this.editingLayout || this.residentEnabled) return;
|
||||
if (!this.win || !this.customLayout || this.residentEnabled) return;
|
||||
const area = screen.getDisplayNearestPoint(this.win.getBounds()).workArea;
|
||||
const current = this.win.getBounds();
|
||||
const width = Math.max(40, Math.min(Math.ceil(value.width), area.width - 2 * ISLAND_SHADOW_PAD));
|
||||
@@ -557,13 +535,12 @@ class IslandController {
|
||||
* 因此这里再用**指针位置**兜一层:指针还在岛上就绝不收起(详见 isCursorOnIsland)。
|
||||
*/
|
||||
win.on('resize', () => {
|
||||
if (this.customLayout && !this.editingLayout && this.ready && !win.isDestroyed()) {
|
||||
if (this.customLayout && this.ready && !win.isDestroyed()) {
|
||||
const { width, height } = win.getContentBounds();
|
||||
win.webContents.send('island:viewport', { width, height });
|
||||
}
|
||||
});
|
||||
win.on('blur', () => {
|
||||
if (this.editingLayout) return;
|
||||
// 冒烟里可以临时关掉"失焦收起",避免测试过程被无关的焦点变化打断(默认开启)
|
||||
if (!this.blurCollapseEnabled) return;
|
||||
if (this.state.mode !== 'expanded') return;
|
||||
@@ -576,7 +553,7 @@ class IslandController {
|
||||
}
|
||||
// 触摸屏上没有"指针"可依据(isCursorOnIsland 恒为 false),只能用更宽的宽限期覆盖
|
||||
// 上面实测到的 70~520ms 抖动区间,否则手指点开后约 0.5s 会莫名缩回胶囊。
|
||||
const grace = this.touchMode || this.editingLayout ? BLUR_GRACE_TOUCH_MS : BLUR_GRACE_MS;
|
||||
const grace = this.touchMode ? BLUR_GRACE_TOUCH_MS : BLUR_GRACE_MS;
|
||||
if (sinceActivated < grace) {
|
||||
logger.info(`灵动岛:忽略激活后 ${sinceActivated}ms 内的失焦(宽限期内不收起)`);
|
||||
return;
|
||||
@@ -1153,14 +1130,7 @@ class IslandController {
|
||||
if (this.customLayout)
|
||||
setTimeout(() => {
|
||||
// 提醒沿原路径收回后,隐藏窗口再缩回组件栏;时钟等普通组件继续显示。
|
||||
if (
|
||||
!this.win ||
|
||||
this.win.isDestroyed() ||
|
||||
!this.customLayout ||
|
||||
this.editingLayout ||
|
||||
this.state.mode !== 'hidden'
|
||||
)
|
||||
return;
|
||||
if (!this.win || this.win.isDestroyed() || !this.customLayout || this.state.mode !== 'hidden') return;
|
||||
this.win.hide();
|
||||
const area = screen.getDisplayNearestPoint(this.win.getBounds()).workArea;
|
||||
this.customSize = {
|
||||
@@ -1432,7 +1402,7 @@ class IslandController {
|
||||
*/
|
||||
private syncWindow(): void {
|
||||
if (!this.win || this.win.isDestroyed()) return;
|
||||
if (this.coursewareShowing && !this.editingLayout) {
|
||||
if (this.coursewareShowing) {
|
||||
this.cancelFade();
|
||||
if (!this.win.isVisible() || this.customLayout) this.applyWindowLayout();
|
||||
this.syncTouchLayout();
|
||||
@@ -1442,10 +1412,6 @@ class IslandController {
|
||||
this.setInteractive(false, '课件传输不遮挡桌面操作');
|
||||
return;
|
||||
}
|
||||
if (this.editingLayout) {
|
||||
this.setInteractive(true, '布局编辑');
|
||||
return;
|
||||
}
|
||||
if (this.customLayout) {
|
||||
if (this.settlingLayout) return;
|
||||
this.cancelFade();
|
||||
@@ -1613,7 +1579,6 @@ class IslandController {
|
||||
private applyWindowLayout(): void {
|
||||
if (!this.win || this.win.isDestroyed()) return;
|
||||
const next = this.windowBounds();
|
||||
if (this.editingLayout) return;
|
||||
const current = this.win.getBounds();
|
||||
if (
|
||||
current.x === next.x &&
|
||||
@@ -1677,7 +1642,6 @@ class IslandController {
|
||||
*/
|
||||
private applyFocusable(): void {
|
||||
if (!this.win || this.win.isDestroyed()) return;
|
||||
if (this.editingLayout) return;
|
||||
if (!this.win.isFocusable()) this.win.setFocusable(true);
|
||||
if (this.state.mode === 'expanded') {
|
||||
this.win.focus();
|
||||
@@ -1817,7 +1781,7 @@ class IslandController {
|
||||
const next =
|
||||
passthrough || this.residentFaded
|
||||
? false
|
||||
: this.touchMode || this.editingLayout || (this.customLayout && !this.residentEnabled)
|
||||
: this.touchMode || (this.customLayout && !this.residentEnabled)
|
||||
? true
|
||||
: interactive;
|
||||
if (this.interactive === next) return;
|
||||
@@ -1879,7 +1843,6 @@ class IslandController {
|
||||
const faded =
|
||||
this.residentEnabled &&
|
||||
settings.pointerFadeEnabled &&
|
||||
!this.editingLayout &&
|
||||
!this.lessonShowing &&
|
||||
Date.now() >= this.residentTouchUntil &&
|
||||
Date.now() >= this.residentMotionUntil &&
|
||||
@@ -2403,13 +2366,6 @@ export function registerIslandIpc(): void {
|
||||
event.sender === island.getWindow()?.webContents ? island.getTimePoints() : [],
|
||||
);
|
||||
ipcMain.handle('island:get-layout', () => getConfig().islandLayout);
|
||||
ipcMain.handle('island:save-layout', (_event, value: unknown) => {
|
||||
const result = saveConfig({ islandLayout: normalizeIslandLayouts(value) }).islandLayout;
|
||||
island.syncCustomLayout();
|
||||
return result;
|
||||
});
|
||||
ipcMain.handle('island:edit-layout', () => island.editLayout());
|
||||
ipcMain.handle('island:get-editing', () => island.getEditingLayout());
|
||||
ipcMain.handle(
|
||||
'island:get-visible',
|
||||
(event) => event.sender === island.getWindow()?.webContents && (island.getWindow()?.isVisible() ?? false),
|
||||
@@ -2420,7 +2376,6 @@ export function registerIslandIpc(): void {
|
||||
ipcMain.on('island:resident-touch', (event) => {
|
||||
if (event.sender === island.getWindow()?.webContents) island.noteResidentTouch();
|
||||
});
|
||||
ipcMain.handle('island:set-editing', (_event, value: unknown) => island.editLayout(value === true));
|
||||
ipcMain.on('island:content-size', (event, value) => {
|
||||
if (event.sender === island.getWindow()?.webContents) island.reportCustomSize(value);
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from 'node:fs';
|
||||
import { BrowserWindow } from 'electron';
|
||||
import path from 'node:path';
|
||||
import { BrowserWindow } from 'electron';
|
||||
import { island } from './island.js';
|
||||
import { getConfig, saveConfig } from './config.js';
|
||||
import {
|
||||
@@ -11,22 +11,28 @@ import {
|
||||
} from '@classhelper/shared';
|
||||
import { getIslandWeather } from './island-weather.js';
|
||||
import { verifyResidentSmoke } from './smoke-resident.js';
|
||||
|
||||
/**
|
||||
* 自定义岛回归:班级端只运行服务端下发的方案,布局编辑器已迁到 Web 管理端。
|
||||
* 这里验证“无本地编辑入口 + 固定行高居中渲染 + 通知宿主 + 天气边界”。
|
||||
*/
|
||||
export async function verifyLayoutSmoke(
|
||||
check: (name: string, action: () => Promise<boolean | string> | boolean) => Promise<void>,
|
||||
) {
|
||||
): Promise<void> {
|
||||
const original = getConfig().islandLayout;
|
||||
await island.init(null);
|
||||
island.setTestInputPassthrough(true);
|
||||
const win = island.getWindow()!;
|
||||
const editor = BrowserWindow.getAllWindows().find(
|
||||
(w) => w !== win && !w.isDestroyed() && /\/index\.html(?:#|$)/.test(w.webContents.getURL()),
|
||||
const main = BrowserWindow.getAllWindows().find(
|
||||
(item) => item !== win && !item.isDestroyed() && /\/index\.html(?:#|$)/.test(item.webContents.getURL()),
|
||||
)!;
|
||||
let editingBounds = win.getBounds();
|
||||
const pause = () => new Promise<void>((r) => setTimeout(r, 400));
|
||||
const pause = (ms = 400) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
try {
|
||||
await pause();
|
||||
await check('默认 fixed 布局且尺寸上报不参与', async () => {
|
||||
saveConfig({ islandLayout: defaultIslandLayouts() });
|
||||
island.syncCustomLayout();
|
||||
const before = win.getBounds();
|
||||
island.reportCustomSize({ width: 900, height: 900 });
|
||||
await pause();
|
||||
@@ -37,193 +43,46 @@ export async function verifyLayoutSmoke(
|
||||
getConfig().islandLayout.layout === 'fixed'
|
||||
);
|
||||
});
|
||||
await check('自定义编辑模式可进入并添加组件行', async () => {
|
||||
saveConfig({ islandLayout: { ...defaultIslandLayouts(), layout: 'custom' } });
|
||||
|
||||
await check('班级端不再注册灵动岛布局编辑路由', async () => {
|
||||
await main.webContents.executeJavaScript(`location.hash = '#/settings/island/editor'`);
|
||||
await pause();
|
||||
return main.webContents.executeJavaScript(
|
||||
`!location.hash.includes('/settings/island/editor') && !document.querySelector('.island-editor-page')`,
|
||||
);
|
||||
});
|
||||
|
||||
await check('服务端自定义布局按 40px 行高居中渲染', async () => {
|
||||
const custom = defaultIslandLayouts();
|
||||
custom.layout = 'custom';
|
||||
custom.residentEnabled = true;
|
||||
saveConfig({ islandLayout: custom });
|
||||
island.syncCustomLayout();
|
||||
await pause();
|
||||
editingBounds = win.getBounds();
|
||||
await editor.webContents.executeJavaScript('window.__classhelperSmoke__.islandEditorSmoke(true)');
|
||||
await pause();
|
||||
if (process.env.ISLAND_SHOTS_DIR) {
|
||||
fs.mkdirSync(process.env.ISLAND_SHOTS_DIR, { recursive: true });
|
||||
const bounds = editor.getContentBounds();
|
||||
editor.setContentSize(1600, 1000);
|
||||
for (const theme of ['light', 'dark']) {
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.documentElement.classList.toggle('dark', ${theme === 'dark'})`,
|
||||
);
|
||||
await pause();
|
||||
fs.writeFileSync(
|
||||
path.join(process.env.ISLAND_SHOTS_DIR, `component-editor-${theme}.png`),
|
||||
(await editor.webContents.capturePage()).toPNG(),
|
||||
);
|
||||
}
|
||||
await editor.webContents.executeJavaScript(`document.documentElement.classList.remove('dark')`);
|
||||
editor.setContentSize(bounds.width, bounds.height);
|
||||
await pause();
|
||||
}
|
||||
return (
|
||||
(await editor.webContents.executeJavaScript(
|
||||
'location.hash.includes("/settings/island/editor") && Boolean(document.querySelector(".aside"))',
|
||||
)) &&
|
||||
editor.webContents.executeJavaScript(
|
||||
`(() => { const b=[...document.querySelectorAll('button')].find(b=>b.textContent.trim()==='新增行');b?.click();return document.querySelectorAll('.component-library > .component-options:first-of-type .library-item').length===11 && !document.querySelector('.layout-editor, iframe'); })()`,
|
||||
)
|
||||
await pause(650);
|
||||
const geometry = await win.webContents.executeJavaScript(`(() => {
|
||||
const card = document.querySelector('.resident-card');
|
||||
const source = card?.querySelector('.resident-compact');
|
||||
const rows = [...document.querySelectorAll('.resident-compact .layout-row')];
|
||||
if (!card || !source || !rows.length) return null;
|
||||
const r = card.getBoundingClientRect();
|
||||
const s = source.getBoundingClientRect();
|
||||
return {
|
||||
centered: Math.abs(r.left + r.width / 2 - s.left - s.width / 2) <= 2,
|
||||
contained:
|
||||
s.left >= ${ISLAND_SHADOW_PAD} - 1 &&
|
||||
s.right <= innerWidth - ${ISLAND_SHADOW_PAD} + 1 &&
|
||||
s.top >= ${ISLAND_SHADOW_PAD} - 1 &&
|
||||
s.bottom <= innerHeight - ${ISLAND_SHADOW_PAD} + 1,
|
||||
rowHeights: rows.map((row) => Math.round(row.getBoundingClientRect().height)),
|
||||
};
|
||||
})()`);
|
||||
return Boolean(
|
||||
geometry?.centered &&
|
||||
geometry.contained &&
|
||||
geometry.rowHeights.every((height: number) => Math.abs(height - 40) <= 1),
|
||||
);
|
||||
});
|
||||
await check('触摸拖动可跨行并持久化', async () => {
|
||||
await pause();
|
||||
const dragGeometry = await editor.webContents.executeJavaScript(`(() => {
|
||||
const handle=document.querySelector('.node-handle[data-kind=clock]');
|
||||
const row=document.querySelectorAll('[data-row]')[1]; if(!handle||!row)throw Error('缺少拖动目标');
|
||||
document.querySelector('.preview-canvas')?.scrollIntoView({block:'center'});
|
||||
const r=row.getBoundingClientRect(); const x=r.left+Math.min(20,r.width/2),y=r.top+r.height/2;
|
||||
handle.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true,pointerId:19,pointerType:'touch',clientX:10,clientY:10}));
|
||||
handle.dispatchEvent(new PointerEvent('pointermove',{bubbles:true,pointerId:19,pointerType:'touch',clientX:x,clientY:y}));
|
||||
handle.dispatchEvent(new PointerEvent('pointerup',{bubbles:true,pointerId:19,pointerType:'touch',clientX:x,clientY:y}));
|
||||
return {row:r.toJSON(), point:{x,y}, hit:document.elementFromPoint(x,y)?.outerHTML.slice(0,600), canvas:document.querySelector('.preview-canvas')?.getBoundingClientRect().toJSON()};
|
||||
})()`);
|
||||
await pause();
|
||||
const moved =
|
||||
getConfig().islandLayout.schemes[0]?.rows[1]?.nodes.some((n) => n.kind === 'clock') === true;
|
||||
if (!moved) throw new Error(JSON.stringify(dragGeometry));
|
||||
return true;
|
||||
});
|
||||
await check('组件可以包裹进容器且设置独立保存', async () => {
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('.node-handle[data-kind=clock]')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('[data-action=wrap] .el-select__wrapper')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`(() => { const option=[...document.querySelectorAll('.el-select-dropdown__item')].find(e=>e.textContent.trim()==='分组容器'); if(!option)throw Error('容器菜单未出现');option.click(); })()`,
|
||||
);
|
||||
await pause();
|
||||
return (
|
||||
getConfig().islandLayout.schemes[0]?.rows.some((r) =>
|
||||
r.nodes.some((n) => n.kind === 'group' && n.children.some((c) => c.kind === 'clock')),
|
||||
) === true
|
||||
);
|
||||
});
|
||||
await check('组件设置按内容外观高级切换,整体外观单独显示', async () => {
|
||||
const initial = await editor.webContents.executeJavaScript(`(() => {
|
||||
const panel=[...document.querySelectorAll('.component-settings .el-tab-pane')].find(e=>getComputedStyle(e).display!=='none');
|
||||
return panel?.textContent.includes('排列方向') && !panel.textContent.includes('背景颜色');
|
||||
})()`);
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelectorAll('.component-settings .el-tabs__item')[1].click()`,
|
||||
);
|
||||
await pause();
|
||||
const appearance = await editor.webContents.executeJavaScript(`(() => {
|
||||
const panel=[...document.querySelectorAll('.component-settings .el-tab-pane')].find(e=>getComputedStyle(e).display!=='none');
|
||||
return panel?.textContent.includes('正文字号') && !panel.textContent.includes('排列方向');
|
||||
})()`);
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelectorAll('.component-settings .el-tabs__item')[2].click()`,
|
||||
);
|
||||
await pause();
|
||||
const advanced = await editor.webContents.executeJavaScript(`(() => {
|
||||
const panel=[...document.querySelectorAll('.component-settings .el-tab-pane')].find(e=>getComputedStyle(e).display!=='none');
|
||||
return panel?.textContent.includes('隐藏条件') && !panel.textContent.includes('背景颜色');
|
||||
})()`);
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelectorAll('.component-settings .el-tabs__item')[0].click()`,
|
||||
);
|
||||
await pause();
|
||||
return initial && appearance && advanced;
|
||||
});
|
||||
await check('主窗口编辑器的预览完整适配画布且不遮挡缩放控件', async () => {
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('.el-drawer__close-btn')?.click();document.querySelector('.surface-actions button:last-child')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
return editor.webContents.executeJavaScript(`(() => {
|
||||
const canvas=document.querySelector('.preview-canvas')?.getBoundingClientRect();
|
||||
const footer=document.querySelector('.preview-toolbar')?.getBoundingClientRect();
|
||||
return Boolean(canvas&&footer&&canvas.bottom<=footer.top+1&&document.documentElement.scrollWidth<=innerWidth);
|
||||
})()`);
|
||||
});
|
||||
await check('原生编辑页使用客户端主题并兼容深色', async () => {
|
||||
return editor.webContents.executeJavaScript(`(() => {
|
||||
const root=document.documentElement, wasDark=root.classList.contains('dark');
|
||||
root.classList.add('dark');
|
||||
const page=document.querySelector('.island-editor-page'), style=getComputedStyle(page);
|
||||
const ok=style.getPropertyValue('--ch-text').trim() && !document.querySelector('.layout-editor, iframe') && document.querySelector('.component-library .library-title') && document.querySelector('.scheme-controls');
|
||||
root.classList.toggle('dark',wasDark);return Boolean(ok);
|
||||
})()`);
|
||||
});
|
||||
await check('从常驻组件库拖入容器,阻止将父组件放进自己的后代', async () => {
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('.surface-actions button:last-child')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(`(() => {
|
||||
const source=document.querySelector('[data-library-kind=text]'), target=document.querySelector('.editor-component.container');
|
||||
if(!source||!target)throw Error('缺少组件库或容器');
|
||||
const r=target.getBoundingClientRect(), x=r.left+r.width/2, y=r.top+r.height/2;
|
||||
source.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true,pointerId:21,clientX:10,clientY:10}));
|
||||
source.dispatchEvent(new PointerEvent('pointermove',{bubbles:true,pointerId:21,clientX:x,clientY:y}));
|
||||
source.dispatchEvent(new PointerEvent('pointerup',{bubbles:true,pointerId:21,clientX:x,clientY:y}));
|
||||
})()`);
|
||||
await pause();
|
||||
const group = getConfig()
|
||||
.islandLayout.schemes[0]!.rows.flatMap((r) => r.nodes)
|
||||
.find((n) => n.kind === 'group');
|
||||
if (!group?.children.some((n) => n.kind === 'text')) throw Error('组件库内容没有进入容器');
|
||||
const before = JSON.stringify(getConfig().islandLayout);
|
||||
await editor.webContents.executeJavaScript(`(() => {
|
||||
const source=document.querySelector('.editor-component.container > .node-handle'), target=document.querySelector('.editor-component.container .container-children .node-handle');
|
||||
const r=target.getBoundingClientRect(), x=r.left+r.width/2, y=r.top+r.height/2;
|
||||
source.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true,pointerId:22,clientX:10,clientY:10}));
|
||||
source.dispatchEvent(new PointerEvent('pointerup',{bubbles:true,pointerId:22,clientX:x,clientY:y}));
|
||||
})()`);
|
||||
await pause();
|
||||
return before === JSON.stringify(getConfig().islandLayout);
|
||||
});
|
||||
await check('常态与无通知展开内容分别保存,日期倒计时可配置并预览', async () => {
|
||||
const before = JSON.stringify(getConfig().islandLayout.schemes[0]!.rows);
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelectorAll('.surface-tabs button')[1].click();document.querySelector('[data-library-kind=countdown]').click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(`(() => {
|
||||
const set=(input,value)=>{input.value=value;input.dispatchEvent(new Event('input',{bubbles:true}));input.dispatchEvent(new Event('change',{bubbles:true}));};
|
||||
const field=[...document.querySelectorAll('.component-settings .el-form-item')].find(e=>e.textContent.includes('目标名称'));
|
||||
set(field.querySelector('input'),'运动会');
|
||||
document.querySelector('.component-settings .el-date-editor input').focus();
|
||||
})()`);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(`(() => {
|
||||
const picker=document.querySelector('.component-settings .el-date-editor input');
|
||||
picker.value='2099-10-25';picker.dispatchEvent(new Event('input',{bubbles:true}));
|
||||
})()`);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(`(() => {
|
||||
const picker=document.querySelector('.component-settings .el-date-editor input');
|
||||
picker.dispatchEvent(new Event('change',{bubbles:true}));picker.dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',code:'Enter',bubbles:true}));picker.blur();
|
||||
})()`);
|
||||
await pause();
|
||||
const added = getConfig()
|
||||
.islandLayout.schemes[0]!.expandedRows.flatMap((r) => r.nodes)
|
||||
.find((n) => n.kind === 'countdown');
|
||||
if (added?.settings.targetDate !== '2099-10-25' || added.settings.countdownTitle !== '运动会')
|
||||
throw Error(JSON.stringify(added?.settings));
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('.el-drawer__close-btn')?.click();document.querySelector('.surface-actions button:last-child')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
const preview = await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('.island-preview .countdown')?.textContent.includes('距运动会')`,
|
||||
);
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelectorAll('.surface-tabs button')[0].click()`,
|
||||
);
|
||||
await pause();
|
||||
return preview && JSON.stringify(getConfig().islandLayout.schemes[0]!.rows) === before;
|
||||
});
|
||||
|
||||
await check('天气坐标校验、并发合并与缓存使用 mock,不访问外网', async () => {
|
||||
let calls = 0;
|
||||
const request: typeof fetch = async (input) => {
|
||||
@@ -246,149 +105,23 @@ export async function verifyLayoutSmoke(
|
||||
} catch {
|
||||
invalid = true;
|
||||
}
|
||||
const weather = islandNode('weather', 'weather-test'),
|
||||
countdown = islandNode('countdown', 'countdown-test');
|
||||
weather.settings.latitude = NaN;
|
||||
const weather = islandNode('weather', 'weather-test');
|
||||
const countdown = islandNode('countdown', 'countdown-test');
|
||||
weather.settings.latitude = Number.NaN;
|
||||
countdown.settings.targetDate = '2026-02-31';
|
||||
const config = defaultIslandLayouts();
|
||||
config.schemes[0]!.rows[0]!.nodes = [weather, countdown];
|
||||
const normalized = normalizeIslandLayouts(config).schemes[0]!.rows[0]!.nodes;
|
||||
return (
|
||||
calls === 1 &&
|
||||
results.every((r) => r.temperature === 23.4 && !r.stale) &&
|
||||
results.every((result) => result.temperature === 23.4 && !result.stale) &&
|
||||
invalid &&
|
||||
normalized[0]!.settings.latitude === null &&
|
||||
normalized[1]!.settings.targetDate === ''
|
||||
);
|
||||
});
|
||||
await check('右上角新建、重置和删除方案均可保存并恢复原方案', async () => {
|
||||
await editor.webContents.executeJavaScript(`document.querySelector('[aria-label="新建方案"]').click()`);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`(() => { const input=[...document.querySelectorAll('.el-message-box__input input')].filter(e=>e.getBoundingClientRect().width>0).at(-1); input.value='组件方案验收';input.dispatchEvent(new Event('input',{bubbles:true}));[...document.querySelectorAll('.el-message-box__btns .el-button--primary')].filter(e=>e.getBoundingClientRect().width>0).at(-1).click(); })()`,
|
||||
);
|
||||
await pause();
|
||||
if (getConfig().islandLayout.schemes.length !== 2) throw Error('新建方案没有保存');
|
||||
await editor.webContents.executeJavaScript(
|
||||
`document.querySelector('[aria-label="重置当前方案"]').click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`[...document.querySelectorAll('.el-message-box__btns .el-button--primary')].filter(e=>e.getBoundingClientRect().width>0).at(-1).click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(`document.querySelector('[aria-label="管理方案"]').click()`);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`[...document.querySelectorAll('.el-dropdown-menu__item')].find(e=>e.textContent.trim()==='删除方案').click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`[...document.querySelectorAll('.el-message-box__btns .el-button--primary')].filter(e=>e.getBoundingClientRect().width>0).at(-1).click()`,
|
||||
);
|
||||
await pause();
|
||||
const restored =
|
||||
getConfig().islandLayout.schemes.length === 1 &&
|
||||
getConfig().islandLayout.activeSchemeId === 'default' &&
|
||||
getConfig().islandLayout.schemes[0]!.rows.length === 2;
|
||||
if (!restored)
|
||||
throw Error(
|
||||
'方案未恢复:' +
|
||||
JSON.stringify({
|
||||
active: getConfig().islandLayout.activeSchemeId,
|
||||
schemes: getConfig().islandLayout.schemes.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
rows: s.rows.length,
|
||||
})),
|
||||
}),
|
||||
);
|
||||
return restored;
|
||||
});
|
||||
await check('方案 JSON 导入导出保留容器结构并重新生成标识', async () => {
|
||||
await editor.webContents.executeJavaScript(`document.querySelector('[aria-label="管理方案"]').click()`);
|
||||
await pause();
|
||||
const exported = await editor.webContents.executeJavaScript(`(async () => {
|
||||
let blob; const originalURL=URL.createObjectURL, originalClick=HTMLAnchorElement.prototype.click;
|
||||
try {
|
||||
URL.createObjectURL=value=>{blob=value;return 'blob:editor-smoke';};HTMLAnchorElement.prototype.click=()=>{};
|
||||
[...document.querySelectorAll('.el-dropdown-menu__item')].find(e=>e.textContent.trim()==='导出方案').click();
|
||||
} finally { URL.createObjectURL=originalURL;HTMLAnchorElement.prototype.click=originalClick; }
|
||||
const text=await blob.text(), parsed=JSON.parse(text);
|
||||
const input=document.querySelector('.island-editor-page input[type=file]'), transfer=new DataTransfer();
|
||||
transfer.items.add(new File([text],'组件方案.json',{type:'application/json'}));input.files=transfer.files;
|
||||
input.dispatchEvent(new Event('change',{bubbles:true}));return parsed;
|
||||
})()`);
|
||||
await pause();
|
||||
const layouts = getConfig().islandLayout;
|
||||
const imported = layouts.schemes.find((s) => s.id === layouts.activeSchemeId)!;
|
||||
const shape = (nodes: ReturnType<typeof islandNode>[]): string =>
|
||||
JSON.stringify(
|
||||
nodes.map((n) => ({ kind: n.kind, children: shape(n.children), settings: n.settings })),
|
||||
);
|
||||
const preserved =
|
||||
exported.format === 'classhelper-island-layout' &&
|
||||
imported.id !== exported.scheme.id &&
|
||||
imported.rows.every(
|
||||
(row, index) =>
|
||||
row.id !== exported.scheme.rows[index].id &&
|
||||
shape(row.nodes) === shape(exported.scheme.rows[index].nodes),
|
||||
);
|
||||
await editor.webContents.executeJavaScript(`document.querySelector('[aria-label="管理方案"]').click()`);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`[...document.querySelectorAll('.el-dropdown-menu__item')].find(e=>e.textContent.trim()==='删除方案').click()`,
|
||||
);
|
||||
await pause();
|
||||
await editor.webContents.executeJavaScript(
|
||||
`[...document.querySelectorAll('.el-message-box__btns .el-button--primary')].filter(e=>e.getBoundingClientRect().width>0).at(-1).click()`,
|
||||
);
|
||||
await pause();
|
||||
if (!preserved || getConfig().islandLayout.schemes.length !== 1)
|
||||
throw Error(
|
||||
'方案导入或收尾不一致:' +
|
||||
JSON.stringify({
|
||||
preserved,
|
||||
schemes: getConfig().islandLayout.schemes.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
rows: s.rows.length,
|
||||
})),
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
});
|
||||
if (process.env.ISLAND_SHOTS_DIR) {
|
||||
await editor.webContents.executeJavaScript(`document.querySelector('.main').scrollTop=0`);
|
||||
fs.mkdirSync(process.env.ISLAND_SHOTS_DIR, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(process.env.ISLAND_SHOTS_DIR, 'custom-editor.png'),
|
||||
(await editor.webContents.capturePage()).toPNG(),
|
||||
);
|
||||
}
|
||||
await check('退出编辑后配置可从 getConfig 读回', async () => {
|
||||
await editor.webContents.executeJavaScript(
|
||||
`[...document.querySelectorAll('button')].find(b=>b.textContent.trim()==='应用并返回')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
return (
|
||||
!island.getEditingLayout() &&
|
||||
getConfig().islandLayout.schemes[0]!.rows.length === 2 &&
|
||||
!editor.webContents.getURL().includes('/editor') &&
|
||||
win.getBounds().width === editingBounds.width
|
||||
);
|
||||
});
|
||||
await editor.webContents.executeJavaScript('window.__classhelperSmoke__.islandEditorSmoke(false)');
|
||||
await check('自定义岛统一使用固定画布且常态组件居中适配', async () => {
|
||||
await pause();
|
||||
return win.webContents.executeJavaScript(`(() => {
|
||||
const card=document.querySelector('.resident-card'), source=card?.querySelector('.resident-compact');
|
||||
if(!card||!source)return false;
|
||||
const r=card.getBoundingClientRect(),s=source.getBoundingClientRect();
|
||||
return r.width<=innerWidth-${2 * ISLAND_SHADOW_PAD}&&r.height<=innerHeight-${2 * ISLAND_SHADOW_PAD}&&Math.abs(r.left+r.width/2-s.left-s.width/2)<=2;
|
||||
})()`);
|
||||
});
|
||||
await check('自定义岛紧急通知立即弹出并复用经典通知内容', async () => {
|
||||
|
||||
await check('班级端自定义岛仍可处理紧急通知', async () => {
|
||||
island.setClassState({ inClass: false, currentPeriodEnd: null, week: 1 });
|
||||
island.pushNotification({
|
||||
id: 'custom-smoke-alert',
|
||||
@@ -399,45 +132,41 @@ export async function verifyLayoutSmoke(
|
||||
teacherName: '临时教师',
|
||||
courseName: null,
|
||||
});
|
||||
await pause();
|
||||
await pause();
|
||||
await pause(800);
|
||||
const result = await win.webContents.executeJavaScript(`(() => {
|
||||
const card=document.querySelector('.resident-card'), content=card?.querySelector('.classic-notifications'),r=card?.getBoundingClientRect(),c=content?.getBoundingClientRect();
|
||||
const shape=card?.querySelectorAll('.shape').length;
|
||||
const radius=parseFloat(card ? getComputedStyle(card).borderTopLeftRadius : '0');
|
||||
const valid=Boolean(content&&content.textContent.includes('组件化提醒验收')&&shape===0&&radius>0&&c.left>=r.left-1&&c.right<=r.right+1&&c.bottom<=r.bottom+1);
|
||||
return {valid,card:r?.toJSON(),content:c?.toJSON(),shape,radius};
|
||||
const card = document.querySelector('.resident-card');
|
||||
const content = card?.querySelector('.classic-notifications');
|
||||
if (!card || !content) return false;
|
||||
const r = card.getBoundingClientRect();
|
||||
const c = content.getBoundingClientRect();
|
||||
return (
|
||||
content.textContent.includes('组件化提醒验收') &&
|
||||
c.left >= r.left - 1 &&
|
||||
c.right <= r.right + 1 &&
|
||||
c.bottom <= r.bottom + 1
|
||||
);
|
||||
})()`);
|
||||
if (!result.valid) throw Error(JSON.stringify(result));
|
||||
return island.getState().mode === 'expanded';
|
||||
if (process.env.ISLAND_SHOTS_DIR) {
|
||||
fs.mkdirSync(process.env.ISLAND_SHOTS_DIR, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(process.env.ISLAND_SHOTS_DIR, 'custom-alert.png'),
|
||||
(await win.webContents.capturePage()).toPNG(),
|
||||
);
|
||||
}
|
||||
return Boolean(result) && island.getState().mode === 'expanded';
|
||||
});
|
||||
if (process.env.ISLAND_SHOTS_DIR)
|
||||
fs.writeFileSync(
|
||||
path.join(process.env.ISLAND_SHOTS_DIR, 'custom-alert.png'),
|
||||
(await win.webContents.capturePage()).toPNG(),
|
||||
);
|
||||
|
||||
await win.webContents.executeJavaScript(
|
||||
`document.querySelector('#custom-alert-host .solid-btn')?.click()`,
|
||||
);
|
||||
await pause();
|
||||
await pause();
|
||||
await pause();
|
||||
await check('提醒收回后缩回组件栏,保留时钟与可见状态', async () => {
|
||||
const content = await win.webContents.executeJavaScript(
|
||||
`Boolean(document.querySelector('.custom-card .clock'))`,
|
||||
);
|
||||
const visible = process.env.ELECTRON_SMOKE_MODE === 'visual' ? win.isVisible() : !win.isVisible();
|
||||
return content && visible && island.getState().mode === 'hidden';
|
||||
});
|
||||
await check('没有提醒时消息组件不占位', async () => {
|
||||
return win.webContents.executeJavaScript(
|
||||
`document.querySelectorAll('.custom-card .component-node.notification, .custom-card .component-node.homework, .custom-card .component-node.call').length === 0`,
|
||||
);
|
||||
await pause(900);
|
||||
await check('通知收回后保留常驻组件状态', async () => {
|
||||
const state = island.getState();
|
||||
return state.mode === 'hidden' && state.active === null;
|
||||
});
|
||||
|
||||
await verifyResidentSmoke(check);
|
||||
} finally {
|
||||
if (editor && !editor.isDestroyed())
|
||||
await editor.webContents.executeJavaScript('window.__classhelperSmoke__.islandEditorSmoke(false)');
|
||||
saveConfig({ islandLayout: original });
|
||||
island.syncCustomLayout();
|
||||
win.hide();
|
||||
|
||||
@@ -90,7 +90,6 @@ export async function runQuickSmoke(win: BrowserWindow): Promise<void> {
|
||||
);
|
||||
const shots = path.resolve(app.getAppPath(), '../../docs/screenshots/desktop-responsive');
|
||||
fs.mkdirSync(shots, { recursive: true });
|
||||
await win.webContents.executeJavaScript('window.__classhelperSmoke__.islandEditorSmoke(true)');
|
||||
try {
|
||||
for (const [width, height] of [
|
||||
[1000, 540],
|
||||
@@ -111,7 +110,6 @@ export async function runQuickSmoke(win: BrowserWindow): Promise<void> {
|
||||
'/settings/general',
|
||||
'/settings/appearance',
|
||||
'/settings/island',
|
||||
'/settings/island/editor',
|
||||
'/settings/reminder',
|
||||
'/settings/account',
|
||||
'/settings/about',
|
||||
@@ -130,7 +128,7 @@ export async function runQuickSmoke(win: BrowserWindow): Promise<void> {
|
||||
}
|
||||
} finally {
|
||||
await win.webContents.executeJavaScript(
|
||||
`document.documentElement.className=${JSON.stringify(appearance.className)};document.documentElement.setAttribute('style',${JSON.stringify(appearance.style || '')});window.__classhelperSmoke__.islandEditorSmoke(false)`,
|
||||
`document.documentElement.className=${JSON.stringify(appearance.className)};document.documentElement.setAttribute('style',${JSON.stringify(appearance.style || '')})`,
|
||||
);
|
||||
win.setContentSize(bounds.width, bounds.height);
|
||||
}
|
||||
|
||||
@@ -30,19 +30,17 @@ export async function verifyResidentSmoke(
|
||||
path.join(process.env.ISLAND_SHOTS_DIR, `${name}.png`),
|
||||
(
|
||||
await win.webContents.capturePage(
|
||||
island.getEditingLayout()
|
||||
? undefined
|
||||
: (() => {
|
||||
const r = island.getHitRect();
|
||||
return r
|
||||
? {
|
||||
x: Math.max(0, Math.floor(r.x - 8)),
|
||||
y: Math.max(0, Math.floor(r.y - 8)),
|
||||
width: Math.ceil(r.width + 16),
|
||||
height: Math.ceil(r.height + 16),
|
||||
}
|
||||
: undefined;
|
||||
})(),
|
||||
(() => {
|
||||
const r = island.getHitRect();
|
||||
return r
|
||||
? {
|
||||
x: Math.max(0, Math.floor(r.x - 8)),
|
||||
y: Math.max(0, Math.floor(r.y - 8)),
|
||||
width: Math.ceil(r.width + 16),
|
||||
height: Math.ceil(r.height + 16),
|
||||
}
|
||||
: undefined;
|
||||
})(),
|
||||
)
|
||||
).toPNG(),
|
||||
);
|
||||
@@ -875,21 +873,6 @@ export async function verifyResidentSmoke(
|
||||
island.setTouchMode(false);
|
||||
}
|
||||
});
|
||||
await check('编辑入口交给主窗口,浮岛不会变成额外的全屏编辑窗口', async () => {
|
||||
const before = win.getBounds();
|
||||
let opened = false;
|
||||
island.setEditLayoutHandler(() => {
|
||||
opened = true;
|
||||
});
|
||||
island.editLayout();
|
||||
await pause(100);
|
||||
return (
|
||||
opened &&
|
||||
!island.getEditingLayout() &&
|
||||
JSON.stringify(before) === JSON.stringify(win.getBounds()) &&
|
||||
!(await win.webContents.executeJavaScript('Boolean(document.querySelector(".layout-editor"))'))
|
||||
);
|
||||
});
|
||||
await check('通知、作业、叫人均使用不透明背景和原生窗口,收起后恢复常驻透明度', async () => {
|
||||
const appearance = island.getAppearance();
|
||||
try {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { island } from './island.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Menu, Tray, app, nativeImage } from 'electron';
|
||||
@@ -39,7 +38,6 @@ export function createTray(handlers: TrayHandlers): Tray | null {
|
||||
tray.setContextMenu(
|
||||
Menu.buildFromTemplate([
|
||||
{ label: '显示主窗口', click: () => handlers.onShow() },
|
||||
{ label: '编辑灵动岛布局', click: () => island.editLayout() },
|
||||
{ label: '隐藏到托盘', click: () => handlers.onHide() },
|
||||
{ type: 'separator' },
|
||||
{ label: '退出 ClassHelper', click: () => handlers.onQuit() },
|
||||
|
||||
@@ -34,12 +34,6 @@ const bridge: DesktopBridge = {
|
||||
ipcRenderer.on('courseware:progress', listener);
|
||||
return () => ipcRenderer.removeListener('courseware:progress', listener);
|
||||
},
|
||||
islandEditLayout: () => ipcRenderer.invoke('island:edit-layout'),
|
||||
onIslandEditorOpen: (handler) => {
|
||||
const listener = () => handler();
|
||||
ipcRenderer.on('island:open-editor', listener);
|
||||
return () => ipcRenderer.removeListener('island:open-editor', listener);
|
||||
},
|
||||
smokeTest: process.env.ELECTRON_SMOKE_TEST === '1',
|
||||
// 冒烟凭据:只在冒烟模式下透传,供渲染进程的冒烟钩子构造测试数据用。
|
||||
// **不走代码字面量**——本文件与渲染产物都会进 app.asar,写死账号等于随安装包把教师口令发出去。
|
||||
|
||||
@@ -16,12 +16,9 @@ export interface IslandBridge {
|
||||
onTheme(handler: (theme: 'light' | 'dark') => void): void;
|
||||
getIslandWeather(coordinates: { latitude: number; longitude: number }): Promise<IslandWeather>;
|
||||
getLayout(): Promise<ContractIslandLayoutSettings>;
|
||||
saveLayout(value: ContractIslandLayoutSettings): Promise<ContractIslandLayoutSettings>;
|
||||
onLayout(handler: (value: ContractIslandLayoutSettings) => void): void;
|
||||
getEditing(): Promise<boolean>;
|
||||
getVisible(): Promise<boolean>;
|
||||
onVisibility(handler: (visible: boolean) => void): void;
|
||||
setEditing(value: boolean): Promise<void>;
|
||||
onEditing(handler: (value: boolean) => void): void;
|
||||
reportSize(value: { width: number; height: number }): void;
|
||||
reportResidentControl(value: { x: number; y: number; width: number; height: number } | null): void;
|
||||
@@ -70,16 +67,13 @@ const bridge: IslandBridge = {
|
||||
},
|
||||
getIslandWeather: (coordinates) => ipcRenderer.invoke('island:weather', coordinates),
|
||||
getLayout: () => ipcRenderer.invoke('island:get-layout'),
|
||||
saveLayout: (value) => ipcRenderer.invoke('island:save-layout', value),
|
||||
onLayout: (handler) => {
|
||||
ipcRenderer.on('island:layout', (_event, value) => handler(value));
|
||||
},
|
||||
getEditing: () => ipcRenderer.invoke('island:get-editing'),
|
||||
getVisible: () => ipcRenderer.invoke('island:get-visible'),
|
||||
onVisibility: (handler) => {
|
||||
ipcRenderer.on('island:visibility', (_event, value) => handler(value));
|
||||
},
|
||||
setEditing: (value) => ipcRenderer.invoke('island:set-editing', value),
|
||||
onEditing: (handler) => {
|
||||
ipcRenderer.on('island:editing', (_event, value) => handler(value));
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
API_PATHS,
|
||||
type ClassDetailDto,
|
||||
type ClassDto,
|
||||
type ClassIslandLayoutDto,
|
||||
type CourseDto,
|
||||
type ExamDto,
|
||||
type ExamRankingDto,
|
||||
@@ -46,6 +47,12 @@ export const classApi = {
|
||||
detail: (id: string): Promise<ClassDetailDto> => api.get(`${API_PATHS.classes}/${id}`),
|
||||
};
|
||||
|
||||
/** 班级级灵动岛:教室端只读本班方案,编辑入口只在 Web 管理端。 */
|
||||
export const classIslandLayoutApi = {
|
||||
get: (classId: string): Promise<ClassIslandLayoutDto> =>
|
||||
api.get(`${API_PATHS.classes}/${classId}/island-layout`),
|
||||
};
|
||||
|
||||
export const scheduleApi = {
|
||||
list: (params: { classId?: string; week?: number }): Promise<ScheduleDto[]> =>
|
||||
api.get(API_PATHS.schedules, params),
|
||||
|
||||
@@ -1294,48 +1294,9 @@ export async function islandScheduleSyncSelfTest(): Promise<SmokeCheckResult> {
|
||||
}
|
||||
}
|
||||
|
||||
let restoreIslandEditorSmoke: (() => Promise<void>) | undefined;
|
||||
/** 主窗口内编辑器验收使用纯本地 API 替身,结束后恢复登录态、路由与方法。 */
|
||||
async function islandEditorSmoke(open: boolean): Promise<void> {
|
||||
if (!open) {
|
||||
await restoreIslandEditorSmoke?.();
|
||||
restoreIslandEditorSmoke = undefined;
|
||||
return;
|
||||
}
|
||||
const [{ api }, { useAuthStore }, { router }] = await Promise.all([
|
||||
import('../api/http.js'),
|
||||
import('../stores/auth.js'),
|
||||
import('../router/index.js'),
|
||||
]);
|
||||
const auth = useAuthStore(),
|
||||
token = auth.token,
|
||||
path = router.currentRoute.value.fullPath,
|
||||
originalGet = api.get;
|
||||
const onboardingDone = (await window.desktop!.getConfig()).onboardingDone;
|
||||
await window.desktop!.saveConfig({ onboardingDone: true });
|
||||
api.get = (async (url: string) => {
|
||||
if (url.includes('unread-count')) return { count: 0 };
|
||||
if (url.includes('active-week')) return { days: [] };
|
||||
if (url.includes('term')) return { currentWeek: 1, maxWeek: 40 };
|
||||
return [];
|
||||
}) as typeof api.get;
|
||||
auth.applyToken('local-editor-smoke');
|
||||
const { useOnboardingStore } = await import('../stores/onboarding.js');
|
||||
useOnboardingStore().close();
|
||||
restoreIslandEditorSmoke = async () => {
|
||||
await router.push('/login');
|
||||
auth.applyToken(token);
|
||||
await router.push(path);
|
||||
api.get = originalGet;
|
||||
await window.desktop!.saveConfig({ onboardingDone });
|
||||
};
|
||||
await router.push('/settings/island/editor');
|
||||
}
|
||||
|
||||
/** 注册到 window,供主进程冒烟脚本调用 */
|
||||
export function registerSmokeHooks(): void {
|
||||
window.__classhelperSmoke__ = {
|
||||
islandEditorSmoke,
|
||||
islandScheduleSyncSelfTest,
|
||||
cacheSelfTest,
|
||||
cacheIsolationSelfTest,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ActiveClassPlanWeekDto as ContractActiveClassPlanWeekDto } from '@
|
||||
import { watch, type WatchStopHandle } from 'vue';
|
||||
import {
|
||||
SOCKET_EVENTS,
|
||||
defaultIslandLayouts,
|
||||
resolveClassStatus,
|
||||
type ClassPeriod,
|
||||
type HomeworkDto,
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
type ScheduleDto,
|
||||
} from '@classhelper/shared';
|
||||
import { api } from '../api/http.js';
|
||||
import { notificationApi } from '../api/index.js';
|
||||
import { classIslandLayoutApi, notificationApi } from '../api/index.js';
|
||||
import { fetchWithCache } from '../cache/index.js';
|
||||
import { getCacheScope } from '../cache/scope.js';
|
||||
import { clearOfflineSince, readOfflineSince, useAppStore } from '../stores/app.js';
|
||||
@@ -40,6 +41,8 @@ let refreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let stopWeekWatch: WatchStopHandle | null = null;
|
||||
let scheduleRequest = 0;
|
||||
let scheduleWeek = 1;
|
||||
let appliedIslandLayout = '';
|
||||
let islandLayoutRequest = 0;
|
||||
|
||||
/** 供通知投递时读取:当前是否上课 + 本节课结束时间 */
|
||||
export function getIslandClassContext(): { inClass: boolean; currentPeriodEnd: string | null } {
|
||||
@@ -135,6 +138,47 @@ export async function refreshIslandSchedules(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步 Web 管理端为当前班保存的灵动岛方案。
|
||||
*
|
||||
* 班级端没有编辑入口:这里只拉取、比较并写入本机配置,主进程收到 config 补丁后会重启岛布局。
|
||||
* 服务端返回 `null` 表示尚未配置,保留本机默认/兼容方案;切换班级后旧响应不得落到新班。
|
||||
*/
|
||||
export async function syncClassIslandLayout(): Promise<void> {
|
||||
const auth = useAuthStore();
|
||||
const classId = auth.classId;
|
||||
if (!auth.token || !classId || !window.desktop?.saveConfig) return;
|
||||
const request = ++islandLayoutRequest;
|
||||
try {
|
||||
const result = await classIslandLayoutApi.get(classId);
|
||||
const current = await window.desktop.getConfig();
|
||||
if (request !== islandLayoutRequest || useAuthStore().classId !== classId) return;
|
||||
const local = current?.islandLayout ?? defaultIslandLayouts();
|
||||
const next = result.layout
|
||||
? {
|
||||
...result.layout,
|
||||
// 提醒阈值与指针避让属于教室本机偏好,服务端只下发班级布局。
|
||||
pointerFadeEnabled: local.pointerFadeEnabled,
|
||||
pointerFadeReversed: local.pointerFadeReversed,
|
||||
lessonReminders: local.lessonReminders,
|
||||
}
|
||||
: {
|
||||
...defaultIslandLayouts(),
|
||||
pointerFadeEnabled: local.pointerFadeEnabled,
|
||||
pointerFadeReversed: local.pointerFadeReversed,
|
||||
lessonReminders: local.lessonReminders,
|
||||
};
|
||||
const key = JSON.stringify(next);
|
||||
if (key === appliedIslandLayout) return;
|
||||
if (JSON.stringify(current?.islandLayout) !== key) {
|
||||
await window.desktop.saveConfig({ islandLayout: next });
|
||||
}
|
||||
if (request === islandLayoutRequest && useAuthStore().classId === classId) appliedIslandLayout = key;
|
||||
} catch {
|
||||
// 离线时保留本机已缓存的班级方案;恢复连接后由 class:updated / 周期同步补取。
|
||||
}
|
||||
}
|
||||
|
||||
let sentDay = '';
|
||||
let sentTimePoints = '';
|
||||
function timePointsKey(): string {
|
||||
@@ -413,6 +457,11 @@ function onScheduleUpdated(): void {
|
||||
void refreshIslandSchedules().catch(() => undefined);
|
||||
}
|
||||
|
||||
/** 班级资料变化:布局下发也走 class:updated,收到后静默补取。 */
|
||||
function onClassUpdated(): void {
|
||||
void syncClassIslandLayout();
|
||||
}
|
||||
|
||||
export function startIslandBridge(): void {
|
||||
if (tickTimer) return;
|
||||
stopWeekWatch = watch(
|
||||
@@ -423,14 +472,17 @@ export function startIslandBridge(): void {
|
||||
);
|
||||
|
||||
onScheduleUpdated();
|
||||
void syncClassIslandLayout();
|
||||
useRealtimeStore().on('__connected__', onScheduleUpdated);
|
||||
|
||||
// 课表变更(教师改课)立即复算,避免"下课后不弹出"或"上课没隐藏"
|
||||
useRealtimeStore().on(SOCKET_EVENTS.scheduleUpdated, onScheduleUpdated);
|
||||
useRealtimeStore().on(SOCKET_EVENTS.classUpdated, onClassUpdated);
|
||||
|
||||
tickTimer = setInterval(() => recomputeClassState(), TICK_INTERVAL_MS);
|
||||
refreshTimer = setInterval(() => {
|
||||
onScheduleUpdated();
|
||||
void syncClassIslandLayout();
|
||||
}, REFRESH_INTERVAL_MS);
|
||||
}
|
||||
|
||||
@@ -448,10 +500,12 @@ export function stopIslandBridge(): void {
|
||||
tickTimer = null;
|
||||
refreshTimer = null;
|
||||
scheduleRequest += 1;
|
||||
islandLayoutRequest += 1;
|
||||
stopWeekWatch?.();
|
||||
stopWeekWatch = null;
|
||||
|
||||
useRealtimeStore().off(SOCKET_EVENTS.scheduleUpdated, onScheduleUpdated);
|
||||
useRealtimeStore().off(SOCKET_EVENTS.classUpdated, onClassUpdated);
|
||||
useRealtimeStore().off('__connected__', onScheduleUpdated);
|
||||
sentDay = '';
|
||||
sentTimePoints = '';
|
||||
@@ -459,6 +513,7 @@ export function stopIslandBridge(): void {
|
||||
dayTimePoints = [];
|
||||
currentPeriod = null;
|
||||
inClass = false;
|
||||
appliedIslandLayout = '';
|
||||
|
||||
// 把"不在上课"同步给主进程:否则主进程还记着上一个会话的"上课中",
|
||||
// 重新登录后若第一轮课表刷新失败(离线且无缓存),灵动岛会继续按上课态把通知压着不弹,
|
||||
|
||||
@@ -20,11 +20,6 @@ const auth = useAuthStore();
|
||||
const realtime = useRealtimeStore();
|
||||
const notifications = useNotificationStore();
|
||||
const ui = useUiStore();
|
||||
const stopEditorNavigation = window.desktop?.onIslandEditorOpen(
|
||||
() => void router.push('/settings/island/editor'),
|
||||
);
|
||||
onUnmounted(() => stopEditorNavigation?.());
|
||||
|
||||
/**
|
||||
* 主侧边栏。
|
||||
*
|
||||
|
||||
@@ -18,7 +18,12 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import('../layouts/ClientLayout.vue'),
|
||||
redirect: '/schedule',
|
||||
children: [
|
||||
{ path: 'courseware', name: 'courseware', component: () => import('../views/CoursewareView.vue'), meta: { title: '课件' } },
|
||||
{
|
||||
path: 'courseware',
|
||||
name: 'courseware',
|
||||
component: () => import('../views/CoursewareView.vue'),
|
||||
meta: { title: '课件' },
|
||||
},
|
||||
{
|
||||
path: 'schedule',
|
||||
name: 'schedule',
|
||||
@@ -66,12 +71,6 @@ const routes: RouteRecordRaw[] = [
|
||||
component: () => import('../views/settings/IslandSettingsView.vue'),
|
||||
meta: { title: '灵动岛' },
|
||||
},
|
||||
{
|
||||
path: 'settings/island/editor',
|
||||
name: 'settings-island-editor',
|
||||
component: () => import('../views/settings/IslandEditorView.vue'),
|
||||
meta: { title: '自定义灵动岛' },
|
||||
},
|
||||
{
|
||||
path: 'settings/reminder',
|
||||
name: 'settings-reminder',
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { confirmAction } from '../../composables/confirm.js';
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { useRouter } from 'vue-router';
|
||||
import {
|
||||
CLASSISLAND_TOKENS,
|
||||
DEFAULT_ISLAND_APPEARANCE,
|
||||
@@ -28,38 +27,16 @@ import {
|
||||
*/
|
||||
const island = ref<IslandAppearance>({ ...DEFAULT_ISLAND_APPEARANCE });
|
||||
const savingIsland = ref(false);
|
||||
const router = useRouter();
|
||||
function editLayout() {
|
||||
layoutMode.value = 'custom';
|
||||
void router.push('/settings/island/editor');
|
||||
}
|
||||
const layoutMode = ref<'fixed' | 'custom'>('fixed');
|
||||
const layoutSettings = ref(defaultIslandLayouts());
|
||||
const layoutMode = computed(() => layoutSettings.value.layout);
|
||||
const activeScheme = computed(() =>
|
||||
layoutSettings.value.schemes.find((s) => s.id === layoutSettings.value.activeSchemeId)!,
|
||||
);
|
||||
const currentRadius = computed(() =>
|
||||
layoutMode.value === 'custom' ? activeScheme.value.radius : island.value.radius,
|
||||
);
|
||||
const residentEnabled = ref(false);
|
||||
const pointerFadeEnabled = ref(true);
|
||||
const pointerFadeReversed = ref(false);
|
||||
async function changeLayout() {
|
||||
const config = await window.desktop?.getConfig();
|
||||
if (config)
|
||||
await window.desktop?.saveConfig({
|
||||
islandLayout: {
|
||||
...config.islandLayout,
|
||||
layout: layoutMode.value,
|
||||
residentEnabled: residentEnabled.value,
|
||||
},
|
||||
});
|
||||
}
|
||||
async function chooseLayout(mode: 'fixed' | 'custom') {
|
||||
layoutMode.value = mode;
|
||||
residentEnabled.value = mode === 'custom';
|
||||
await changeLayout();
|
||||
}
|
||||
async function changePointerFade(
|
||||
key: 'pointerFadeEnabled' | 'pointerFadeReversed',
|
||||
value: boolean | string | number,
|
||||
@@ -77,8 +54,6 @@ async function changePointerFade(
|
||||
async function loadLayout() {
|
||||
const settings = (await window.desktop?.getConfig())?.islandLayout;
|
||||
if (settings) layoutSettings.value = settings;
|
||||
layoutMode.value = settings?.layout ?? 'fixed';
|
||||
residentEnabled.value = settings?.residentEnabled ?? false;
|
||||
pointerFadeEnabled.value = settings?.pointerFadeEnabled ?? true;
|
||||
pointerFadeReversed.value = settings?.pointerFadeReversed ?? false;
|
||||
}
|
||||
@@ -179,32 +154,15 @@ onMounted(async () => {
|
||||
|
||||
<el-card shadow="never" class="layout-mode-card">
|
||||
<template #header><span>岛内布局</span></template>
|
||||
<div class="layout-choices">
|
||||
<button
|
||||
class="layout-choice"
|
||||
:class="{ active: layoutMode === 'fixed' }"
|
||||
:aria-pressed="layoutMode === 'fixed'"
|
||||
@click="chooseLayout('fixed')"
|
||||
>
|
||||
<strong>经典灵动岛</strong>
|
||||
<span>显示课程进度、上下课提醒与班级消息</span>
|
||||
</button>
|
||||
<button
|
||||
class="layout-choice"
|
||||
:class="{ active: layoutMode === 'custom' }"
|
||||
:aria-pressed="layoutMode === 'custom'"
|
||||
@click="chooseLayout('custom')"
|
||||
>
|
||||
<strong>自定义灵动岛</strong>
|
||||
<span>ClassIsland 风格,常驻显示时钟、课程等组件</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="layoutMode === 'custom'" class="layout-edit-entry">
|
||||
<div class="layout-managed">
|
||||
<div>
|
||||
<strong>按你的习惯布置岛内内容</strong>
|
||||
<p>编辑常态内容与无通知展开内容;课前自动提示,通知操作与经典岛共用。</p>
|
||||
<strong>{{ layoutMode === 'custom' ? '班级自定义灵动岛' : '默认经典灵动岛' }}</strong>
|
||||
<p v-if="layoutMode === 'custom'">
|
||||
当前班使用网页管理端下发的组件方案;班级端只读并自动同步,不再提供本地编辑入口。
|
||||
</p>
|
||||
<p v-else>当前班尚未由网页管理端下发自定义方案,暂时使用默认经典灵动岛。</p>
|
||||
</div>
|
||||
<el-button type="primary" @click="editLayout">编辑岛内组件</el-button>
|
||||
<el-tag type="info" effect="plain">{{ layoutMode === 'custom' ? '服务端同步' : '默认方案' }}</el-tag>
|
||||
</div>
|
||||
<div v-if="layoutMode === 'custom'" class="resident-window-options">
|
||||
<div>
|
||||
@@ -522,19 +480,17 @@ onMounted(async () => {
|
||||
outline: 2px solid var(--el-color-primary);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.layout-edit-entry {
|
||||
.layout-managed {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
margin-top: 20px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid var(--el-border-color-lighter);
|
||||
padding: 4px 2px;
|
||||
}
|
||||
.layout-edit-entry strong {
|
||||
.layout-managed strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
.layout-edit-entry p {
|
||||
.layout-managed p {
|
||||
margin: 8px 0 0;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-size: 12px;
|
||||
@@ -544,9 +500,8 @@ onMounted(async () => {
|
||||
.layout-choices {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.layout-edit-entry {
|
||||
.layout-managed {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -120,8 +120,6 @@ export interface DesktopBridge {
|
||||
onCoursewareTransfer(
|
||||
handler: (value: import('@classhelper/shared').CoursewareTransfer | null) => void,
|
||||
): () => void;
|
||||
islandEditLayout(): Promise<void>;
|
||||
onIslandEditorOpen(handler: () => void): () => void;
|
||||
getUpdateProgress(): Promise<ContractReleaseProgressDto>;
|
||||
onUpdateProgress(handler: (progress: ContractReleaseProgressDto) => void): () => void;
|
||||
/** 是否处于冒烟验证模式(由 ELECTRON_SMOKE_TEST=1 触发),同步可读 */
|
||||
@@ -243,7 +241,6 @@ declare global {
|
||||
island?: IslandRendererBridge;
|
||||
/** 冒烟验证钩子,仅在 ELECTRON_SMOKE_TEST=1 时由渲染进程注册 */
|
||||
__classhelperSmoke__?: {
|
||||
islandEditorSmoke(open: boolean): Promise<void>;
|
||||
islandScheduleSyncSelfTest(): Promise<{ ok: boolean; detail: string }>;
|
||||
cacheSelfTest(): Promise<{ ok: boolean; detail: string }>;
|
||||
cacheIsolationSelfTest(): Promise<{ ok: boolean; detail: string }>;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- 班级级自定义灵动岛:由 Web 管理端编辑,教室客户端只读同步。
|
||||
ALTER TABLE `Class` ADD COLUMN `islandLayoutJson` TEXT;
|
||||
ALTER TABLE `Class` ADD COLUMN `islandLayoutUpdatedAt` DATETIME;
|
||||
@@ -236,6 +236,10 @@ model Class {
|
||||
/// 是否允许 ClassHelper 班级端按学号查询本班学生的成绩明细(默认开启)。
|
||||
/// 关闭后班级端查成绩一律 403;教师端不受影响。
|
||||
studentGradeQueryEnabled Boolean @default(true)
|
||||
/// Web 管理端下发的班级级自定义灵动岛方案(shared 的 IslandLayoutSettings 归一化 JSON)。
|
||||
/// 空值表示尚未配置,教室端沿用本机默认方案。
|
||||
islandLayoutJson String?
|
||||
islandLayoutUpdatedAt DateTime?
|
||||
/// 毕业归档所属届别;null = 在读(常规班级列表只显示未归档的)
|
||||
archivedYearId String?
|
||||
archivedAt DateTime?
|
||||
|
||||
@@ -15,6 +15,7 @@ import { readFileSync } from 'node:fs';
|
||||
* VERIFY_BASE_URL 默认 http://127.0.0.1:4000
|
||||
*/
|
||||
import { io } from 'socket.io-client';
|
||||
import { defaultIslandLayouts } from '@classhelper/shared';
|
||||
import { verifyClassPlanYamlApi } from './verify-class-plan-yaml-api.mjs';
|
||||
|
||||
const BASE_URL = process.env.VERIFY_BASE_URL ?? `http://127.0.0.1:${process.env.PORT ?? 4000}`;
|
||||
@@ -161,6 +162,33 @@ async function main() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 班级灵动岛同步与只读边界
|
||||
const classIslandBaseline = await api(`/classes/${classId}/island-layout`, { token: teacherToken });
|
||||
const classIslandLayout = defaultIslandLayouts();
|
||||
classIslandLayout.layout = 'custom';
|
||||
classIslandLayout.residentEnabled = true;
|
||||
const saveClassIsland = await api(`/classes/${classId}/island-layout`, {
|
||||
method: 'PATCH',
|
||||
token: teacherToken,
|
||||
body: { layout: classIslandLayout },
|
||||
});
|
||||
const classDeviceIsland = await api(`/classes/${classId}/island-layout`, { token: studentToken });
|
||||
const classDeviceWrite = await api(`/classes/${classId}/island-layout`, {
|
||||
method: 'PATCH',
|
||||
token: studentToken,
|
||||
body: { layout: classIslandLayout },
|
||||
});
|
||||
record(
|
||||
'班级灵动岛:班主任保存、班级端只读同步、班级端写入被拒',
|
||||
classIslandBaseline.status === 200 &&
|
||||
saveClassIsland.status === 200 &&
|
||||
saveClassIsland.payload?.data?.layout?.layout === 'custom' &&
|
||||
classDeviceIsland.status === 200 &&
|
||||
classDeviceIsland.payload?.data?.layout?.schemes?.[0]?.rows?.length > 0 &&
|
||||
classDeviceWrite.status === 403,
|
||||
`baseline=${classIslandBaseline.status} save=${saveClassIsland.status} read=${classDeviceIsland.status} write=${classDeviceWrite.status}`,
|
||||
);
|
||||
|
||||
// teacher2 名下但 teacher1 无权访问的班级,用于验证教师间权限隔离。
|
||||
// 注意:演示库里可能被人工改过(管理员自己建班、给别的班加协作教师),
|
||||
// 因此这里**不允许依赖种子数据的班级布局**:没有现成的就现建一个临时班级,收尾删除。
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
listClassesQuerySchema,
|
||||
promoteClassesSchema,
|
||||
updateClassAccountSchema,
|
||||
updateClassIslandLayoutSchema,
|
||||
updateClassSchema,
|
||||
updateClassSettingsSchema,
|
||||
type UpdateClassSettingsInput,
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
type AssignSubjectTeachersInput,
|
||||
type CreateClassInput,
|
||||
type UpdateClassAccountInput,
|
||||
type UpdateClassIslandLayoutInput,
|
||||
type UpdateClassInput,
|
||||
type UpdateStudentGradeQueryInput,
|
||||
} from './classes.schemas.js';
|
||||
@@ -128,6 +130,36 @@ router.patch(
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/classes/:id/island-layout - 班级级灵动岛方案(班级端可只读本班)
|
||||
* PATCH 同路径 - Web 管理端保存;仅本班班主任或管理员,班级端不可写
|
||||
*/
|
||||
router.get(
|
||||
'/:id/island-layout',
|
||||
requirePermissionOrClassDevice('class:read'),
|
||||
validate({ params: idParamSchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const { id } = validatedParams<{ id: string }>(req);
|
||||
sendOk(res, await classService.getClassIslandLayout(user, id), '获取班级灵动岛方案成功');
|
||||
},
|
||||
);
|
||||
|
||||
router.patch(
|
||||
'/:id/island-layout',
|
||||
requirePermission('class:settings'),
|
||||
validate({ params: idParamSchema, body: updateClassIslandLayoutSchema }),
|
||||
async (req, res) => {
|
||||
const user = getAuthUser(req);
|
||||
const { id } = validatedParams<{ id: string }>(req);
|
||||
sendOk(
|
||||
res,
|
||||
await classService.updateClassIslandLayout(user, id, validatedBody<UpdateClassIslandLayoutInput>(req)),
|
||||
'班级灵动岛方案已保存',
|
||||
);
|
||||
},
|
||||
);
|
||||
/** DELETE /api/classes/:id - 删除班级 */
|
||||
router.delete(
|
||||
'/:id',
|
||||
|
||||
@@ -53,6 +53,11 @@ export const updateClassSettingsSchema = z.strictObject({
|
||||
termWeeks: z.coerce.number().int().min(1).max(60).optional(),
|
||||
});
|
||||
|
||||
/** 班级级灵动岛方案:具体结构由 shared 的 normalizeIslandLayouts 统一收敛。 */
|
||||
export const updateClassIslandLayoutSchema = z.strictObject({
|
||||
layout: z.unknown(),
|
||||
});
|
||||
|
||||
/** 学年升级(批量改年级,不归档) */
|
||||
export const promoteClassesSchema = z.strictObject({
|
||||
classIds: z.array(z.string().min(1)).min(1, '请至少选择一个班级').max(200),
|
||||
@@ -130,3 +135,4 @@ export type AddStudentInput = z.infer<typeof addStudentSchema>;
|
||||
export type AssignSubjectTeachersInput = z.infer<typeof assignSubjectTeachersSchema>;
|
||||
|
||||
export type UpdateClassSettingsInput = z.infer<typeof updateClassSettingsSchema>;
|
||||
export type UpdateClassIslandLayoutInput = z.infer<typeof updateClassIslandLayoutSchema>;
|
||||
@@ -1,8 +1,14 @@
|
||||
import { disconnectUserSessions, refreshClassSubscriptions } from '../../realtime/bus.js';
|
||||
import { assertHeadOnly, assertManage } from '../../lib/authz/index.js';
|
||||
import { auditData } from '../permissions/permissions.service.js';
|
||||
import type { ClassDetailDto, ClassDto, StudentDto, SubjectTeacherDto } from '@classhelper/shared';
|
||||
import { SOCKET_EVENTS, formatClassName } from '@classhelper/shared';
|
||||
import type {
|
||||
ClassDetailDto,
|
||||
ClassDto,
|
||||
ClassIslandLayoutDto,
|
||||
StudentDto,
|
||||
SubjectTeacherDto,
|
||||
} from '@classhelper/shared';
|
||||
import { SOCKET_EVENTS, formatClassName, normalizeIslandLayouts } from '@classhelper/shared';
|
||||
import { env } from '../../config/env.js';
|
||||
import {
|
||||
assertCanAssignTeachers,
|
||||
@@ -26,6 +32,7 @@ import type {
|
||||
AssignSubjectTeachersInput,
|
||||
CreateClassInput,
|
||||
UpdateClassInput,
|
||||
UpdateClassIslandLayoutInput,
|
||||
UpdateClassSettingsInput,
|
||||
UpdateStudentGradeQueryInput,
|
||||
} from './classes.schemas.js';
|
||||
@@ -441,6 +448,94 @@ export async function updateClassSettings(
|
||||
emitToClass(classId, SOCKET_EVENTS.classUpdated, { classId, action: 'updated' });
|
||||
return toClassDto(updated);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取班级级灵动岛方案。
|
||||
*
|
||||
* 班级端必须能读自己的方案(allowClassDevice),教师/管理员仍按 class:read + 班级范围判定。
|
||||
* 尚未配置时返回 `layout: null`,不能在读取阶段把服务端默认值写回班级,避免管理页一打开就产生写操作。
|
||||
*/
|
||||
export async function getClassIslandLayout(
|
||||
user: TokenPayload,
|
||||
classId: string,
|
||||
): Promise<ClassIslandLayoutDto> {
|
||||
await assertClassAccess(user, classId, 'class:read');
|
||||
const record = await prisma.class.findUnique({
|
||||
where: { id: classId },
|
||||
select: { id: true, islandLayoutJson: true, islandLayoutUpdatedAt: true },
|
||||
});
|
||||
if (!record) throw ApiError.notFound('班级不存在');
|
||||
const layout = parseStoredIslandLayout(record.islandLayoutJson, classId);
|
||||
return {
|
||||
classId: record.id,
|
||||
layout,
|
||||
updatedAt: record.islandLayoutUpdatedAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存班级级灵动岛方案。
|
||||
*
|
||||
* 编辑入口只在 Web 管理端;班级端没有写接口。班主任可维护本班,管理员不受班主任关系限制。
|
||||
* 保存后广播 class:updated,教室端重新拉取并更新常驻岛。
|
||||
*/
|
||||
export async function updateClassIslandLayout(
|
||||
user: TokenPayload,
|
||||
classId: string,
|
||||
input: UpdateClassIslandLayoutInput,
|
||||
): Promise<ClassIslandLayoutDto> {
|
||||
await assertHeadOnly(user, 'class:settings', classId);
|
||||
if (!input.layout || typeof input.layout !== 'object') throw ApiError.badRequest('灵动岛方案格式不正确');
|
||||
|
||||
const layout = normalizeIslandLayouts(input.layout);
|
||||
// 班级方案是“Web 端自由编辑的常驻岛”,不把 fixed 模式误下发成关闭自定义布局。
|
||||
layout.layout = 'custom';
|
||||
layout.residentEnabled = true;
|
||||
const before = await prisma.class.findUniqueOrThrow({
|
||||
where: { id: classId },
|
||||
select: { islandLayoutJson: true, islandLayoutUpdatedAt: true },
|
||||
});
|
||||
const updated = await prisma.class.update({
|
||||
where: { id: classId },
|
||||
data: {
|
||||
islandLayoutJson: JSON.stringify(layout),
|
||||
islandLayoutUpdatedAt: new Date(),
|
||||
},
|
||||
select: { id: true, islandLayoutJson: true, islandLayoutUpdatedAt: true },
|
||||
});
|
||||
const summary = (value: ClassIslandLayoutDto['layout']) => ({
|
||||
configured: Boolean(value),
|
||||
schemeCount: value?.schemes.length ?? 0,
|
||||
rowCount: value?.schemes.reduce((count, scheme) => count + scheme.rows.length, 0) ?? 0,
|
||||
activeSchemeId: value?.activeSchemeId ?? null,
|
||||
});
|
||||
await prisma.permissionAudit.create({
|
||||
data: auditData(
|
||||
user,
|
||||
'class-island-layout',
|
||||
'class',
|
||||
classId,
|
||||
summary(parseStoredIslandLayout(before.islandLayoutJson, classId)),
|
||||
summary(layout),
|
||||
),
|
||||
});
|
||||
emitToClass(classId, SOCKET_EVENTS.classUpdated, { classId, action: 'island-layout' });
|
||||
return {
|
||||
classId: updated.id,
|
||||
layout,
|
||||
updatedAt: updated.islandLayoutUpdatedAt?.toISOString() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function parseStoredIslandLayout(value: string | null, classId: string): ClassIslandLayoutDto['layout'] {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return normalizeIslandLayouts(JSON.parse(value));
|
||||
} catch {
|
||||
logger.warn(`班级灵动岛方案 JSON 无法解析,已按未配置处理:classId=${classId}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 学年升级(按升级权限与班级范围):把若干班级的年级改掉,**不归档、数据沿用**。
|
||||
*
|
||||
|
||||
@@ -273,7 +273,7 @@ export const PERMISSION_LABELS: Record<PermissionKey, string> = {
|
||||
'class:read': '查看班级与班级列表',
|
||||
'class:manage': '创建 / 修改 / 删除班级',
|
||||
'class:account': '管理本班班级码与密码(仅班主任)',
|
||||
'class:settings': '管理本班学期设置(仅班主任)',
|
||||
'class:settings': '管理本班学期设置与灵动岛(仅班主任)',
|
||||
'roster:read': '查看学生名单',
|
||||
'roster:manage': '学生名单管理(资料 / 调班 / 转入转出 / 停用)',
|
||||
'teacher:read': '查看教师名单',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AiConversationRequest, AiReasoningEffort } from './ai.js';
|
||||
import type { CoursewareTransfer } from './courseware.js';
|
||||
import type { IslandLayoutSettings } from './island-layout.js';
|
||||
import type {
|
||||
ClientUpdateProgressDto,
|
||||
PermissionScope as ContractPermissionScope,
|
||||
@@ -477,6 +478,22 @@ export interface ClassDetailDto extends ClassDto {
|
||||
subjectTeachers: SubjectTeacherDto[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 班级级自定义灵动岛方案。
|
||||
*
|
||||
* `layout` 为空表示该班尚未在 Web 管理端配置,教室端继续使用本机默认/兼容配置;
|
||||
* 一旦保存,教室端登录本班后会以服务端方案为准。
|
||||
*/
|
||||
export interface ClassIslandLayoutDto {
|
||||
classId: string;
|
||||
layout: IslandLayoutSettings | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateClassIslandLayoutRequest {
|
||||
layout: IslandLayoutSettings;
|
||||
}
|
||||
|
||||
export interface CreateClassRequest {
|
||||
/**
|
||||
* 班级称呼。**可以留空** —— 填了 `enrollmentYear` 与 `classIndex` 时由服务端生成「2026级1班」,
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type AssignUserGroupsRequest,
|
||||
type ClassDetailDto,
|
||||
type ClassDto,
|
||||
type ClassIslandLayoutDto,
|
||||
type AutoTermWeeksRequest,
|
||||
type ClassPlanImportResultDto,
|
||||
type ClassPlanPreviewDto,
|
||||
@@ -85,6 +86,7 @@ import {
|
||||
type TimeLayoutParsePreview,
|
||||
type UpdateAiSettingsRequest,
|
||||
type UpdateClassAccountRequest,
|
||||
type UpdateClassIslandLayoutRequest,
|
||||
type UpdateClassRequest,
|
||||
type UpdateInfo,
|
||||
type UpdatePermissionGroupRequest,
|
||||
@@ -143,6 +145,10 @@ export const classApi = {
|
||||
api.patch(`${API_PATHS.classes}/${id}/class-account`, payload),
|
||||
setGradeQuery: (id: string, enabled: boolean): Promise<{ studentGradeQueryEnabled: boolean }> =>
|
||||
api.patch(`${API_PATHS.classes}/${id}/student-grade-query`, { enabled }),
|
||||
islandLayout: (id: string): Promise<ClassIslandLayoutDto> =>
|
||||
api.get(`${API_PATHS.classes}/${id}/island-layout`),
|
||||
saveIslandLayout: (id: string, payload: UpdateClassIslandLayoutRequest): Promise<ClassIslandLayoutDto> =>
|
||||
api.patch(`${API_PATHS.classes}/${id}/island-layout`, payload),
|
||||
/** 学年升级:只改年级,不归档、数据沿用 */
|
||||
promote: (classIds: string[]): Promise<{ promoted: number }> =>
|
||||
api.post(`${API_PATHS.classes}/promote`, { classIds }),
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<script setup lang="ts">
|
||||
import type { IslandComponentKind } from '@classhelper/shared';
|
||||
|
||||
defineProps<{ kind: IslandComponentKind }>();
|
||||
|
||||
const paths: Record<IslandComponentKind, string> = {
|
||||
clock: 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0ZM12 7v5l3 2',
|
||||
weather:
|
||||
'M16 12a4 4 0 1 1-8 0 4 4 0 0 1 8 0ZM12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5',
|
||||
date: 'M6 5h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2ZM8 3v4m8-4v4M4 10h16M8 14h2m4 0h2m-8 3h2',
|
||||
schedule: 'M9 5h11M9 12h11M9 19h11M4 5h1m-1 7h1m-1 7h1',
|
||||
countdown: 'M6 3h12M6 21h12M8 3v4l4 5-4 5v4m8-18v4l-4 5 4 5v4',
|
||||
text: 'M6 3h12a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3Zm1 5h10M7 12h7m-7 4h10',
|
||||
separator: 'M12 4v16M5 8v8m14-8v8',
|
||||
notification: 'M9 19a3 3 0 0 0 6 0M6 10a6 6 0 0 1 12 0v4l2 3H4l2-3v-4Z',
|
||||
homework: 'M9 4H6a2 2 0 0 0-2 2v14h16V6a2 2 0 0 0-2-2h-3M9 3h6v4H9V3Zm-1 9h8m-8 4h5',
|
||||
call: 'M4 10h4l6-5v14l-6-5H4v-4Zm13-2a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14',
|
||||
group: 'M3 5h18v14H3V5Zm4 4h4v6H7V9Zm8 0h2v6h-2V9Z',
|
||||
stack: 'm12 3 9 5-9 5-9-5 9-5ZM3 12l9 5 9-5M3 16l9 5 9-5',
|
||||
slide: 'M6 5h12v14H6V5ZM2 8v8m20-8v8m-12 7h4',
|
||||
rolling: 'M3 8h17m-4-4 4 4-4 4M21 16H4m4-4-4 4 4 4',
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
height="24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.5"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path :d="paths[kind]" />
|
||||
</svg>
|
||||
</template>
|
||||
+1
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
/** Web 管理端班级灵动岛的组件检查器。 */
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import {
|
||||
CLASSISLAND_TOKENS,
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { ISLAND_COMPONENT_LABELS, type IslandComponentNode } from '@classhelper/shared';
|
||||
import ComponentIcon from '../../island/ComponentIcon.vue';
|
||||
import ComponentIcon from './ComponentIcon.vue';
|
||||
const props = defineProps<{
|
||||
node: IslandComponentNode;
|
||||
selectedId: string;
|
||||
@@ -0,0 +1,330 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, type CSSProperties } from 'vue';
|
||||
import {
|
||||
ISLAND_COMPONENT_LABELS,
|
||||
resolveClassStatus,
|
||||
type IslandComponentNode,
|
||||
type IslandState,
|
||||
type IslandTimePointDto,
|
||||
type ScheduleDto,
|
||||
} from '@classhelper/shared';
|
||||
|
||||
const props = defineProps<{
|
||||
node: IslandComponentNode;
|
||||
state: IslandState;
|
||||
now: number;
|
||||
schedules: ScheduleDto[];
|
||||
timePoints: IslandTimePointDto[];
|
||||
editing: boolean;
|
||||
selectedId: string;
|
||||
alertNodeId: string;
|
||||
parentHasWidth?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{ select: [id: string]; drag: [event: PointerEvent, id: string] }>();
|
||||
const container = computed(() => ['group', 'stack', 'slide', 'rolling'].includes(props.node.kind));
|
||||
const today = computed(() =>
|
||||
props.schedules
|
||||
.filter((item) => item.dayOfWeek === (new Date(props.now).getDay() || 7))
|
||||
.sort((a, b) => a.startTime.localeCompare(b.startTime)),
|
||||
);
|
||||
const status = computed(() => resolveClassStatus(today.value, new Date(props.now)));
|
||||
const current = computed(() => today.value.find((item) => item.id === status.value.current?.scheduleId));
|
||||
const next = computed(() => today.value.find((item) => item.id === status.value.next?.scheduleId));
|
||||
|
||||
function timeAt(time: string): number {
|
||||
const date = new Date(props.now);
|
||||
const [hour, minute, second = 0] = time.split(':').map(Number);
|
||||
date.setHours(hour!, minute!, second, 0);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
const dayPoints = computed<IslandTimePointDto[]>(() => {
|
||||
const points = props.timePoints.length
|
||||
? props.timePoints
|
||||
: today.value.map<IslandTimePointDto>((item) => ({
|
||||
id: item.id,
|
||||
timeType: 'LESSON',
|
||||
name: '',
|
||||
courseName: item.course?.name ?? null,
|
||||
startTime: item.startTime,
|
||||
endTime: item.endTime,
|
||||
isHideDefault: false,
|
||||
}));
|
||||
return [...points].sort((a, b) => a.startTime.localeCompare(b.startTime));
|
||||
});
|
||||
const currentPoint = computed(
|
||||
() =>
|
||||
dayPoints.value.find(
|
||||
(point) =>
|
||||
point.timeType !== 'DIVIDER' &&
|
||||
point.timeType !== 'ACTION' &&
|
||||
props.now >= timeAt(point.startTime) &&
|
||||
props.now < timeAt(point.endTime),
|
||||
) ?? null,
|
||||
);
|
||||
const currentLesson = computed(() => (currentPoint.value?.timeType === 'LESSON' ? currentPoint.value : null));
|
||||
const schedulePoints = computed(() => {
|
||||
if (props.node.settings.display === 'next')
|
||||
return dayPoints.value
|
||||
.filter((point) => point.timeType === 'LESSON' && timeAt(point.startTime) > props.now)
|
||||
.slice(0, 1);
|
||||
if (props.node.settings.display === 'current')
|
||||
return currentPoint.value
|
||||
? [currentPoint.value]
|
||||
: dayPoints.value
|
||||
.filter((point) => point.timeType === 'LESSON' && timeAt(point.startTime) > props.now)
|
||||
.slice(0, 1);
|
||||
return dayPoints.value
|
||||
.filter(
|
||||
(point) =>
|
||||
point.timeType === 'DIVIDER' ||
|
||||
point.id === currentPoint.value?.id ||
|
||||
(point.timeType === 'LESSON' && !point.isHideDefault),
|
||||
)
|
||||
.slice(0, Math.max(1, props.node.settings.count));
|
||||
});
|
||||
const elapsed = computed(() => {
|
||||
const point = currentLesson.value;
|
||||
if (!point) return 0;
|
||||
const start = timeAt(point.startTime);
|
||||
return Math.max(0, Math.min(1, (props.now - start) / Math.max(1, timeAt(point.endTime) - start)));
|
||||
});
|
||||
const hidden = computed(
|
||||
() =>
|
||||
!props.editing &&
|
||||
((['notification', 'homework', 'call'].includes(props.node.kind) &&
|
||||
(!props.state.active || props.state.mode === 'hidden' || props.node.id !== props.alertNodeId)) ||
|
||||
props.node.advanced.hideRules.some(
|
||||
(rule) =>
|
||||
(rule === 'in-class' && props.state.inClass) ||
|
||||
(rule === 'no-message' && !props.state.active) ||
|
||||
(rule === 'no-class' && !currentLesson.value),
|
||||
)),
|
||||
);
|
||||
const visibleChildren = computed(() =>
|
||||
props.node.kind === 'slide' && !props.editing ? props.node.children.slice(0, 1) : props.node.children,
|
||||
);
|
||||
const content = computed(() => {
|
||||
const node = props.node;
|
||||
const date = new Date(props.now);
|
||||
if (node.kind === 'date')
|
||||
return date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric', weekday: 'long' });
|
||||
if (node.kind === 'clock')
|
||||
return date.toLocaleTimeString('zh-CN', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
...(node.settings.seconds ? { second: '2-digit' } : {}),
|
||||
hour12: node.settings.hour12,
|
||||
});
|
||||
if (node.kind === 'text')
|
||||
return node.settings.template
|
||||
? node.settings.text
|
||||
.replaceAll('{date}', date.toLocaleDateString('zh-CN'))
|
||||
.replaceAll('{time}', date.toLocaleTimeString('zh-CN'))
|
||||
.replaceAll('{course}', current.value?.course?.name || '暂无课程')
|
||||
: node.settings.text;
|
||||
if (node.kind === 'countdown') {
|
||||
if (node.settings.target === 'date') {
|
||||
if (!node.settings.targetDate) return '请设置目标日期';
|
||||
const [year, month, day] = node.settings.targetDate.split('-').map(Number);
|
||||
const days = Math.round(
|
||||
(Date.UTC(year!, month! - 1, day!) - Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())) /
|
||||
86400000,
|
||||
);
|
||||
return days >= 0
|
||||
? `距${node.settings.countdownTitle} ${days} 天`
|
||||
: `${node.settings.countdownTitle}已过 ${-days} 天`;
|
||||
}
|
||||
const end = node.settings.target === 'end' || (node.settings.target === 'auto' && !!current.value);
|
||||
const time =
|
||||
node.settings.target === 'school'
|
||||
? today.value.at(-1)?.endTime
|
||||
: end
|
||||
? current.value?.endTime
|
||||
: next.value?.startTime;
|
||||
return time ? `${end ? '距下课' : '距上课'} ${time}` : '今日课程已结束';
|
||||
}
|
||||
if (node.kind === 'weather')
|
||||
return node.settings.locationName ? `${node.settings.locationName} · 天气预览` : '天气简报';
|
||||
return '';
|
||||
});
|
||||
const style = computed<CSSProperties>(() => {
|
||||
const node = props.node;
|
||||
const appearance = node.appearance;
|
||||
const override = appearance.resourceOverridingEnabled;
|
||||
const alpha = appearance.customBackgroundOpacityEnabled ? appearance.backgroundOpacity : 1;
|
||||
return {
|
||||
opacity: appearance.opacity,
|
||||
width: node.advanced.width ? `${node.advanced.width}px` : undefined,
|
||||
maxWidth: node.advanced.maxWidth ? `${node.advanced.maxWidth}px` : undefined,
|
||||
alignSelf:
|
||||
props.parentHasWidth && override
|
||||
? ({ stretch: 'stretch', start: 'flex-start', center: 'center', end: 'flex-end' } as const)[
|
||||
node.advanced.align
|
||||
]
|
||||
: undefined,
|
||||
textAlign: node.advanced.align === 'start' ? 'start' : node.advanced.align === 'end' ? 'end' : 'center',
|
||||
background:
|
||||
override && appearance.customBackgroundEnabled
|
||||
? `color-mix(in srgb, ${appearance.background} ${alpha * 100}%, transparent)`
|
||||
: undefined,
|
||||
color: override && appearance.customForegroundEnabled ? appearance.foreground : 'var(--ci-text-1)',
|
||||
borderRadius:
|
||||
override && appearance.customCornerRadiusEnabled ? `${appearance.cornerRadius}px` : undefined,
|
||||
fontSize: override ? `${appearance.bodyFontSize}px` : undefined,
|
||||
flexDirection: container.value ? (node.settings.direction === 'vertical' ? 'column' : 'row') : undefined,
|
||||
gap: container.value ? `${node.settings.gap}px` : undefined,
|
||||
display: container.value ? 'flex' : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
function select(event: MouseEvent): void {
|
||||
if (!props.editing) return;
|
||||
event.stopPropagation();
|
||||
emit('select', props.node.id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="!hidden"
|
||||
class="preview-node"
|
||||
:class="[{ selected: editing && selectedId === node.id, container, 'node-editing': editing }, node.kind]"
|
||||
:style="style"
|
||||
:data-node="node.id"
|
||||
@click="select"
|
||||
>
|
||||
<button
|
||||
v-if="editing"
|
||||
class="node-handle"
|
||||
type="button"
|
||||
:aria-label="`拖动${ISLAND_COMPONENT_LABELS[node.kind]}`"
|
||||
@pointerdown.stop="emit('drag', $event, node.id)"
|
||||
>
|
||||
⠿ {{ ISLAND_COMPONENT_LABELS[node.kind] }}
|
||||
</button>
|
||||
<template v-if="container">
|
||||
<IslandPreviewNode
|
||||
v-for="child in visibleChildren"
|
||||
:key="child.id"
|
||||
:node="child"
|
||||
:state="state"
|
||||
:now="now"
|
||||
:schedules="schedules"
|
||||
:time-points="timePoints"
|
||||
:editing="editing"
|
||||
:selected-id="selectedId"
|
||||
:alert-node-id="alertNodeId"
|
||||
:parent-has-width="Boolean(node.advanced.width || node.advanced.maxWidth)"
|
||||
@select="emit('select', $event)"
|
||||
@drag="(event, id) => emit('drag', event, id)"
|
||||
/>
|
||||
</template>
|
||||
<span v-else-if="node.kind === 'separator'" class="preview-separator" aria-hidden="true" />
|
||||
<template v-else-if="node.kind === 'schedule'">
|
||||
<span v-for="point in schedulePoints" :key="point.id" class="preview-lesson">
|
||||
<strong>{{ point.courseName || point.name || '—' }}</strong>
|
||||
<small v-if="point.id === currentPoint?.id && node.settings.showPeriod">
|
||||
{{ point.startTime }}–{{ point.endTime }}
|
||||
</small>
|
||||
<i
|
||||
v-if="point.id === currentPoint?.id && point.timeType === 'LESSON' && node.settings.showProgress"
|
||||
class="preview-progress"
|
||||
:style="{ transform: `scaleX(${elapsed})` }"
|
||||
/>
|
||||
</span>
|
||||
<span v-if="!schedulePoints.length">暂无课程</span>
|
||||
</template>
|
||||
<span v-else-if="['notification', 'homework', 'call'].includes(node.kind)">
|
||||
{{ ISLAND_COMPONENT_LABELS[node.kind] }}
|
||||
</span>
|
||||
<span v-else>{{ content }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.preview-node {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
min-height: var(--ci-island-height);
|
||||
padding: 6px;
|
||||
color: var(--ci-text-1);
|
||||
line-height: var(--ci-line-height-body);
|
||||
}
|
||||
.preview-node.clock,
|
||||
.preview-node.date,
|
||||
.preview-node.countdown {
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.preview-node.schedule {
|
||||
flex-direction: row;
|
||||
gap: var(--ci-component-gap);
|
||||
}
|
||||
.preview-lesson {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding-bottom: 3px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.preview-lesson small {
|
||||
color: var(--ci-text-3);
|
||||
font-size: var(--ci-fs-secondary);
|
||||
}
|
||||
.preview-progress {
|
||||
position: absolute;
|
||||
inset: auto 0 0;
|
||||
height: var(--ci-progress-height);
|
||||
border-radius: 1.5px;
|
||||
background: var(--ci-accent);
|
||||
transform-origin: left;
|
||||
}
|
||||
.preview-separator {
|
||||
width: 1px;
|
||||
height: 20px;
|
||||
background: currentColor;
|
||||
opacity: 0.25;
|
||||
}
|
||||
.container {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
.container.stack {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.selected {
|
||||
border-radius: var(--ci-radius-island);
|
||||
background: var(--ci-accent-fill-tertiary);
|
||||
outline: 2px solid var(--ci-stroke-drag);
|
||||
}
|
||||
.node-editing {
|
||||
cursor: pointer;
|
||||
}
|
||||
.node-handle {
|
||||
margin-right: 5px;
|
||||
padding: 3px 6px;
|
||||
border: 0;
|
||||
border-radius: var(--ci-radius-control);
|
||||
background: var(--ci-fill-secondary);
|
||||
color: var(--ci-text-3);
|
||||
font: inherit;
|
||||
font-size: var(--ci-fs-caption);
|
||||
white-space: nowrap;
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
}
|
||||
.node-handle:hover {
|
||||
background: var(--ci-accent-soft);
|
||||
color: var(--ci-text-1);
|
||||
}
|
||||
.notification,
|
||||
.homework,
|
||||
.call {
|
||||
min-width: 64px;
|
||||
}
|
||||
</style>
|
||||
@@ -16,7 +16,15 @@ export const MANAGEMENT_GROUPS = [
|
||||
id: 'school',
|
||||
title: '班级与人员',
|
||||
icon: 'School',
|
||||
paths: ['/classes', '/students', '/teachers', '/term-weeks', '/promotion', '/archives'],
|
||||
paths: [
|
||||
'/classes',
|
||||
'/students',
|
||||
'/teachers',
|
||||
'/island-layouts',
|
||||
'/term-weeks',
|
||||
'/promotion',
|
||||
'/archives',
|
||||
],
|
||||
},
|
||||
{ id: 'devices', title: '设备运维', icon: 'Monitor', paths: ['/clients'] },
|
||||
{
|
||||
|
||||
@@ -70,6 +70,17 @@ const routes: RouteRecordRaw[] = [
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'island-layouts',
|
||||
name: 'island-layouts',
|
||||
component: () => import('@/views/IslandLayoutsView.vue'),
|
||||
meta: {
|
||||
title: '班级灵动岛',
|
||||
icon: 'MagicStick',
|
||||
permission: 'class:read',
|
||||
menuActions: ['class:settings'],
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'students',
|
||||
name: 'students',
|
||||
|
||||
+101
-4
@@ -1,3 +1,4 @@
|
||||
/* Web 管理端班级灵动岛编辑器。 */
|
||||
.island-editor-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -24,6 +25,33 @@
|
||||
min-height: 30px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.class-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--ch-border);
|
||||
border-radius: var(--ch-radius-control);
|
||||
background: var(--ch-surface);
|
||||
}
|
||||
.class-toolbar strong {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
}
|
||||
.class-toolbar p {
|
||||
margin: 5px 0 0;
|
||||
color: var(--ch-text-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.class-select {
|
||||
width: min(320px, 42vw);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.readonly-alert {
|
||||
margin: 12px 0;
|
||||
}
|
||||
.save-status {
|
||||
color: var(--ch-text-tertiary);
|
||||
font-size: 12px;
|
||||
@@ -184,30 +212,82 @@
|
||||
.preview-canvas.live-preview {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 160px;
|
||||
min-height: 220px;
|
||||
padding: 24px;
|
||||
background: var(--ch-layer-alt);
|
||||
border-radius: 6px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.preview-stage {
|
||||
position: relative;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-width: 540px;
|
||||
min-height: 150px;
|
||||
padding: 30px 80px;
|
||||
border: 1px solid color-mix(in srgb, var(--ch-border) 70%, transparent);
|
||||
border-radius: 8px;
|
||||
background:
|
||||
radial-gradient(
|
||||
circle at 30% 20%,
|
||||
color-mix(in srgb, var(--ch-accent) 12%, transparent),
|
||||
transparent 38%
|
||||
),
|
||||
linear-gradient(145deg, var(--ch-layer-alt), var(--ch-surface));
|
||||
}
|
||||
.preview-stage-label {
|
||||
position: absolute;
|
||||
align-self: start;
|
||||
justify-self: start;
|
||||
margin: -16px 0 0 -60px;
|
||||
color: var(--ch-text-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.island-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--preview-gap);
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: calc(var(--ci-component-gap) / 2);
|
||||
width: max-content;
|
||||
min-width: 80px;
|
||||
color: var(--ci-text-1);
|
||||
padding: var(--ci-island-pad-x);
|
||||
border-radius: var(--preview-radius);
|
||||
background: var(--preview-background);
|
||||
font-family: var(--ci-font-island);
|
||||
font-weight: var(--ci-font-weight);
|
||||
transition:
|
||||
background-color var(--ci-duration) linear,
|
||||
border-radius var(--ci-duration) var(--ci-ease-out);
|
||||
}
|
||||
.preview-rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--preview-gap);
|
||||
}
|
||||
.preview-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: max-content;
|
||||
height: var(--ci-island-height);
|
||||
min-width: 120px;
|
||||
min-height: 44px;
|
||||
border-radius: var(--preview-radius);
|
||||
overflow: hidden;
|
||||
}
|
||||
.preview-bell {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
flex: 0 0 28px;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
color: var(--ci-text-3);
|
||||
}
|
||||
.preview-bell svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
}
|
||||
.island-preview.separated {
|
||||
background: transparent;
|
||||
@@ -217,6 +297,11 @@
|
||||
padding: var(--ci-island-pad-x);
|
||||
background: var(--preview-background);
|
||||
}
|
||||
.separated .preview-bell {
|
||||
width: 48px;
|
||||
border-radius: var(--preview-radius);
|
||||
background: var(--preview-background);
|
||||
}
|
||||
.empty-preview {
|
||||
color: var(--ci-text-2);
|
||||
background: transparent;
|
||||
@@ -408,6 +493,18 @@
|
||||
.scheme-tools {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
.class-toolbar {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
}
|
||||
.class-select {
|
||||
width: 100%;
|
||||
}
|
||||
.preview-stage {
|
||||
min-width: 420px;
|
||||
padding-right: 36px;
|
||||
padding-left: 36px;
|
||||
}
|
||||
.preview-toolbar .hint {
|
||||
display: none;
|
||||
}
|
||||
+246
-78
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue';
|
||||
import { onBeforeRouteLeave, useRouter } from 'vue-router';
|
||||
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import {
|
||||
CLASSISLAND_ISLAND_METRICS as METRICS,
|
||||
@@ -16,30 +16,44 @@ import {
|
||||
type IslandLayoutScheme,
|
||||
type IslandState,
|
||||
type IslandAppearance,
|
||||
type ClassDto,
|
||||
type IslandTimePointDto,
|
||||
type ScheduleDto,
|
||||
} from '@classhelper/shared';
|
||||
import ComponentNode from '../../../island/ComponentNode.vue';
|
||||
import ComponentIcon from '../../../island/ComponentIcon.vue';
|
||||
import IslandEditorNode from '../../components/IslandEditorNode.vue';
|
||||
import IslandComponentSettings from '../../components/IslandComponentSettings.vue';
|
||||
import { getIslandSchedules, getIslandTimePoints } from '../../island/bridge.js';
|
||||
import { classApi, scheduleApi } from '@/api';
|
||||
import { useAuthStore } from '@/stores/auth';
|
||||
import ComponentNode from '@/components/IslandPreviewNode.vue';
|
||||
import ComponentIcon from '@/components/ComponentIcon.vue';
|
||||
import IslandEditorNode from '@/components/IslandEditorNode.vue';
|
||||
import IslandComponentSettings from '@/components/IslandComponentSettings.vue';
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const classes = ref<ClassDto[]>([]);
|
||||
const selectedClassId = ref('');
|
||||
const settings = ref(defaultIslandLayouts()),
|
||||
appearance = ref<IslandAppearance>({ ...DEFAULT_ISLAND_APPEARANCE });
|
||||
const schedules = ref(getIslandSchedules()),
|
||||
timePoints = ref(getIslandTimePoints()),
|
||||
const schedules = ref<ScheduleDto[]>([]),
|
||||
timePoints = ref<IslandTimePointDto[]>([]),
|
||||
now = ref(Date.now()),
|
||||
classesBusy = ref(false),
|
||||
ready = ref(false),
|
||||
error = ref(''),
|
||||
pending = ref(0),
|
||||
saved = ref(false);
|
||||
saved = ref(false),
|
||||
dirty = ref(false);
|
||||
const surface = ref<'compact' | 'expanded'>('compact'),
|
||||
panel = ref<'scheme' | 'row' | 'component'>('scheme');
|
||||
const selectedId = ref(''),
|
||||
rowId = ref(''),
|
||||
inspectorOpen = ref(false),
|
||||
editMode = ref(false),
|
||||
editMode = ref(true),
|
||||
zoom = ref(1),
|
||||
importInput = ref<HTMLInputElement>();
|
||||
const selectedClass = computed(() => classes.value.find((item) => item.id === selectedClassId.value) ?? null);
|
||||
const canEdit = computed(
|
||||
() => Boolean(selectedClass.value) && (auth.isAdmin || selectedClass.value?.teacherId === auth.user?.id),
|
||||
);
|
||||
const scheme = computed(() =>
|
||||
settings.value.schemes.find((item) => item.id === settings.value.activeSchemeId)!,
|
||||
);
|
||||
@@ -86,7 +100,8 @@ function previewStyle(): Record<string, string> {
|
||||
}
|
||||
: {};
|
||||
return {
|
||||
zoom: String(scheme.value.scale * zoom.value),
|
||||
transform: `scale(${scheme.value.scale * zoom.value})`,
|
||||
transformOrigin: 'center center',
|
||||
'--preview-gap': `${scheme.value.spacing}px`,
|
||||
'--preview-radius': `${scheme.value.radius}px`,
|
||||
'--preview-background': scheme.value.customBackgroundEnabled
|
||||
@@ -139,22 +154,30 @@ const selected = computed(() =>
|
||||
let saveQueue = Promise.resolve(),
|
||||
revision = 0,
|
||||
clock: ReturnType<typeof setInterval>;
|
||||
let scheduleClock: ReturnType<typeof setInterval> | undefined;
|
||||
function save() {
|
||||
if (!ready.value) return saveQueue;
|
||||
if (!ready.value || !selectedClassId.value || !canEdit.value) return saveQueue;
|
||||
const targetClassId = selectedClassId.value;
|
||||
const snapshot = normalizeIslandLayouts(JSON.parse(JSON.stringify(settings.value)));
|
||||
// 班级端只运行 Web 下发方案;保存时强制进入常驻自定义岛。
|
||||
snapshot.layout = 'custom';
|
||||
snapshot.residentEnabled = true;
|
||||
const current = ++revision;
|
||||
dirty.value = true;
|
||||
pending.value++;
|
||||
saved.value = false;
|
||||
saveQueue = saveQueue.then(async () => {
|
||||
try {
|
||||
if (!window.desktop) throw new Error('请在桌面客户端中保存方案');
|
||||
await window.desktop.saveConfig({ islandLayout: snapshot });
|
||||
if (current === revision) {
|
||||
await classApi.saveIslandLayout(targetClassId, { layout: snapshot });
|
||||
if (current === revision && selectedClassId.value === targetClassId) {
|
||||
error.value = '';
|
||||
saved.value = true;
|
||||
dirty.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : '保存失败,请重试';
|
||||
if (selectedClassId.value === targetClassId) {
|
||||
error.value = e instanceof Error ? e.message : '保存失败,请重试';
|
||||
}
|
||||
} finally {
|
||||
pending.value--;
|
||||
}
|
||||
@@ -162,13 +185,14 @@ function save() {
|
||||
return saveQueue;
|
||||
}
|
||||
function selectNode(nodeId: string) {
|
||||
if (suppressClick) return;
|
||||
if (suppressClick || !canEdit.value) return;
|
||||
selectedId.value = nodeId;
|
||||
panel.value = 'component';
|
||||
rowId.value = rows.value.find((row) => all(row.nodes).some((node) => node.id === nodeId))?.id ?? '';
|
||||
inspectorOpen.value = true;
|
||||
}
|
||||
function selectRow(value: string) {
|
||||
if (!canEdit.value) return;
|
||||
rowId.value = value;
|
||||
selectedId.value = '';
|
||||
panel.value = 'row';
|
||||
@@ -186,7 +210,7 @@ function switchScheme() {
|
||||
void save();
|
||||
}
|
||||
function add(kind: IslandComponentKind) {
|
||||
if (suppressClick || !capacity()) return;
|
||||
if (!canEdit.value || suppressClick || !capacity()) return;
|
||||
const target = selected.value && containers.includes(selected.value.kind) ? selected.value : undefined;
|
||||
if (target && depthOf(target.id) >= 6) {
|
||||
ElMessage.warning('最多嵌套 6 层容器');
|
||||
@@ -198,6 +222,7 @@ function add(kind: IslandComponentKind) {
|
||||
void save();
|
||||
}
|
||||
function addRow() {
|
||||
if (!canEdit.value) return;
|
||||
if (rows.value.length >= 12) {
|
||||
ElMessage.warning('每种内容最多添加 12 行');
|
||||
return;
|
||||
@@ -352,29 +377,116 @@ async function importScheme(event: Event) {
|
||||
}
|
||||
}
|
||||
async function apply() {
|
||||
if (!ready.value) return;
|
||||
if (!ready.value || !canEdit.value) return;
|
||||
settings.value.layout = 'custom';
|
||||
settings.value.residentEnabled = true;
|
||||
await save();
|
||||
if (!error.value) {
|
||||
ElMessage.success('自定义灵动岛已应用');
|
||||
await router.push('/settings/island');
|
||||
ElMessage.success(`已保存 ${selectedClass.value?.name ?? '本班'} 的灵动岛方案`);
|
||||
}
|
||||
}
|
||||
async function load() {
|
||||
|
||||
function editableDefault(): ReturnType<typeof defaultIslandLayouts> {
|
||||
const value = defaultIslandLayouts();
|
||||
value.layout = 'custom';
|
||||
value.residentEnabled = true;
|
||||
return value;
|
||||
}
|
||||
|
||||
function clockText(date: Date): string {
|
||||
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** 没有当天课表时也给网页预览一份稳定的情境数据,便于看到真实排版。 */
|
||||
function sampleSchedules(classId: string): ScheduleDto[] {
|
||||
const dayOfWeek = new Date().getDay() || 7;
|
||||
const nowDate = new Date();
|
||||
const firstStart = new Date(nowDate.getTime() - 20 * 60_000);
|
||||
const firstEnd = new Date(nowDate.getTime() + 25 * 60_000);
|
||||
const secondStart = new Date(nowDate.getTime() + 35 * 60_000);
|
||||
const secondEnd = new Date(nowDate.getTime() + 80 * 60_000);
|
||||
const rows = [
|
||||
['预览-数学', firstStart, firstEnd],
|
||||
['预览-语文', secondStart, secondEnd],
|
||||
] as const;
|
||||
return rows.map(([name, start, end], index) => ({
|
||||
id: `preview-${index}`,
|
||||
classId,
|
||||
courseId: `preview-course-${index}`,
|
||||
dayOfWeek,
|
||||
startTime: clockText(start),
|
||||
endTime: clockText(end),
|
||||
location: null,
|
||||
weekStart: 1,
|
||||
weekEnd: 30,
|
||||
weekParity: 'ALL',
|
||||
createdAt: new Date().toISOString(),
|
||||
course: { id: `preview-course-${index}`, name },
|
||||
}));
|
||||
}
|
||||
|
||||
async function loadSchedules(): Promise<void> {
|
||||
if (!selectedClassId.value) return;
|
||||
try {
|
||||
const config = await window.desktop?.getConfig();
|
||||
if (!config) throw new Error('请在桌面客户端中打开组件编辑器');
|
||||
if (config) {
|
||||
settings.value = normalizeIslandLayouts(config.islandLayout);
|
||||
appearance.value = config.island;
|
||||
}
|
||||
const all = await scheduleApi.list({ classId: selectedClassId.value });
|
||||
const today = new Date().getDay() || 7;
|
||||
const current = all.filter((item) => item.dayOfWeek === today);
|
||||
schedules.value = current.length ? current : sampleSchedules(selectedClassId.value);
|
||||
} catch {
|
||||
schedules.value = sampleSchedules(selectedClassId.value);
|
||||
}
|
||||
timePoints.value = [];
|
||||
}
|
||||
|
||||
async function loadSelectedLayout(): Promise<void> {
|
||||
const classId = selectedClassId.value;
|
||||
if (!classId) {
|
||||
ready.value = false;
|
||||
return;
|
||||
}
|
||||
ready.value = false;
|
||||
error.value = '';
|
||||
revision += 1;
|
||||
dirty.value = false;
|
||||
try {
|
||||
const result = await classApi.islandLayout(classId);
|
||||
if (selectedClassId.value !== classId) return;
|
||||
settings.value = normalizeIslandLayouts(result.layout ?? editableDefault());
|
||||
appearance.value = { ...DEFAULT_ISLAND_APPEARANCE };
|
||||
resetSelection();
|
||||
saved.value = Boolean(result.layout);
|
||||
await loadSchedules();
|
||||
ready.value = true;
|
||||
error.value = '';
|
||||
} catch (e) {
|
||||
error.value = String(e);
|
||||
if (selectedClassId.value === classId) {
|
||||
ready.value = false;
|
||||
error.value = e instanceof Error ? e.message : '加载班级灵动岛失败';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function switchClass(classId: string): Promise<void> {
|
||||
selectedClassId.value = classId;
|
||||
await router.replace({ query: { ...route.query, classId } });
|
||||
await loadSelectedLayout();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
classesBusy.value = true;
|
||||
try {
|
||||
classes.value = await classApi.list();
|
||||
if (!classes.value.length) throw new Error('当前账号没有可管理的班级');
|
||||
const requested = typeof route.query.classId === 'string' ? route.query.classId : '';
|
||||
selectedClassId.value = classes.value.find((item) => item.id === requested)?.id ?? classes.value[0]!.id;
|
||||
await router.replace({ query: { ...route.query, classId: selectedClassId.value } });
|
||||
await loadSelectedLayout();
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : '加载班级灵动岛失败';
|
||||
} finally {
|
||||
classesBusy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
window.addEventListener('pointermove', moveDrag, { passive: false });
|
||||
window.addEventListener('pointerup', dropPreview);
|
||||
@@ -383,19 +495,19 @@ onMounted(async () => {
|
||||
await load();
|
||||
clock = setInterval(() => {
|
||||
now.value = Date.now();
|
||||
schedules.value = getIslandSchedules();
|
||||
timePoints.value = getIslandTimePoints();
|
||||
}, 1000);
|
||||
scheduleClock = setInterval(() => void loadSchedules(), 30_000);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
clearInterval(clock);
|
||||
if (scheduleClock) clearInterval(scheduleClock);
|
||||
window.removeEventListener('pointermove', moveDrag);
|
||||
window.removeEventListener('pointerup', dropPreview);
|
||||
window.removeEventListener('pointercancel', cancelDrag);
|
||||
window.removeEventListener('blur', cancelDrag);
|
||||
});
|
||||
onBeforeRouteLeave(async () => {
|
||||
if (!ready.value) return true;
|
||||
if (!ready.value || !canEdit.value || !dirty.value) return true;
|
||||
await save();
|
||||
return !error.value;
|
||||
});
|
||||
@@ -510,7 +622,7 @@ type Drop = { row: IslandLayoutRow; node?: IslandComponentNode; position: 'befor
|
||||
const drop = ref<Drop | null>(null);
|
||||
let suppressClick = false;
|
||||
function beginDrag(event: PointerEvent, source: Omit<Drag, 'x' | 'y' | 'moved'>) {
|
||||
if (event.button !== 0 || !ready.value) return;
|
||||
if (!canEdit.value || event.button !== 0 || !ready.value) return;
|
||||
dragging.value = { ...source, x: event.clientX, y: event.clientY, moved: false };
|
||||
pointer.value = { x: event.clientX, y: event.clientY };
|
||||
try {
|
||||
@@ -604,19 +716,55 @@ function dropPreview(event: PointerEvent) {
|
||||
|
||||
<template>
|
||||
<section class="page island-editor-page" aria-label="自定义灵动岛设置">
|
||||
<div class="class-toolbar" v-loading="classesBusy">
|
||||
<div>
|
||||
<strong>编辑班级</strong>
|
||||
<p>每个班保存独立方案,教室端登录后自动同步;班级端只读,不提供编辑入口。</p>
|
||||
</div>
|
||||
<el-select
|
||||
v-model="selectedClassId"
|
||||
class="class-select"
|
||||
aria-label="选择班级"
|
||||
:disabled="classesBusy || classes.length < 2"
|
||||
@change="switchClass"
|
||||
>
|
||||
<el-option
|
||||
v-for="item in classes"
|
||||
:key="item.id"
|
||||
:label="`${item.name} · ${item.grade}`"
|
||||
:value="item.id"
|
||||
/>
|
||||
</el-select>
|
||||
</div>
|
||||
<div class="editor-actions">
|
||||
<span class="save-status" :class="{ failed: error }" role="status">
|
||||
{{ error ? '保存失败' : pending ? '正在保存…' : saved ? '已自动保存' : '更改自动保存到本机' }}
|
||||
{{
|
||||
error
|
||||
? '保存失败'
|
||||
: pending
|
||||
? '正在保存…'
|
||||
: saved
|
||||
? '已同步到本班'
|
||||
: canEdit
|
||||
? '更改会自动保存到服务端'
|
||||
: '只读预览'
|
||||
}}
|
||||
</span>
|
||||
<el-button text size="small" @click="router.push('/settings/island')">返回设置</el-button>
|
||||
<el-button type="primary" size="small" :loading="!!pending" :disabled="!ready" @click="apply">
|
||||
应用并返回
|
||||
<el-button text size="small" @click="router.push('/classes')">班级管理</el-button>
|
||||
<el-button
|
||||
type="primary"
|
||||
size="small"
|
||||
:loading="!!pending"
|
||||
:disabled="!ready || !canEdit"
|
||||
@click="apply"
|
||||
>
|
||||
保存方案
|
||||
</el-button>
|
||||
</div>
|
||||
<header class="page-header component-heading">
|
||||
<div class="heading-copy">
|
||||
<h2 class="page-title">组件</h2>
|
||||
<p>以下组件将显示在主界面上,从组件库拖动组件以添加组件。</p>
|
||||
<h2 class="page-title">班级灵动岛</h2>
|
||||
<p>为当前班自由编排常态内容与无通知展开内容,右侧检查器可调整组件和行级样式。</p>
|
||||
</div>
|
||||
<div class="scheme-tools" :aria-busy="!ready">
|
||||
<label id="scheme-label">配置方案</label>
|
||||
@@ -625,7 +773,7 @@ function dropPreview(event: PointerEvent) {
|
||||
v-model="settings.activeSchemeId"
|
||||
aria-labelledby="scheme-label"
|
||||
aria-label="当前方案"
|
||||
:disabled="!ready"
|
||||
:disabled="!ready || !canEdit"
|
||||
@change="switchScheme"
|
||||
>
|
||||
<el-option v-for="item in settings.schemes" :key="item.id" :label="item.name" :value="item.id" />
|
||||
@@ -635,7 +783,7 @@ function dropPreview(event: PointerEvent) {
|
||||
class="icon-button"
|
||||
title="重置当前方案"
|
||||
aria-label="重置当前方案"
|
||||
:disabled="!ready"
|
||||
:disabled="!ready || !canEdit"
|
||||
@click="resetScheme"
|
||||
>
|
||||
<el-icon><Refresh /></el-icon>
|
||||
@@ -645,12 +793,12 @@ function dropPreview(event: PointerEvent) {
|
||||
class="icon-button"
|
||||
title="新建方案"
|
||||
aria-label="新建方案"
|
||||
:disabled="!ready"
|
||||
:disabled="!ready || !canEdit"
|
||||
@click="newScheme"
|
||||
>
|
||||
<el-icon><Plus /></el-icon>
|
||||
</el-button>
|
||||
<el-dropdown trigger="click" :disabled="!ready" @command="schemeCommand">
|
||||
<el-dropdown trigger="click" :disabled="!ready || !canEdit" @command="schemeCommand">
|
||||
<el-button text class="icon-button" title="管理方案" aria-label="管理方案" :disabled="!ready">
|
||||
<el-icon><FolderOpened /></el-icon>
|
||||
</el-button>
|
||||
@@ -672,6 +820,13 @@ function dropPreview(event: PointerEvent) {
|
||||
<el-alert v-if="error" type="error" :closable="false" :title="error">
|
||||
<el-button link type="primary" @click="ready ? save() : load()">重试</el-button>
|
||||
</el-alert>
|
||||
<el-alert
|
||||
v-if="ready && !canEdit"
|
||||
class="readonly-alert"
|
||||
type="info"
|
||||
:closable="false"
|
||||
title="此班由其他班主任管理,你可以查看实时预览,但不能保存修改。"
|
||||
/>
|
||||
<template v-if="ready">
|
||||
<div class="surface-toolbar">
|
||||
<div class="surface-tabs" role="tablist" aria-label="编辑内容">
|
||||
@@ -699,8 +854,9 @@ function dropPreview(event: PointerEvent) {
|
||||
</button>
|
||||
</div>
|
||||
<div class="surface-actions">
|
||||
<el-button text size="small" @click="addRow">新增行</el-button>
|
||||
<el-button v-if="canEdit" text size="small" @click="addRow">新增行</el-button>
|
||||
<el-button
|
||||
v-if="canEdit"
|
||||
text
|
||||
size="small"
|
||||
@click="
|
||||
@@ -711,7 +867,7 @@ function dropPreview(event: PointerEvent) {
|
||||
行设置
|
||||
</el-button>
|
||||
<el-button text size="small" :type="editMode ? 'primary' : 'default'" @click="editMode = !editMode">
|
||||
{{ editMode ? '退出编辑模式' : '进入编辑模式' }}
|
||||
{{ editMode ? '返回结构排列' : '预览组件外观' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -757,34 +913,46 @@ function dropPreview(event: PointerEvent) {
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div v-else class="island-preview" :class="{ separated: scheme.separated }" :style="previewStyle()">
|
||||
<section
|
||||
v-for="row in rows"
|
||||
:key="row.id"
|
||||
class="preview-row"
|
||||
:class="{ 'drop-row': drop?.row.id === row.id && !drop.node }"
|
||||
:data-row="row.id"
|
||||
:style="rowStyle(row)"
|
||||
@click.self="selectRow(row.id)"
|
||||
>
|
||||
<ComponentNode
|
||||
v-for="node in row.nodes"
|
||||
:key="node.id"
|
||||
:node="node"
|
||||
:state="state"
|
||||
:now="now"
|
||||
:schedules="schedules"
|
||||
:time-points="timePoints"
|
||||
editing
|
||||
:selected-id="selectedId"
|
||||
alert-node-id=""
|
||||
@select="selectNode"
|
||||
@drag="startDrag"
|
||||
/>
|
||||
<button v-if="!row.nodes.length" class="empty-preview" @click="selectRow(row.id)">
|
||||
将组件拖到这里
|
||||
</button>
|
||||
</section>
|
||||
<div v-else class="preview-stage">
|
||||
<span class="preview-stage-label">
|
||||
桌面预览 · {{ selectedClass?.name ?? '当前班级' }} · 40px 行高居中
|
||||
</span>
|
||||
<div class="island-preview" :class="{ separated: scheme.separated }" :style="previewStyle()">
|
||||
<div class="preview-rows">
|
||||
<section
|
||||
v-for="row in rows"
|
||||
:key="row.id"
|
||||
class="preview-row"
|
||||
:class="{ 'drop-row': drop?.row.id === row.id && !drop.node }"
|
||||
:data-row="row.id"
|
||||
:style="rowStyle(row)"
|
||||
@click.self="selectRow(row.id)"
|
||||
>
|
||||
<ComponentNode
|
||||
v-for="node in row.nodes"
|
||||
:key="node.id"
|
||||
:node="node"
|
||||
:state="state"
|
||||
:now="now"
|
||||
:schedules="schedules"
|
||||
:time-points="timePoints"
|
||||
:editing="false"
|
||||
:selected-id="selectedId"
|
||||
alert-node-id=""
|
||||
@select="selectNode"
|
||||
@drag="startDrag"
|
||||
/>
|
||||
<button v-if="!row.nodes.length && canEdit" class="empty-preview" @click="selectRow(row.id)">
|
||||
将组件拖到这里
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
<span v-if="surface === 'compact'" class="preview-bell" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">
|
||||
<path d="m8 10 4 4 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="editMode" class="preview-toolbar">
|
||||
@@ -797,9 +965,9 @@ function dropPreview(event: PointerEvent) {
|
||||
:format-tooltip="(v: number) => `${Math.round(v * 100)}%`"
|
||||
/>
|
||||
<el-button text size="small" @click="zoom = 1">重置缩放</el-button>
|
||||
<span class="hint">点选组件调整内容、外观和隐藏条件</span>
|
||||
<span class="hint">这里展示最终外观;返回结构排列后可点选组件调整参数。</span>
|
||||
</div>
|
||||
<section class="component-library" aria-labelledby="library-heading">
|
||||
<section v-if="canEdit" class="component-library" aria-labelledby="library-heading">
|
||||
<h3 id="library-heading" class="library-title">组件库</h3>
|
||||
<div class="component-options">
|
||||
<button
|
||||
@@ -989,9 +1157,9 @@ function dropPreview(event: PointerEvent) {
|
||||
<el-switch v-model="scheme.separated" @change="save" />
|
||||
</el-form-item>
|
||||
<p class="hint">位置与动画与灵动岛共用设置。</p>
|
||||
<el-button link type="primary" @click="router.push('/settings/island')">前往灵动岛外观设置</el-button>
|
||||
<p class="hint">位置、动画与教室设备外观仍由各客户端本机保存;这里下发全班的岛内组件方案。</p>
|
||||
</el-form>
|
||||
</el-drawer>
|
||||
</section>
|
||||
</template>
|
||||
<style scoped src="../../styles/island-editor.css"></style>
|
||||
<style scoped src="../styles/island-editor.css"></style>
|
||||
@@ -10,9 +10,10 @@ const scopedFiles = [
|
||||
path.join(root, 'packages/desktop-client/src/main/island.ts'),
|
||||
path.join(root, 'packages/desktop-client/src/main/config.ts'),
|
||||
path.join(root, 'packages/desktop-client/src/preload/island.ts'),
|
||||
path.join(root, 'packages/desktop-client/src/renderer/components/IslandComponentSettings.vue'),
|
||||
path.join(root, 'packages/desktop-client/src/renderer/styles/island-editor.css'),
|
||||
path.join(root, 'packages/desktop-client/src/renderer/views/settings/IslandEditorView.vue'),
|
||||
path.join(root, 'packages/web-admin/src/components/IslandComponentSettings.vue'),
|
||||
path.join(root, 'packages/web-admin/src/components/IslandPreviewNode.vue'),
|
||||
path.join(root, 'packages/web-admin/src/styles/island-editor.css'),
|
||||
path.join(root, 'packages/web-admin/src/views/IslandLayoutsView.vue'),
|
||||
path.join(root, 'packages/desktop-client/src/renderer/views/settings/IslandSettingsView.vue'),
|
||||
];
|
||||
const source = fs.readFileSync(tokenFile, 'utf8');
|
||||
|
||||
@@ -17,7 +17,7 @@ try {
|
||||
import {defaultIslandLayouts,DEFAULT_ISLAND_APPEARANCE} from './packages/shared/dist/index.js';
|
||||
import Runtime from './packages/desktop-client/src/island/CustomIslandRuntime.vue';
|
||||
import Reminder from './packages/desktop-client/src/island/LessonReminderContent.vue';
|
||||
import Editor from './packages/desktop-client/src/renderer/views/settings/IslandEditorView.vue';
|
||||
import Editor from './packages/web-admin/src/views/IslandLayoutsView.vue';
|
||||
import Settings from './packages/desktop-client/src/renderer/views/settings/IslandSettingsView.vue';
|
||||
import ElementPlus from './packages/desktop-client/node_modules/element-plus/es/index.mjs';
|
||||
import * as icons from './packages/desktop-client/node_modules/@element-plus/icons-vue/dist/index.js';
|
||||
@@ -84,6 +84,9 @@ try {
|
||||
bundle: true,
|
||||
format: 'iife',
|
||||
platform: 'browser',
|
||||
alias: {
|
||||
'@': path.join(root, 'packages/web-admin/src'),
|
||||
},
|
||||
define: {
|
||||
'process.env.NODE_ENV': '"test"',
|
||||
__VUE_OPTIONS_API__: 'true',
|
||||
@@ -95,15 +98,23 @@ try {
|
||||
name: '真实Vue组件',
|
||||
setup(b) {
|
||||
b.onResolve({ filter: /^vue-router$/ }, () => ({ path: 'router', namespace: 'island-test' }));
|
||||
b.onResolve({ filter: /island\/bridge\.js$/ }, () => ({
|
||||
path: 'bridge',
|
||||
b.onResolve({ filter: /^@\/api$/ }, () => ({ path: 'api', namespace: 'island-test' }));
|
||||
b.onResolve({ filter: /^@\/stores\/auth$/ }, () => ({
|
||||
path: 'auth',
|
||||
namespace: 'island-test',
|
||||
}));
|
||||
b.onLoad({ filter: /.*/, namespace: 'island-test' }, (a) => ({
|
||||
contents:
|
||||
a.path === 'router'
|
||||
? 'export const useRouter=()=>({push:async()=>{}});export function onBeforeRouteLeave(){}'
|
||||
: 'export const getIslandSchedules=()=>[];export const getIslandTimePoints=()=>[];',
|
||||
? 'export const useRoute=()=>({query:{}});export const useRouter=()=>({push:async()=>{},replace:async()=>{}});export function onBeforeRouteLeave(){}'
|
||||
: a.path === 'auth'
|
||||
? 'export const useAuthStore=()=>({isAdmin:true,user:{id:"island-test-teacher"}})'
|
||||
: `export const classApi={
|
||||
list:async()=>[{id:"island-test-class",name:"2026级1班",grade:"高一",enrollmentYear:2026,classIndex:1,teacherId:"island-test-teacher",createdAt:new Date().toISOString(),termWeeks:20,studentGradeQueryEnabled:true}],
|
||||
islandLayout:async()=>({classId:"island-test-class",layout:null,updatedAt:null}),
|
||||
saveIslandLayout:async(_id,payload)=>{window.__savedIslandLayout=payload.layout;return {classId:"island-test-class",layout:payload.layout,updatedAt:new Date().toISOString()};}
|
||||
};
|
||||
export const scheduleApi={list:async()=>[]};`,
|
||||
loader: 'js',
|
||||
}));
|
||||
b.onLoad({ filter: /\.vue$/ }, (args) => {
|
||||
@@ -160,6 +171,7 @@ try {
|
||||
);
|
||||
const env = { ...process.env };
|
||||
delete env.ELECTRON_RUN_AS_NODE;
|
||||
console.log('[verify-island-editor] Web 编辑器 bundle 构建完成,启动 Chromium 验证...');
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
const p = spawn(require('electron'), [path.join(temp, 'main.cjs')], {
|
||||
env,
|
||||
@@ -169,6 +181,7 @@ try {
|
||||
p.on('error', reject);
|
||||
p.on('exit', resolve);
|
||||
});
|
||||
if (code !== 0) console.error(`[verify-island-editor] Chromium 退出码 ${code}`);
|
||||
if (code !== 0) process.exitCode = 1;
|
||||
} finally {
|
||||
if (path.dirname(temp) !== path.join(root, '.cache')) throw new Error('拒绝清理工作区外路径');
|
||||
|
||||
Reference in new issue
Block a user