feat: 统一两端界面并扩展受权限约束的AI助手

This commit is contained in:
LoveChengke committed 2026-11-07 16:27:38 +08:00
1 parent 79a31ebe9d
commit 0b35a58f07
141 files changed
+7999 -2213

No files matched your search

@@ -1,3 +1,4 @@
import '@classhelper/ui/tokens.css';
import { createApp } from 'vue';
import IslandApp from './LayoutIslandApp.vue';
import { applyMotionTokens } from '../renderer/composables/motion.js';
@@ -38,6 +38,7 @@ interface PersistedConfig {
homeworkPhrases?: string[];
/** 是否已看过初次启动引导(向后兼容:旧配置没有该字段视为没看过,首启弹一次) */
onboardingDone?: boolean;
onboardingVersion?: number;
/** 界面主题(向后兼容:旧配置没有该字段用浅色) */
theme?: 'light' | 'dark';
/** 主侧边栏是否折叠(向后兼容:旧配置没有该字段视为展开) */
@@ -69,6 +70,7 @@ const DEFAULT_CONFIG: PersistedConfig = {
homeworkBoard: { ...DEFAULT_HOMEWORK_BOARD },
homeworkPhrases: [...HOMEWORK_PHRASE_DEFAULTS],
onboardingDone: false,
onboardingVersion: 0,
theme: 'light',
sidebarCollapsed: false,
ignoredUpdateVersion: '',
@@ -210,6 +212,7 @@ function readPersistedFromDisk(): PersistedConfig {
homeworkBoard: normalizeHomeworkBoard(parsed.homeworkBoard),
homeworkPhrases: normalizeHomeworkPhrases(parsed.homeworkPhrases),
onboardingDone: parsed.onboardingDone === true,
onboardingVersion: Number.isInteger(parsed.onboardingVersion) ? Number(parsed.onboardingVersion) : 0,
theme: normalizeTheme(parsed.theme),
sidebarCollapsed: parsed.sidebarCollapsed === true,
ignoredUpdateVersion:
@@ -373,6 +376,7 @@ function toDesktopConfig(state: ConfigCache): DesktopStoredConfig {
homeworkBoard: normalizeHomeworkBoard(persisted.homeworkBoard),
homeworkPhrases: normalizeHomeworkPhrases(persisted.homeworkPhrases),
onboardingDone: persisted.onboardingDone === true,
onboardingVersion: persisted.onboardingVersion ?? 0,
theme: normalizeTheme(persisted.theme),
sidebarCollapsed: persisted.sidebarCollapsed === true,
ignoredUpdateVersion: persisted.ignoredUpdateVersion ?? '',
@@ -460,6 +464,11 @@ export function saveConfig(patch: Partial<DesktopStoredConfig>): DesktopStoredCo
if (patch.onboardingDone === true) {
persisted.onboardingDone = true;
}
if (
Number.isInteger(patch.onboardingVersion) &&
Number(patch.onboardingVersion) > (persisted.onboardingVersion ?? 0)
)
persisted.onboardingVersion = Number(patch.onboardingVersion);
if (patch.theme !== undefined) {
persisted.theme = normalizeTheme(patch.theme);
}
@@ -265,7 +265,7 @@ export async function verifyLayoutSmoke(
await editor.webContents.executeJavaScript(`document.querySelector('[aria-label="新建方案"]').click()`);
await pause();
await editor.webContents.executeJavaScript(
`(() => { const input=document.querySelector('.el-message-box__input input'); input.value='组件方案验收';input.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('.el-message-box__btns .el-button--primary').click(); })()`,
`(() => { 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('新建方案没有保存');
@@ -274,7 +274,7 @@ export async function verifyLayoutSmoke(
);
await pause();
await editor.webContents.executeJavaScript(
`document.querySelector('.el-message-box__btns .el-button--primary').click()`,
`[...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()`);
@@ -284,14 +284,26 @@ export async function verifyLayoutSmoke(
);
await pause();
await editor.webContents.executeJavaScript(
`document.querySelector('.el-message-box__btns .el-button--primary').click()`,
`[...document.querySelectorAll('.el-message-box__btns .el-button--primary')].filter(e=>e.getBoundingClientRect().width>0).at(-1).click()`,
);
await pause();
return (
const restored =
getConfig().islandLayout.schemes.length === 1 &&
getConfig().islandLayout.activeSchemeId === 'default' &&
getConfig().islandLayout.schemes[0]!.rows.length === 2
);
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()`);
@@ -329,10 +341,22 @@ export async function verifyLayoutSmoke(
);
await pause();
await editor.webContents.executeJavaScript(
`document.querySelector('.el-message-box__btns .el-button--primary').click()`,
`[...document.querySelectorAll('.el-message-box__btns .el-button--primary')].filter(e=>e.getBoundingClientRect().width>0).at(-1).click()`,
);
await pause();
return preserved && getConfig().islandLayout.schemes.length === 1;
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`);
+4 -2
View File
@@ -3078,7 +3078,9 @@ async function runIslandChecks(
`${islandStateSummary()}`,
);
// 10.7) 视觉风格:纯黑 / 毛玻璃(亚克力)/ 主题色渐变,切换立即生效
// 消息使用实色底;先清空消息,单独验证用户设置的三种基础风格。
await drainIsland();
await sleep(260);
const probeStyle = async (style: IslandAppearance['style']): Promise<{ fill: string; stroke: string }> => {
island.setAppearance({ ...appearanceBefore, style });
await sleep(260);
@@ -3102,7 +3104,7 @@ async function runIslandChecks(
const glassStyle = await probeStyle('glass');
const tintedStyle = await probeStyle('tinted');
record(
'视觉风格切换立刻生效(纯黑 / 毛玻璃半透明 / 主题色)',
'无消息时视觉风格切换立刻生效(纯黑 / 毛玻璃半透明 / 主题色)',
blackStyle.fill === 'rgb(0, 0, 0)' &&
glassStyle.fill.startsWith('rgba(32, 32, 36') &&
tintedStyle.fill === 'rgb(11, 11, 15)',
+3 -2
View File
@@ -13,6 +13,7 @@ import {
import OnboardingWelcome from './components/OnboardingWelcome.vue';
import { useAppStore } from './stores/app.js';
import { useAuthStore } from './stores/auth.js';
import { ONBOARDING_VERSION } from '@classhelper/ui';
import { useOnboardingStore } from './stores/onboarding.js';
import { useRealtimeStore } from './stores/realtime.js';
import { useUiStore } from './stores/ui.js';
@@ -123,13 +124,13 @@ onMounted(async () => {
if (auth.isAuthenticated) await router.replace('/schedule');
else await router.replace('/login');
// 初次启动引导:配置里没记「已看过」就自动弹一次(完成/跳过后由引导组件写入配置)。
// 引导按版本展示,完成或跳过后记住当前版本。
// 稍等一拍再弹:让登录页/主界面先渲染完,避免和启动过渡的收尾抢帧。
window.setTimeout(() => {
void window.desktop
?.getConfig()
.then((config) => {
if (config.onboardingDone !== true) onboarding.open();
if ((config.onboardingVersion ?? 0) < ONBOARDING_VERSION) onboarding.open();
})
.catch(() => undefined);
}, 400);
@@ -67,8 +67,15 @@ export const homeworkApi = {
date?: string;
}): Promise<HomeworkDto[]> => api.get(API_PATHS.homeworks, params),
/** 哪些天有作业(日期选择器高亮) */
days: (params: { classId?: string; from?: string; to?: string; days?: number }): Promise<HomeworkDaysDto> =>
api.get(`${API_PATHS.homeworks}/days`, params),
days: (params: {
classId?: string;
courseId?: string;
keyword?: string;
pendingOnly?: boolean;
from?: string;
to?: string;
days?: number;
}): Promise<HomeworkDaysDto> => api.get(`${API_PATHS.homeworks}/days`, params),
/** 在教室机器上直接录入作业(班级账号可调用;也可选所属日期) */
create: (payload: {
classId: string;
@@ -88,8 +95,21 @@ export const homeworkApi = {
};
export const notificationApi = {
list: (params?: { classId?: string; unreadOnly?: boolean }): Promise<NotificationDto[]> =>
api.get(API_PATHS.notifications, params),
days: (params: {
classId?: string;
from?: string;
to?: string;
createdBy?: string;
priority?: string;
unreadOnly?: boolean;
}): Promise<{ days: { date: string; count: number }[] }> => api.get('/notifications/days', params),
list: (params?: {
classId?: string;
unreadOnly?: boolean;
date?: string;
createdBy?: string;
priority?: string;
}): Promise<NotificationDto[]> => api.get(API_PATHS.notifications, params),
unreadCount: (): Promise<{ count: number }> => api.get(`${API_PATHS.notifications}/unread-count`),
// id 来自服务端或灵动岛(作业卡是本地合成的 `homework-…`),一律 encodeURIComponent:
// 否则含 `/` 或 `..` 的 id 会改变实际请求的路径
+9 -12
View File
@@ -885,14 +885,7 @@ export async function islandHomeworkSuppressionCheck(): Promise<SmokeCheckResult
}
}
/**
* 冒烟自检(不需要后端):**初次启动引导**。
*
* 冒烟每次都用全新配置目录(等于"首次启动"),因此引导必须自动弹出;
* 这里真实点击把它一步步走完,断言:遮罩关闭 + `onboardingDone` 已写入配置。
* 关闭判据用「元素从 DOM 消失」——引导是 v-if 自绘遮罩(特意不用 el-dialog,
* 避免"关闭后 DOM 残留在文档里"的误报,见 AGENTS §7 第 22 条)。
*/
/** 全新配置首次展示全屏引导,完成后保存版本标记。 */
export async function onboardingSelfTest(): Promise<SmokeCheckResult> {
try {
// 引导在启动后延迟 ~400ms 弹出,这里轮询等它出现
@@ -908,7 +901,10 @@ export async function onboardingSelfTest(): Promise<SmokeCheckResult> {
};
}
// 逐页「下一步」到最后一页再点「开始使用」(按钮由 data-action 标识,不依赖文案)
const guide = document.querySelector<HTMLElement>('.ch-guide')!;
const bounds = guide.getBoundingClientRect();
const fullscreen = Math.abs(bounds.width - innerWidth) < 2 && Math.abs(bounds.height - innerHeight) < 2;
const focused = guide.contains(document.activeElement);
const clicks: string[] = [];
for (let attempt = 0; attempt < 12; attempt += 1) {
const action = document.querySelector('.onboarding-welcome [data-action="finish"]') ? 'finish' : 'next';
@@ -928,10 +924,11 @@ export async function onboardingSelfTest(): Promise<SmokeCheckResult> {
}
const config = await window.desktop?.getConfig?.();
const done = config?.onboardingDone === true;
const { ONBOARDING_VERSION } = await import('@classhelper/ui');
const done = config?.onboardingDone === true && config.onboardingVersion === ONBOARDING_VERSION;
return {
ok: closed && done,
detail: `步骤点击=[${clicks.join(',')}] 已关闭=${closed} onboardingDone=${config?.onboardingDone ?? '-'}`,
ok: closed && done && fullscreen && focused,
detail: `步骤点击=[${clicks.join(',')}] 全屏=${fullscreen} 焦点=${focused} 已关闭=${closed} 引导版本=${config?.onboardingVersion ?? '-'}`,
};
} catch (error) {
return {
@@ -52,7 +52,7 @@ const containers = ['group', 'stack', 'slide', 'rolling'] as const;
<el-input v-model="node.settings.countdownTitle" :maxlength="64" @change="emit('change')" />
</el-form-item>
<el-form-item label="目标日期">
<el-date-picker
<ch-date-picker
v-model="node.settings.targetDate"
type="date"
value-format="YYYY-MM-DD"
@@ -1,309 +1,59 @@
<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from 'vue';
import { FullScreenGuide, ONBOARDING_VERSION } from '@classhelper/ui';
import { useOnboardingStore } from '../stores/onboarding.js';
/**
* 初次启动引导(六步向导)。
*
* - 首次启动自动弹出(App.vue 按 `onboardingDone` 判定);完成 / 跳过(右上角按钮 / Esc)
* 都算看过,由这里写入主进程配置,之后不再自动弹出。
* - 登录页与设置页的「使用引导」入口可随时重看(重看关闭时再写一次也无副作用)。
* - **用 v-if 自绘遮罩而不是 el-dialog**:关闭即从 DOM 卸载。冒烟断言"引导已关闭"时
* 不会踩 el-dialog「DOM 残留在文档里」的坑(AGENTS §7 第 22 条)。
* - 操作按钮用 `data-action` 标识(prev/next/finish/skip),冒烟点击不依赖按钮文案。
*/
import { BRAND_LOGO_URL } from '../config.js';
const onboarding = useOnboardingStore();
const steps = [
{
icon: 'School',
title: '欢迎使用 ClassHelper',
lines: [
'这台电脑将以「班级」的身份使用 ClassHelper:实时接收课表、作业、通知与成绩。',
'第一次使用,先花半分钟看看怎么开始。',
],
id: 'server',
title: '连接学校服务器',
text: '填写管理员提供的服务器地址,测试连接后继续。',
example: ['服务器地址', '测试连接', '连接成功'],
},
{
icon: 'Link',
title: '第一步 · 连接服务器',
lines: [
'在登录页填写老师或管理员提供的服务器地址(通常形如 http://192.168.x.x:4000)。',
'点「测试连接」确认可达;以后也能在「设置」里随时修改。',
],
id: 'login',
title: '登录班级',
text: '使用班级码和班级密码登录,这台设备将代表本班。',
example: ['班级码', '班级密码', '登录'],
},
{
icon: 'Key',
title: '第二步 · 登录班级',
lines: [
'使用班级码 + 班级密码登录(向老师或管理员索取)。',
'登录后这台设备就代表全班:作业完成、通知已读都会按全班记录,不需要每个学生单独登录。',
],
id: 'teaching',
title: '查看课表与作业',
text: '从菜单切换页面,用日历查找记录;断网时可查看已缓存的内容。',
example: ['今日课表', '作业看板', '日期下方的圆点 ·'],
},
{
icon: 'Calendar',
title: '登录之后',
lines: [
'左侧菜单切换「课表 / 作业 / 通知 / 成绩」四个页面,作业支持看板全屏展示。',
'断网时自动显示最近同步的缓存数据,联网后自动更新。',
],
id: 'files',
title: '接收通知与课件',
text: '新内容自动同步,课件下载后由你选择如何打开。',
example: ['班级通知', '课件传输进度', '打开所在文件夹'],
},
{
icon: 'Bell',
title: '灵动岛提醒',
lines: [
'屏幕上方会有一条「灵动岛」浮窗:新通知、叫人、作业都会在那里弹出。',
'上课时段自动隐藏、下课自动弹出;外观与位置可在「设置 → 灵动岛」调整。',
],
id: 'island',
title: '选择灵动岛模式',
text: '经典模式自动呈现提醒;常驻模式先显示消息数量,由你展开查看。',
example: ['经典模式', '自定义常驻模式', '设置 → 灵动岛'],
},
{
icon: 'CircleCheckFilled',
id: 'settings',
title: '准备好了',
lines: [
'按上面的步骤登录就可以开始使用了。',
'侧边栏「设置」分组里有通用、外观(深色模式)、灵动岛等页面;这份引导可以在登录页或「设置 → 通用 → 使用引导」随时重看。',
],
text: '在设置中调整外观和关怀模式,也可以随时重看引导。',
example: ['通用设置', '外观', '使用引导'],
},
];
const index = ref(0);
const current = computed(() => steps[index.value] ?? steps[0]);
const isFirst = computed(() => index.value === 0);
const isLast = computed(() => index.value === steps.length - 1);
/** 每次打开都从第一步开始(重看入口也走完整流程) */
watch(
() => onboarding.visible,
(visible) => {
if (visible) index.value = 0;
},
);
function goNext(): void {
if (isLast.value) finish();
else index.value += 1;
}
function goPrev(): void {
if (!isFirst.value) index.value -= 1;
}
/** 完成 / 跳过统一走这里:记「已看过」并关闭(重看时重复写一次无副作用) */
function finish(): void {
const bridge = window.desktop;
// 桥接不可用(浏览器调试)也要能正常关掉引导
if (!bridge) {
async function finish(): Promise<void> {
try {
await window.desktop?.saveConfig({ onboardingDone: true, onboardingVersion: ONBOARDING_VERSION });
} finally {
onboarding.close();
return;
}
void bridge
.saveConfig({ onboardingDone: true })
.then(() => onboarding.close())
.catch(() => onboarding.close());
}
function onKeydown(event: KeyboardEvent): void {
if (onboarding.visible && event.key === 'Escape') finish();
}
if (typeof window !== 'undefined') {
window.addEventListener('keydown', onKeydown);
}
onUnmounted(() => {
window.removeEventListener('keydown', onKeydown);
});
</script>
<template>
<Transition name="onboarding-fade">
<div
v-if="onboarding.visible"
class="onboarding-mask"
role="dialog"
aria-modal="true"
aria-label="初次启动引导"
>
<div class="onboarding-card onboarding-welcome">
<div class="onboarding-head">
<span class="onboarding-logo">
<el-icon :size="18"><School /></el-icon>
</span>
<div class="onboarding-heading">
<h2 class="onboarding-title">ClassHelper</h2>
<p class="onboarding-sub">初次启动引导 · 第 {{ index + 1 }} / {{ steps.length }} 步</p>
</div>
<el-button link class="onboarding-skip" data-action="skip" @click="finish">跳过引导</el-button>
</div>
<div class="onboarding-body">
<span class="onboarding-icon">
<el-icon :size="30"><component :is="current.icon" /></el-icon>
</span>
<h3 class="onboarding-step-title">{{ current.title }}</h3>
<p v-for="(line, lineIndex) in current.lines" :key="lineIndex" class="onboarding-line">
{{ line }}
</p>
</div>
<div class="onboarding-foot">
<div class="onboarding-dots">
<span
v-for="(step, dotIndex) in steps"
:key="dotIndex"
class="dot"
:class="{ active: dotIndex === index }"
/>
</div>
<div class="onboarding-actions">
<el-button v-if="!isFirst" data-action="prev" @click="goPrev">上一步</el-button>
<el-button v-if="!isLast" type="primary" data-action="next" @click="goNext">下一步</el-button>
<el-button v-else type="primary" data-action="finish" @click="finish">开始使用</el-button>
</div>
</div>
</div>
</div>
</Transition>
<FullScreenGuide
:model-value="onboarding.visible"
:steps="steps"
:brand-logo="BRAND_LOGO_URL"
@finish="finish"
/>
</template>
<style scoped>
.onboarding-mask {
position: fixed;
inset: 0;
z-index: 3000;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(15, 30, 50, 0.55);
}
.onboarding-card {
width: 520px;
max-width: 92vw;
max-height: 86vh;
overflow-y: auto;
background: var(--ch-layer-solid);
border-radius: 16px;
padding: 22px 24px 18px;
box-shadow: 0 24px 64px rgba(15, 30, 50, 0.35);
}
.onboarding-head {
display: flex;
align-items: center;
gap: 10px;
}
.onboarding-logo {
display: inline-flex;
align-items: center;
justify-content: center;
width: 34px;
height: 34px;
border-radius: 9px;
color: #fff;
background: linear-gradient(135deg, var(--ch-accent) 0%, #4d94d1 100%);
}
.onboarding-heading {
flex: 1;
min-width: 0;
}
.onboarding-title {
margin: 0;
font-size: 15px;
line-height: 1.3;
}
.onboarding-sub {
margin: 2px 0 0;
font-size: 12px;
color: var(--ch-text-tertiary);
}
.onboarding-body {
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 18px 4px 6px;
}
.onboarding-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 58px;
height: 58px;
border-radius: 16px;
margin-bottom: 14px;
color: var(--ch-accent);
background: var(--ch-accent-soft);
}
.onboarding-step-title {
margin: 0 0 10px;
font-size: 18px;
}
.onboarding-line {
margin: 0 0 8px;
font-size: 13px;
line-height: 1.8;
color: var(--ch-text-secondary);
}
.onboarding-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--ch-divider);
}
.onboarding-dots {
display: flex;
align-items: center;
gap: 6px;
}
.dot {
width: 7px;
height: 7px;
border-radius: 999px;
background: var(--ch-border-strong);
transition: all 0.2s ease;
}
.dot.active {
width: 20px;
background: var(--ch-accent);
}
.onboarding-actions {
display: flex;
align-items: center;
gap: 8px;
}
/* 进出场:淡入 + 轻微上浮,跟随系统"动画"开关无强依赖 */
.onboarding-fade-enter-active,
.onboarding-fade-leave-active {
transition: opacity 0.22s ease;
}
.onboarding-fade-enter-active .onboarding-card,
.onboarding-fade-leave-active .onboarding-card {
transition: transform 0.22s ease;
}
.onboarding-fade-enter-from,
.onboarding-fade-leave-to {
opacity: 0;
}
.onboarding-fade-enter-from .onboarding-card,
.onboarding-fade-leave-to .onboarding-card {
transform: translateY(10px) scale(0.98);
}
</style>
@@ -11,6 +11,8 @@ import router from './router/index.js';
import { registerAppIcons } from './icons.js';
import { applyMotionTokens } from './composables/motion.js';
import './styles/index.css';
import { registerSharedUi } from '@classhelper/ui';
import '@classhelper/ui/theme.css';
const app = createApp(App);
@@ -20,6 +22,7 @@ registerAppIcons(app);
app.use(createPinia());
app.use(router);
app.use(ElementPlus, { locale: zhCn });
registerSharedUi(app);
// 冒烟验证模式:把缓存自检钩子暴露给主进程调用(正常运行时不存在)。
//
@@ -1,14 +1,7 @@
import { ref } from 'vue';
import { defineStore } from 'pinia';
/**
* 初次启动引导的显示状态。
*
* 首次启动由 App.vue 按「配置里是否记过 onboardingDone」自动弹出;
* 登录页与设置页的「使用引导」入口调用 open() 随时重看。
* 单独一个 store 而不是组件内部 ref:触发入口(登录页 / 设置页)与
* 渲染点(App.vue 顶层)分处两棵互不相干的子树。
*/
/** App.vue 按引导版本自动展示;登录页和设置页可随时重看。 */
export const useOnboardingStore = defineStore('onboarding', () => {
const visible = ref(false);
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { countDates } from '@classhelper/ui';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import {
@@ -14,24 +15,15 @@ import { useRealtimeStore } from '../stores/realtime.js';
const realtime = useRealtimeStore();
const localItems = ref<CoursewareDto[]>([]),
library = ref<'shared' | 'local'>('shared'),
teacher = ref(''),
archive = ref('');
teacher = ref('');
const source = computed(() => (library.value === 'local' ? localItems.value : items.value));
const teachers = computed(() => [...new Set(source.value.map((item) => item.teacher.name))]);
const archiveFolders = computed(() => [
...new Set(
source.value
.filter((item) => !teacher.value || item.teacher.name === teacher.value)
.map((item) => item.archivePath?.split('/').slice(0, -1).join('/') || item.archiveDate),
),
]);
async function refreshLocal() {
localItems.value = (await window.desktop?.listLocalCourseware()) || [];
}
// 两个来源的教师与目录不通用,切换时清空,避免看到空列表却找不到原因。
watch(library, () => {
teacher.value = '';
archive.value = '';
});
const items = ref<CoursewareDto[]>([]),
loading = ref(false),
@@ -42,17 +34,18 @@ const query = ref(''),
date = ref(''),
busy = ref<string[]>([]),
transfer = ref<CoursewareTransfer | null>(null);
const filtered = computed(() =>
const dateSource = computed(() =>
source.value.filter(
(item) =>
(!query.value || `${item.name} ${item.teacher.name}`.includes(query.value)) &&
(!category.value || item.category === category.value) &&
(!teacher.value || item.teacher.name === teacher.value) &&
(!archive.value ||
(item.archivePath?.startsWith(archive.value + '/') ?? item.archiveDate === archive.value)) &&
(!date.value || item.archiveDate === date.value),
(!teacher.value || item.teacher.name === teacher.value),
),
);
const dateMarks = computed(() => countDates(dateSource.value, (item) => item.archiveDate));
const filtered = computed(() =>
dateSource.value.filter((item) => !date.value || item.archiveDate === date.value),
);
let disposed = false;
async function refresh() {
await refreshLocal();
@@ -153,17 +146,14 @@ onUnmounted(() => {
<el-radio-button value="shared">班级共享</el-radio-button>
<el-radio-button value="local">本机归档</el-radio-button>
</el-radio-group>
<el-select v-model="teacher" clearable placeholder="全部教师" @change="archive = ''">
<el-select v-model="teacher" clearable placeholder="全部教师">
<el-option v-for="name in teachers" :key="name" :label="name" :value="name" />
</el-select>
<el-select v-model="archive" clearable filterable placeholder="年 / 月 / 日 / 时间">
<el-option v-for="folder in archiveFolders" :key="folder" :label="folder" :value="folder" />
</el-select>
<el-input v-model="query" clearable placeholder="搜索课件或教师" />
<el-select v-model="category" clearable placeholder="全部类型">
<el-option v-for="(label, key) in COURSEWARE_CATEGORIES" :key="key" :label="label" :value="key" />
</el-select>
<el-date-picker v-model="date" value-format="YYYY-MM-DD" placeholder="归档日期" />
<ch-date-picker v-model="date" :marks="dateMarks" value-format="YYYY-MM-DD" placeholder="归档日期" />
</div>
<el-card shadow="never" class="table-card" v-loading="loading">
<el-table
@@ -1,4 +1,6 @@
<script setup lang="ts">
import { getCacheScope } from '../cache/scope.js';
import type { CalendarRange } from '@classhelper/ui';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
@@ -60,19 +62,13 @@ const selectedDate = ref(
? route.query.date
: dayKeyLocal(new Date()),
);
/** 有作业的日期(日期选择器高亮):来自 GET /homeworks/days */
const dayMarks = ref<Map<string, number>>(new Map());
const calendarRevision = ref(0);
/** 录入作业的科目下拉 */
const courses = ref<CourseDto[]>([]);
/** 选中的是否就是今天(标题与按钮文案用) */
const isToday = computed(() => selectedDate.value === dayKeyLocal(now.value));
/** 日期选择器:给有作业的日期加高亮类 */
function dayCellClass(date: Date): string {
return dayMarks.value.has(dayKeyLocal(date)) ? 'day-has-homework' : '';
}
async function selectDate(value: string | null): Promise<void> {
if (!value || !isDayKey(value)) return;
selectedDate.value = value;
@@ -279,6 +275,7 @@ function onResize(): void {
/* ------------------------------------------------------------ 数据加载 */
async function loadHomework(): Promise<void> {
calendarRevision.value++;
loading.value = true;
try {
const classId = auth.classId ?? undefined;
@@ -294,7 +291,6 @@ async function loadHomework(): Promise<void> {
fromCache.value = result.fromCache;
updatedAt.value = result.updatedAt;
if (!result.fromCache) appStore.markSynced();
void loadDayMarks(classId);
if (current.value) {
current.value = homeworks.value.find((item) => item.id === current.value?.id) ?? current.value;
}
@@ -304,22 +300,15 @@ async function loadHomework(): Promise<void> {
}
}
/**
* 拉取"哪些天有作业"(日期选择器高亮)。
*
* 范围取当前查看日期前后各 45 天:教室电脑上翻月份也能看到有作业的日子。
*/
async function loadDayMarks(classId: string | undefined): Promise<void> {
try {
const from = shiftDayKey(selectedDate.value, -45);
const to = shiftDayKey(selectedDate.value, 45);
const result = await homeworkApi.days({ classId, from, to });
dayMarks.value = new Map(result.days.map((item) => [item.date, item.count]));
} catch {
// 离线/失败时保留上一次的高亮,不打断展示
}
async function calendarDays(range: CalendarRange) {
const result = await fetchWithCache(
'homeworks',
`days:${JSON.stringify(range)}`,
() => homeworkApi.days({ ...range, classId: auth.classId || undefined }),
{ days: [] as { date: string; count: number }[] },
);
return result.data.days;
}
/** 科目下拉(录入作业时可选) */
async function loadCourses(): Promise<void> {
if (!auth.classId) return;
@@ -569,15 +558,19 @@ onUnmounted(() => {
<el-button-group>
<el-button :icon="'ArrowLeft'" @click="shiftDate(-1)">前一天</el-button>
<el-button :disabled="isToday" @click="selectDate(dayKeyLocal(now))">今天</el-button>
<el-button @click="shiftDate(1)">后一天<el-icon class="ml-4"><ArrowRight /></el-icon></el-button>
<el-button @click="shiftDate(1)">
后一天
<el-icon class="ml-4"><ArrowRight /></el-icon>
</el-button>
</el-button-group>
<el-date-picker
<ch-date-picker
:model-value="selectedDate"
type="date"
value-format="YYYY-MM-DD"
placeholder="选择日期"
class="day-picker"
:cell-class-name="dayCellClass"
:load-marks="calendarDays"
:scope-key="JSON.stringify([getCacheScope(), selectedDate, calendarRevision])"
@update:model-value="(value: string | null) => selectDate(value)"
/>
<el-radio-group v-model="viewMode" @change="saveBoardSettings">
@@ -765,11 +758,12 @@ onUnmounted(() => {
<el-dialog v-model="createVisible" title="录入作业" width="620px">
<el-form label-width="90px">
<el-form-item label="所属日期">
<el-date-picker
<ch-date-picker
:model-value="selectedDate"
type="date"
value-format="YYYY-MM-DD"
:cell-class-name="dayCellClass"
:load-marks="calendarDays"
:scope-key="JSON.stringify([getCacheScope(), calendarRevision])"
@update:model-value="(value: string | null) => selectDate(value)"
/>
<span class="text-muted ml-8">默认就是当前正在查看的这一天</span>
@@ -810,7 +804,9 @@ onUnmounted(() => {
>
{{ item }}
</el-tag>
<span class="text-muted">点一下追加到「{{ lastFocused === 'title' ? '标题' : '作业要求' }}」</span>
<span class="text-muted">
点一下追加到「{{ lastFocused === 'title' ? '标题' : '作业要求' }}」
</span>
</div>
</el-form-item>
</el-form>
@@ -880,19 +876,6 @@ onUnmounted(() => {
</template>
<style scoped>
/* 日期选择器:有作业的日子加一个圆点,翻月份时一眼看出哪天有作业 */
:deep(.day-has-homework .el-date-table-cell__text)::after {
content: '';
position: absolute;
left: 50%;
bottom: 2px;
width: 4px;
height: 4px;
margin-left: -2px;
border-radius: 50%;
background: currentColor;
}
.day-picker {
width: 168px;
}
@@ -1,5 +1,11 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { notificationApi } from '../api/index.js';
import { fetchWithCache } from '../cache/index.js';
import { getCacheScope } from '../cache/scope.js';
import { useAuthStore } from '../stores/auth.js';
import type { CalendarRange } from '@classhelper/ui';
import { countDates } from '@classhelper/ui';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import {
NOTIFICATION_PRIORITIES,
@@ -22,21 +28,70 @@ const filter = ref<'all' | 'unread'>('all');
const detailVisible = ref(false);
const current = ref<NotificationDto | null>(null);
const marking = ref(false);
const auth = useAuthStore();
const calendarRevision = ref(0);
const dayItems = ref<NotificationDto[] | null>(null);
let calendarRequest = 0,
disposed = false;
async function calendarDays(range: CalendarRange) {
const params = {
...range,
classId: auth.classId || undefined,
createdBy: creatorFilter.value || undefined,
priority: priorityFilter.value || undefined,
unreadOnly: filter.value === 'unread',
};
const result = await fetchWithCache(
'notifications',
'days:' + JSON.stringify(params),
() => notificationApi.days(params),
{ days: dateMarks.value },
);
return result.data.days;
}
async function loadDay(): Promise<void> {
const request = ++calendarRequest,
scope = getCacheScope();
if (!dayFilter.value) {
dayItems.value = null;
return;
}
const params = {
date: dayFilter.value,
classId: auth.classId || undefined,
createdBy: creatorFilter.value || undefined,
priority: priorityFilter.value || undefined,
unreadOnly: filter.value === 'unread',
};
const fallback = store.items.filter((item) => assignDay(item) === params.date);
dayItems.value = [];
const result = await fetchWithCache<NotificationDto[]>(
'notifications',
'date:' + JSON.stringify(params),
() => notificationApi.list(params),
fallback,
);
if (!disposed && request === calendarRequest && scope === getCacheScope()) dayItems.value = result.data;
}
const visibleItems = computed(() =>
filter.value === 'unread' ? store.items.filter((item) => !item.read) : store.items,
filter.value === 'unread'
? (dayItems.value ?? store.items).filter((item) => !item.read)
: (dayItems.value ?? store.items),
);
/* ------------------------------------------------------- 按天归档 / 按发布人 / 按类型 */
/**
* 三个筛选都在**已加载的列表**上做,不再请求服务端:
* 客户端是离线优先的(AGENTS.md 的现行工程约定),断网回退缓存时归档功能必须照常可用。
* 口径与服务端一致:按 `assignDate`(本地日期)分组 —— 用 createdAt 的 UTC 切片会把晚上
* 发出来的通知算到第二天(AGENTS.md 的现行工程约定)。
*/
watch(
() => store.items,
() => {
calendarRevision.value++;
},
);
const dayFilter = ref('');
const creatorFilter = ref('');
const priorityFilter = ref('');
watch([dayFilter, creatorFilter, priorityFilter, filter, () => store.items], () => {
void loadDay();
});
/**
* 一条通知归到哪一天。
@@ -47,16 +102,17 @@ function assignDay(item: NotificationDto): string {
return item.assignDate || dayKeyLocal(new Date(item.createdAt));
}
const dayOptions = computed(() => {
const map = new Map<string, number>();
for (const item of store.items) {
const day = assignDay(item);
map.set(day, (map.get(day) ?? 0) + 1);
}
return [...map.entries()]
.sort((a, b) => b[0].localeCompare(a[0]))
.map(([date, count]) => ({ date, count }));
});
const dateMarks = computed(() =>
countDates(
store.items.filter(
(item) =>
(filter.value !== 'unread' || !item.read) &&
(!creatorFilter.value || item.createdBy === creatorFilter.value) &&
(!priorityFilter.value || item.priority === priorityFilter.value),
),
assignDay,
),
);
const creatorOptions = computed(() => {
const map = new Map<string, { name: string; count: number }>();
@@ -117,6 +173,7 @@ async function markRead(item: NotificationDto): Promise<void> {
marking.value = true;
try {
await store.markRead(item.id);
item.read = true;
if (current.value?.id === item.id) current.value = { ...item, read: true };
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '标记已读失败');
@@ -147,6 +204,8 @@ onMounted(async () => {
});
onUnmounted(() => {
disposed = true;
++calendarRequest;
// store 是全局的,这里无需清理;保留钩子以便将来取消订阅
});
</script>
@@ -175,16 +234,14 @@ onUnmounted(() => {
</div>
<el-card v-loading="store.loading" shadow="never">
<!-- 按天归档 + 按发布人 + 按类型;都在本地已加载的列表上筛(离线也能用) -->
<div class="notice-filters">
<el-select v-model="dayFilter" placeholder="按天归档" clearable size="small" style="width: 150px">
<el-option
v-for="item in dayOptions"
:key="item.date"
:label="`${item.date}(${item.count})`"
:value="item.date"
/>
</el-select>
<ch-date-picker
v-model="dayFilter"
:load-marks="calendarDays"
:scope-key="JSON.stringify([creatorFilter, priorityFilter, filter, calendarRevision])"
placeholder="日期"
clearable
/>
<el-select
v-model="creatorFilter"
placeholder="全部发布人"
@@ -75,7 +75,6 @@ onMounted(async () => {
<div class="page-header">
<div>
<h2 class="page-title">关于</h2>
<p class="page-subtitle">版本、诊断信息与鸣谢</p>
</div>
</div>
@@ -27,7 +27,6 @@ async function logout(): Promise<void> {
<div class="page-header">
<div>
<h2 class="page-title">账号</h2>
<p class="page-subtitle">本机登录的班级账号</p>
</div>
</div>
@@ -26,7 +26,6 @@ async function selectTheme(value: 'light' | 'dark'): Promise<void> {
<div class="page-header">
<div>
<h2 class="page-title">外观</h2>
<p class="page-subtitle">黑夜与白天模式,切换立即生效并自动保存</p>
</div>
</div>
@@ -50,7 +49,10 @@ async function selectTheme(value: 'light' | 'dark'): Promise<void> {
</span>
</span>
<span class="theme-name">
<el-icon><Sunny v-if="option.value === 'light'" /><Moon v-else /></el-icon>
<el-icon>
<Sunny v-if="option.value === 'light'" />
<Moon v-else />
</el-icon>
{{ option.label }}
</span>
<span class="theme-desc">{{ option.desc }}</span>
@@ -221,7 +221,6 @@ onMounted(async () => {
<div class="page-header">
<div>
<h2 class="page-title">开发者</h2>
<p class="page-subtitle">版本与平台、设备上报、日志、更新与调试工具</p>
</div>
<el-button :loading="loading" data-test="dev-refresh" @click="loadAll">
<el-icon><Refresh /></el-icon>
@@ -308,7 +308,6 @@ onBeforeUnmount(() => {
<div class="page-header">
<div>
<h2 class="page-title">通用</h2>
<p class="page-subtitle">服务器连接、离线缓存与作业录入</p>
</div>
<!-- 重看初次启动引导(首启时由 App.vue 自动弹出过一次) -->
<el-button @click="onboarding.open()">
@@ -149,7 +149,6 @@ onMounted(async () => {
<div class="page-header">
<div>
<h2 class="page-title">灵动岛</h2>
<p class="page-subtitle">自定义组件与 ClassIsland 提醒,共用停靠位置、动画开关与通知规则</p>
</div>
</div>
@@ -49,7 +49,6 @@ onMounted(loadGradeQuery);
<div class="page-header">
<div>
<h2 class="page-title">提醒</h2>
<p class="page-subtitle">通知提醒与成绩查询状态</p>
</div>
</div>
+2 -6
View File
@@ -48,13 +48,9 @@ export interface DesktopStoredConfig {
* 录入作业时点一下就追加到标题/内容里,少打字(例如 P、大本、背诵)。
*/
homeworkPhrases: string[];
/**
* 是否已看过「初次启动引导」。
*
* 首次启动自动弹出一次(完成或跳过即记为看过并写入配置,之后不再自动弹出);
* 登录页与设置页的「使用引导」入口可随时重看(重看不改变该值)。
*/
/** 兼容旧配置;新版引导是否展示由 onboardingVersion 决定。 */
onboardingDone: boolean;
onboardingVersion: number;
/** 界面主题:light=浅色(默认)/ dark=深色(黑夜模式) */
theme: 'light' | 'dark';
/** 主侧边栏是否折叠成图标栏(可由顶栏汉堡按钮切换) */