3 Commits
Author SHA1 Message Date
LoveChengke f6dd59aa25 feat: 支持班级灵动岛云端配置与跨端同步
发布官网与文档站 / build (push) Blocked by required conditions
发布官网与文档站 / deploy (push) Blocked by required conditions
2026-11-18 17:46:26 +08:00
LoveChengke 4449fbd0a1 feat(desktop): 完善灵动岛设计令牌与外观配置
发布官网与文档站 / build (push) Waiting to run
2026-11-17 18:57:32 +08:00
LoveChengke 195ee3b90a fix(ai): 修复追问与删除确认并支持删除对话 2026-11-08 11:13:43 +08:00
88 changed files with 3472 additions and 1169 deletions

No files matched your search

+5 -1
View File
@@ -45,6 +45,10 @@ description: 多轮对话、文件处理与操作计划,核对后通过现有
## 对话与轮次
对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会显示问题卡片,可选答案或在输入框自由回答;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。
对话历史按账号保存在服务器。每次发送是一轮,右侧横条可跳转轮次,新对话独立保存。助手缺少必要信息时会弹出提问窗口,可选答案或自由回答。关闭窗口后可通过历史消息中的“回答问题”再次打开,刷新页面也能恢复待回答的问题;追问阶段不执行写入。格式自动修正每轮至多一次,失败后保留明确的重试入口。
勾选“本轮明确替换当前待确认计划”后,新计划形成时只使选中的旧计划失效,历史记录保留。不勾选时保留旧计划;新建对话不影响其他对话的计划。
删除课表等危险操作时,目标明确后会先生成变更预览,点击“确认执行”才弹出危险操作确认窗口。聊天中的“确认”回答只用于继续生成预览,不代替最终执行确认。
在对话历史中选择对话后,可点击“删除对话”。确认后清除该对话的轮次和暂存附件,未完成计划失效;已执行的业务操作及审计记录保留。仍有后台任务时,请先停止或等待完成再删除。
+14 -10
View File
@@ -5,8 +5,9 @@ description: 经典提醒、自定义常驻方案、课程与课件传输。
# 灵动岛
灵动岛是客户端的独立透明窗口,不占任务栏。设置中可选择经典 fixed 或自定义 custom,默认 fixed。
自定义当前即常驻模式;旧 residentEnabled 字段只作兼容,不是另一个独立开关。
灵动岛是客户端的独立透明窗口,不占任务栏。每个班的岛内方案由 Web 管理端「班级灵动岛」维护,
教室端登录本班后自动同步;未配置的班使用经典 fixed,默认 fixed。自定义当前即常驻模式;
旧 residentEnabled 字段只作兼容,不是另一个独立开关。
两种布局共用一个原生窗口,切布局不会新开第二个岛。
## 两种消息展示
@@ -33,27 +34,30 @@ description: 经典提醒、自定义常驻方案、课程与课件传输。
| 展开详情 | ![详情](../images/island-5-clicked.png) |
| 紧急通知 | ![紧急](../images/island-3-urgent.png) |
## 编辑自定义方案
## 在 Web 管理端编辑班级方案
“设置 → 灵动岛 → 自定义 → 编辑岛内组件”进入主窗口设置页。
Web 管理端打开「班级与人员 → 班级灵动岛」,先选择班级,再编辑这个班独立的方案。
页面上方排列当前组件,右上角选择配置方案;刷新图标重置当前方案,加号新建方案,文件夹菜单提供方案设置、复制、删除及 JSON 导入导出。
下方组件库常驻显示文本、分割线、课程表、日期、时钟、天气简报、倒计时和组合容器。通知、作业和叫人通过岛内铃铛及共用消息面板展示,组件库不再提供这些消息选项;已有方案中的消息节点仍兼容。
从组件库拖入上方的行或容器以添加,拖动已有组件调整顺序或跨行移动;也可点击组件库添加到选中的容器或当前行。
分别编辑常态 rows 与无消息展开 expandedRows,点选组件打开内容、外观、尺寸与隐藏条件设置;行可以新增、排序、设为主要行或删除。
“进入编辑模式”切换为实际内容预览,支持预览缩放;退出后回到组件标签排列。轮播和滚动容器在编辑时展示全部子组件,便于选择和排列。
“预览组件外观”展示接近教室端的最终岛体,支持预览缩放;常态行固定 40px 高并保持水平、垂直居中。
返回结构排列后继续拖拽。轮播和滚动容器在结构排列中展示全部子组件,便于选择和排列。
倒计时可指定目标名称与日期,也可按课表倒数至上课、下课或放学。
天气简报需填写地点名称及经纬度,使用 [Open-Meteo](https://open-meteo.com/en/docs) 的天气数据,每 15 分钟更新;断网时保留本次客户端运行中的缓存并标明“缓存”。天气提示根据天气概况生成,不提供官方气象预警。
方案保存到本机 config.json.islandLayout,不增加服务端同步。
编辑预览不创建额外桌面窗口;打开编辑页不自动切布局,应用后启用自定义方案。
保存按序进行,失败可重试,主题与关怀模式沿用客户端设置。
方案保存到班级记录,仅本班班主任或管理员可写;班级账号和教室客户端只读本班方案。
保存后服务端广播 `class:updated`,客户端立即拉取;断线时保留本机上一次已同步方案。
客户端设置页不再提供岛内组件编辑入口,只展示当前是否使用服务端下发方案。
提醒阈值与指针避让仍按教室本机偏好保存,不随班级布局覆盖。
## 外观、位置与输入
经典模式可调宽高、字号、主题色、黑色/半透明/渐变、停靠与边距;自定义内容根据实际测量适配工作区。
自定义方案可配置缩放、圆角、颜色和行间距,默认值与范围在 shared/island-layout.ts。外观页的圆角滑块同步修改当前自定义方案的常态圆角,与编辑器设置一致。
自定义方案可配置缩放、四档字号、字重、圆角、背景/前景色和行间距,默认值与范围在 shared/island-layout.ts。四档字号输入范围是 1–40px,可按组件或单行覆盖;关闭行级覆盖后只回落该行,不影响其他行。
强调色支持自定义、壁纸调色板、跟随系统和屏幕调色板四种来源;自定义背景与前景可分别关闭,关闭后回落当前亮/暗主题。前景色会派生 100% / 85.5% / 77.3% / 52.9% / 36.5% 五级文字 alpha。外观页的圆角滑块同步修改当前自定义方案的常态圆角,与编辑器设置一致。
左右边距只在左/右停靠时生效,居中锚点仍在屏幕中线。
触摸屏自动进入触摸模式,保留触摸命中和失焦宽限;鼠标模式按光标控制输入穿透。
自定义常驻内容支持鼠标避让淡化及反转,交互入口、展开/编辑和触摸操作按实现暂停避让。
自定义常驻内容支持鼠标避让淡化及反转,交互入口、展开和触摸操作按实现暂停避让。
应用内动画开关决定岛动画,不能用主窗口的减少动态效果说明替代岛自身规则。
经典几何与配色参考见[设计令牌](../dev/winisland-design-tokens.md),实现入口见[当前实现约定](../dev/implementation.md)。
+13 -12
View File
@@ -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 | 当前有效权限、目录、组与账号分组 |
## 教学与文件
+8 -3
View File
@@ -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` 显示进度。
+54 -10
View File
@@ -10,15 +10,17 @@ description: 本地经典/自定义岛的几何、外观与动画入口。
## 经典几何与外观
| 来源 | 内容 |
| ---------------------------------------------------- | ----------------------------------------------------- |
| shared/src/constants.ts 的 DEFAULT_ISLAND_APPEARANCE | 默认宽 268、高 44、圆角 20、字号 13、边距 8,顶部居中 |
| ISLAND_APPEARANCE_RANGES | 滑块与主进程归一化共用的范围 |
| ISLAND_SIZE_DELTA | 展开、紧急与叫人相对尺寸 |
| ISLAND_SHADOW_PAD | 窗口边界的透明留白 |
| ISLAND_LIST_METRICS / islandListLayout | 主进程和渲染层共用列表度量,控制行数与工作区高度 |
| desktop-client/src/island/squircle.ts | 超椭圆路径 |
| desktop-client/src/island/classic-island.css | 经典底色、文字、图形与状态样式 |
| 来源 | 内容 |
| ---------------------------------------------------- | --------------------------------------------------------------------- |
| shared/src/constants.ts 的 DEFAULT_ISLAND_APPEARANCE | 默认宽 268、高 44、圆角 20、字号 13、边距 8,顶部居中 |
| shared/src/constants.ts 的 CLASSISLAND_TOKENS | 岛层颜色、字体、字号、圆角、间距、阴影、层级与 DPI 的 TypeScript 来源 |
| ISLAND_APPEARANCE_RANGES | 滑块与主进程归一化共用的范围 |
| ISLAND_SIZE_DELTA | 展开、紧急与叫人相对尺寸 |
| ISLAND_SHADOW_PAD | 窗口边界的透明留白 |
| ISLAND_LIST_METRICS / islandListLayout | 主进程和渲染层共用列表度量,控制行数与工作区高度 |
| desktop-client/src/island/squircle.ts | 超椭圆路径 |
| desktop-client/src/island/classic-island.css | 经典底色、文字、图形与状态样式 |
| ui/src/tokens.css | `--ci-*` 亮/暗两套 CSS 变量,以及五级文字工具类 |
classic 的 black/glass/tinted 是本地 CSS 外观;glass 使用半透明色,不采样桌面模糊。
不要对透明岛调用 setBackgroundMaterial:系统材质作用于整窗矩形,可能破坏逐像素透明。
@@ -41,6 +43,47 @@ CLASSISLAND_ISLAND_METRICS 位于 shared/src/island-layout.ts:
方案有常态 rows 和无通知展开 expandedRows,运行时由 CustomIslandRuntime.vue 测量自然内容,
再按屏幕工作区与方案缩放适配。字体与外观覆盖按组件契约生效,不能拿经典固定宽高解释自定义内容尺寸。
自定义岛默认使用 CSS `border-radius`;经典岛继续保留连续圆角。圆角同时作用于自绘背景与内容裁切,
默认 8px、范围 0–20px、步进 0.5px。背景色只通过 `--resident-background` 派生,背景 alpha 与整行
`opacity` 分开计算,避免整行不透明度连带淡化投影和覆盖层。
### ClassIsland token 层
`CLASSISLAND_TOKENS` 与 `--ci-*` 一一对应,应用外壳继续使用 `--ch-*` / `--ch-ui-*`。
ClassIsland 源值中的颜色采用 Avalonia `AARRGGBB`,写入 CSS 时统一转换为
`RRGGBBAA`,alpha 数值不变。
| 类别 | 关键值 |
| -------- | ------------------------------------------------------------------------ |
| 强调色 | PrimaryColor / DeepSkyBlue、SecondaryColor / Aquamarine、DodgerBlue 兜底 |
| 五级前景 | 100% / 85.5% / 77.3% / 52.9% / 36.5%,开启自定义前景时写进颜色 alpha |
| 四档字号 | 14 / 16 / 18 / 20px,设置范围 1–40px,步进 0.5px |
| 字重 | 100–900 逐值映射,默认 500;其他值回落 400 |
| 圆角 | 岛 8、弹窗 6、卡片与控件 4、抽屉 8 8 0 0、胶囊 999px |
| 间距 | 行高 40、左右 12、组件间距 12、行距 5、进度条 3px |
| 层级 | 遮罩/拖拽 1、抽屉 10、时间轴装饰 9999、哨兵 2147483647 |
| DPI | 96 DPI 基准、缩放 0.75–2.5、Fluent 竖直安全区 20px |
四档字号可写在组件自身、单个行或方案根元素。行级与组件级都通过 CSS 变量覆盖;关闭覆盖时删除
对应内联变量并回落到方案或 `:root`。自定义前景关闭时同样删除行内五级变量,由 `html.dark` 切换
主题默认值。
强调色来源严格区分自定义、壁纸调色板、跟随系统与屏幕调色板;主进程输出 `resolvedAccent`,设置页
仍保留用户选择的 `accent`,避免切换来源时覆盖原自定义色。主题切换通过岛桥接的 `island:theme`
事件实时同步 `html.dark`,不依赖主窗口的 DOM。
### 主界面对照
| 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`,嵌入自定义岛或经典岛 |
## 动画与命中
经典与自定义岛的形变都使用 src/island/spring.ts 的 SpringValue;默认 stiffness=0.10、damping=0.68,
@@ -55,5 +98,6 @@ CLASSISLAND_ISLAND_METRICS 位于 shared/src/island-layout.ts:
## 修改入口
外观范围改 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
View File
@@ -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)。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 KiB

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 69 KiB

+2 -1
View File
@@ -16,8 +16,9 @@
"build": "pnpm build:shared && pnpm --filter @classhelper/server build && pnpm --filter @classhelper/web-admin build && pnpm --filter @classhelper/desktop-client build",
"build:desktop": "pnpm build:shared && pnpm --filter @classhelper/desktop-client build",
"check:icons": "node scripts/check-icons.mjs",
"check:design-tokens": "node scripts/check-design-tokens.mjs",
"typecheck": "pnpm build:shared && pnpm -r --workspace-concurrency=1 --no-bail typecheck",
"lint": "node scripts/check-authz.mjs && eslint .",
"lint": "node scripts/check-authz.mjs && node scripts/check-design-tokens.mjs && eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write \"**/*.{ts,js,mjs,cjs,vue,json,md,yaml,yml,css,scss,html}\"",
"format:check": "prettier --check \"**/*.{ts,js,mjs,cjs,vue,json,md,yaml,yml,css,scss,html}\"",
@@ -180,11 +180,18 @@ const style = computed<CSSProperties>(() => {
const n = props.node,
a = n.appearance,
override = a.resourceOverridingEnabled;
const color =
a.background +
Math.round((a.customBackgroundOpacityEnabled ? a.backgroundOpacity : 1) * 255)
.toString(16)
.padStart(2, '0');
const alpha = a.customBackgroundOpacityEnabled ? a.backgroundOpacity : 1;
const color = `color-mix(in srgb, ${a.background} ${alpha * 100}%, transparent)`;
const customText: Record<string, string> =
override && a.customForegroundEnabled
? {
'--ci-text-1': a.foreground,
'--ci-text-2': `color-mix(in srgb, ${a.foreground} 85.5%, transparent)`,
'--ci-text-3': `color-mix(in srgb, ${a.foreground} 77.3%, transparent)`,
'--ci-text-4': `color-mix(in srgb, ${a.foreground} 52.9%, transparent)`,
'--ci-text-5': `color-mix(in srgb, ${a.foreground} 36.5%, transparent)`,
}
: {};
return {
opacity: a.opacity,
width: n.advanced.width ? `${n.advanced.width}px` : undefined,
@@ -195,17 +202,19 @@ const style = computed<CSSProperties>(() => {
n.advanced.align
],
textAlign: n.advanced.align === 'start' ? 'start' : n.advanced.align === 'end' ? 'end' : 'center',
color: override && a.customForegroundEnabled ? a.foreground : undefined,
color: 'var(--ci-text-1)',
background: override && a.customBackgroundEnabled ? color : undefined,
borderRadius: override && a.customCornerRadiusEnabled ? `${a.cornerRadius}px` : undefined,
fontSize: override ? `${a.bodyFontSize}px` : undefined,
'--secondary': override ? `${a.secondaryFontSize}px` : undefined,
'--emphasized': override ? `${a.emphasizedFontSize}px` : undefined,
'--large': override ? `${a.largeFontSize}px` : undefined,
'--ci-fs-secondary': override ? `${a.secondaryFontSize}px` : undefined,
'--ci-fs-body': override ? `${a.bodyFontSize}px` : undefined,
'--ci-fs-emphasized': override ? `${a.emphasizedFontSize}px` : undefined,
'--ci-fs-large': override ? `${a.largeFontSize}px` : undefined,
'--rolling-duration': `${Math.max(1, 200 / n.settings.speed)}s`,
flexDirection: container.value ? (n.settings.direction === 'vertical' ? 'column' : 'row') : undefined,
gap: container.value ? `${n.settings.gap}px` : undefined,
display: container.value ? 'flex' : undefined,
...customText,
};
});
</script>
@@ -298,9 +307,10 @@ const style = computed<CSSProperties>(() => {
padding: 6px;
flex-shrink: 0;
position: relative;
color: var(--ci-text-1);
}
.component-node:not(.node-editing) {
line-height: 1.4;
line-height: var(--ci-line-height-body);
}
.clock {
font-variant-numeric: tabular-nums;
@@ -316,7 +326,7 @@ const style = computed<CSSProperties>(() => {
flex-direction: row;
align-items: center;
justify-content: center;
gap: 6px;
gap: calc(var(--ci-component-gap) / 2);
padding-bottom: 3px;
}
.lesson-line strong {
@@ -326,10 +336,10 @@ const style = computed<CSSProperties>(() => {
white-space: nowrap;
}
.lesson-line.current strong {
color: #fff;
color: var(--ci-text-1);
}
.lesson-line.break {
opacity: 0.86;
color: var(--ci-text-3);
}
.time-divider {
display: block;
@@ -344,19 +354,21 @@ const style = computed<CSSProperties>(() => {
flex-shrink: 0;
font-variant-numeric: tabular-nums;
white-space: nowrap;
color: var(--ci-text-3);
font-size: var(--ci-fs-secondary);
}
.lesson-progress {
position: absolute;
inset: auto 0 0;
height: 2px;
background: #ffffff24;
height: var(--ci-progress-height);
background: var(--ci-fill-strong);
overflow: hidden;
border-radius: 1px;
border-radius: calc(var(--ci-progress-height) / 3);
}
.lesson-progress i {
display: block;
height: 100%;
background: var(--island-accent, #60a5fa);
background: var(--island-accent, var(--ci-accent));
transform-origin: left;
transition: transform 1s linear;
}
@@ -391,28 +403,26 @@ const style = computed<CSSProperties>(() => {
animation: none;
}
.selected {
outline: 2px solid #85aaff;
border-radius: 8px;
background: #759cff14;
outline: 2px solid var(--ci-stroke-drag);
border-radius: var(--ci-radius-island);
background: var(--ci-accent-fill-tertiary);
}
.node-handle {
touch-action: none;
cursor: grab;
display: block;
font:
10px 'Microsoft YaHei',
sans-serif;
font: var(--ci-fw-normal) var(--ci-fs-version) / 1.2 var(--ci-font);
padding: 3px 6px;
border: 0;
border-radius: 4px;
border-radius: var(--ci-radius-control);
min-height: 24px;
margin-bottom: 4px;
color: #ffffff80;
background: #ffffff0d;
color: var(--ci-text-3);
background: var(--ci-fill-secondary);
}
.node-handle:hover {
background: #ffffff20;
color: #fff;
background: var(--ci-accent-soft);
color: var(--ci-text-1);
}
.notification,
.homework,
@@ -429,19 +439,19 @@ const style = computed<CSSProperties>(() => {
cursor: pointer;
}
.node-editing:hover {
box-shadow: inset 0 0 0 1px #ffffff28;
border-radius: 8px;
box-shadow: inset 0 0 0 var(--ci-stroke-island-w) var(--ci-stroke-control);
border-radius: var(--ci-radius-island);
}
small {
font-size: var(--secondary, 12px);
opacity: 0.7;
color: var(--ci-text-3);
font-size: var(--ci-fs-secondary);
}
strong,
.emphasized {
font-size: var(--emphasized, 20px);
font-size: var(--ci-fs-emphasized);
}
.large {
font-size: var(--large, 28px);
font-size: var(--ci-fs-large);
}
@keyframes rolling {
from {
@@ -453,4 +463,3 @@ strong,
}
</style>
<style src="./lesson-ending.css"></style>
<style src="./lesson-ending.css"></style>
@@ -20,7 +20,8 @@ const style = computed(() => {
: position.endsWith('right')
? { right: `${ISLAND_SHADOW_PAD}px` }
: { left: '50%', transform: 'translateX(-50%)' }),
'--transfer-accent': props.appearance.accent,
'--ci-accent': props.appearance.resolvedAccent ?? props.appearance.accent,
'--transfer-accent': 'var(--ci-accent)',
};
});
const status = computed(
@@ -68,15 +69,12 @@ onUnmounted(() => window.removeEventListener('resize', report));
.courseware-transfer {
position: fixed;
box-sizing: border-box;
padding: 17px 24px;
border-radius: 24px;
color: white;
background: rgba(20, 20, 24, 0.97);
box-shadow: 0 2px 8px #0004;
font:
13px/1.4 'Segoe UI',
'Microsoft YaHei',
sans-serif;
padding: calc(var(--ci-popup-pad) + var(--ci-line-gap)) calc(var(--ci-popup-pad) * 2);
border-radius: var(--ci-radius-oobe-btn);
color: var(--ci-text-1);
background: color-mix(in srgb, var(--ci-bg-secondary) 97%, transparent);
box-shadow: var(--ci-shadow-island);
font: var(--ci-fw-normal) var(--ci-fs-control-base) / 1.4 var(--ci-font);
overflow: hidden;
pointer-events: none;
}
@@ -84,26 +82,26 @@ header,
.metadata {
display: flex;
justify-content: space-between;
gap: 10px;
gap: calc(var(--ci-component-gap) * 0.8);
}
header {
color: #ffffffb8;
font-size: 12px;
color: var(--ci-text-2);
font-size: var(--ci-fs-caption);
}
header strong {
color: var(--transfer-accent);
}
.filename {
font-weight: 600;
font-size: 16px;
font-weight: var(--ci-fw-semi-bold);
font-size: var(--ci-fs-title);
margin: 5px 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.metadata {
color: #ffffffb8;
font-size: 12px;
color: var(--ci-text-2);
font-size: var(--ci-fs-caption);
}
progress {
display: block;
@@ -111,20 +109,20 @@ progress {
height: 5px;
margin-top: 11px;
border: 0;
border-radius: 8px;
border-radius: var(--ci-radius-island);
overflow: hidden;
accent-color: var(--transfer-accent);
}
progress::-webkit-progress-bar {
background: #ffffff30;
background: var(--ci-fill-strong);
}
progress::-webkit-progress-value {
background: var(--transfer-accent);
}
p {
margin: 3px 0;
font-size: 11px;
color: #ffb4ab;
font-size: var(--ci-fs-caption);
color: var(--ci-warning-critical);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
@@ -4,6 +4,7 @@ import {
ISLAND_SHADOW_PAD,
PRIORITY_RANK,
type IslandAppearance,
type IslandLayoutRow,
type IslandLayoutSettings,
type IslandState,
type IslandTimePointDto,
@@ -13,7 +14,6 @@ import {
import ComponentNode from './ComponentNode.vue';
import ComponentIcon from './ComponentIcon.vue';
import ClassicNotifications from './ClassicNotifications.vue';
import { squirclePath } from './squircle.js';
import { SpringValue } from './spring.js';
import LessonReminderContent from './LessonReminderContent.vue';
@@ -78,6 +78,33 @@ function fitted(size: { width: number; height: number }) {
);
return { scale, width: Math.ceil(size.width * scale), height: Math.ceil(size.height * scale) };
}
/** 页面配置里的十六进制颜色转成背景 alpha;输入已由 shared 归一化。 */
function withAlpha(hex: string, alpha: number): string {
return `color-mix(in srgb, ${hex} ${Math.min(1, Math.max(0, alpha)) * 100}%, transparent)`;
}
/** 自定义前景色必须写进颜色 alpha,不能用 opacity 连带淡化子元素与阴影。 */
function foregroundVars(hex: string): Record<string, string> {
return {
'--ci-text-1': hex,
'--ci-text-2': `color-mix(in srgb, ${hex} 85.5%, transparent)`,
'--ci-text-3': `color-mix(in srgb, ${hex} 77.3%, transparent)`,
'--ci-text-4': `color-mix(in srgb, ${hex} 52.9%, transparent)`,
'--ci-text-5': `color-mix(in srgb, ${hex} 36.5%, transparent)`,
};
}
function rowStyle(row: IslandLayoutRow): Record<string, string> {
const style: Record<string, string> = {
'--row-gap': `${row.gap}px`,
opacity: String(row.opacity),
};
if (row.fontOverridesEnabled) {
style['--ci-fs-secondary'] = `${row.secondaryFontSize}px`;
style['--ci-fs-body'] = `${row.bodyFontSize}px`;
style['--ci-fs-emphasized'] = `${row.emphasizedFontSize}px`;
style['--ci-fs-large'] = `${row.largeFontSize}px`;
}
return style;
}
const compactFit = computed(() => fitted(natural.value.compact));
const detailsFit = computed(() => fitted(natural.value.details));
const lessonFit = computed(() => fitted(natural.value.lesson));
@@ -98,30 +125,44 @@ const progress = ref(0);
const lessonProgress = ref(0);
const compactAlpha = computed(() => Math.max(0, 1 - progress.value * 1.5) * (1 - lessonProgress.value));
const detailsAlpha = computed(() => progress.value * progress.value * (1 - lessonProgress.value));
const path = computed(() => squirclePath(morph.value.width, morph.value.height, morph.value.radius));
const style = computed<CSSProperties>(() => ({
width: `${morph.value.width}px`,
height: `${morph.value.height}px`,
'--card-path': `path("${path.value}")`,
'--island-font': `${props.appearance.fontSize}px`,
'--island-accent': props.appearance.accent,
'--state-color':
props.state.active?.priority === 'URGENT'
? '#ff453a'
: props.state.active?.kind === 'call'
? '#ff9f0a'
: props.appearance.accent,
'--resident-background': 'var(--wn-bg)',
'--resident-radius': `${morph.value.radius}px`,
'--resident-scale': fit.value.scale,
'--custom-row-gap': `${scheme.value.spacing}px`,
'--resident-row-width': `${Math.max(60, available.value.width / scheme.value.scale - 58)}px`,
'--secondary': `${(props.appearance.fontSize / 13) * 14}px`,
'--emphasized': `${(props.appearance.fontSize / 13) * 18}px`,
'--large': `${(props.appearance.fontSize / 13) * 20}px`,
'--ci-body-font': `${(props.appearance.fontSize / 13) * 16}px`,
'--resident-fade-duration': motion.value ? `${200 / props.appearance.speed}ms` : '0ms',
}));
const style = computed<CSSProperties>(() => {
const current = scheme.value;
const background = lesson.value
? 'transparent'
: expanded.value && messages.value.length
? current.customForegroundEnabled
? 'var(--ci-brand-dark)'
: 'var(--ci-bg-base)'
: current.customBackgroundEnabled
? withAlpha(current.color, current.opacity)
: 'var(--ci-bg-secondary)';
return {
width: `${morph.value.width}px`,
height: `${morph.value.height}px`,
'--island-font': `${current.bodyFontSize}px`,
'--ci-fs-secondary': `${current.secondaryFontSize}px`,
'--ci-fs-body': `${current.bodyFontSize}px`,
'--ci-fs-emphasized': `${current.emphasizedFontSize}px`,
'--ci-fs-large': `${current.largeFontSize}px`,
'--ci-font-weight': String(current.fontWeight),
'--ci-scale': String(current.scale),
'--ci-accent': props.appearance.resolvedAccent ?? props.appearance.accent,
'--state-color':
props.state.active?.priority === 'URGENT'
? 'var(--ci-danger)'
: props.state.active?.kind === 'call'
? 'var(--ci-warning-caution)'
: 'var(--ci-accent)',
'--resident-background': background,
'--resident-radius': `${morph.value.radius}px`,
'--resident-scale': fit.value.scale,
'--custom-row-gap': `${current.spacing}px`,
'--resident-row-width': `${Math.max(60, available.value.width / current.scale - 58)}px`,
'--ci-body-font': `${current.bodyFontSize}px`,
'--resident-fade-duration': motion.value ? `${200 / props.appearance.speed}ms` : '0ms',
...(current.customForegroundEnabled ? foregroundVars(current.foreground) : {}),
};
});
let morphFrame = 0;
let morphFallback: ReturnType<typeof setTimeout> | undefined;
function animate() {
@@ -342,6 +383,16 @@ onUnmounted(() => {
:data-bottom="appearance.position.startsWith('bottom')"
@pointerdown.capture="pointer"
>
<span
class="resident-shadow"
:class="{ 'resident-shadow-hidden': lesson || (scheme.separated && !expanded) }"
:style="{
width: `${morph.width}px`,
height: `${morph.height}px`,
borderRadius: `${morph.radius}px`,
}"
aria-hidden="true"
/>
<section
ref="shell"
class="custom-card resident-card island-card"
@@ -371,16 +422,6 @@ onUnmounted(() => {
@keydown="key"
@transitionend.self="reportHit"
>
<svg
class="shape"
:width="morph.width"
:height="morph.height"
:viewBox="`0 0 ${morph.width} ${morph.height}`"
preserveAspectRatio="none"
aria-hidden="true"
>
<path :d="path" />
</svg>
<span class="tint" aria-hidden="true" />
<div
class="resident-page resident-compact-page"
@@ -400,7 +441,7 @@ onUnmounted(() => {
:key="row.id"
class="layout-row"
:data-row="row.id"
:style="{ '--row-gap': `${row.gap}px` }"
:style="rowStyle(row)"
>
<div class="row-components">
<ComponentNode
@@ -482,7 +523,7 @@ onUnmounted(() => {
:key="row.id"
class="layout-row"
:data-row="row.id"
:style="{ '--row-gap': `${row.gap}px` }"
:style="rowStyle(row)"
>
<div class="row-components">
<ComponentNode
@@ -29,10 +29,10 @@ onUnmounted(() => clearInterval(clock));
* - 造型:**连续圆角(超椭圆 squircle)**而不是 border-radius(WinIsland `utils/shape.rs`);
* 展开卡半径取 `min(48 * 圆角系数, w/2, h/2)`,胶囊半径取 `h/2`(满圆角);
* - 底色:默认纯黑(WinIsland `default` 风格),可选半透明毛玻璃(`glass`;
* **纯 CSS 实现**,取 WinIsland 拿不到 host backdrop 时的降级色 `rgba(32,32,36,.804)`——
* **纯 CSS 实现**,取 WinIsland 拿不到 host backdrop 时的 80.4% 深色降级底——
* Electron 的 `setBackgroundMaterial()` 不能用在逐像素透明窗口上,原因见 `main/island.ts`);
* - 描边:1px 白、alpha 30(纯黑)/ 40(玻璃、主题色),与 WinIsland `BORDER_*_ALPHA` 同值;
* - 阴影:只在展开态,`0 2px 3px rgba(0,0,0,.11)`(WinIsland `draw_expanded_shadow`);
* - 阴影:只在展开态,2px 偏移、3px 模糊、11% 黑(WinIsland `draw_expanded_shadow`);
* - 排版:白字 + alpha 分级(.92/.72/.58),**所有文本 = 基础字号 × 排版系数**,
* 因此「字号」设置一改,岛内文字整体等比缩放(WinIsland `font_size` 模型);
* - 动效:**单调缓动(无过冲、无回弹)**,只有淡入淡出与窗口形变,符合"开合不震动"。
@@ -150,8 +150,8 @@ const showAfterClassHint = computed(() => state.value.reason === 'after-class' &
/** 状态色(WinIsland 资源占用色板同源):危险红 / 警告橙 / 强调蓝 */
const stateColor = computed(() => {
if (isUrgent.value) return '#ff453a';
if (isCall.value) return '#ff9f0a';
if (isUrgent.value) return 'var(--ci-danger)';
if (isCall.value) return 'var(--ci-warning-caution)';
if (isHomework.value) return appearance.value.accent;
return '';
});
@@ -519,7 +519,8 @@ function applyAppearance(next: IslandAppearance | null | undefined): void {
if (!next) return;
appearance.value = next;
const style = document.documentElement.style;
style.setProperty('--island-accent', next.accent);
style.setProperty('--ci-accent', next.resolvedAccent ?? next.accent);
style.setProperty('--ci-accent-fill', 'var(--ci-accent)');
style.setProperty('--island-radius', `${next.radius}px`);
style.setProperty('--island-font', `${next.fontSize}px`);
style.setProperty('--island-w', `${next.width}px`);
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import {
defaultIslandLayouts,
DEFAULT_ISLAND_APPEARANCE,
@@ -18,6 +18,7 @@ const schedules = ref<ScheduleDto[]>([]);
const timePoints = ref<IslandTimePointDto[]>([]);
const appearance = ref<IslandAppearance>({ ...DEFAULT_ISLAND_APPEARANCE });
const nativeVisible = ref(false);
const theme = ref<'light' | 'dark'>('light');
const resident = () => settings.value.layout === 'custom';
const state = ref<IslandState>({
mode: 'hidden',
@@ -31,11 +32,15 @@ const state = ref<IslandState>({
updatedAt: 0,
});
let heartbeat: ReturnType<typeof setInterval>;
watch(theme, (value) => document.documentElement.classList.toggle('dark', value === 'dark'), {
immediate: true,
});
onUnmounted(() => clearInterval(heartbeat));
onMounted(async () => {
heartbeat = setInterval(() => window.island?.alive(), 5000);
const bridge = window.island;
if (bridge) {
bridge.onTheme((value) => (theme.value = value));
bridge.onLayout((value) => (settings.value = value));
bridge.onSchedules((value) => (schedules.value = value));
bridge.onTimePoints((value) => (timePoints.value = value));
@@ -43,6 +48,7 @@ onMounted(async () => {
bridge.onAppearance((value) => (appearance.value = value));
bridge.onVisibility((value) => (nativeVisible.value = value));
nativeVisible.value = await bridge.getVisible();
theme.value = await bridge.getTheme();
appearance.value = await bridge.getAppearance();
settings.value = await bridge.getLayout();
schedules.value = await bridge.getSchedules();
@@ -198,20 +198,20 @@ onUnmounted(() => {
width: max-content;
min-width: 300px;
max-width: 800px;
height: 40px;
height: var(--ci-island-height);
overflow: hidden;
color: #fff;
font-size: 16px;
color: var(--ci-text-1);
font-size: var(--ci-fs-body);
line-height: 1;
border-radius: 8px;
background: #20202080;
border-radius: var(--ci-radius-island);
background: color-mix(in srgb, var(--ci-bg-base) 50%, transparent);
}
.ci-lesson-info {
height: 40px;
height: var(--ci-island-height);
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
gap: var(--ci-component-gap);
padding: 0 14px;
white-space: nowrap;
transition: opacity var(--ci-duration) ease-in;
@@ -230,25 +230,26 @@ onUnmounted(() => {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
gap: calc(var(--ci-component-gap) / 2);
}
.ci-lesson-course strong {
font-size: 20px;
font-size: var(--ci-fs-large);
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.ci-lesson-course small {
flex-shrink: 0;
font-size: 14px;
color: var(--ci-text-3);
font-size: var(--ci-fs-secondary);
font-variant-numeric: tabular-nums;
}
.ci-mask {
position: absolute;
inset: 0;
width: 100%;
height: 40px;
fill: var(--island-accent, #60a5fa);
height: var(--ci-island-height);
fill: var(--island-accent, var(--ci-accent));
pointer-events: none;
}
.ci-mask-title {
@@ -257,9 +258,9 @@ onUnmounted(() => {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
gap: calc(var(--ci-component-gap) * 0.67);
opacity: 0;
font-size: 18px;
font-size: var(--ci-fs-emphasized);
transform: scale(1.1);
transition:
opacity var(--ci-duration) linear,
@@ -309,8 +310,8 @@ onUnmounted(() => {
bottom: 0;
left: 0;
width: 100%;
height: 2px;
background: var(--island-accent, #60a5fa);
height: var(--ci-progress-height);
background: var(--island-accent, var(--ci-accent));
transform-origin: left;
transition: transform 50ms linear;
}
@@ -86,6 +86,7 @@ const advice = computed(() => {
}
small {
display: block;
font-size: var(--secondary, 12px);
color: var(--ci-text-3);
font-size: var(--ci-fs-secondary);
}
</style>
@@ -18,10 +18,13 @@ body,
user-select: none;
}
:root {
/* 经典岛沿用历史变量名,但颜色唯一来源仍是 --ci-accent。 */
--island-accent: var(--ci-accent);
}
body {
font-family:
-apple-system, 'Segoe UI Variable Display', 'Segoe UI', 'Microsoft YaHei', 'PingFang SC',
'Helvetica Neue', sans-serif;
font-family: var(--ci-font-island);
-webkit-font-smoothing: antialiased;
}
@@ -53,36 +56,38 @@ body {
margin: 0;
border: none;
background: none;
color: rgba(255, 255, 255, 0.92);
color: var(--ci-text-on-accent);
font-family: var(--ci-font-island);
font-size: var(--island-font, 13px);
font-weight: var(--ci-font-weight);
text-align: left;
cursor: pointer;
/* 配色 token(默认:WinIsland 纯黑风格) */
--wn-bg: #000000;
--wn-border: rgba(255, 255, 255, 0.118);
--wn-text-1: rgba(255, 255, 255, 0.92);
--wn-text-2: rgba(255, 255, 255, 0.72);
--wn-text-3: rgba(255, 255, 255, 0.58);
--wn-surface: rgba(255, 255, 255, 0.1);
--wn-surface-hover: rgba(255, 255, 255, 0.18);
--wn-divider: rgba(255, 255, 255, 0.09);
--wn-bg: var(--ci-island-bg-custom);
--wn-border: var(--ci-stroke-island);
--wn-text-1: var(--ci-text-on-accent);
--wn-text-2: color-mix(in srgb, var(--ci-text-on-accent) 85.5%, transparent);
--wn-text-3: color-mix(in srgb, var(--ci-text-on-accent) 77.3%, transparent);
--wn-surface: var(--ci-fill-secondary);
--wn-surface-hover: var(--ci-accent-soft);
--wn-divider: var(--ci-stroke-divider);
}
.island-card[data-style='glass'] {
/* WinIsland「glass 无 host backdrop」降级色:比纯黑透一点,但保证任何桌面下都不是白底 */
--wn-bg: rgba(32, 32, 36, 0.804);
--wn-border: rgba(255, 255, 255, 0.157);
--wn-surface: rgba(255, 255, 255, 0.14);
--wn-surface-hover: rgba(255, 255, 255, 0.22);
--wn-bg: color-mix(in srgb, var(--ci-bg-base) 80.4%, transparent);
--wn-border: var(--ci-stroke-control);
--wn-surface: var(--ci-fill-secondary);
--wn-surface-hover: var(--ci-accent-fill-tertiary);
}
.island-card[data-style='tinted'] {
--wn-bg: #0b0b0f;
--wn-border: rgba(255, 255, 255, 0.14);
--wn-bg: color-mix(in srgb, var(--ci-island-bg-custom) 88%, var(--ci-accent));
--wn-border: var(--ci-stroke-control);
}
/* 阅读老师消息时使用实色底,玻璃风格也不透出桌面。 */
.island-card.message-surface {
--wn-bg: #202020;
--wn-bg: var(--ci-brand-dark);
}
.island-card.hidden-placeholder {
@@ -120,7 +125,9 @@ body {
胶囊态用 0 0 0:硬轮廓投影正好压在路径底下,肉眼等同无投影,与 WinIsland
"只有展开态有投影"的观感一致。
*/
filter: drop-shadow(0 var(--card-shadow-y, 0px) var(--card-shadow-blur, 0px) rgba(0, 0, 0, 0.11));
filter: drop-shadow(
0 var(--card-shadow-y, 0px) var(--card-shadow-blur, 0px) color-mix(in srgb, black 11%, transparent)
);
}
/* 内容层裁切到同一形状内;内部两层(胶囊层 / 展开层)交叉淡入 */
@@ -145,7 +152,7 @@ body {
pointer-events: auto;
}
/* 展开态投影(WinIsland: rgba(0,0,0,.11)、y+2、σ=3 → CSS 0 2px 3px)。
/* 展开态投影(WinIsland: 11% 黑、y+2、σ=3 → CSS 0 2px 3px)。
只改参数、不动 filter 声明本身,理由见上面的 .shape path。 */
.island-card.expanded .shape path {
--card-shadow-y: 2px;
@@ -155,7 +162,7 @@ body {
/* 状态色:只做"内层微染 + 描边",不外溢(保持桌面干净,也不会有光晕硬边) */
.island-card.urgent .shape path,
.island-card.call .shape path {
stroke: color-mix(in srgb, var(--state-color) 62%, rgba(255, 255, 255, 0.2));
stroke: color-mix(in srgb, var(--state-color) 62%, var(--ci-stroke-control));
}
.island-card .tint {
@@ -167,12 +174,20 @@ body {
.island-card.urgent .tint {
opacity: 1;
background: radial-gradient(120% 90% at 50% 0%, rgba(255, 69, 58, 0.22), transparent 68%);
background: radial-gradient(
120% 90% at 50% 0%,
color-mix(in srgb, var(--ci-danger) 22%, transparent),
transparent 68%
);
}
.island-card.call .tint {
opacity: 1;
background: radial-gradient(120% 90% at 50% 0%, rgba(255, 159, 10, 0.2), transparent 68%);
background: radial-gradient(
120% 90% at 50% 0%,
color-mix(in srgb, var(--ci-warning-caution) 20%, transparent),
transparent 68%
);
}
.island-card[data-style='tinted'] .tint {
@@ -242,7 +257,7 @@ body {
flex: 0 0 auto;
width: calc(var(--island-font, 13px) * 1.24);
height: calc(var(--island-font, 13px) * 1.24);
border-radius: 50%;
border-radius: var(--ci-radius-pill);
background: var(--wn-surface);
color: var(--wn-text-1);
}
@@ -253,11 +268,11 @@ body {
}
.pill-icon.call {
color: #ff9f0a;
color: var(--ci-warning-caution);
}
.pill-icon.urgent {
color: #ff453a;
color: var(--ci-danger);
}
.pill-icon.homework {
@@ -305,8 +320,8 @@ body {
font-size: calc(var(--island-font, 13px) * 0.6);
line-height: 1.4;
padding: 0 calc(var(--island-font, 13px) * 0.36);
border-radius: 999px;
background: rgba(255, 255, 255, 0.12);
border-radius: var(--ci-radius-pill);
background: var(--ci-fill-secondary);
color: var(--wn-text-2);
white-space: nowrap;
}
@@ -314,7 +329,7 @@ body {
.pill-chevron {
display: inline-flex;
align-items: center;
color: rgba(255, 255, 255, 0.34);
color: var(--ci-text-5);
flex: 0 0 auto;
}
@@ -386,7 +401,7 @@ body {
padding: 0 calc(var(--island-font, 13px) * 0.6);
border: none;
border-radius: calc(var(--island-font, 13px) * 0.5);
background: rgba(255, 255, 255, 0.045);
background: var(--ci-accent-soft);
color: var(--wn-text-1);
text-align: left;
cursor: pointer;
@@ -411,7 +426,7 @@ body {
}
.row-icon.call {
color: #ff9f0a;
color: var(--ci-warning-caution);
}
.row-icon.homework {
@@ -451,11 +466,11 @@ body {
flex: 0 0 auto;
height: calc(var(--island-font, 13px) * 1.25);
padding: 0 calc(var(--island-font, 13px) * 0.5);
border-radius: 999px;
border-radius: var(--ci-radius-pill);
font-size: calc(var(--island-font, 13px) * 0.68);
font-weight: 600;
background: rgba(255, 255, 255, 0.12);
color: rgba(255, 255, 255, 0.78);
background: var(--ci-fill-secondary);
color: var(--ci-text-3);
}
/* 列表底部的提示行:能展开时是按钮,屏幕到任务栏了就是一句"去应用里看" */
@@ -511,13 +526,13 @@ body {
}
.head-icon.urgent {
background: rgba(255, 69, 58, 0.2);
color: #ff453a;
background: color-mix(in srgb, var(--ci-danger) 20%, transparent);
color: var(--ci-danger);
}
.head-icon.call {
background: rgba(255, 159, 10, 0.2);
color: #ff9f0a;
background: color-mix(in srgb, var(--ci-warning-caution) 20%, transparent);
color: var(--ci-warning-caution);
}
.head-icon.homework {
@@ -538,39 +553,39 @@ body {
align-items: center;
height: calc(var(--island-font, 13px) * 1.5);
padding: 0 calc(var(--island-font, 13px) * 0.62);
border-radius: 999px;
border-radius: var(--ci-radius-pill);
font-size: calc(var(--island-font, 13px) * 0.76);
font-weight: 600;
letter-spacing: 0.02em;
background: color-mix(in srgb, var(--island-accent) 26%, transparent);
color: color-mix(in srgb, var(--island-accent) 70%, #ffffff);
color: color-mix(in srgb, var(--island-accent) 70%, var(--ci-text-1));
flex: 0 0 auto;
}
.badge-urgent {
background: rgba(255, 69, 58, 0.24);
color: #ff6961;
background: color-mix(in srgb, var(--ci-danger) 24%, transparent);
color: var(--ci-danger);
}
.badge-high {
background: rgba(255, 159, 10, 0.22);
color: #ffb340;
background: color-mix(in srgb, var(--ci-warning-caution) 22%, transparent);
color: var(--ci-warning-caution);
}
.badge-low,
.badge-normal {
background: rgba(255, 255, 255, 0.12);
color: rgba(255, 255, 255, 0.78);
background: var(--ci-fill-secondary);
color: var(--ci-text-3);
}
.badge-call {
background: rgba(255, 159, 10, 0.24);
color: #ffb340;
background: color-mix(in srgb, var(--ci-warning-caution) 24%, transparent);
color: var(--ci-warning-caution);
}
.badge-homework {
background: color-mix(in srgb, var(--island-accent) 26%, transparent);
color: color-mix(in srgb, var(--island-accent) 72%, #ffffff);
color: color-mix(in srgb, var(--island-accent) 72%, var(--ci-text-1));
}
.live-dot {
@@ -578,12 +593,12 @@ body {
align-items: center;
gap: calc(var(--island-font, 13px) * 0.32);
font-size: calc(var(--island-font, 13px) * 0.76);
color: #ff6961;
color: var(--ci-danger);
white-space: nowrap;
}
.live-dot.call {
color: #ffb340;
color: var(--ci-warning-caution);
}
.live-dot.muted {
@@ -605,9 +620,9 @@ body {
width: calc(var(--island-font, 13px) * 1.7);
height: calc(var(--island-font, 13px) * 1.7);
border: none;
border-radius: 50%;
border-radius: var(--ci-radius-pill);
background: var(--wn-surface);
color: rgba(255, 255, 255, 0.72);
color: var(--ci-text-3);
cursor: pointer;
flex: 0 0 auto;
transition:
@@ -625,7 +640,7 @@ body {
font-size: calc(var(--island-font, 13px) * 1.08);
font-weight: 700;
line-height: 1.3;
color: #fff;
color: var(--ci-text-1);
flex: 0 0 auto;
display: -webkit-box;
-webkit-line-clamp: 2;
@@ -654,7 +669,7 @@ body {
margin: 0;
font-size: calc(var(--island-font, 13px) * 0.85);
line-height: 1.4;
color: color-mix(in srgb, var(--state-color) 66%, #ffffff);
color: color-mix(in srgb, var(--state-color) 66%, var(--ci-text-1));
word-break: break-word;
}
@@ -691,7 +706,7 @@ body {
height: calc(var(--island-font, 13px) * 2.05);
padding: 0 calc(var(--island-font, 13px) * 0.9);
border: none;
border-radius: 999px;
border-radius: var(--ci-radius-pill);
font-size: calc(var(--island-font, 13px) * 0.76);
font-weight: 600;
cursor: pointer;
@@ -707,18 +722,18 @@ body {
}
.solid-btn {
background: #ffffff;
color: #0b0b0f;
background: var(--ci-text-1);
color: var(--ci-bg-base);
}
.island-card.call .solid-btn {
background: #ff9f0a;
color: #1a1205;
background: var(--ci-warning-caution);
color: var(--ci-brand-dark);
}
.island-card.urgent .solid-btn {
background: #ff453a;
color: #ffffff;
background: var(--ci-danger);
color: var(--ci-text-on-accent);
}
.ghost-btn:active,
@@ -745,7 +760,7 @@ body {
.icon-btn:hover {
background: var(--wn-surface-hover);
color: #ffffff;
color: var(--ci-text-1);
}
}
@@ -7,11 +7,12 @@
box-sizing: border-box;
padding: 12px;
overflow: hidden;
background: var(--custom-color);
border-radius: var(--custom-radius);
background: var(--resident-background, var(--ci-island-bg-custom));
color: var(--ci-text-1);
border-radius: var(--resident-radius, var(--ci-radius-island));
box-shadow:
inset 0 0 0 1px #ffffff1e,
0 2px 3px #0000001c;
inset 0 0 0 var(--ci-stroke-island-w) var(--ci-stroke-island),
var(--ci-shadow-island);
}
.custom-inner {
width: max-content;
@@ -63,7 +64,7 @@
cursor: pointer;
}
.custom-card[role='button']:focus-visible {
outline: 2px solid #8dafff;
outline: 2px solid var(--ci-stroke-drag);
outline-offset: -3px;
}
.custom-card .resident-bell {
@@ -76,16 +77,16 @@
margin: 0;
padding: 4px;
border: 0;
border-radius: 6px;
border-radius: var(--ci-radius-popup);
background: transparent;
color: #ffda8b;
color: var(--ci-warning-caution);
cursor: pointer;
}
.custom-card .resident-bell:hover {
background: #ffffff1a;
background: var(--ci-fill-secondary);
}
.custom-card .resident-bell.bell-empty {
color: #ffffff60;
color: var(--ci-text-3);
}
.custom-card .resident-bell svg {
width: 18px;
@@ -100,13 +101,11 @@
min-width: 14px;
height: 14px;
padding: 0 3px;
border-radius: 7px;
background: #f45b58;
color: white;
font:
600 9px/1 'Segoe UI',
sans-serif;
box-shadow: 0 0 0 2px var(--custom-color);
border-radius: var(--ci-radius-pill);
background: var(--ci-danger);
color: var(--ci-text-on-accent);
font: var(--ci-fw-semi-bold) var(--ci-fs-version) / 1 var(--ci-font);
box-shadow: 0 0 0 2px var(--resident-background, var(--ci-island-bg-custom));
}
.custom-card .resident-panel-heading {
display: flex;
@@ -114,17 +113,17 @@
justify-content: space-between;
gap: 24px;
padding: 4px 6px 12px;
border-bottom: 1px solid #ffffff1a;
border-bottom: var(--ci-stroke-island-w) solid var(--ci-stroke-divider);
margin-bottom: 4px;
color: #ffffff94;
font-size: 12px;
color: var(--ci-text-2);
font-size: var(--ci-fs-caption);
}
.custom-card .resident-panel-heading button {
min-height: 30px;
padding: 4px 10px;
border: 0;
border-radius: 8px;
background: #ffffff0d;
border-radius: var(--ci-radius-control);
background: var(--ci-fill-secondary);
color: inherit;
font: inherit;
cursor: pointer;
@@ -135,12 +134,12 @@
gap: 6px;
}
.layout-editor .surface-tabs button {
font-size: 12px;
font-size: var(--ci-fs-caption);
}
.layout-editor .surface-tabs button.active {
color: var(--editor-accent);
background: #edf2ff;
border-color: #b6c8f0;
color: var(--ci-accent-text);
background: var(--ci-accent-fill-tertiary);
border-color: var(--ci-stroke-drag);
}
.custom-card .layout-row {
display: flex;
@@ -168,8 +167,8 @@
}
.custom-card.has-alert {
box-shadow:
inset 0 0 0 1px #ffffff2b,
0 2px 3px #0000001c;
inset 0 0 0 var(--ci-stroke-island-w) var(--ci-stroke-control),
var(--ci-shadow-mask);
}
.custom-card.separated {
background: transparent;
@@ -177,10 +176,10 @@
padding: 0;
}
.custom-card.separated .layout-row {
background: var(--custom-color);
border-radius: var(--custom-radius);
padding: 12px;
box-shadow: inset 0 0 0 1px #ffffff1e;
background: var(--resident-background, var(--ci-island-bg-custom));
border-radius: var(--resident-radius, var(--ci-radius-island));
padding: var(--ci-island-pad-x);
box-shadow: inset 0 0 0 var(--ci-stroke-island-w) var(--ci-stroke-island);
}
/* 自定义模式只保留一个岛壳。原提醒渲染器继续负责内容、动画和按钮。 */
.custom-card .island-root.embedded .shape,
@@ -198,7 +197,7 @@
justify-content: flex-start;
}
.custom-card .island-root.embedded {
border-top: 1px solid #ffffff1a;
border-top: var(--ci-stroke-island-w) solid var(--ci-stroke-divider);
}
.custom-window .preview-stage {
width: max-content;
@@ -16,14 +16,48 @@
max-width: none;
max-height: none;
overflow: hidden;
clip-path: var(--card-path);
isolation: isolate;
pointer-events: auto;
background: none;
background: var(--resident-background);
border: var(--ci-stroke-island-w) solid var(--ci-stroke-island);
border-radius: var(--resident-radius);
color: var(--ci-text-1);
font-family: var(--ci-font-island);
font-size: var(--island-font);
font-weight: var(--ci-font-weight);
line-height: 1.4;
box-shadow: none;
z-index: var(--ci-z-content);
transition: background-color var(--ci-duration) linear;
}
.resident-window .resident-shadow {
position: absolute;
left: 50%;
top: 0;
transform: translateX(-50%);
pointer-events: none;
box-shadow: var(--ci-shadow-island);
z-index: var(--ci-z-window);
transition: opacity var(--ci-duration) linear;
}
.resident-window[data-anchor='left'] .resident-shadow {
left: 0;
transform: none;
}
.resident-window[data-anchor='right'] .resident-shadow {
left: auto;
right: 0;
transform: none;
}
.resident-window[data-bottom='true'] .resident-shadow {
top: auto;
bottom: 0;
}
.resident-window .resident-shadow-hidden {
opacity: 0;
}
.resident-window .resident-card > .shape {
display: none;
}
.resident-window[data-anchor='left'] .resident-card {
left: 0;
@@ -72,10 +106,10 @@
.resident-card .resident-compact {
display: flex;
align-items: center;
gap: 6px;
padding: 0 12px;
min-height: max(40px, calc(var(--island-font) * 2.5));
font-size: var(--ci-body-font, 16px);
gap: calc(var(--ci-component-gap) / 2);
padding: 0 var(--ci-island-pad-x);
min-height: var(--ci-island-height);
font-size: var(--ci-fs-body);
}
.resident-window .resident-card.resident-separated {
background: transparent;
@@ -88,7 +122,7 @@
align-items: center;
}
.resident-separated .resident-compact .layout-row {
padding: 0 12px;
padding: 0 var(--ci-island-pad-x);
background: var(--resident-background);
border-radius: var(--resident-radius);
}
@@ -102,15 +136,23 @@
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;
min-height: max(40px, calc(var(--island-font) * 2.5));
height: var(--ci-island-height);
min-height: var(--ci-island-height);
}
.resident-card .resident-compact .component-node:not(.container) {
min-height: max(40px, calc(var(--island-font) * 2.5));
min-height: var(--ci-island-height);
display: flex;
align-items: center;
@@ -129,7 +171,7 @@
}
.resident-card .resident-compact .schedule {
flex-direction: row;
gap: 12px;
gap: var(--ci-component-gap);
}
.resident-card .resident-compact .schedule > div + div {
margin-top: 0;
@@ -142,14 +184,14 @@
color: inherit;
}
.resident-card .resident-bell.bell-empty {
color: #ffffff80;
color: var(--ci-text-3);
}
.resident-card .resident-bell span {
animation: resident-indicator-in var(--resident-fade-duration) cubic-bezier(0.25, 1, 0.5, 1);
}
.resident-card .resident-details {
min-width: 160px;
padding: 0 12px 12px;
padding: 0 var(--ci-island-pad-x) var(--ci-island-pad-x);
text-align: center;
}
.resident-card .resident-panel-heading {
@@ -157,12 +199,12 @@
align-items: center;
justify-content: space-between;
gap: 24px;
height: 40px;
height: var(--ci-island-height);
padding: 0 6px;
margin: 0;
border: 0;
color: #ffffff94;
font-size: 12px;
color: var(--ci-text-2);
font-size: var(--ci-fs-caption);
}
.resident-card .resident-panel-heading .icon-btn {
min-height: 28px;
@@ -176,24 +218,25 @@
display: block;
}
.resident-card .resident-expanded-rows {
font-size: var(--ci-body-font, 16px);
border-top: 1px solid #ffffff1a;
padding-top: 8px;
font-size: var(--ci-fs-body);
border-top: var(--ci-stroke-island-w) solid var(--ci-stroke-divider);
padding-top: calc(var(--ci-component-gap) / 2);
}
.resident-card .resident-expanded-rows .row-components {
gap: var(--row-gap, 12px);
gap: var(--row-gap, var(--ci-component-gap));
}
.resident-card #custom-alert-host {
width: 100%;
max-width: 100%;
}
.resident-card button:focus-visible {
outline: 2px solid #adc4ff;
outline: 2px solid var(--ci-stroke-drag);
outline-offset: -2px;
}
@media (hover: hover) and (pointer: fine) {
.resident-card button:hover {
filter: brightness(1.18);
background: var(--ci-accent-soft);
color: var(--ci-text-1);
}
}
@keyframes resident-indicator-in {
@@ -240,8 +283,14 @@
}
/* ClassIsland Fluent MainWindowLine:半透明底、1px 边框,强调遮罩只在提醒时播放。 */
.resident-window .resident-card {
--wn-bg: #20202080;
--wn-border: #ffffff26;
--wn-bg: var(--resident-background);
--wn-border: var(--ci-stroke-island);
--wn-text-1: var(--ci-text-1);
--wn-text-2: var(--ci-text-2);
--wn-text-3: var(--ci-text-3);
--wn-surface: var(--ci-fill-secondary);
--wn-surface-hover: var(--ci-accent-soft);
--wn-divider: var(--ci-stroke-divider);
}
.resident-window .resident-card > .tint {
display: none;
@@ -250,6 +299,9 @@
fill: transparent;
stroke: none;
}
.resident-window .resident-card.message-surface {
--wn-bg: #202020;
.resident-card.resident-lesson {
border-color: transparent;
}
.resident-window .resident-card.message-surface {
--resident-background: var(--ci-brand-dark);
}
@@ -6,11 +6,11 @@
flex: 0 0 auto;
width: 30px;
height: 30px;
border-radius: 50%;
color: #fff;
background: #0a84ff;
font-size: 12px;
font-weight: 600;
border-radius: var(--ci-radius-pill);
color: var(--ci-text-on-accent);
background: var(--ci-accent-fill);
font-size: var(--ci-fs-caption);
font-weight: var(--ci-fw-semi-bold);
font-variant-numeric: tabular-nums;
line-height: 1;
}
@@ -136,6 +136,14 @@ function normalizeIslandAppearance(input?: Partial<IslandAppearance>): IslandApp
'bottom-right',
];
const styles: IslandAppearance['style'][] = ['black', 'glass', 'tinted'];
const accentPalette = Array.isArray(input?.accentPalette)
? input.accentPalette
.filter((value): value is string => typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value))
.slice(0, 32)
: [...DEFAULT_ISLAND_APPEARANCE.accentPalette];
const accentSource = [0, 1, 2, 3].includes(input?.accentSource as number)
? (input?.accentSource as IslandAppearance['accentSource'])
: DEFAULT_ISLAND_APPEARANCE.accentSource;
return {
height: clamp(input?.height, 36, 72, DEFAULT_ISLAND_APPEARANCE.height),
width: clamp(input?.width, 220, 420, DEFAULT_ISLAND_APPEARANCE.width),
@@ -145,6 +153,11 @@ function normalizeIslandAppearance(input?: Partial<IslandAppearance>): IslandApp
typeof input?.accent === 'string' && /^#[0-9a-fA-F]{6}$/.test(input.accent)
? input.accent
: DEFAULT_ISLAND_APPEARANCE.accent,
accentSource,
accentPalette: accentPalette.length ? accentPalette : [...DEFAULT_ISLAND_APPEARANCE.accentPalette],
accentPaletteIndex: Math.round(
clamp(input?.accentPaletteIndex, 0, Math.max(0, accentPalette.length - 1), 0),
),
fontSize: clamp(input?.fontSize, 11, 20, DEFAULT_ISLAND_APPEARANCE.fontSize),
animations: input?.animations !== false,
speed: clamp(input?.speed, 0.5, 2, DEFAULT_ISLAND_APPEARANCE.speed),
@@ -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;
+1
View File
@@ -40,6 +40,7 @@ export function registerIpcHandlers(): void {
delete allowed.pendingUpdateVersion;
const saved = saveConfig(allowed);
if (allowed.islandLayout) island.syncCustomLayout();
if (allowed.theme !== undefined) island.syncTheme();
return saved;
},
);
+76 -61
View File
@@ -4,13 +4,13 @@ import type {
} from '@classhelper/shared';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { BrowserWindow, ipcMain, screen } from 'electron';
import { BrowserWindow, ipcMain, screen, systemPreferences } from 'electron';
import {
COURSEWARE_ISLAND_SIZE,
CLASSISLAND_TOKENS,
type CoursewareTransfer,
DEFAULT_ISLAND_APPEARANCE,
CLASSISLAND_ISLAND_METRICS,
normalizeIslandLayouts,
ISLAND_POSITIONS,
ISLAND_SHADOW_PAD,
ISLAND_SIZE_DELTA,
@@ -26,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';
/** 生产环境的灵动岛页面地址(导航白名单的精确比对用) */
@@ -174,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 &&
@@ -255,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 };
@@ -279,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;
@@ -288,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)),
@@ -314,9 +304,6 @@ class IslandController {
);
} else apply();
}
getEditingLayout(): boolean {
return this.editingLayout;
}
syncCustomLayout(): void {
this.refreshLessonReminder();
if (this.residentEnabled !== this.residentWasEnabled) {
@@ -336,6 +323,13 @@ class IslandController {
this.syncResidentShape(true);
this.syncWindow();
}
/** 主题独立于外观补丁,主窗口切肤时实时同步给岛渲染进程。 */
syncTheme(): void {
if (!this.win || this.win.isDestroyed()) return;
this.win.webContents.send('island:theme', getConfig().theme);
}
/** 仅用于首次切换布局、启动与退出编辑;日常常驻岛开合保持窗口可见。 */
private settleCustomLayout(): void {
if (this.layoutSettleTimer) clearTimeout(this.layoutSettleTimer);
@@ -347,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 ||
@@ -364,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;
@@ -383,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));
@@ -549,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;
@@ -568,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;
@@ -623,6 +608,7 @@ class IslandController {
}
// 首次进入时同步一次外观与状态,保证渲染进程不会停在初始默认值
this.emitAppearance();
this.syncTheme();
this.win?.webContents.send('island:schedules', this.schedules);
this.win?.webContents.send('island:time-points', this.timePoints);
this.emit();
@@ -774,7 +760,7 @@ class IslandController {
private refreshViewport(): void {
const area = this.targetDisplay().workArea;
const anchor = this.resolveAnchor();
const marginY = Math.round(this.appearance.marginY ?? ISLAND_MARGIN);
const marginY = this.verticalMargin();
const available =
anchor.vMode === 'bottom'
? anchor.vValue - (area.y + marginY)
@@ -1144,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 = {
@@ -1333,7 +1312,7 @@ class IslandController {
const display = this.targetDisplay();
const area = display.workArea;
const marginX = Math.round(this.appearance.marginX ?? ISLAND_MARGIN);
const marginY = Math.round(this.appearance.marginY ?? ISLAND_MARGIN);
const marginY = this.verticalMargin();
const center = Math.round(area.x + area.width / 2);
// 6 个停靠位置(顶/底 × 左/中/右),与 WinIsland 的 DockPosition 一一对应
@@ -1350,6 +1329,12 @@ class IslandController {
return { hMode, hValue, vMode, vValue };
}
/** 自定义岛遵循 ClassIsland Fluent 的 20px 竖直安全区;经典岛保留原有外观边距。 */
private verticalMargin(): number {
const configured = Math.round(this.appearance.marginY ?? ISLAND_MARGIN);
return this.customLayout ? Math.max(configured, CLASSISLAND_TOKENS.dpi.verticalSafeArea) : configured;
}
/** 当前应该把岛放在哪块屏上:跟随鼠标时用光标所在屏,否则用主屏 */
private targetDisplay(cursor?: { x: number; y: number } | null): Electron.Display {
return this.appearance.followCursorDisplay
@@ -1417,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();
@@ -1427,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();
@@ -1524,7 +1505,7 @@ class IslandController {
// 与 ClassIsland 一样,让背景/内容在固定画布内过渡。预留一帧绘制边界,避免过冲裁切。
return {
width: Math.min(960, area.width),
height: Math.min(640, Math.max(60, area.height - this.appearance.marginY)),
height: Math.min(640, Math.max(60, area.height - this.verticalMargin())),
};
}
if (this.customLayout)
@@ -1598,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 &&
@@ -1662,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();
@@ -1735,14 +1714,14 @@ class IslandController {
* 2. 材质的明暗跟随**应用主题**:本客户端是浅色 Fluent 主题,亚克力必然是浅色,
* 无法像 WinIsland 那样自带深色 tint(`Color::from_argb(150, 10, 10, 14)`)。
* 3. 更糟的是:只要调用过一次(**包括 `'none'`**),窗口就再也不是逐像素透明的了 ——
* Electron 会让它回落到默认不透明底色(`backgroundColor` 默认 `#FFF`),
* Electron 会让它回落到默认不透明白色底,
* 于是从 `glass` 切到 `black` / `tinted` 之后,卡片周围会永久留一圈**纯白**。
* 这正好对应"毛玻璃和主题色渐变会出现白底"的现象。
* 4. CSS `backdrop-filter: blur()` 也不能替代:透明窗口里 Chromium 采样不到窗口之后的桌面,
* 真机实测与不加模糊的像素完全一致(卡片区域离散度都是 12.7)。
*
* 结论:`glass` 风格改为**纯 CSS 半透明深色卡片**(取 WinIsland 拿不到 host backdrop 时的
* 官方降级色 `rgba(32,32,36,0.804)`,见 `docs/dev/winisland-design-tokens.md`),
* 官方 80.4% 深色降级底,见 `docs/dev/winisland-design-tokens.md`),
* 桌面透过率由卡片自身 alpha 决定,窗口始终保持 `transparent: true` 的逐像素透明。
* 回归用例:「个性设置:卡片外圈透出桌面(三种风格都没有白底面板)」。
*/
@@ -1802,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;
@@ -1864,7 +1843,6 @@ class IslandController {
const faded =
this.residentEnabled &&
settings.pointerFadeEnabled &&
!this.editingLayout &&
!this.lessonShowing &&
Date.now() >= this.residentTouchUntil &&
Date.now() >= this.residentMotionUntil &&
@@ -2173,7 +2151,40 @@ class IslandController {
}
getAppearance(): IslandAppearance {
return { ...this.appearance };
return { ...this.appearance, resolvedAccent: this.effectiveAccent() };
}
/** ClassIsland ColorSource 分支;1/3 取已选调色板,2 取系统强调色。 */
private effectiveAccent(): string {
const fallback = CLASSISLAND_TOKENS.colors.light.accentPaletteFallback;
const { accentSource, accent, accentPalette, accentPaletteIndex } = this.appearance;
if (accentSource === 0) return accent || fallback;
if (accentSource === 1 || accentSource === 3) {
return accentPalette[accentPaletteIndex] ?? fallback;
}
if (accentSource === 2) {
try {
let value: string | boolean | undefined;
try {
value = systemPreferences.getAccentColor?.();
} catch {
// Windows 旧系统可能只在窗口 API 暴露系统强调色。
}
if (typeof value !== 'string' && process.platform === 'win32') value = this.win?.getAccentColor();
if (typeof value === 'string') {
const hex = value.replace('#', '');
return `#${hex.length === 8 ? hex.slice(0, 6) : hex.slice(-6)}`;
}
} catch {
// 平台不提供系统强调色时走 ClassIsland 的 DodgerBlue 兜底。
}
}
return fallback;
}
/** 系统强调色变化时仅刷新“跟随系统”来源,不影响自定义色和其他来源。 */
syncSystemAccent(): void {
if (this.appearance.accentSource === 2) this.emitAppearance();
}
/** 把外观同步给灵动岛渲染进程(CSS 变量) */
@@ -2243,12 +2254,22 @@ const clamp = (value: number, min: number, max: number, fallback: number): numbe
/** 夹紧外观取值(越界值直接收敛,避免用户配置破坏布局) */
export function normalizeAppearance(input: IslandAppearance): IslandAppearance {
const fallbackOf = DEFAULT_ISLAND_APPEARANCE;
const accentPalette = Array.isArray(input.accentPalette)
? input.accentPalette
.filter((value) => typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value))
.slice(0, 32)
: [...fallbackOf.accentPalette];
return {
height: clamp(input.height, 36, 72, fallbackOf.height),
width: clamp(input.width, 220, 420, fallbackOf.width),
radius: clamp(input.radius, 8, 32, fallbackOf.radius),
opacity: clamp(input.opacity, 0.4, 1, fallbackOf.opacity),
accent: /^#[0-9a-fA-F]{6}$/.test(input.accent) ? input.accent : DEFAULT_ISLAND_APPEARANCE.accent,
accentSource: [0, 1, 2, 3].includes(input.accentSource) ? input.accentSource : fallbackOf.accentSource,
accentPalette: accentPalette.length ? accentPalette : [...fallbackOf.accentPalette],
accentPaletteIndex: Math.round(
clamp(input.accentPaletteIndex, 0, Math.max(0, accentPalette.length - 1), 0),
),
fontSize: clamp(input.fontSize, 11, 20, fallbackOf.fontSize),
animations: input.animations !== false,
speed: clamp(input.speed, 0.5, 2, fallbackOf.speed),
@@ -2336,6 +2357,8 @@ export const island = new IslandController();
/** 注册灵动岛相关 IPC(主窗口渲染进程 -> 主进程;灵动岛渲染进程 -> 主进程) */
export function registerIslandIpc(): void {
systemPreferences.on('accent-color-changed', () => island.syncSystemAccent());
ipcMain.handle('island:get-theme', () => getConfig().theme);
ipcMain.handle('island:get-schedules', (event) =>
event.sender === island.getWindow()?.webContents ? island.getSchedules() : [],
);
@@ -2343,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),
@@ -2360,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);
});
+81 -350
View File
@@ -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,43 +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 valid=Boolean(content&&content.textContent.includes('组件化提醒验收')&&card.querySelectorAll('.shape').length===1&&c.left>=r.left-1&&c.right<=r.right+1&&c.bottom<=r.bottom+1);
return {valid,card:r?.toJSON(),content:c?.toJSON(),shape:card?.querySelectorAll('.shape').length};
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 {
@@ -910,9 +893,12 @@ export async function verifyResidentSmoke(
const solid = await win.webContents.executeJavaScript(`(() => {
const card=document.querySelector('${layout === 'custom' ? '.resident-card' : '.island-card'}');
if (!card?.classList.contains('message-surface')) return false;
const probe=document.createElement('span');probe.style.background='var(--wn-bg)';card.append(probe);
const color=getComputedStyle(probe).backgroundColor;probe.remove();
return color==='rgb(32, 32, 32)'&&!!card.querySelector('.classic-notifications');
let color=getComputedStyle(card).backgroundColor;
if (${JSON.stringify(layout)} === 'fixed') {
const probe=document.createElement('span');probe.style.background='var(--wn-bg)';card.append(probe);
color=getComputedStyle(probe).backgroundColor;probe.remove();
}
return color!=='transparent'&&!color.includes('rgba')&&!!card.querySelector('.classic-notifications');
})()`);
if (!solid || Math.abs(win.getOpacity() - 1) > 0.01 || island.getAppearance().opacity !== 0.45)
return false;
@@ -933,12 +919,15 @@ export async function verifyResidentSmoke(
island.setClassState({ inClass: false, currentPeriodEnd: null, week: 1 });
saveConfig({ islandLayout: defaultIslandLayouts() });
island.syncCustomLayout();
await pause();
return (
!win.isVisible() &&
!getConfig().islandLayout.residentEnabled &&
(await win.webContents.executeJavaScript(`!document.querySelector('.custom-card')`))
await pause(400);
const visible = win.isVisible();
const residentEnabled = getConfig().islandLayout.residentEnabled;
const customDom = await win.webContents.executeJavaScript(
`Boolean(document.querySelector('.custom-card'))`,
);
if (visible || residentEnabled || customDom)
throw new Error(JSON.stringify({ visible, residentEnabled, customDom }));
return true;
});
island.setHitTestCursor(null);
island.setTouchMode(originalTouchMode);
+4 -4
View File
@@ -2659,7 +2659,7 @@ async function runIslandChecks(
h: style.getPropertyValue('--island-h').trim(),
w: style.getPropertyValue('--island-w').trim(),
font: style.getPropertyValue('--island-font').trim(),
accent: style.getPropertyValue('--island-accent').trim(),
accent: style.getPropertyValue('--ci-accent').trim(),
};
})()`,
)
@@ -2716,7 +2716,7 @@ async function runIslandChecks(
w: style.getPropertyValue('--island-w').trim(),
radius: style.getPropertyValue('--island-radius').trim(),
font: style.getPropertyValue('--island-font').trim(),
accent: style.getPropertyValue('--island-accent').trim(),
accent: style.getPropertyValue('--ci-accent').trim(),
cardHeight: card ? Math.round(card.getBoundingClientRect().height) : 0,
};
})()`,
@@ -3302,9 +3302,9 @@ async function runIslandChecks(
island.setAppearance({ ...appearanceBefore, accent: '#ff7043' });
await sleep(200);
const accentVar = await islandWindow?.webContents.executeJavaScript(
`getComputedStyle(document.documentElement).getPropertyValue('--island-accent').trim()`,
`getComputedStyle(document.documentElement).getPropertyValue('--ci-accent').trim()`,
);
record('个性设置:主题色生效(CSS 变量)', accentVar === '#ff7043', `CSS --island-accent=${accentVar}`);
record('个性设置:主题色生效(CSS 变量)', accentVar === '#ff7043', `CSS --ci-accent=${accentVar}`);
// 11.2b) 三种视觉风格的**底色**:黑 / 毛玻璃 / 主题色渐变都必须是深色卡片
// 并且卡片**外面那一圈**必须完全透明(用户反馈:毛玻璃与主题色渐变会出现白底 ——
-2
View File
@@ -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,写死账号等于随安装包把教师口令发出去。
@@ -12,14 +12,13 @@ import type { IslandAppearance, IslandState } from '@classhelper/shared';
* 只暴露「订阅状态/外观」与「发送用户操作」两件事,渲染进程不接触任何 Node 能力。
*/
export interface IslandBridge {
getTheme(): Promise<'light' | 'dark'>;
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;
@@ -62,18 +61,19 @@ export interface IslandBridge {
}
const bridge: IslandBridge = {
getTheme: () => ipcRenderer.invoke('island:get-theme'),
onTheme: (handler) => {
ipcRenderer.on('island:theme', (_event, theme: 'light' | 'dark') => handler(theme));
},
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),
-39
View File
@@ -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,16 +2,18 @@
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,
defaultIslandLayouts,
ISLAND_APPEARANCE_RANGES as RANGES,
ISLAND_ACCENT_SOURCES,
ISLAND_POSITION_LABELS,
ISLAND_POSITIONS,
ISLAND_STYLE_LABELS,
ISLAND_STYLES,
type IslandAppearance,
type IslandAccentColorSource,
type IslandPosition,
type IslandStyle,
} from '@classhelper/shared';
@@ -25,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,
@@ -74,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;
}
@@ -121,6 +99,13 @@ function applyIslandAppearance(patch: Partial<IslandAppearance> = {}): void {
window.desktop?.islandSetAppearance({ ...island.value });
}
function setAccentPaletteColor(value: string | null): void {
if (!value) return;
const palette = [...island.value.accentPalette];
palette[island.value.accentPaletteIndex] = value;
applyIslandAppearance({ accentPalette: palette });
}
async function saveIslandAppearance(): Promise<void> {
if (!window.desktop?.saveConfig) return;
savingIsland.value = true;
@@ -169,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>
@@ -281,13 +249,49 @@ onMounted(async () => {
@input="(value: number) => applyIslandAppearance({ speed: value })"
/>
</el-form-item>
<el-form-item label="主题色">
<el-form-item label="强调色来源">
<el-select
:model-value="island.accentSource"
style="width: 180px"
@change="(value: IslandAccentColorSource) => applyIslandAppearance({ accentSource: value })"
>
<el-option
v-for="item in ISLAND_ACCENT_SOURCES"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<span class="text-muted ml-8">自定义 / 壁纸 / 跟随系统 / 屏幕主题色,未知来源回落 DodgerBlue</span>
</el-form-item>
<el-form-item v-if="island.accentSource === 0" label="主题色">
<el-color-picker
:model-value="island.accent"
@change="(value: string | null) => applyIslandAppearance({ accent: value ?? '#0a84ff' })"
@change="
(value: string | null) =>
applyIslandAppearance({ accent: value ?? CLASSISLAND_TOKENS.colors.light.primaryColor })
"
/>
<span class="text-muted ml-8">用于高亮、按钮与进度条</span>
</el-form-item>
<el-form-item v-else-if="island.accentSource === 1 || island.accentSource === 3" label="调色板颜色">
<el-color-picker
:model-value="island.accentPalette[island.accentPaletteIndex]"
@change="setAccentPaletteColor"
/>
<el-input-number
:model-value="island.accentPaletteIndex"
:min="0"
:max="Math.max(0, island.accentPalette.length - 1)"
@change="
(value: number | undefined) => applyIslandAppearance({ accentPaletteIndex: Number(value ?? 0) })
"
/>
<span class="text-muted ml-8">按 SelectedPlatteIndex 取当前候选颜色</span>
</el-form-item>
<el-form-item v-else label="主题色">
<span class="text-muted">跟随操作系统强调色;不可用时回落 DodgerBlue</span>
</el-form-item>
<el-form-item label="视觉风格">
<span v-if="layoutMode === 'custom'">ClassIsland · 半透明横条</span>
<el-select
@@ -476,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;
@@ -498,9 +500,8 @@ onMounted(async () => {
.layout-choices {
grid-template-columns: 1fr;
}
.layout-edit-entry {
.layout-managed {
align-items: flex-start;
flex-direction: column;
}
}
</style>
-3
View File
@@ -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;
+4
View File
@@ -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?
+76
View File
@@ -813,6 +813,21 @@ try {
assert.equal(incompleteBody.code, 'AI_TASK_INCOMPLETE');
assert(!incompleteBody.message.includes('换一种说法'));
check('持续异常保持明确未完成状态和重试入口,不伪报执行成功');
const questionSamples = [
'请确认是否删除“周一课表”?确认后我会继续。',
{ message: '请确认是否删除“周一课表”?', queries: [], operations: [] },
{ questions: [{ question: '要删除哪张课表?', options: ['周一', '周五'] }], queries: [], operations: [] },
];
for (const sample of questionSamples) {
const before = modelBodies.length;
modelReplies.push(sample);
const reply = await api('/ai/interpret', teacher, 'POST', { text: '删除课表' });
assert.equal(modelBodies.length, before + 1, '自然语言追问不应进入格式校正循环');
assert.equal(reply.planId, null);
assert.equal(reply.steps.length, 0);
assert(reply.questions?.length);
}
check('普通中文确认、message追问和question别名均转为可交互问题,不触发校正或写入');
modelReplies.push({ questions: [{ id: 'subject', text: '请选择科目', options: ['数学', '语文'] }] });
const clarification = await api('/ai/interpret', teacher, 'POST', { text: '给这个班布置作业' });
assert.equal(clarification.planId, null);
@@ -870,6 +885,10 @@ try {
});
const reader = connection.body!.getReader();
assert((await reader.read()).value!.length > 0);
const runningConversation = (await prisma.aiTask.findUniqueOrThrow({ where: { id: background.id } }))
.conversationId!;
await api(`/ai/conversations/${runningConversation}`, teacher, 'DELETE', undefined, 409);
assert.equal(await prisma.aiTask.count({ where: { id: background.id } }), 1);
await reader.cancel();
releaseModel();
modelHold = undefined;
@@ -1184,6 +1203,63 @@ try {
assert.notEqual(tf.find((f) => f.path === path)!.id, af.find((f) => f.path === path)!.id);
}
check('三层目录自动补建父目录,同名目录按教师身份独立保存');
const deletable = await api('/ai/conversations', teacher, 'POST', {});
const deletingTask = await api('/ai/tasks', teacher, 'POST', {
conversationId: deletable.id,
text: '对话删除验收',
});
const pendingPlan = await interpret([
{
action: 'notifications.create',
params: { classId: A.id, title: '删除对话不发布', content: '只生成预览' },
},
]);
await prisma.aiTask.update({
where: { id: deletingTask.id },
data: {
state: 'ready',
result: (await import('../src/lib/secrets.js')).encryptSecret(JSON.stringify(pendingPlan)),
},
});
const auditCount = await prisma.aiAudit.count();
const actualNotificationCount = await prisma.notification.count();
await api(`/ai/conversations/${deletable.id}`, admin, 'DELETE', undefined, 403);
await api(`/ai/conversations/${deletable.id}`, teacher, 'DELETE');
assert.equal(await prisma.aiConversation.count({ where: { id: deletable.id } }), 0);
assert.equal(await prisma.aiTask.count({ where: { conversationId: deletable.id } }), 0);
assert.equal(await prisma.aiAudit.count(), auditCount);
assert.equal(await prisma.notification.count(), actualNotificationCount);
assert(
(await prisma.aiPlanStep.findMany({ where: { auditId: pendingPlan.planId! } })).every(
(s) => s.state === 'blocked',
),
);
await api('/ai/tasks', teacher, 'POST', { conversationId: deletable.id, text: '不能继续已删除对话' }, 403);
const attachmentChat = await api('/ai/conversations', teacher, 'POST', {});
const attachmentTask = await api('/ai/tasks', teacher, 'POST', {
conversationId: attachmentChat.id,
text: '暂存附件',
attachments: [attachment],
});
await api(`/ai/tasks/${attachmentTask.id}/files/${attachment.id}`, teacher, 'PUT', bytes, 200, {
'content-type': 'application/octet-stream',
});
const stagedPath = path.join(
process.env.COURSEWARE_DIR!,
'.ai-tasks',
createHash('sha256').update(attachmentTask.id).digest('hex'),
createHash('sha256').update(attachment.id).digest('hex'),
);
assert(fs.existsSync(stagedPath));
await api(`/ai/conversations/${attachmentChat.id}`, teacher, 'DELETE');
assert(!fs.existsSync(stagedPath));
const executedConversation = (await prisma.aiTask.findUniqueOrThrow({ where: { id: staged.id } }))
.conversationId!;
const homeworkCount = await prisma.homework.count();
await api(`/ai/conversations/${executedConversation}`, teacher, 'DELETE');
assert.equal(await prisma.homework.count(), homeworkCount);
check('删除对话仅限本人,轮次清除、待确认计划失效且业务数据与审计保留');
console.log(`AI 隔离验收通过:${checks} 项`);
} finally {
globalThis.fetch = realFetch;
+28
View File
@@ -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 无权访问的班级,用于验证教师间权限隔离。
// 注意:演示库里可能被人工改过(管理员自己建班、给别的班加协作教师),
// 因此这里**不允许依赖种子数据的班级布局**:没有现成的就现建一个临时班级,收尾删除。
@@ -27,6 +27,14 @@ import { setTimeout as delay } from 'node:timers/promises';
const router = Router();
router.use(authenticate());
router.delete(
'/conversations/:id',
requirePermission('ai:use'),
validate({ params: planIdSchema }),
async (req, res) => {
sendOk(res, await tasks.deleteConversation(getAuthUser(req), String(req.params.id)));
},
);
router.post('/conversations', requirePermission('ai:use'), async (req, res) => {
sendOk(res, await tasks.createConversation(getAuthUser(req)));
});
+6 -32
View File
@@ -1,4 +1,4 @@
import { z } from 'zod';
import { modelReplySchema as replySchema, normalizeModelReply, type ModelReply } from './model-reply.js';
import {
dayKeyLocal,
type AiInterpretResult,
@@ -17,30 +17,6 @@ import { planWithModel, sanitizePrompt, type AgentRun } from './model-planner.js
import { getAiSettings } from './ai.service.js';
import type { AiInterpretInput } from './ai.schemas.js';
const operationSchema = z
.object({
action: z.string().min(1).max(80),
target: z.record(z.string(), z.string().max(100)).optional(),
params: z.record(z.string(), z.unknown()).optional(),
query: z.record(z.string(), z.unknown()).optional(),
attachmentId: z.string().max(100).optional(),
})
.strict();
const replySchema = z.object({
questions: z
.array(
z.object({
id: z.string().min(1).max(100),
text: z.string().min(1).max(1000),
options: z.array(z.string().max(200)).max(10).optional(),
}),
)
.max(3)
.optional(),
message: z.string().max(4000).optional(),
queries: z.array(operationSchema).max(8).default([]),
operations: z.array(operationSchema).max(16).default([]),
});
const aliases: Record<string, string> = {
create_homework: 'homeworks.create',
create_notification: 'notifications.create',
@@ -48,10 +24,7 @@ const aliases: Record<string, string> = {
};
/** 本地确定性解析只用于 mock 和原有模型之外的文件、查询入口,不新增任何模型出站数据。 */
function localReply(
input: AiInterpretInput,
classes: { id: string; name: string }[],
): z.infer<typeof replySchema> | null {
function localReply(input: AiInterpretInput, classes: { id: string; name: string }[]): ModelReply | null {
const classId =
input.classId ||
classes.find((item) => input.text.includes(item.name))?.id ||
@@ -139,10 +112,10 @@ export async function interpretConversation(
const classes = tools.some((item) => item.action === 'classes.list')
? ((await runRead(user, { action: 'classes.list' })) as { id: string; name: string }[])
: [];
let reply: z.infer<typeof replySchema> | null = null;
let reply: ModelReply | null = null;
if (settings.provider === 'mock') {
try {
reply = replySchema.parse(JSON.parse(input.text));
reply = normalizeModelReply(JSON.parse(input.text));
} catch {
/* 自然语言示例继续走本地解析。 */
}
@@ -186,6 +159,7 @@ export async function interpretConversation(
});
else reply = replySchema.parse({ message: '离线示例未识别此任务,请配置模型或补充具体操作。' });
}
reply = normalizeModelReply(reply);
if (reply.questions?.length)
return {
planId: null,
@@ -252,7 +226,7 @@ export async function interpretConversation(
{ role: 'assistant' as const, content: JSON.stringify(reply).slice(0, 8000) },
{
role: 'user' as const,
content: `预览校验未通过:${sanitizePrompt(error.message)}。请查询真实数据后修正参数,不能省略用户要求。信息不足时提出具体问题。`,
content: `预览校验未通过:${sanitizePrompt(error.message)}。请查询真实数据后修正参数,不能省略用户要求。信息不足时通过 questions:[{id,text,options?}] 提出具体问题,并清空 operations 和 queries。`,
},
].slice(-20),
},
@@ -1,4 +1,4 @@
import { z } from 'zod';
import { parseModelReply, type ModelReply } from './model-reply.js';
import { setTimeout as delay } from 'node:timers/promises';
import {
dayKeyLocal,
@@ -18,50 +18,7 @@ import { redact } from './business-read.js';
import type { AiInterpretInput } from './ai.schemas.js';
import { modelEndpoint, readCompletion } from './model-transport.js';
const operationSchema = z
.object({
action: z.string().min(1).max(80),
target: z.record(z.string(), z.string().max(100)).optional(),
params: z.record(z.string(), z.unknown()).optional(),
query: z.record(z.string(), z.unknown()).optional(),
attachmentId: z.string().max(100).optional(),
})
.strict();
const replySchema = z
.object({
questions: z
.array(
z.object({
id: z.string().min(1).max(100),
text: z.string().min(1).max(1000),
options: z.array(z.string().max(200)).max(10).optional(),
}),
)
.max(3)
.optional(),
message: z.string().max(4000).optional(),
queries: z.array(operationSchema).max(8).default([]),
operations: z.array(operationSchema).max(16).default([]),
})
.refine(
(value) =>
!!value.message?.trim() ||
!!value.questions?.length ||
value.queries.length > 0 ||
value.operations.length > 0,
'回复不能是空对象',
);
export function parseModelReply(content: string) {
const trimmed = content
.trim()
.replace(/^```(?:json)?\s*/i, '')
.replace(/\s*```$/, '');
// 只修正展示包装,不猜测 ID、不补写业务参数,不执行任意文本。
const start = trimmed.indexOf('{'),
end = trimmed.lastIndexOf('}');
return replySchema.parse(JSON.parse(start >= 0 && end >= start ? trimmed.slice(start, end + 1) : trimmed));
}
export { parseModelReply } from './model-reply.js';
function visibleMessage(content: string): string | undefined {
const match = content.match(/"message"\s*:\s*"((?:[^"\\]|\\.)*)/);
@@ -107,9 +64,11 @@ export async function planWithModel(
{
role: 'system',
content: [
'你是 ClassHelper 助手。只输出严格 JSON:{message,queries:[{action,target?,query?}],operations:[{action,target?,params?,attachmentId?}]}。',
'你是 ClassHelper 助手。只输出严格 JSON:{message,questions?:[{id,text,options?}],queries:[{action,target?,query?}],operations:[{action,target?,params?,attachmentId?}]}。',
'例如普通回复:{"message":"你好,需要处理什么?","queries":[],"operations":[]};查询:{"message":"正在查询班级","queries":[{"action":"classes.list"}],"operations":[]}。禁止 Markdown 围栏,message 只写简短进度或给用户的回复。',
'缺少用户才能提供的必要信息时,返回 questions:[{id,text,options?}],operations 和 queries 必须为空,等待用户回答。',
'提问示例:{"message":"请选择要删除的课表","questions":[{"id":"plan","text":"要删除哪张课表?","options":["周一","周五"]}],"queries":[],"operations":[]}。',
'删除等危险操作的最终确认由客户端操作预览和确认窗口完成,不需要反复在聊天里索取口头确认。目标明确且已查询真实 id 时直接返回待确认 operations,例如 plans.delete 的 target:{id:真实课表id};目标不明时才通过 questions 追问,不得声称已经删除。',
'queries 只能查询,operations 是待确认写操作,不能声称已执行。先查询真实 id 和现状,再规划修改;不猜测班级、账号、学生、课程和时间点 id。信息不足时追问。',
'仅可选择工具目录中的 action。工具 schema.target 列出路径参数,schema.params 是 params 的 JSON Schema。查询条件放 query。所有数据和动作遵循操作者的实时权限。',
'数据库备份/恢复/清空/切换/SQL、服务器配置/启停/升级和密钥维护禁止执行。密码字段留空,由用户在专门表单输入。',
@@ -178,7 +137,7 @@ export async function planWithModel(
'AI_PROVIDER_ERROR',
`模型服务暂不可用(HTTP ${response.status}),请检查服务地址、模型与密钥。任务尚未执行。`,
);
let reply: z.infer<typeof replySchema>;
let reply: ModelReply;
try {
let published = '';
let lastReasoningUpdate = 0;
@@ -212,7 +171,7 @@ export async function planWithModel(
messages.push({
role: 'user',
content:
'上一轮输出未通过校验或被截断。请重新输出完整 JSON 对象,包含 message 字符串、queries 数组和 operations 数组;不使用 Markdown,不添加解释。不确定的业务参数请在 message 中追问,不猜测。',
'上一轮输出未通过校验或被截断。请重新输出完整 JSON 对象,包含 message 字符串、queries 数组和 operations 数组;不使用 Markdown,不添加解释。缺少用户信息时返回 questions:[{id,text,options?}],并令 queries 和 operations 为空;不要在 message 中反复询问确认,不猜测业务参数。',
});
continue;
}
@@ -0,0 +1,107 @@
import { z } from 'zod';
const operationSchema = z
.object({
action: z.string().min(1).max(80),
target: z.record(z.string(), z.string().max(100)).optional(),
params: z.record(z.string(), z.unknown()).optional(),
query: z.record(z.string(), z.unknown()).optional(),
attachmentId: z.string().max(100).optional(),
})
.strict();
export const modelReplySchema = z
.object({
message: z.string().max(4000).optional(),
questions: z
.array(
z.object({
id: z.string().min(1).max(100),
text: z.string().min(1).max(1000),
options: z.array(z.string().min(1).max(200)).max(10).optional(),
}),
)
.max(3)
.optional(),
queries: z.array(operationSchema).max(8).default([]),
operations: z.array(operationSchema).max(16).default([]),
})
.refine(
(v) => !!v.message?.trim() || !!v.questions?.length || v.queries.length > 0 || v.operations.length > 0,
'回复不能是空对象',
);
export type ModelReply = z.infer<typeof modelReplySchema>;
function isQuestion(text: string) {
return /[??]|是否|能否|可否|请(?:问|确认|选择|提供|补充|说明|指定)|which\b|would you\b|could you\b/i.test(
text,
);
}
function questionFromText(text: string) {
return {
id: 'question-1',
text: text.slice(0, 1000),
...(/请确认|是否确认|确定(?:要|删除)|are you sure/i.test(text)
? { options: ['继续生成操作预览', '取消本次请求'] }
: {}),
};
}
/** 仅兼容展示与追问字段,不从自然语言推断任何业务动作、对象 id 或执行许可。 */
export function normalizeModelReply(value: unknown): ModelReply {
if (typeof value === 'string') {
const text = value.trim();
if (!text || !isQuestion(text)) throw new Error('模型回复不是有效的操作协议或追问');
return modelReplySchema.parse({
message: text,
questions: [questionFromText(text)],
});
}
if (!value || typeof value !== 'object' || Array.isArray(value)) return modelReplySchema.parse(value);
const raw = value as Record<string, unknown>;
const requested = raw.questions ?? (raw.question === undefined ? undefined : [raw.question]);
let questions: unknown = requested;
if (requested !== undefined) {
const list = Array.isArray(requested) ? requested : [requested];
questions = list.map((item, index) => {
if (typeof item === 'string') return { id: `question-${index + 1}`, text: item.trim() };
if (!item || typeof item !== 'object' || Array.isArray(item)) return item;
const question = item as Record<string, unknown>;
return {
id: question.id || `question-${index + 1}`,
text: question.text ?? question.question,
options: Array.isArray(question.options)
? question.options.map((option) =>
typeof option === 'object' && option !== null && !Array.isArray(option)
? (option as Record<string, unknown>).label
: option,
)
: question.options,
};
});
}
// 文字追问只能在没有业务动作/查询时转成问题;已有删除预览保留原有确认链。
if (
(questions === undefined || (Array.isArray(questions) && questions.length === 0)) &&
typeof raw.message === 'string' &&
isQuestion(raw.message) &&
(raw.operations === undefined || (Array.isArray(raw.operations) && raw.operations.length === 0)) &&
(raw.queries === undefined || (Array.isArray(raw.queries) && raw.queries.length === 0))
) {
questions = [questionFromText(raw.message.trim())];
}
if (Array.isArray(questions) && questions.length) {
return modelReplySchema.parse({ ...raw, questions, queries: [], operations: [] });
}
return modelReplySchema.parse({ ...raw, questions });
}
export function parseModelReply(content: string): ModelReply {
const trimmed = content
.trim()
.replace(/^```(?:json)?\s*/i, '')
.replace(/\s*```$/, '');
const start = trimmed.indexOf('{'),
end = trimmed.lastIndexOf('}');
if (start >= 0 && end >= start) return normalizeModelReply(JSON.parse(trimmed.slice(start, end + 1)));
// 不把截断的 JSON 或损坏的动作协议当普通提问吞掉。
if (/^[{[\"]|^```/.test(trimmed)) return normalizeModelReply(JSON.parse(trimmed));
return normalizeModelReply(trimmed);
}
+60 -11
View File
@@ -8,6 +8,7 @@ import type { Request } from 'express';
import type { AiAgentEvent, AiConversationResult, AiTaskDto } from '@classhelper/shared';
import { prisma } from '../../lib/db.js';
import { ApiError } from '../../lib/http.js';
import { logger } from '../../lib/logger.js';
import { assertPermission, loadAuthPrincipal } from '../../lib/authz/index.js';
import { loadSessionUser } from '../../lib/authz/session.js';
import { encryptSecret, decryptSecret } from '../../lib/secrets.js';
@@ -141,13 +142,27 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
messages: context.map((item) => ({ ...item, content: sanitizePrompt(item.content).slice(0, 8000) })),
};
Object.assign(safe, { accessStamp: await accessStamp(user) });
const row = await prisma.aiTask.create({
data: {
userId: user.sub,
conversationId: conversation.id,
turnNumber: (previous.at(-1)?.turnNumber ?? 0) + 1,
input: encryptSecret(JSON.stringify(safe)),
},
const row = await prisma.$transaction(async (tx) => {
// 与删除对话共用同一行锁,避免新轮次写入已删除的对话。
const locked = await tx.aiConversation.updateMany({
where: { id: conversation.id, userId: user.sub },
data: { updatedAt: new Date(), title: conversation.title || sanitizePrompt(input.text).slice(0, 80) },
});
if (!locked.count) throw ApiError.forbidden('此对话已删除或无法访问');
const latest = await tx.aiTask.findFirst({
where: { conversationId: conversation.id, userId: user.sub },
orderBy: { turnNumber: 'desc' },
});
if ((latest?.turnNumber ?? 0) !== (previous.at(-1)?.turnNumber ?? 0))
throw ApiError.conflict('对话已有新轮次,请重新发送');
return tx.aiTask.create({
data: {
userId: user.sub,
conversationId: conversation.id,
turnNumber: (latest?.turnNumber ?? 0) + 1,
input: encryptSecret(JSON.stringify(safe)),
},
});
});
if (last && inherited?.length) {
for (const attachment of inherited) {
@@ -158,10 +173,6 @@ export async function createTask(user: TokenPayload, input: AiInterpretInput) {
await fsp.copyFile(source, target);
}
}
await prisma.aiConversation.update({
where: { id: conversation.id },
data: { title: conversation.title || sanitizePrompt(input.text).slice(0, 80), updatedAt: new Date() },
});
return { id: row.id, conversationId: conversation.id };
}
export async function stageAttachment(
@@ -505,3 +516,41 @@ export async function conversationTurns(user: TokenPayload, id: string, before?:
});
return Promise.all(rows.reverse().map((row) => task(user, row.id)));
}
/** 删除自己的对话,不回滚已执行业务,也不删除业务审计。 */
export async function deleteConversation(user: TokenPayload, id: string) {
await ownedConversation(user, id);
const rows = await prisma.$transaction(async (tx) => {
const locked = await tx.aiConversation.updateMany({
where: { id, userId: user.sub },
data: { updatedAt: new Date() },
});
if (!locked.count) throw ApiError.forbidden('无法访问此对话');
const tasks = await tx.aiTask.findMany({ where: { conversationId: id, userId: user.sub } });
if (tasks.some((t) => active.has(t.id) || ['planning', 'executing'].includes(t.state)))
throw ApiError.conflict('对话仍有后台任务,请先停止或等待完成后再删除');
const planIds = tasks.flatMap((t) =>
t.result ? [decode<AiConversationResult>(t.result).planId].filter((p): p is string => Boolean(p)) : [],
);
if (
await tx.aiPlanStep.count({ where: { auditId: { in: planIds }, userId: user.sub, state: 'running' } })
)
throw ApiError.conflict('业务操作正在执行,请等待完成后再删除');
await tx.aiPlanStep.updateMany({
where: {
auditId: { in: planIds },
userId: user.sub,
state: { in: ['draft', 'prepared', 'confirmed', 'failed'] },
},
data: { state: 'blocked', result: JSON.stringify({ message: '对话已删除,未完成计划已取消' }) },
});
await tx.aiTask.deleteMany({ where: { conversationId: id, userId: user.sub } });
await tx.aiConversation.delete({ where: { id } });
return tasks;
});
for (const row of rows)
await cleanup(row.id, decode<AiInterpretInput>(row.input)).catch(() =>
logger.warn('AI 对话已删除,暂存附件清理未完成'),
);
return { id };
}
@@ -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;
}
}
/**
* 学年升级(按升级权限与班级范围):把若干班级的年级改掉,**不归档、数据沿用**。
*
+232 -2
View File
@@ -261,14 +261,236 @@ export const WEEK_PARITY_VALUES: readonly ('ALL' | 'ODD' | 'EVEN')[] = ['ALL', '
/** 一个学期按多少周为一个单双周循环(ClassIsland WeekCountDivTotal 的默认值) */
export const WEEK_PARITY_CYCLE = 2;
/**
* ClassIsland 岛层设计 token 的 TypeScript 单一来源。
*
* CSS 变量在 `packages/ui/src/tokens.css` 中按 `--ci-*` 一一映射;窗口几何、
* 主进程安全区与设置页范围直接复用本对象,避免 TypeScript 与 CSS 各写一套。
* 应用外壳仍使用 `--ch-*` / `--ch-ui-*`,本对象只服务于岛与课程信息层。
*/
export const CLASSISLAND_TOKENS = {
colors: {
light: {
primaryColor: '#00BFFF',
secondaryColor: '#7FFFD4',
accentFallback: '#1E90FF',
accentPaletteFallback: '#1E90FF',
/** ClassIsland 原值 #E4000000(AARRGGBB),CSS 写作 RRGGBBAA。 */
text1: '#000000E4',
/** ClassIsland 浅色主题对 InformativeSecondary 的覆盖值。 */
text2: '#000000C0',
text3: '#00000072',
text4: '#0000005C',
text5: '#0000002E',
textOnAccent: '#FFFFFFFF',
bgBase: '#F3F3F3',
bgSecondary: '#EEEEEE',
bgTertiary: '#F9F9F9',
fillSecondary: '#0000000A',
smoke: '#00000066',
islandBgCustom: '#000000',
strokeIsland: '#00000014',
strokeControl: '#00000024',
strokeDivider: '#00000014',
strokeFlyout: '#0000001B',
fillStrong: '#00000072',
strokeCard: '#00000016',
strokeDrag: '#1E90FF',
strokeTutorial: '#1E90FF',
aqi1: '#228B22',
aqi2: '#CCCC00',
aqi3: '#FF8C00',
aqi4: '#CD5C5C',
aqi5: '#8B0000',
aqi6: '#800080',
weatherRain: '#0000FF',
glowClass: '#FFFF00',
danger: '#CD5C5C',
warningCritical: '#C42B1C',
warningCaution: '#9D5D00',
warningCautionBackground: '#FFF4CE',
},
dark: {
primaryColor: '#00BFFF',
secondaryColor: '#7FFFD4',
accentFallback: '#1E90FF',
accentPaletteFallback: '#1E90FF',
text1: '#FFFFFFFF',
/** ClassIsland 深色主题对 InformativeSecondary 的覆盖值。 */
text2: '#FFFFFFDA',
text3: '#FFFFFFC5',
text4: '#FFFFFF87',
text5: '#FFFFFF5D',
textOnAccent: '#FFFFFFFF',
bgBase: '#202020',
bgSecondary: '#1C1C1C',
bgTertiary: '#282828',
fillSecondary: '#FFFFFF14',
smoke: '#00000066',
islandBgCustom: '#000000',
strokeIsland: '#FFFFFF26',
strokeControl: '#FFFFFF3D',
strokeDivider: '#FFFFFF26',
strokeFlyout: '#FFFFFF33',
fillStrong: '#FFFFFF8A',
strokeCard: '#FFFFFF26',
strokeDrag: '#00BFFF',
strokeTutorial: '#00BFFF',
aqi1: '#3CB371',
aqi2: '#FFFF00',
aqi3: '#FFA500',
aqi4: '#CD5C5C',
aqi5: '#8B0000',
aqi6: '#9370DB',
weatherRain: '#00BFFF',
glowClass: '#FFFF00',
danger: '#CD5C5C',
warningCritical: '#FF99A4',
warningCaution: '#FCE100',
warningCautionBackground: '#433519',
},
},
fonts: {
app: "'HarmonyOS Sans SC', 'Microsoft YaHei UI', 'Noto Sans CJK SC', 'Noto Sans SC', 'PingFang SC', 'Source Han Sans SC', SimHei, 'WenQuanYi Micro Hei', sans-serif",
island:
"'HarmonyOS Sans SC', 'Microsoft YaHei UI', 'Noto Sans CJK SC', 'Noto Sans SC', 'PingFang SC', 'Source Han Sans SC', SimHei, 'WenQuanYi Micro Hei', sans-serif",
harmonyOsSans: "'HarmonyOS Sans SC', 'Microsoft YaHei UI', SimHei",
backend: "'Microsoft YaHei UI'",
iconFluent: "'FluentSystemIcons-Resizable'",
iconLucide: "'lucide'",
iconSf: "'SF-Symbols'",
},
fontWeights: {
thin: 100,
extraLight: 200,
light: 300,
normal: 400,
medium: 500,
semiBold: 600,
bold: 700,
extraBold: 800,
black: 900,
},
fontSizes: {
secondary: 14,
body: 16,
emphasized: 18,
large: 20,
version: 9,
caption: 12,
controlBase: 13,
label: 14,
title: 16,
rolling: 17,
oobeBody: 18,
brand: 20,
weather: 22,
oobeTitle: 32,
inputMin: 1,
inputMax: 40,
inputStep: 0.5,
},
radii: {
island: 8,
islandLocal: 0,
islandMax: 20,
islandStep: 0.5,
popup: 6,
card: 4,
control: 4,
drawer: '8px 8px 0 0',
pill: 999,
iconButton: 14,
oobeButton: 24,
},
spacing: {
islandHeight: 40,
islandPadX: 12,
islandMinWidth: 20,
componentGap: 12,
lineGap: 5,
settingsMaxWidth: 960,
popupPad: 12,
progressHeight: 3,
editbarBottom: 64,
splashWidth: 400,
splashHeight: 100,
},
shadows: {
island: '0 4px 8px 2px #00000048',
mask: '0 8px 32px 0 #00000066',
drawer: '0 8px 32px 0 #00000066',
drawerX: '0 0 8px #00000033',
classicMask: '0 0 8px #000000',
adorn: '0 0 8px #00000066',
},
opacity: {
islandBackground: 0.5,
line: 1,
pointerFaded: 0.05,
maskFrom: 0,
maskTo: 1,
},
layers: {
windowBottom: 0,
windowTop: 1,
content: 0,
mask: 1,
drag: 1,
drawer: 10,
timelineAdorn: 9999,
guide: 10000,
/** 原值 33550336;Web 层用浏览器最大安全整数哨兵表达同一语义。 */
sentinel: 2147483647,
},
dpi: {
/** ClassIsland 的所有视觉值都以 96 DPI 的 CSS px 为基准。 */
basis: 96,
scale: 1,
scaleMin: 0.75,
scaleMax: 2.5,
scaleStep: 0.05,
verticalSafeArea: 20,
tutorialSafeArea: 150,
effectScale: 1,
},
misc: {
rippleStroke: 200,
maskFade: 'linear-gradient(to bottom, #FFFFFF00, #FFFFFF00 65%, #FFFFFFFF)',
scrimTutorial: '#00000099',
debugBackground: '#22222277',
splashBackground: '#11111188',
brandGradientA: '#0C0E1F',
brandGradientB: '#0D1111',
brandDark: '#0D1111',
},
} as const;
/** ClassIsland `IntToFontWeightConverter` 的逐值映射;其他值回落 Normal。 */
export function classislandFontWeight(value: unknown): number {
if (
typeof value === 'number' &&
value >= CLASSISLAND_TOKENS.fontWeights.thin &&
value <= CLASSISLAND_TOKENS.fontWeights.black &&
value % 100 === 0
) {
return value;
}
return CLASSISLAND_TOKENS.fontWeights.normal;
}
/** 灵动岛默认外观(设置页个性化项的初始值,也是区间校验的单一来源) */
export const DEFAULT_ISLAND_APPEARANCE = {
height: 44,
width: 268,
radius: 20,
opacity: 1,
/** 默认强调色采用 Apple 系统蓝(与 WinIsland 的系统色体系一致) */
accent: '#0a84ff',
/** 默认强调色与 ClassIsland 的 PrimaryColor 对齐。 */
accent: CLASSISLAND_TOKENS.colors.light.primaryColor,
/** 0=自定义,1=壁纸主题色,2=跟随系统,3=屏幕主题色;未知值回落兜底色。 */
accentSource: 0,
accentPalette: [CLASSISLAND_TOKENS.colors.light.primaryColor] as string[],
accentPaletteIndex: 0,
fontSize: 13,
animations: true,
speed: 1,
@@ -320,6 +542,14 @@ export const ISLAND_POSITION_LABELS: Record<(typeof ISLAND_POSITIONS)[number], s
'bottom-right': '右下角',
};
/** ClassIsland `ColorSource` 的显示顺序与中文说明。 */
export const ISLAND_ACCENT_SOURCES = [
{ value: 0, label: '自定义颜色' },
{ value: 1, label: '壁纸主题色' },
{ value: 2, label: '跟随系统' },
{ value: 3, label: '屏幕主题色' },
] as const;
/** 视觉风格可选值(参考 WinIsland 的 island_style) */
export const ISLAND_STYLES = ['black', 'glass', 'tinted'] as const;
+170 -42
View File
@@ -1,4 +1,5 @@
import { isDayKey } from './utils.js';
import { CLASSISLAND_TOKENS, classislandFontWeight } from './constants.js';
export const ISLAND_COMPONENTS = [
'date',
@@ -18,21 +19,21 @@ export const ISLAND_COMPONENTS = [
] as const;
/** ClassIsland master:MainWindowLine 与 Models/Settings.cs(2026-10-17 核对)。 */
export const CLASSISLAND_ISLAND_METRICS = {
rowHeight: 40,
horizontalPadding: 12,
radius: 8,
opacity: 0.5,
scale: 1,
scaleMin: 0.75,
scaleMax: 2.5,
radiusMax: 20,
rowHeight: CLASSISLAND_TOKENS.spacing.islandHeight,
horizontalPadding: CLASSISLAND_TOKENS.spacing.islandPadX,
radius: CLASSISLAND_TOKENS.radii.island,
opacity: CLASSISLAND_TOKENS.opacity.islandBackground,
scale: CLASSISLAND_TOKENS.dpi.scale,
scaleMin: CLASSISLAND_TOKENS.dpi.scaleMin,
scaleMax: CLASSISLAND_TOKENS.dpi.scaleMax,
radiusMax: CLASSISLAND_TOKENS.radii.islandMax,
rowSpacingMax: 150,
secondaryFontSize: 14,
bodyFontSize: 16,
emphasizedFontSize: 18,
largeFontSize: 20,
rowSpacing: 5,
fadedOpacity: 0.05,
secondaryFontSize: CLASSISLAND_TOKENS.fontSizes.secondary,
bodyFontSize: CLASSISLAND_TOKENS.fontSizes.body,
emphasizedFontSize: CLASSISLAND_TOKENS.fontSizes.emphasized,
largeFontSize: CLASSISLAND_TOKENS.fontSizes.large,
rowSpacing: CLASSISLAND_TOKENS.spacing.lineGap,
fadedOpacity: CLASSISLAND_TOKENS.opacity.pointerFaded,
} as const;
export type IslandComponentKind = (typeof ISLAND_COMPONENTS)[number];
export interface IslandWeather {
@@ -74,6 +75,13 @@ export interface ComponentAppearance {
cornerRadius: number;
opacity: number;
}
/** 四档核心字号;组件与行级覆盖共用同一字段名。 */
export interface IslandFontSizes {
secondaryFontSize: number;
bodyFontSize: number;
emphasizedFontSize: number;
largeFontSize: number;
}
export interface IslandComponentNode {
id: string;
kind: IslandComponentKind;
@@ -112,6 +120,14 @@ export interface IslandLayoutRow {
main: boolean;
allowNotifications: boolean;
gap: number;
/** 整行透明度,默认 1;不再与背景 alpha 相乘。 */
opacity: number;
/** 是否把四档字号写到这一行根元素,只影响本行。 */
fontOverridesEnabled: boolean;
secondaryFontSize: number;
bodyFontSize: number;
emphasizedFontSize: number;
largeFontSize: number;
nodes: IslandComponentNode[];
}
export interface IslandLayoutScheme {
@@ -123,8 +139,17 @@ export interface IslandLayoutScheme {
scale: number;
color: string;
foreground: string;
/** false 时回落当前亮/暗主题背景。 */
customBackgroundEnabled: boolean;
/** false 时回落当前亮/暗主题的 5 级前景色。 */
customForegroundEnabled: boolean;
opacity: number;
radius: number;
fontWeight: number;
secondaryFontSize: number;
bodyFontSize: number;
emphasizedFontSize: number;
largeFontSize: number;
separated: boolean;
spacing: number;
}
@@ -166,10 +191,21 @@ function defaultExpandedRows(): IslandLayoutRow[] {
main: true,
allowNotifications: false,
gap: 12,
opacity: CLASSISLAND_TOKENS.opacity.line,
fontOverridesEnabled: false,
...defaultCoreFontSizes(),
nodes: [islandNode('date', 'expanded-date'), course],
},
];
}
function defaultCoreFontSizes(): IslandFontSizes {
return {
secondaryFontSize: CLASSISLAND_TOKENS.fontSizes.secondary,
bodyFontSize: CLASSISLAND_TOKENS.fontSizes.body,
emphasizedFontSize: CLASSISLAND_TOKENS.fontSizes.emphasized,
largeFontSize: CLASSISLAND_TOKENS.fontSizes.large,
};
}
export function islandNode(kind: IslandComponentKind, id: string): IslandComponentNode {
return {
id,
@@ -197,19 +233,16 @@ export function islandNode(kind: IslandComponentKind, id: string): IslandCompone
},
appearance: {
resourceOverridingEnabled: false,
secondaryFontSize: 14,
bodyFontSize: 16,
emphasizedFontSize: 18,
largeFontSize: 20,
...defaultCoreFontSizes(),
customForegroundEnabled: false,
foreground: '#ffffff',
foreground: CLASSISLAND_TOKENS.colors.light.textOnAccent,
customBackgroundEnabled: false,
background: '#202024',
background: CLASSISLAND_TOKENS.colors.light.islandBgCustom,
customBackgroundOpacityEnabled: false,
backgroundOpacity: 0.5,
backgroundOpacity: CLASSISLAND_TOKENS.opacity.islandBackground,
customCornerRadiusEnabled: false,
cornerRadius: 16,
opacity: 1,
cornerRadius: CLASSISLAND_TOKENS.radii.island,
opacity: CLASSISLAND_TOKENS.opacity.line,
},
advanced: { hideRules: [], align: 'stretch', width: 0, maxWidth: 0 },
};
@@ -234,6 +267,9 @@ export function defaultIslandLayouts(): IslandLayoutSettings {
main: true,
allowNotifications: true,
gap: 12,
opacity: CLASSISLAND_TOKENS.opacity.line,
fontOverridesEnabled: false,
...defaultCoreFontSizes(),
nodes: [
islandNode('date', 'date'),
islandNode('clock', 'clock'),
@@ -243,12 +279,16 @@ export function defaultIslandLayouts(): IslandLayoutSettings {
},
],
scale: 1,
color: '#000000',
foreground: '#ffffff',
opacity: 0.5,
radius: 8,
color: CLASSISLAND_TOKENS.colors.light.islandBgCustom,
foreground: CLASSISLAND_TOKENS.colors.light.textOnAccent,
customBackgroundEnabled: true,
customForegroundEnabled: true,
opacity: CLASSISLAND_TOKENS.opacity.islandBackground,
radius: CLASSISLAND_TOKENS.radii.island,
fontWeight: CLASSISLAND_TOKENS.fontWeights.medium,
...defaultCoreFontSizes(),
separated: false,
spacing: 5,
spacing: CLASSISLAND_TOKENS.spacing.lineGap,
},
],
};
@@ -304,19 +344,44 @@ export function normalizeIslandLayouts(input: unknown): IslandLayoutSettings {
},
appearance: {
resourceOverridingEnabled: a.resourceOverridingEnabled === true,
secondaryFontSize: clamp(a.secondaryFontSize, 8, 96, 14),
bodyFontSize: clamp(a.bodyFontSize, 8, 96, 16),
emphasizedFontSize: clamp(a.emphasizedFontSize, 8, 96, 18),
largeFontSize: clamp(a.largeFontSize, 8, 128, 20),
secondaryFontSize: clamp(
a.secondaryFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.secondary,
),
bodyFontSize: clamp(
a.bodyFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.body,
),
emphasizedFontSize: clamp(
a.emphasizedFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.emphasized,
),
largeFontSize: clamp(
a.largeFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.large,
),
customForegroundEnabled: a.customForegroundEnabled === true,
foreground: color(a.foreground, '#ffffff'),
foreground: color(a.foreground, CLASSISLAND_TOKENS.colors.light.textOnAccent),
customBackgroundEnabled: a.customBackgroundEnabled === true,
background: color(a.background, '#202024'),
background: color(a.background, CLASSISLAND_TOKENS.colors.light.islandBgCustom),
customBackgroundOpacityEnabled: a.customBackgroundOpacityEnabled === true,
backgroundOpacity: clamp(a.backgroundOpacity, 0, 1, 0.5),
backgroundOpacity: clamp(a.backgroundOpacity, 0, 1, CLASSISLAND_TOKENS.opacity.islandBackground),
customCornerRadiusEnabled: a.customCornerRadiusEnabled === true,
cornerRadius: clamp(a.cornerRadius, 0, 100, 16),
opacity: clamp(a.opacity, 0, 1, 1),
cornerRadius: clamp(
a.cornerRadius,
0,
CLASSISLAND_TOKENS.radii.islandMax,
CLASSISLAND_TOKENS.radii.island,
),
opacity: clamp(a.opacity, 0, 1, CLASSISLAND_TOKENS.opacity.line),
},
advanced: {
hideRules: Array.isArray(adv.hideRules)
@@ -341,6 +406,32 @@ export function normalizeIslandLayouts(input: unknown): IslandLayoutSettings {
main: r.main === true,
allowNotifications: r.allowNotifications !== false,
gap: clamp(r.gap, 0, 64, 8),
opacity: clamp(r.opacity, 0, 1, CLASSISLAND_TOKENS.opacity.line),
fontOverridesEnabled: r.fontOverridesEnabled === true,
secondaryFontSize: clamp(
r.secondaryFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.secondary,
),
bodyFontSize: clamp(
r.bodyFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.body,
),
emphasizedFontSize: clamp(
r.emphasizedFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.emphasized,
),
largeFontSize: clamp(
r.largeFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.large,
),
nodes: (Array.isArray(r.nodes) ? r.nodes : [])
.map((n) => node(n, 0))
.filter((n): n is IslandComponentNode => Boolean(n)),
@@ -373,12 +464,49 @@ export function normalizeIslandLayouts(input: unknown): IslandLayoutSettings {
resident ? CLASSISLAND_ISLAND_METRICS.scaleMax : 3,
1,
),
color: color(scheme.color, '#000000'),
foreground: color(scheme.foreground, '#ffffff'),
opacity: clamp(scheme.opacity, resident ? 0 : 0.1, 1, 0.5),
radius: clamp(scheme.radius, 0, resident ? CLASSISLAND_ISLAND_METRICS.radiusMax : 100, 8),
color: color(scheme.color, CLASSISLAND_TOKENS.colors.light.islandBgCustom),
foreground: color(scheme.foreground, CLASSISLAND_TOKENS.colors.light.textOnAccent),
customBackgroundEnabled: scheme.customBackgroundEnabled !== false,
customForegroundEnabled: scheme.customForegroundEnabled !== false,
opacity: clamp(scheme.opacity, resident ? 0 : 0.1, 1, CLASSISLAND_TOKENS.opacity.islandBackground),
radius: clamp(
scheme.radius,
0,
resident ? CLASSISLAND_ISLAND_METRICS.radiusMax : 100,
CLASSISLAND_TOKENS.radii.island,
),
fontWeight: classislandFontWeight(scheme.fontWeight),
secondaryFontSize: clamp(
scheme.secondaryFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.secondary,
),
bodyFontSize: clamp(
scheme.bodyFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.body,
),
emphasizedFontSize: clamp(
scheme.emphasizedFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.emphasized,
),
largeFontSize: clamp(
scheme.largeFontSize,
CLASSISLAND_TOKENS.fontSizes.inputMin,
CLASSISLAND_TOKENS.fontSizes.inputMax,
CLASSISLAND_TOKENS.fontSizes.large,
),
separated: scheme.separated === true,
spacing: clamp(scheme.spacing, 0, resident ? CLASSISLAND_ISLAND_METRICS.rowSpacingMax : 100, 5),
spacing: clamp(
scheme.spacing,
0,
resident ? CLASSISLAND_ISLAND_METRICS.rowSpacingMax : 100,
CLASSISLAND_TOKENS.spacing.lineGap,
),
});
}
return {
+1 -1
View File
@@ -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': '查看教师名单',
+29
View File
@@ -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班」,
@@ -1143,6 +1160,8 @@ export interface IslandNotification {
}
/** 灵动岛外观设置(设置页可调,主进程持久化并按此驱动窗口与渲染进程) */
export type IslandAccentColorSource = 0 | 1 | 2 | 3;
export interface IslandAppearance {
/** 胶囊高度(px,36~72):展开卡高度按比例联动,保证布局不错乱 */
height: number;
@@ -1154,6 +1173,16 @@ export interface IslandAppearance {
opacity: number;
/** 主题色(强调色,用于高亮与按钮) */
accent: string;
/**
* ClassIsland 强调色来源:
* 0=自定义、1=壁纸主题色、2=跟随系统、3=屏幕主题色。
*/
accentSource: IslandAccentColorSource;
/** 壁纸/屏幕主题色候选;来源为 1 或 3 时按索引取色。 */
accentPalette: string[];
accentPaletteIndex: number;
/** 主进程按 accentSource 解析出的只读实际颜色,不参与用户选择。 */
resolvedAccent?: string;
/**
* 基础字号(px,11~20)——参考 WinIsland 的 font_size:
* 岛内**所有文本**都由它乘以各自的排版系数得出,因此改字号会整体等比缩放。
+8 -7
View File
@@ -1,12 +1,13 @@
@import './tokens.css';
:root:root {
--el-color-primary: var(--ch-ui-primary);
--el-color-primary-light-3: color-mix(in srgb, var(--ch-ui-primary) 70%, var(--ch-ui-surface));
--el-color-primary-light-5: color-mix(in srgb, var(--ch-ui-primary) 50%, var(--ch-ui-surface));
--el-color-primary-light-7: color-mix(in srgb, var(--ch-ui-primary) 30%, var(--ch-ui-surface));
--el-color-primary-light-8: color-mix(in srgb, var(--ch-ui-primary) 20%, var(--ch-ui-surface));
--el-color-primary-light-9: color-mix(in srgb, var(--ch-ui-primary) 10%, var(--ch-ui-surface));
--el-color-primary-dark-2: color-mix(in srgb, var(--ch-ui-primary) 80%, #000);
/* ClassIsland accent 的单一入口;改 --ci-accent 时 Element Plus 同步派生。 */
--el-color-primary: var(--ci-accent);
--el-color-primary-light-3: color-mix(in srgb, var(--ci-accent) 70%, var(--ch-ui-surface));
--el-color-primary-light-5: color-mix(in srgb, var(--ci-accent) 50%, var(--ch-ui-surface));
--el-color-primary-light-7: color-mix(in srgb, var(--ci-accent) 30%, var(--ch-ui-surface));
--el-color-primary-light-8: color-mix(in srgb, var(--ci-accent) 20%, var(--ch-ui-surface));
--el-color-primary-light-9: color-mix(in srgb, var(--ci-accent) 10%, var(--ch-ui-surface));
--el-color-primary-dark-2: color-mix(in srgb, var(--ci-accent) 80%, black);
--el-border-radius-base: var(--ch-ui-radius);
--el-bg-color: var(--ch-ui-surface);
--el-bg-color-overlay: var(--ch-ui-surface);
+344
View File
@@ -1,3 +1,12 @@
/*
* 设计 token 分两层:
* - --ch-ui-*:应用外壳(设置中心、管理页);
* - --ci-*:ClassIsland 岛与课程信息层。
*
* --ci-* 的亮/暗键集合必须完全一致。组件只消费 token,不在局部重定义颜色;
* 行级字号与自定义前景色是唯一允许的元素级覆盖。
* ClassIsland 源值使用 AARRGGBB;CSS 统一转换为 RRGGBBAA。
*/
:root {
--ch-ui-primary: #5d6bfa;
--ch-ui-bg: #f7f8fa;
@@ -9,7 +18,164 @@
--ch-ui-radius: 8px;
--ch-ui-gap: 16px;
--ch-ui-shadow: 0 8px 30px rgb(30 40 70 / 8%);
--ch-z-guide: 10000;
--ch-z-view-old: 1;
--ch-z-view-new: 2;
--ci-accent: #00bfff;
--ci-accent-2: #7fffd4;
--ci-accent-fallback: #1e90ff;
--ci-accent-palette-fallback: #1e90ff;
--ci-accent-fill: var(--ci-accent);
--ci-accent-fill-tertiary: color-mix(in srgb, var(--ci-accent) 16%, transparent);
--ci-accent-text: var(--ci-accent);
--ci-text-on-accent: #ffffff;
--ci-accent-soft: color-mix(in srgb, var(--ci-accent) 10%, transparent);
--ci-text-1: #000000e4;
--ci-text-2: #000000c0;
--ci-text-3: #00000072;
--ci-text-4: #0000005c;
--ci-text-5: #0000002e;
--ci-bg-base: #f3f3f3;
--ci-bg-secondary: #eeeeee;
--ci-bg-tertiary: #f9f9f9;
--ci-fill-secondary: #0000000a;
--ci-smoke: #00000066;
--ci-island-bg-custom: #000000;
--ci-island-opacity: 0.5;
--ci-island-bg-opacity: var(--ci-island-opacity);
--ci-line-opacity: 1;
--ci-pointer-faded-opacity: 0.05;
--ci-stroke-island: color-mix(in srgb, var(--ci-accent) 24%, transparent);
--ci-stroke-island-w: 1px;
--ci-stroke-control: #00000024;
--ci-stroke-divider: #00000014;
--ci-stroke-flyout: #0000001b;
--ci-fill-strong: #00000072;
--ci-stroke-card: #00000016;
--ci-stroke-drag: var(--ci-accent-text);
--ci-stroke-tutorial: var(--ci-accent-text);
--ci-stroke-tutorial-w: 2.5px;
--ci-stroke-tutorial-corner-w: 3px;
--ci-aqi-1: #228b22;
--ci-aqi-2: #cccc00;
--ci-aqi-3: #ff8c00;
--ci-aqi-4: #cd5c5c;
--ci-aqi-5: #8b0000;
--ci-aqi-6: #800080;
--ci-weather-rain: #0000ff;
--ci-glow-class: #ffff00;
--ci-glow-class-blur: 6px;
--ci-danger: #cd5c5c;
--ci-warning-critical: #c42b1c;
--ci-warning-caution: #9d5d00;
--ci-warning-caution-bg: #fff4ce;
--ci-shadow-island: 0 4px 8px 2px #00000048;
--ci-shadow-mask: 0 8px 32px 0 #00000066;
--ci-shadow-drawer: 0 8px 32px 0 #00000066;
--ci-shadow-drawer-x: 0 0 8px #00000033;
--ci-shadow-classic-mask: 0 0 8px #000000;
--ci-shadow-adorn: 0 0 8px #00000066;
--ci-mask-fade: linear-gradient(to bottom, #ffffff00, #ffffff00 65%, #ffffff);
--ci-scrim-tutorial: #00000099;
--ci-debug-bg: #22222277;
--ci-splash-bg: #11111188;
--ci-brand-gradient-a: #0c0e1f;
--ci-brand-gradient-b: #0d1111;
--ci-brand-dark: #0d1111;
--ci-ripple: var(--ci-accent-fill);
--ci-ripple-stroke: 200;
--ci-font:
'HarmonyOS Sans SC', 'Microsoft YaHei UI', 'Noto Sans CJK SC', 'Noto Sans SC', 'PingFang SC',
'Source Han Sans SC', SimHei, 'WenQuanYi Micro Hei', sans-serif;
--ci-font-island: var(--ci-font);
--ci-font-harmony: 'HarmonyOS Sans SC', 'Microsoft YaHei UI', SimHei;
--ci-font-backend: 'Microsoft YaHei UI';
--ci-font-icon-fluent: 'FluentSystemIcons-Resizable';
--ci-font-icon-lucide: 'lucide';
--ci-font-icon-sf: 'SF-Symbols';
--ci-fw-thin: 100;
--ci-fw-extra-light: 200;
--ci-fw-light: 300;
--ci-fw-normal: 400;
--ci-fw-medium: 500;
--ci-fw-semi-bold: 600;
--ci-fw-bold: 700;
--ci-fw-extra-bold: 800;
--ci-fw-black: 900;
--ci-font-weight: var(--ci-fw-medium);
--ci-line-height-body: 1.25;
--ci-line-height-caption: 1.6;
--ci-fs-secondary: 14px;
--ci-fs-body: 16px;
--ci-fs-emphasized: 18px;
--ci-fs-large: 20px;
--ci-fs-version: 9px;
--ci-fs-caption: 12px;
--ci-fs-control-base: 13px;
--ci-fs-label: 14px;
--ci-fs-title: 16px;
--ci-fs-rolling: 17px;
--ci-fs-oobe-body: 18px;
--ci-fs-brand: 20px;
--ci-fs-weather: 22px;
--ci-fs-oobe-title: 32px;
--ci-radius-island: 8px;
--ci-radius-island-local: 0;
--ci-radius-popup: 6px;
--ci-radius-card: 4px;
--ci-radius-control: 4px;
--ci-radius-drawer: 8px 8px 0 0;
--ci-radius-pill: 999px;
--ci-radius-icon-btn: 14px;
--ci-radius-oobe-btn: 24px;
--ci-island-height: 40px;
--ci-island-pad-x: 12px;
--ci-island-min-w: 20px;
--ci-component-gap: 12px;
--ci-line-gap: 5px;
--ci-settings-pad: 12px 12px 18px 12px;
--ci-settings-max-w: 960px;
--ci-component-settings-pad: 4px 0 4px 12px;
--ci-popup-pad: 12px;
--ci-theme-card-h: 150px;
--ci-theme-card-w: 328px;
--ci-editbar-bottom: 64px;
--ci-splash-w: 400px;
--ci-splash-h: 100px;
--ci-progress-height: 3px;
--ci-island-pad-factor: 0.78;
--ci-island-gap-factor: 0.62;
--ci-window-transparent: transparent;
--ci-edit-blur: 16px;
--ci-effect-scale: 1;
--ci-z-window: 0;
--ci-z-window-top: 1;
--ci-z-content: 0;
--ci-z-mask: 1;
--ci-z-drag: 1;
--ci-z-drawer: 10;
--ci-z-timeline-adorn: 9999;
--ci-z-sentinel: 2147483647;
--ci-dpi-basis: 96;
--ci-scale: 1;
--ci-vertical-safe-area: 20px;
--ci-tutorial-safe-area: 150;
--ci-duration: 200ms;
}
html.dark {
--ch-ui-bg: #14161a;
--ch-ui-surface: #1d2027;
@@ -18,4 +184,182 @@ html.dark {
--ch-ui-text: #e9edf5;
--ch-ui-muted: #a2abbd;
--ch-ui-shadow: 0 8px 30px rgb(0 0 0 / 25%);
--ci-accent: #00bfff;
--ci-accent-2: #7fffd4;
--ci-accent-fallback: #1e90ff;
--ci-accent-palette-fallback: #1e90ff;
--ci-accent-fill: var(--ci-accent);
--ci-accent-fill-tertiary: color-mix(in srgb, var(--ci-accent) 16%, transparent);
--ci-accent-text: var(--ci-accent);
--ci-text-on-accent: #ffffff;
--ci-accent-soft: color-mix(in srgb, var(--ci-accent) 10%, transparent);
--ci-text-1: #ffffffff;
--ci-text-2: #ffffffda;
--ci-text-3: #ffffffc5;
--ci-text-4: #ffffff87;
--ci-text-5: #ffffff5d;
--ci-bg-base: #202020;
--ci-bg-secondary: #1c1c1c;
--ci-bg-tertiary: #282828;
--ci-fill-secondary: #ffffff14;
--ci-smoke: #00000066;
--ci-island-bg-custom: #000000;
--ci-island-opacity: 0.5;
--ci-island-bg-opacity: var(--ci-island-opacity);
--ci-line-opacity: 1;
--ci-pointer-faded-opacity: 0.05;
--ci-stroke-island: color-mix(in srgb, var(--ci-accent) 28%, transparent);
--ci-stroke-island-w: 1px;
--ci-stroke-control: #ffffff3d;
--ci-stroke-divider: #ffffff26;
--ci-stroke-flyout: #ffffff33;
--ci-fill-strong: #ffffff8a;
--ci-stroke-card: #ffffff26;
--ci-stroke-drag: var(--ci-accent-text);
--ci-stroke-tutorial: var(--ci-accent-text);
--ci-stroke-tutorial-w: 2.5px;
--ci-stroke-tutorial-corner-w: 3px;
--ci-aqi-1: #3cb371;
--ci-aqi-2: #ffff00;
--ci-aqi-3: #ffa500;
--ci-aqi-4: #cd5c5c;
--ci-aqi-5: #8b0000;
--ci-aqi-6: #9370db;
--ci-weather-rain: #00bfff;
--ci-glow-class: #ffff00;
--ci-glow-class-blur: 2px;
--ci-danger: #cd5c5c;
--ci-warning-critical: #ff99a4;
--ci-warning-caution: #fce100;
--ci-warning-caution-bg: #433519;
--ci-shadow-island: 0 4px 8px 2px #00000048;
--ci-shadow-mask: 0 8px 32px 0 #00000066;
--ci-shadow-drawer: 0 8px 32px 0 #00000066;
--ci-shadow-drawer-x: 0 0 8px #00000033;
--ci-shadow-classic-mask: 0 0 8px #000000;
--ci-shadow-adorn: 0 0 8px #00000066;
--ci-mask-fade: linear-gradient(to bottom, #ffffff00, #ffffff00 65%, #ffffff);
--ci-scrim-tutorial: #00000099;
--ci-debug-bg: #22222277;
--ci-splash-bg: #11111188;
--ci-brand-gradient-a: #0c0e1f;
--ci-brand-gradient-b: #0d1111;
--ci-brand-dark: #0d1111;
--ci-ripple: var(--ci-accent-fill);
--ci-ripple-stroke: 200;
--ci-font:
'HarmonyOS Sans SC', 'Microsoft YaHei UI', 'Noto Sans CJK SC', 'Noto Sans SC', 'PingFang SC',
'Source Han Sans SC', SimHei, 'WenQuanYi Micro Hei', sans-serif;
--ci-font-island: var(--ci-font);
--ci-font-harmony: 'HarmonyOS Sans SC', 'Microsoft YaHei UI', SimHei;
--ci-font-backend: 'Microsoft YaHei UI';
--ci-font-icon-fluent: 'FluentSystemIcons-Resizable';
--ci-font-icon-lucide: 'lucide';
--ci-font-icon-sf: 'SF-Symbols';
--ci-fw-thin: 100;
--ci-fw-extra-light: 200;
--ci-fw-light: 300;
--ci-fw-normal: 400;
--ci-fw-medium: 500;
--ci-fw-semi-bold: 600;
--ci-fw-bold: 700;
--ci-fw-extra-bold: 800;
--ci-fw-black: 900;
--ci-font-weight: var(--ci-fw-medium);
--ci-line-height-body: 1.25;
--ci-line-height-caption: 1.6;
--ci-fs-secondary: 14px;
--ci-fs-body: 16px;
--ci-fs-emphasized: 18px;
--ci-fs-large: 20px;
--ci-fs-version: 9px;
--ci-fs-caption: 12px;
--ci-fs-control-base: 13px;
--ci-fs-label: 14px;
--ci-fs-title: 16px;
--ci-fs-rolling: 17px;
--ci-fs-oobe-body: 18px;
--ci-fs-brand: 20px;
--ci-fs-weather: 22px;
--ci-fs-oobe-title: 32px;
--ci-radius-island: 8px;
--ci-radius-island-local: 0;
--ci-radius-popup: 6px;
--ci-radius-card: 4px;
--ci-radius-control: 4px;
--ci-radius-drawer: 8px 8px 0 0;
--ci-radius-pill: 999px;
--ci-radius-icon-btn: 14px;
--ci-radius-oobe-btn: 24px;
--ci-island-height: 40px;
--ci-island-pad-x: 12px;
--ci-island-min-w: 20px;
--ci-component-gap: 12px;
--ci-line-gap: 5px;
--ci-settings-pad: 12px 12px 18px 12px;
--ci-settings-max-w: 960px;
--ci-component-settings-pad: 4px 0 4px 12px;
--ci-popup-pad: 12px;
--ci-theme-card-h: 150px;
--ci-theme-card-w: 328px;
--ci-editbar-bottom: 64px;
--ci-splash-w: 400px;
--ci-splash-h: 100px;
--ci-progress-height: 3px;
--ci-island-pad-factor: 0.78;
--ci-island-gap-factor: 0.62;
--ci-window-transparent: transparent;
--ci-edit-blur: 16px;
--ci-effect-scale: 1;
--ci-z-window: 0;
--ci-z-window-top: 1;
--ci-z-content: 0;
--ci-z-mask: 1;
--ci-z-drag: 1;
--ci-z-drawer: 10;
--ci-z-timeline-adorn: 9999;
--ci-z-sentinel: 2147483647;
--ci-dpi-basis: 96;
--ci-scale: 1;
--ci-vertical-safe-area: 20px;
--ci-tutorial-safe-area: 150;
--ci-duration: 200ms;
}
.l-primary,
.l1 {
color: var(--ci-text-1);
}
.l-secondary,
.l2 {
color: var(--ci-text-2);
}
.l-instructive,
.l3 {
color: var(--ci-text-3);
}
.l-decoration,
.l4 {
color: var(--ci-text-4);
}
.l-inactive,
.l5 {
color: var(--ci-text-5);
}
+6
View File
@@ -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,82 @@
<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import type { AiConversationResult } from '@classhelper/shared';
const props = defineProps<{ questions: NonNullable<AiConversationResult['questions']> }>();
const visible = defineModel<boolean>({ default: false });
const emit = defineEmits<{ answer: [text: string] }>();
const answers = reactive<Record<string, string>>({});
watch(visible, (value) => {
if (value) for (const key of Object.keys(answers)) delete answers[key];
});
const complete = computed(
() => props.questions.length > 0 && props.questions.every((q) => answers[q.id]?.trim()),
);
function submit() {
if (!complete.value) return;
const text = props.questions.map((q) => `${q.text}:${answers[q.id]!.trim()}`).join('\n');
visible.value = false;
emit('answer', text);
}
</script>
<template>
<el-dialog
v-model="visible"
title="AI 需要你补充信息"
width="520px"
append-to-body
:close-on-click-modal="false"
class="assistant-questions-dialog"
>
<p>回答后会继续生成操作预览;删除等操作仍需核对预览并确认执行。</p>
<section v-for="question in questions" :key="question.id" class="question-field">
<h3 :id="'ai-question-' + question.id">{{ question.text }}</h3>
<div class="question-options" :aria-labelledby="'ai-question-' + question.id">
<el-button
v-for="option in question.options || []"
:key="option"
:type="answers[question.id] === option ? 'primary' : 'default'"
:aria-pressed="answers[question.id] === option"
@click="answers[question.id] = option"
>
{{ option }}
</el-button>
</div>
<el-input
v-model="answers[question.id]"
type="textarea"
:autosize="{ minRows: 2, maxRows: 5 }"
maxlength="1000"
placeholder="选择上方答案,或输入自己的回答"
:aria-labelledby="'ai-question-' + question.id"
/>
</section>
<template #footer>
<el-button @click="visible = false">稍后回答</el-button>
<el-button type="primary" :disabled="!complete" @click="submit">发送回答</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.question-field {
margin: 16px 0;
}
.question-field h3 {
font-size: 1em;
overflow-wrap: anywhere;
line-height: 1.6;
}
.question-options {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
.question-options :deep(.el-button) {
height: auto;
white-space: normal;
line-height: 1.5;
text-align: left;
max-width: 100%;
margin: 0;
}
</style>
@@ -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,6 +1,8 @@
<script setup lang="ts">
/** Web 管理端班级灵动岛的组件检查器。 */
import { computed, ref, watch } from 'vue';
import {
CLASSISLAND_TOKENS,
ISLAND_COMPONENT_LABELS,
type IslandComponentNode,
type IslandComponentKind,
@@ -180,8 +182,9 @@ const containers = ['group', 'stack', 'slide', 'rolling'] as const;
<el-input-number
v-model="node.appearance[key]"
:disabled="!node.appearance.resourceOverridingEnabled"
:min="8"
:max="96"
:min="CLASSISLAND_TOKENS.fontSizes.inputMin"
:max="CLASSISLAND_TOKENS.fontSizes.inputMax"
:step="CLASSISLAND_TOKENS.fontSizes.inputStep"
@change="emit('change')"
/>
</el-form-item>
@@ -234,7 +237,8 @@ const containers = ['group', 'stack', 'slide', 'rolling'] as const;
v-if="node.appearance.customCornerRadiusEnabled"
v-model="node.appearance.cornerRadius"
:min="0"
:max="100"
:max="CLASSISLAND_TOKENS.radii.islandMax"
:step="CLASSISLAND_TOKENS.radii.islandStep"
@change="emit('change')"
/>
</el-form-item>
@@ -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>
+9 -1
View File
@@ -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'] },
{
+11
View File
@@ -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',
@@ -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,42 +212,101 @@
.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;
color: #ffffffeb;
padding: 12px;
min-width: 80px;
color: var(--ci-text-1);
padding: var(--ci-island-pad-x);
border-radius: var(--preview-radius);
background: #202024;
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;
padding: 0;
}
.separated .preview-row {
padding: 12px;
background: #202024;
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: #ffffffb8;
color: var(--ci-text-2);
background: transparent;
border: 1px dashed #ffffff60;
border-radius: 5px;
border: var(--ci-stroke-island-w) dashed var(--ci-stroke-control);
border-radius: var(--ci-radius-control);
padding: 10px 20px;
cursor: pointer;
font: inherit;
@@ -246,6 +333,19 @@
line-height: 1.6;
font-size: 12px;
}
.font-preview {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: calc(var(--ci-line-gap) * 2);
margin: 0 0 18px;
padding: var(--ci-popup-pad);
border: var(--ci-stroke-island-w) solid var(--ci-stroke-island);
border-radius: var(--ci-radius-card);
background: var(--ci-island-bg-custom);
line-height: var(--ci-line-height-body);
overflow: auto;
}
.component-library {
border-top: 1px solid var(--ch-border);
margin: 0 -24px;
@@ -393,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;
}
+101 -19
View File
@@ -19,6 +19,7 @@ import { useAuthStore } from '@/stores/auth';
import { hashAttachment, importFileBase64 } from '@/composables/assistantFiles';
import { findClassInSession } from '@/composables/useClassInSession';
import AssistantData from '@/components/AssistantData.vue';
import AssistantQuestions from '@/components/AssistantQuestions.vue';
import UrgentClassWarning from '@/components/UrgentClassWarning.vue';
import { observeTask } from '@/composables/assistantStream';
interface ChatMessage {
@@ -32,22 +33,44 @@ interface ChatMessage {
const auth = useAuthStore();
let viewEpoch = 0;
const replacePlan = ref(false);
const deletingConversation = ref(false);
const questionsVisible = ref(false),
questionSource = ref<ChatMessage>();
function showQuestions(message: ChatMessage) {
if (busy.value || executing.value || !message.result?.questions?.length) return;
questionSource.value = message;
questionsVisible.value = true;
}
async function answerQuestions(answer: string) {
if (busy.value || executing.value) return;
text.value = answer;
await send();
}
const conversationId = ref('');
const conversations = ref<{ id: string; title: string }[]>([]);
let conversationListRequest = 0;
async function loadConversations() {
conversations.value = await api.get('/ai/conversations');
const request = ++conversationListRequest;
const rows = await api.get<{ id: string; title: string }[]>('/ai/conversations');
if (request === conversationListRequest && !disposed) conversations.value = rows;
}
async function openConversation(id: string) {
if ((busy.value || executing.value) && !observing) return;
viewEpoch++;
questionsVisible.value = false;
questionSource.value = undefined;
const epoch = ++viewEpoch;
controller?.abort();
busy.value = false;
executing.value = false;
questionsVisible.value = false;
questionSource.value = undefined;
conversationId.value = id;
attachments.value = [];
files.clear();
replacePlan.value = false;
const turns = await api.get<AiTaskDto[]>(`/ai/conversations/${id}`);
if (epoch !== viewEpoch || disposed) return;
messages.value = turns.flatMap((t) => [
{ role: 'user' as const, content: t.text },
{
@@ -67,6 +90,48 @@ async function openConversation(id: string) {
lastRequest = last ? { text: last.text, conversationId: id } : undefined;
clearCredentials();
if (last && ['planning', 'executing'].includes(last.state)) await resumeTask(last.id, true);
else if (last?.state === 'waiting_input' && messages.value.at(-1)) showQuestions(messages.value.at(-1)!);
}
async function deleteCurrentConversation() {
const id = conversationId.value;
if (!id || busy.value || executing.value || hashing.value || deletingConversation.value) return;
const title = conversations.value.find((c) => c.id === id)?.title || '新对话';
try {
await ElMessageBox.confirm(
`删除“${title}”?对话轮次和暂存附件会清除,未完成计划会取消。已执行的业务操作及审计记录保留。`,
'删除对话',
{ type: 'warning', confirmButtonText: '删除对话', cancelButtonText: '保留对话' },
);
} catch {
return;
}
deletingConversation.value = true;
try {
await api.delete(`/ai/conversations/${encodeURIComponent(id)}`);
viewEpoch++;
controller?.abort();
questionsVisible.value = false;
questionSource.value = undefined;
conversationId.value = '';
taskId.value = '';
messages.value = [];
active.value = undefined;
lastRequest = undefined;
error.value = '';
text.value = '';
attachments.value = [];
files.clear();
clearCredentials();
classId.value = '';
replacePlan.value = false;
await loadConversations();
if (conversations.value[0]) await openConversation(conversations.value[0].id);
ElMessage.success('对话已删除');
} catch (e) {
error.value = failure(e);
} finally {
deletingConversation.value = false;
}
}
async function olderConversations() {
const older = await api.get<{ id: string; title: string }[]>('/ai/conversations', {
@@ -226,7 +291,14 @@ async function retryTask(): Promise<void> {
if (lastRequest) await send(true);
}
async function send(retrying = false): Promise<void> {
if ((!retrying && !text.value.trim()) || busy.value || executing.value || hashing.value) return;
if (
(!retrying && !text.value.trim()) ||
busy.value ||
executing.value ||
hashing.value ||
deletingConversation.value
)
return;
const epoch = viewEpoch;
const supersedesTaskId = replacePlan.value && pending.value ? taskId.value : undefined;
busy.value = true;
@@ -310,6 +382,7 @@ async function send(retrying = false): Promise<void> {
observing = false;
if (message) message.state = controller.signal.aborted || error.value ? 'stopped' : 'done';
busy.value = false;
if (message?.result?.questions?.length && !disposed) showQuestions(message);
if (!disposed) {
taskHistory.value = await aiApi.tasks().catch(() => taskHistory.value);
await loadConversations();
@@ -324,7 +397,9 @@ function composerKey(event: KeyboardEvent): void {
}
}
async function newConversation(): Promise<void> {
if (hashing.value || ((busy.value || executing.value) && !observing)) return;
if (deletingConversation.value || hashing.value || ((busy.value || executing.value) && !observing)) return;
questionsVisible.value = false;
questionSource.value = undefined;
viewEpoch++;
controller?.abort();
busy.value = false;
@@ -481,6 +556,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
error.value = '';
const epoch = viewEpoch;
const saved = await aiApi.task(id);
if (disposed || epoch !== viewEpoch) return;
taskId.value = id;
lastRequest = { text: saved.text };
const message = reactive<ChatMessage>({
@@ -496,6 +572,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
clearCredentials();
if (saved.error) error.value = saved.error;
if (!['planning', 'executing'].includes(saved.state)) {
if (saved.state === 'waiting_input') showQuestions(message);
await scroll();
return;
}
@@ -530,6 +607,7 @@ async function resumeTask(id: string, preserveHistory = false): Promise<void> {
message.state = error.value ? 'stopped' : 'done';
busy.value = false;
executing.value = false;
if (message.result?.questions?.length && !disposed) showQuestions(message);
await scroll();
}
}
@@ -574,12 +652,20 @@ onBeforeUnmount(() => {
</div>
</div>
<div class="agent-header-actions">
<el-button
v-if="conversationId"
:disabled="busy || executing || hashing"
:loading="deletingConversation"
@click="deleteCurrentConversation"
>
删除对话
</el-button>
<el-button v-if="conversations.length >= 30" @click="olderConversations">更多对话</el-button>
<el-select
v-if="conversations.length"
:model-value="conversationId"
placeholder="对话历史"
:disabled="(busy || executing) && !observing"
:disabled="deletingConversation || ((busy || executing) && !observing)"
@change="openConversation"
>
<el-option
@@ -589,7 +675,10 @@ onBeforeUnmount(() => {
:label="item.title || '新对话'"
/>
</el-select>
<el-button :disabled="hashing || ((busy || executing) && !observing)" @click="newConversation">
<el-button
:disabled="deletingConversation || hashing || ((busy || executing) && !observing)"
@click="newConversation"
>
新对话
</el-button>
<el-select
@@ -681,19 +770,7 @@ onBeforeUnmount(() => {
class="assistant-question"
>
<strong>{{ question.text }}</strong>
<div class="question-options">
<el-button
v-for="option in question.options || []"
:key="option"
:disabled="busy"
@click="
text = question.text + ':' + option;
send();
"
>
{{ option }}
</el-button>
</div>
<el-button :disabled="busy || executing" @click="showQuestions(message)">回答问题</el-button>
<small>也可以在下方输入框自由回答。</small>
</el-card>
<el-button
@@ -813,6 +890,11 @@ onBeforeUnmount(() => {
<el-progress v-if="executing && progress > 0" :percentage="progress" />
</section>
</div>
<AssistantQuestions
v-model="questionsVisible"
:questions="questionSource?.result?.questions || []"
@answer="answerQuestions"
/>
<el-alert v-if="error" :title="error" type="warning" :closable="true" show-icon @close="error = ''" />
<el-button v-if="error && !active?.steps.length && !busy && !executing" @click="retryTask">
重试上次任务
@@ -1,9 +1,10 @@
<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,
CLASSISLAND_TOKENS,
DEFAULT_ISLAND_APPEARANCE,
ISLAND_COMPONENT_LABELS,
defaultIslandLayouts,
@@ -15,35 +16,107 @@ 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)!,
);
const rows = computed(() => (surface.value === 'expanded' ? scheme.value.expandedRows : scheme.value.rows));
const activeRow = computed(() => rows.value.find((row) => row.id === rowId.value) ?? rows.value[0]!);
const fontFields = [
{ key: 'secondaryFontSize', label: '辅助文字' },
{ key: 'bodyFontSize', label: '正文' },
{ key: 'emphasizedFontSize', label: '强调文字' },
{ key: 'largeFontSize', label: '大号文字' },
] as const;
const fontWeights = [
{ value: CLASSISLAND_TOKENS.fontWeights.thin, label: '100 Thin' },
{ value: CLASSISLAND_TOKENS.fontWeights.extraLight, label: '200 ExtraLight' },
{ value: CLASSISLAND_TOKENS.fontWeights.light, label: '300 Light' },
{ value: CLASSISLAND_TOKENS.fontWeights.normal, label: '400 Normal' },
{ value: CLASSISLAND_TOKENS.fontWeights.medium, label: '500 Medium(默认)' },
{ value: CLASSISLAND_TOKENS.fontWeights.semiBold, label: '600 SemiBold' },
{ value: CLASSISLAND_TOKENS.fontWeights.bold, label: '700 Bold' },
{ value: CLASSISLAND_TOKENS.fontWeights.extraBold, label: '800 ExtraBold' },
{ value: CLASSISLAND_TOKENS.fontWeights.black, label: '900 Black' },
] as const;
function rowStyle(row: IslandLayoutRow): Record<string, string> {
const style: Record<string, string> = {
'--row-gap': `${row.gap}px`,
opacity: String(row.opacity),
};
if (row.fontOverridesEnabled) {
style['--ci-fs-secondary'] = `${row.secondaryFontSize}px`;
style['--ci-fs-body'] = `${row.bodyFontSize}px`;
style['--ci-fs-emphasized'] = `${row.emphasizedFontSize}px`;
style['--ci-fs-large'] = `${row.largeFontSize}px`;
}
return style;
}
function previewStyle(): Record<string, string> {
const foreground: Record<string, string> = scheme.value.customForegroundEnabled
? {
'--ci-text-1': scheme.value.foreground,
'--ci-text-2': `color-mix(in srgb, ${scheme.value.foreground} 85.5%, transparent)`,
'--ci-text-3': `color-mix(in srgb, ${scheme.value.foreground} 77.3%, transparent)`,
'--ci-text-4': `color-mix(in srgb, ${scheme.value.foreground} 52.9%, transparent)`,
'--ci-text-5': `color-mix(in srgb, ${scheme.value.foreground} 36.5%, transparent)`,
}
: {};
return {
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
? `color-mix(in srgb, ${scheme.value.color} ${scheme.value.opacity * 100}%, transparent)`
: 'var(--ci-bg-secondary)',
'--ci-fs-secondary': `${scheme.value.secondaryFontSize}px`,
'--ci-fs-body': `${scheme.value.bodyFontSize}px`,
'--ci-fs-emphasized': `${scheme.value.emphasizedFontSize}px`,
'--ci-fs-large': `${scheme.value.largeFontSize}px`,
'--ci-font-weight': String(scheme.value.fontWeight),
'--ci-accent': appearance.value.resolvedAccent ?? appearance.value.accent,
fontSize: `${scheme.value.bodyFontSize}px`,
...foreground,
};
}
const state: IslandState = {
mode: 'hidden',
active: null,
@@ -81,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--;
}
@@ -104,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';
@@ -128,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 层容器');
@@ -140,6 +222,7 @@ function add(kind: IslandComponentKind) {
void save();
}
function addRow() {
if (!canEdit.value) return;
if (rows.value.length >= 12) {
ElMessage.warning('每种内容最多添加 12 行');
return;
@@ -150,6 +233,12 @@ function addRow() {
main: false,
allowNotifications: true,
gap: 8,
opacity: CLASSISLAND_TOKENS.opacity.line,
fontOverridesEnabled: false,
secondaryFontSize: CLASSISLAND_TOKENS.fontSizes.secondary,
bodyFontSize: CLASSISLAND_TOKENS.fontSizes.body,
emphasizedFontSize: CLASSISLAND_TOKENS.fontSizes.emphasized,
largeFontSize: CLASSISLAND_TOKENS.fontSizes.large,
nodes: [],
};
rows.value.push(row);
@@ -288,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);
@@ -319,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;
});
@@ -446,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 {
@@ -540,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>
@@ -561,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" />
@@ -571,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>
@@ -581,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>
@@ -608,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="编辑内容">
@@ -635,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="
@@ -647,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>
@@ -693,47 +913,46 @@ function dropPreview(event: PointerEvent) {
</div>
</section>
</div>
<div
v-else
class="island-preview"
:class="{ separated: scheme.separated }"
:style="{
zoom: scheme.scale * zoom,
'--preview-gap': `${scheme.spacing}px`,
'--preview-radius': `${scheme.radius}px`,
'--secondary': `${(appearance.fontSize / 13) * 14}px`,
'--emphasized': `${(appearance.fontSize / 13) * 18}px`,
'--large': `${(appearance.fontSize / 13) * 20}px`,
fontSize: `${(appearance.fontSize / 13) * 16}px`,
}"
>
<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="{ gap: `${row.gap}px` }"
@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">
@@ -746,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
@@ -814,6 +1033,30 @@ function dropPreview(event: PointerEvent) {
<el-form-item label="组件间距">
<el-input-number v-model="activeRow.gap" :min="0" :max="64" @change="save" />
</el-form-item>
<el-form-item label="整行透明度">
<el-slider
v-model="activeRow.opacity"
:min="0"
:max="1"
:step="0.05"
:format-tooltip="(value: number) => value.toFixed(2)"
@change="save"
/>
</el-form-item>
<el-form-item label="行级字号覆盖">
<el-switch v-model="activeRow.fontOverridesEnabled" @change="save" />
</el-form-item>
<el-form-item v-for="field in fontFields" :key="field.key" :label="`${field.label}字号(px)`">
<el-input-number
v-model="activeRow[field.key]"
:disabled="!activeRow.fontOverridesEnabled"
:min="CLASSISLAND_TOKENS.fontSizes.inputMin"
:max="CLASSISLAND_TOKENS.fontSizes.inputMax"
:step="CLASSISLAND_TOKENS.fontSizes.inputStep"
@change="save"
/>
</el-form-item>
<p class="hint">行级字号只写到当前行根元素;关闭覆盖后回落到方案字号。</p>
<el-form-item label="允许显示提醒">
<el-switch v-model="activeRow.allowNotifications" @change="save" />
</el-form-item>
@@ -839,23 +1082,84 @@ function dropPreview(event: PointerEvent) {
v-model="scheme.scale"
:min="METRICS.scaleMin"
:max="METRICS.scaleMax"
:step="0.05"
:step="CLASSISLAND_TOKENS.dpi.scaleStep"
@change="save"
/>
</el-form-item>
<el-form-item label="字体字重">
<el-select v-model="scheme.fontWeight" @change="save">
<el-option
v-for="weight in fontWeights"
:key="weight.value"
:label="weight.label"
:value="weight.value"
/>
</el-select>
</el-form-item>
<el-form-item v-for="field in fontFields" :key="field.key" :label="`${field.label}字号(px)`">
<el-input-number
v-model="scheme[field.key]"
:min="CLASSISLAND_TOKENS.fontSizes.inputMin"
:max="CLASSISLAND_TOKENS.fontSizes.inputMax"
:step="CLASSISLAND_TOKENS.fontSizes.inputStep"
@change="save"
/>
</el-form-item>
<div class="font-preview" aria-label="四档字号预览">
<span class="l1" :style="{ fontSize: `${scheme.secondaryFontSize}px` }">辅助文字</span>
<span class="l2" :style="{ fontSize: `${scheme.bodyFontSize}px` }">正文示例</span>
<span
class="l1"
:style="{ fontSize: `${scheme.emphasizedFontSize}px`, fontWeight: scheme.fontWeight }"
>
强调文字
</span>
<span class="l1" :style="{ fontSize: `${scheme.largeFontSize}px`, fontWeight: scheme.fontWeight }">
大号标题
</span>
</div>
<el-form-item label="行间距">
<el-slider v-model="scheme.spacing" :min="0" :max="METRICS.rowSpacingMax" @change="save" />
</el-form-item>
<el-form-item label="常态圆角">
<el-slider v-model="scheme.radius" :min="0" :max="METRICS.radiusMax" @change="save" />
<el-slider
v-model="scheme.radius"
:min="0"
:max="METRICS.radiusMax"
:step="CLASSISLAND_TOKENS.radii.islandStep"
@change="save"
/>
</el-form-item>
<el-form-item label="自定义背景色">
<el-switch v-model="scheme.customBackgroundEnabled" @change="save" />
<el-color-picker v-if="scheme.customBackgroundEnabled" v-model="scheme.color" @change="save" />
</el-form-item>
<el-form-item label="背景不透明度">
<el-slider
v-model="scheme.opacity"
:min="0"
:max="1"
:step="0.05"
:show-tooltip="true"
:format-tooltip="(value: number) => value.toFixed(2)"
@change="save"
/>
</el-form-item>
<el-form-item label="自定义前景色">
<el-switch v-model="scheme.customForegroundEnabled" @change="save" />
<el-color-picker v-if="scheme.customForegroundEnabled" v-model="scheme.foreground" @change="save" />
</el-form-item>
<p class="hint">
关闭自定义前景色后回落当前亮/暗主题的五级文字色;开启后按 100% / 85.5% / 77.3% / 52.9% / 36.5%
生成颜色 alpha。
</p>
<el-form-item label="各行分离显示">
<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>
<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>
+137
View File
@@ -0,0 +1,137 @@
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
const root = process.cwd();
const tokenFile = path.join(root, 'packages/ui/src/tokens.css');
const islandRoot = path.join(root, 'packages/desktop-client/src/island');
const scopedFiles = [
islandRoot,
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/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');
const rootBlock = source.match(/:root\s*\{([\s\S]*?)\n\}/)?.[1] ?? '';
const darkBlock = source.match(/html\.dark\s*\{([\s\S]*?)\n\}/)?.[1] ?? '';
function tokenNames(block) {
return [...block.matchAll(/(--ci-[a-z0-9-]+)\s*:/g)].map((match) => match[1]);
}
const light = new Set(tokenNames(rootBlock));
const dark = new Set(tokenNames(darkBlock));
const errors = [];
if (!light.size || !dark.size) errors.push('无法解析 :root 或 html.dark 的 --ci-* token');
for (const name of light) if (!dark.has(name)) errors.push(`深色主题缺少 ${name}`);
for (const name of dark) if (!light.has(name)) errors.push(`亮色主题缺少 ${name}`);
const required = [
'--ci-accent',
'--ci-accent-2',
'--ci-accent-fallback',
'--ci-accent-palette-fallback',
'--ci-accent-fill',
'--ci-accent-fill-tertiary',
'--ci-accent-text',
'--ci-text-on-accent',
'--ci-accent-soft',
'--ci-text-1',
'--ci-text-2',
'--ci-text-3',
'--ci-text-4',
'--ci-text-5',
'--ci-bg-base',
'--ci-bg-secondary',
'--ci-bg-tertiary',
'--ci-island-bg-custom',
'--ci-island-opacity',
'--ci-island-bg-opacity',
'--ci-line-opacity',
'--ci-stroke-island',
'--ci-stroke-control',
'--ci-stroke-divider',
'--ci-stroke-flyout',
'--ci-stroke-card',
'--ci-stroke-drag',
'--ci-stroke-tutorial',
'--ci-shadow-island',
'--ci-shadow-mask',
'--ci-shadow-drawer',
'--ci-shadow-drawer-x',
'--ci-shadow-classic-mask',
'--ci-shadow-adorn',
'--ci-font',
'--ci-font-island',
'--ci-font-backend',
'--ci-font-icon-fluent',
'--ci-font-icon-lucide',
'--ci-font-icon-sf',
'--ci-fs-secondary',
'--ci-fs-body',
'--ci-fs-emphasized',
'--ci-fs-large',
'--ci-radius-island',
'--ci-radius-island-local',
'--ci-radius-popup',
'--ci-radius-card',
'--ci-radius-control',
'--ci-radius-drawer',
'--ci-radius-pill',
'--ci-island-height',
'--ci-island-pad-x',
'--ci-island-min-w',
'--ci-component-gap',
'--ci-line-gap',
'--ci-progress-height',
'--ci-z-window',
'--ci-z-window-top',
'--ci-z-mask',
'--ci-z-drag',
'--ci-z-timeline-adorn',
'--ci-z-sentinel',
'--ci-dpi-basis',
'--ci-scale',
'--ci-vertical-safe-area',
];
for (const name of required) if (!light.has(name)) errors.push(`缺少基础 token ${name}`);
function files(directory) {
return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
const target = path.join(directory, entry.name);
return entry.isDirectory() ? files(target) : [target];
});
}
const scoped = scopedFiles.flatMap((file) => (fs.statSync(file).isDirectory() ? files(file) : [file]));
for (const file of scoped.filter((value) => /\.(css|vue|ts)$/.test(value))) {
const text = fs.readFileSync(file, 'utf8');
const relative = path.relative(root, file);
if (/#[0-9a-f]{3,8}\b/i.test(text)) errors.push(`${relative} 含裸颜色字面量`);
if (/(?<![\w-])rgba?\(/i.test(text)) errors.push(`${relative} 含裸 rgb/rgba 色值`);
for (const match of text.matchAll(/--ci-([A-Za-z0-9_-]+)/g)) {
if (/[A-Z_]/.test(match[1])) errors.push(`${relative} 的 token 名不是 kebab-case:--ci-${match[1]}`);
}
}
for (const file of files(path.join(root, 'packages/desktop-client/src')).filter((value) =>
value.endsWith('.css'),
)) {
const text = fs.readFileSync(file, 'utf8');
if (/^\s*--ci-[a-z0-9-]+\s*:/m.test(text)) {
errors.push(`${path.relative(root, file)} 在 tokens.css 之外定义了 --ci-*`);
}
}
if (errors.length) {
console.error(`设计 token 检查失败(${errors.length} 项):`);
for (const error of errors) console.error(`- ${error}`);
process.exitCode = 1;
} else {
console.log(`设计 token 检查通过:亮/暗各 ${light.size} 个 --ci-*,岛相关文件无裸颜色。`);
}
+118
View File
@@ -108,6 +108,124 @@ module.exports = async function runAssistantChecks({ win, target, record, waitFo
);
assert.equal((await request('/homeworks?keyword=' + encodeURIComponent(title))).length, 1);
record('AI 界面确认后通过原业务端点执行并显示结果', true);
const sendChat = async (content) => {
await win.webContents.executeJavaScript(
`(() => {const input=document.querySelector('.assistant-composer textarea');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(input,${JSON.stringify(content)});input.dispatchEvent(new Event('input',{bubbles:true}));})()`,
);
assert(
await waitFor(
win,
`Array.from(document.querySelectorAll('.assistant-composer button')).some(b=>b.textContent.trim()==='发送'&&!b.disabled)`,
),
);
await win.webContents.executeJavaScript(
`Array.from(document.querySelectorAll('.assistant-composer button')).find(b=>b.textContent.trim()==='发送').click()`,
);
};
await sendChat(
JSON.stringify({
message: '请确认要处理哪张课表?',
questions: [{ question: '请选择下一步', options: ['查看本班今天的作业'] }],
}),
);
const questionVisible = `Array.from(document.querySelectorAll('.assistant-questions-dialog')).some(d=>d.getBoundingClientRect().height>0 && d.textContent.includes('请选择下一步'))`;
assert(await waitFor(win, questionVisible));
await screenshot('assistant-question-dialog');
await win.loadURL(origin + '/assistant');
assert(await waitFor(win, questionVisible));
const roundsBefore = await win.webContents.executeJavaScript(
`document.querySelectorAll('.assistant-message.user').length`,
);
await win.webContents.executeJavaScript(
`document.querySelector('.assistant-questions-dialog .question-options button').click()`,
);
assert(
await waitFor(
win,
`Array.from(document.querySelectorAll('.assistant-questions-dialog .el-dialog__footer button')).some(b=>b.textContent.trim()==='发送回答'&&!b.disabled)`,
),
);
await win.webContents.executeJavaScript(
`Array.from(document.querySelectorAll('.assistant-questions-dialog .el-dialog__footer button')).find(b=>b.textContent.trim()==='发送回答').click()`,
);
assert(
await waitFor(
win,
`document.querySelectorAll('.assistant-message.user').length===${roundsBefore + 1} && Array.from(document.querySelectorAll('.assistant-composer button')).some(b=>b.textContent.trim()==='发送'&&!b.disabled)===false && !(${questionVisible})`,
),
);
// 输入为空时发送按钮禁用,等待后台结束由停止生成按钮消失判断。
assert(
await waitFor(
win,
`!Array.from(document.querySelectorAll('.assistant-composer button')).some(b=>b.textContent.trim()==='停止生成')`,
),
);
record('模型提问弹出交互窗口,刷新可恢复,回答作为同一对话的新一轮继续', true);
const layout = await request('/time-layouts', 'POST', {
classId: cls.id,
name: title + '删除作息',
points: [],
});
const day = await request('/class-plans', 'POST', {
classId: cls.id,
name: title + '待删除课表',
timeLayoutId: layout.id,
weekday: 1,
});
await sendChat(JSON.stringify({ operations: [{ action: 'plans.delete', target: { id: day.id } }] }));
assert(
await waitFor(
win,
`document.querySelector('.assistant-step')?.textContent.includes(${JSON.stringify(day.name)}) && document.querySelector('.assistant-step .el-tag')?.textContent.includes('待确认')`,
),
);
assert(
(await request('/class-plans?classId=' + encodeURIComponent(cls.id))).some((p) => p.id === day.id),
);
await win.webContents.executeJavaScript(
`Array.from(document.querySelectorAll('.assistant-plan-actions button')).find(b=>b.textContent.trim()==='确认执行').click()`,
);
assert(
await waitFor(
win,
`(() => {const box=document.querySelector('.el-message-box');if(!box?.textContent.includes(${JSON.stringify(day.name)})||!box.getBoundingClientRect().height)return false;for(let node=box;node;node=node.parentElement){const style=getComputedStyle(node);if(style.display==='none'||style.visibility==='hidden'||Number(style.opacity)<0.99)return false;}return true;})()`,
),
);
await win.webContents.capturePage();
await new Promise((resolve) => setTimeout(resolve, 150));
await screenshot('assistant-delete-confirm');
await win.webContents.executeJavaScript(
`Array.from(document.querySelectorAll('.el-message-box__btns button')).find(b=>b.textContent.trim()==='取消').click()`,
);
assert(
(await request('/class-plans?classId=' + encodeURIComponent(cls.id))).some((p) => p.id === day.id),
);
record('删除课表先显示预览及危险操作确认窗口,取消不会删除', true);
// 对话删除不回滚已完成的作业,也不执行其余待确认删除计划。
const current = (await request('/ai/conversations'))[0];
await win.webContents.executeJavaScript(
`Array.from(document.querySelectorAll('.agent-header-actions button')).find(b=>b.textContent.trim()==='删除对话').click()`,
);
assert(await waitFor(win, `document.querySelector('.el-message-box')?.textContent.includes('删除对话')`));
await win.webContents.executeJavaScript(
`Array.from(document.querySelectorAll('.el-message-box__btns button')).find(b=>b.textContent.trim()==='删除对话').click()`,
);
assert(
await waitFor(
win,
`!document.querySelector('.assistant-step') && !document.querySelector('.assistant-message')`,
),
);
assert(!(await request('/ai/conversations')).some((c) => c.id === current.id));
assert.equal((await request('/homeworks?keyword=' + encodeURIComponent(title))).length, 1);
assert(
(await request('/class-plans?classId=' + encodeURIComponent(cls.id))).some((p) => p.id === day.id),
);
await request('/class-plans/' + day.id, 'DELETE');
await request('/time-layouts/' + layout.id, 'DELETE');
record('界面可以确认删除当前对话,轮次消失,已执行作业保留且待确认课表未删除', true);
const cachedBefore = await request('/update/client/releases');
const cacheVersion = `0.0.0-ai-${Date.now()}`;
const cacheTask = JSON.stringify({
+2 -2
View File
@@ -104,9 +104,9 @@ const child = spawn(executable, [entry], {
}),
});
const timeout = setTimeout(() => {
console.error('[ui-smoke] 后台验收超过 120 秒,终止验证进程');
console.error('[ui-smoke] 后台验收超过 180 秒,终止验证进程');
child.kill();
}, 120_000);
}, 180_000);
child.on('exit', async (code) => {
clearTimeout(timeout);
+55
View File
@@ -0,0 +1,55 @@
/** 真实模型回复解析器的快速回归;不加载业务库,不访问模型服务。 */
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const assert = require('node:assert/strict');
const ts = require('typescript');
const { createRequire } = require('node:module');
const requireServer = createRequire(path.resolve(__dirname, '../packages/server/package.json'));
const output = {};
const source = fs.readFileSync(
path.resolve(__dirname, '../packages/server/src/modules/ai/model-reply.ts'),
'utf8',
);
vm.runInNewContext(
ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText,
{ exports: output, require: requireServer },
);
const parse = output.parseModelReply;
for (const sample of [
'请确认是否删除“周一课表”?确认后我会继续。',
JSON.stringify({ message: '请确认是否删除“周一课表”?', queries: [], operations: [] }),
JSON.stringify({ questions: [{ question: '要删除哪张课表?', options: ['周一', '周五'] }] }),
JSON.stringify({ question: '请选择要删除的课表。' }),
JSON.stringify({ questions: ['请选择要删除的课表。'] }),
JSON.stringify({
questions: [{ text: '请选择课表', options: [{ label: '周一', description: '每周一' }] }],
}),
JSON.stringify('Would you like to continue?'),
]) {
const reply = parse(sample);
assert(reply.questions.length > 0);
assert.equal(reply.operations.length, 0);
assert.equal(reply.queries.length, 0);
}
assert(parse('请确认是否删除课表?').questions[0].options.includes('继续生成操作预览'));
const deletion = {
message: '请确认删除',
operations: [{ action: 'plans.delete', target: { id: 'existing-plan' } }],
};
const plan = parse(JSON.stringify(deletion));
assert.equal(plan.operations[0].target.id, 'existing-plan');
assert(!plan.questions?.length);
const mixed = parse(JSON.stringify({ ...deletion, questions: [{ text: '请选择课表' }] }));
assert.equal(mixed.operations.length, 0);
for (const sample of [
'空白',
'已删除课表。',
'{"message":"确认删除吗?"',
'{"operations":[{"action":"plans.delete","target":{"id":10}}]}',
'{"operations":{}}',
])
assert.throws(() => parse(sample));
console.log('PASS:追问兼容、删除预览保留、问题优先及损坏协议拒绝');
+18 -5
View File
@@ -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('拒绝清理工作区外路径');