智能开屏:显示“姓名+早上/中午/下午/晚上问候”,支持春节、端午、中秋、国庆等节日文案,可点击跳过:[SmartLaunchScreen.vue](E:/jiaowu/web/src/components/SmartLaunchScreen.vue)

长按 App 图标:提供“我的课表、考试安排、课堂签到、消息中心”四个入口。签到会按学生/教师角色自动分流:[shortcuts.xml](E:/jiaowu/web/native/android/app/src/main/res/xml/shortcuts.xml)
桌面小组件:新增“今日课表”和“近期考试”,展示最近同步的数据,点击可进入对应页面:[WidgetRenderer.java](E:/jiaowu/web/native/android/app/src/main/java/edu/mingxu/jiaowu/WidgetRenderer.java)
安全处理:组件只缓存课程和考试摘要,不保存登录令牌;退出账号会清空组件,隔天未刷新时不会继续展示旧的“今日课表”。
原生模板已纳入版本管理,每次 npm run cap:sync 会自动恢复到被忽略的 Android 工程:[configure-capacitor.mjs](E:/jiaowu/web/scripts/configure-capacitor.mjs)
This commit is contained in:
2026-07-29 11:11:37 +08:00 Unverified
parent 93997ea8b1
commit 66622ca207
27 changed files with 1304 additions and 5 deletions
+5
View File
@@ -1,3 +1,8 @@
<script setup lang="ts">
import SmartLaunchScreen from './components/SmartLaunchScreen.vue'
</script>
<template>
<SmartLaunchScreen />
<RouterView />
</template>
+1
View File
@@ -55,6 +55,7 @@ declare module 'vue' {
RichMessageContent: typeof import('./components/RichMessageContent.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
SmartLaunchScreen: typeof import('./components/SmartLaunchScreen.vue')['default']
}
export interface GlobalDirectives {
vLoading: typeof import('element-plus/es')['ElLoadingDirective']
+193
View File
@@ -0,0 +1,193 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { Capacitor } from '@capacitor/core'
import { useAuthStore } from '../stores/auth'
import { getSmartGreeting } from '../utils/smartGreeting'
const auth = useAuthStore()
const previewParams = import.meta.env.DEV
? new URLSearchParams(window.location.search)
: null
const previewNative = previewParams?.has('previewLaunch') ?? false
const previewName = previewParams?.get('previewName')
const visible = ref(Capacitor.isNativePlatform() || previewNative)
const leaving = ref(false)
const greeting = computed(() =>
getSmartGreeting(new Date(), previewName || auth.user?.displayName))
let dismissTimer: ReturnType<typeof setTimeout> | null = null
let removeTimer: ReturnType<typeof setTimeout> | null = null
function dismiss() {
if (!visible.value || leaving.value) return
leaving.value = true
removeTimer = setTimeout(() => {
visible.value = false
}, 360)
}
onMounted(() => {
if (!visible.value) return
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
dismissTimer = setTimeout(dismiss, reducedMotion ? 650 : 1800)
})
onBeforeUnmount(() => {
if (dismissTimer) clearTimeout(dismissTimer)
if (removeTimer) clearTimeout(removeTimer)
})
</script>
<template>
<Transition name="smart-launch">
<section
v-if="visible"
class="smart-launch-screen"
:class="{ leaving }"
role="status"
aria-live="polite"
@click="dismiss"
>
<div class="smart-launch-orbit orbit-one" />
<div class="smart-launch-orbit orbit-two" />
<div class="smart-launch-content">
<div class="smart-launch-mark" aria-hidden="true">
<i v-for="index in 9" :key="index" />
</div>
<span class="smart-launch-brand">MINGXU ACADEMIC</span>
<p>{{ greeting.label }}</p>
<h1>{{ greeting.title }}</h1>
<small>{{ greeting.subtitle }}</small>
</div>
<span class="smart-launch-skip">轻触跳过</span>
</section>
</Transition>
</template>
<style scoped>
.smart-launch-screen {
position: fixed;
inset: 0;
z-index: 99999;
display: grid;
place-items: center;
overflow: hidden;
color: #f8fbff;
background:
radial-gradient(circle at 15% 18%, rgb(74 198 193 / 22%), transparent 28rem),
radial-gradient(circle at 88% 78%, rgb(94 132 255 / 24%), transparent 30rem),
linear-gradient(145deg, #081733, #10275c 55%, #163b71);
cursor: pointer;
}
.smart-launch-content {
position: relative;
z-index: 2;
width: min(86vw, 32rem);
text-align: center;
animation: launch-rise 700ms cubic-bezier(.2, .8, .2, 1) both;
}
.smart-launch-mark {
display: grid;
grid-template-columns: repeat(3, 0.72rem);
gap: 0.3rem;
width: fit-content;
margin: 0 auto 1.6rem;
padding: 1rem;
border: 1px solid rgb(255 255 255 / 16%);
border-radius: 1.25rem;
background: rgb(255 255 255 / 8%);
box-shadow: 0 1.3rem 4rem rgb(0 0 0 / 24%);
backdrop-filter: blur(12px);
}
.smart-launch-mark i {
width: 0.72rem;
aspect-ratio: 1;
border-radius: 0.18rem;
background: #6ee7d8;
}
.smart-launch-mark i:nth-child(2n) { background: #9cb8ff; }
.smart-launch-mark i:nth-child(5) { background: #fff; }
.smart-launch-brand {
display: block;
margin-bottom: 1.7rem;
color: #8fe4dc;
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.28em;
}
.smart-launch-content p {
margin: 0 0 0.75rem;
color: rgb(235 244 255 / 72%);
font-size: 0.82rem;
}
.smart-launch-content h1 {
margin: 0;
font-family: "Noto Serif SC", "Songti SC", serif;
font-size: clamp(1.7rem, 7vw, 2.45rem);
font-weight: 600;
letter-spacing: 0.02em;
line-height: 1.35;
}
.smart-launch-content small {
display: block;
max-width: 24rem;
margin: 1rem auto 0;
color: rgb(235 244 255 / 68%);
font-size: 0.85rem;
line-height: 1.7;
}
.smart-launch-skip {
position: absolute;
bottom: max(2rem, env(safe-area-inset-bottom));
z-index: 2;
color: rgb(255 255 255 / 45%);
font-size: 0.72rem;
letter-spacing: 0.12em;
}
.smart-launch-orbit {
position: absolute;
border: 1px solid rgb(255 255 255 / 8%);
border-radius: 50%;
}
.orbit-one {
width: 24rem;
height: 24rem;
animation: launch-spin 18s linear infinite;
}
.orbit-two {
width: 38rem;
height: 38rem;
border-style: dashed;
animation: launch-spin 28s linear infinite reverse;
}
.smart-launch-leave-active { transition: opacity 360ms ease, transform 360ms ease; }
.smart-launch-leave-to { opacity: 0; transform: scale(1.025); }
@keyframes launch-rise {
from { opacity: 0; transform: translateY(1.2rem); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes launch-spin {
to { transform: rotate(360deg); }
}
@media (prefers-reduced-motion: reduce) {
.smart-launch-content,
.smart-launch-orbit {
animation: none;
}
}
</style>
+2
View File
@@ -4,6 +4,7 @@ import './style.css'
import App from './App.vue'
import router from './router'
import { initializeAppUpdates } from './services/appUpdates'
import { initializeNativeHome } from './services/nativeHome'
import { setRouter } from './utils/navigate'
const app = createApp(App)
@@ -12,3 +13,4 @@ app.use(router)
setRouter(router)
app.mount('#app')
void initializeAppUpdates()
initializeNativeHome(router)
+239
View File
@@ -0,0 +1,239 @@
import { Capacitor, registerPlugin } from '@capacitor/core'
import type { Router } from 'vue-router'
import http from '../api/http'
interface WidgetItem {
title: string
subtitle: string
time: string
}
interface WidgetPayload {
displayName: string
scheduleDate: string
schedule: WidgetItem[]
exams: WidgetItem[]
updatedAt: string
}
interface NativeHomePlugin {
updateWidgets(options: { payload: WidgetPayload }): Promise<void>
clearWidgets(): Promise<void>
getLaunchRoute(): Promise<{ route?: string }>
}
interface StoredUser {
displayName?: string
roles?: string[]
}
const NativeHome = registerPlugin<NativeHomePlugin>('NativeHome')
const native = Capacitor.isNativePlatform()
const syncInterval = 10 * 60 * 1000
let lastSyncAt = 0
let syncPromise: Promise<void> | null = null
function storedUser(): StoredUser | null {
try {
const value = localStorage.getItem('jiaowu_user')
return value ? JSON.parse(value) as StoredUser : null
} catch {
return null
}
}
function dateKey(date: Date) {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
function parseDateOnly(value?: string) {
if (!value) return null
const [year, month, day] = value.slice(0, 10).split('-').map(Number)
return year && month && day ? new Date(year, month - 1, day) : null
}
function slotTime(slots: any[], period: number, field: 'startsAt' | 'endsAt') {
return slots.find((slot) => slot.periodNumber === period)?.[field]?.slice(0, 5) ?? ''
}
function activeWeek(timetable: any, now: Date) {
const start = parseDateOnly(timetable?.term?.startDate)
const end = parseDateOnly(timetable?.term?.endDate)
if (!start || !end || now < start || now > new Date(end.getTime() + 86400000)) return null
const mondayOffset = start.getDay() === 0 ? 6 : start.getDay() - 1
const firstMonday = new Date(start)
firstMonday.setDate(firstMonday.getDate() - mondayOffset)
return Math.floor((now.getTime() - firstMonday.getTime()) / 604800000) + 1
}
function scheduleItems(timetable: any, now: Date): WidgetItem[] {
const week = activeWeek(timetable, now)
if (!week) return []
const weekday = now.getDay() || 7
return (timetable?.entries ?? [])
.filter((entry: any) =>
entry.dayOfWeek === weekday &&
week >= entry.startWeek &&
week <= entry.endWeek &&
(entry.weekPattern === 'All' ||
(entry.weekPattern === 'Odd' && week % 2 === 1) ||
(entry.weekPattern === 'Even' && week % 2 === 0)))
.sort((left: any, right: any) => left.startPeriod - right.startPeriod)
.slice(0, 3)
.map((entry: any) => {
const endPeriod = entry.startPeriod + entry.periodCount - 1
const startsAt = slotTime(timetable.slots ?? [], entry.startPeriod, 'startsAt')
const endsAt = slotTime(timetable.slots ?? [], endPeriod, 'endsAt')
return {
title: String(entry.courseName ?? '未命名课程'),
subtitle: [entry.buildingName, entry.classroomName].filter(Boolean).join(' · ') || '地点待定',
time: startsAt && endsAt ? `${startsAt}${endsAt}` : `${entry.startPeriod}${endPeriod}`,
}
})
}
function examItems(exams: any[], now: Date): WidgetItem[] {
return exams
.map((exam) => {
const startsAt = new Date(exam.startsAt)
const date = Number.isNaN(startsAt.getTime())
? parseDateOnly(exam.examDate)
: startsAt
return { exam, date }
})
.filter(({ date }) => date && date.getTime() >= new Date(
now.getFullYear(), now.getMonth(), now.getDate(),
).getTime())
.sort((left, right) => left.date!.getTime() - right.date!.getTime())
.slice(0, 3)
.map(({ exam, date }) => ({
title: String(exam.courseName ?? '未命名考试'),
subtitle: [
exam.buildingName,
exam.classroomName,
exam.seatNumber ? `${exam.seatNumber} 号座` : '',
].filter(Boolean).join(' · ') || '考场待定',
time: `${date!.getMonth() + 1}/${date!.getDate()} ${
Number.isNaN(new Date(exam.startsAt).getTime())
? '时间待定'
: new Intl.DateTimeFormat('zh-CN', {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(new Date(exam.startsAt))
}`,
}))
}
export async function clearNativeWidgets() {
if (!native) return
try {
await NativeHome.clearWidgets()
} catch (error) {
console.warn('清理 Android 桌面组件失败', error)
}
}
export async function syncNativeWidgets(force = false) {
if (!native) return
if (!localStorage.getItem('jiaowu_token')) {
await clearNativeWidgets()
return
}
if (!force && Date.now() - lastSyncAt < syncInterval) return
if (syncPromise) return syncPromise
syncPromise = (async () => {
const user = storedUser()
const roles = user?.roles ?? []
if (!roles.some((role) => role === 'Student' || role === 'Teacher')) {
await clearNativeWidgets()
return
}
const [timetableResult, examResult] = await Promise.allSettled([
http.get('/timetables/mine'),
http.get('/exams/my-schedule'),
])
const now = new Date()
const payload: WidgetPayload = {
displayName: user?.displayName?.trim() || '同学',
scheduleDate: dateKey(now),
schedule: timetableResult.status === 'fulfilled'
? scheduleItems(timetableResult.value.data, now)
: [],
exams: examResult.status === 'fulfilled'
? examItems(examResult.value.data, now)
: [],
updatedAt: now.toISOString(),
}
await NativeHome.updateWidgets({ payload })
lastSyncAt = Date.now()
})().catch((error) => {
console.warn('同步 Android 桌面组件失败', error)
}).finally(() => {
syncPromise = null
})
return syncPromise
}
function routeForShortcut(route: string) {
const roles = storedUser()?.roles ?? []
if (route === 'timetable') {
return roles.some((role) => role === 'Student' || role === 'Teacher')
? '/my-timetable'
: '/class-timetable'
}
if (route === 'exams') return '/exams'
if (route === 'attendance') {
return roles.includes('Student') ? '/my-attendance' : '/teacher-attendance'
}
if (route === 'notifications') return '/notifications'
return '/dashboard'
}
export function initializeNativeHome(router: Router) {
if (!native) return
const openShortcut = (route?: string) => {
if (!route) return
if (!localStorage.getItem('jiaowu_token')) {
sessionStorage.setItem('mingxu_pending_shortcut', route)
void router.push('/login')
return
}
void router.push(routeForShortcut(route))
}
const shortcutListener = (event: Event) => {
const value = event as CustomEvent<{ route?: string }> & { route?: string }
const eventRoute = value.detail?.route ?? value.route
void NativeHome.getLaunchRoute()
.then(({ route }) => openShortcut(route ?? eventRoute))
.catch(() => openShortcut(eventRoute))
}
window.addEventListener('mingxuShortcut', shortcutListener)
document.addEventListener('visibilitychange', () => {
if (!document.hidden) void syncNativeWidgets()
})
window.addEventListener('mingxu-auth-changed', () => {
lastSyncAt = 0
const pendingShortcut = sessionStorage.getItem('mingxu_pending_shortcut')
if (localStorage.getItem('jiaowu_token') && pendingShortcut) {
sessionStorage.removeItem('mingxu_pending_shortcut')
openShortcut(pendingShortcut)
}
void syncNativeWidgets(true)
})
router.afterEach(() => {
void syncNativeWidgets()
})
void NativeHome.getLaunchRoute()
.then(({ route }) => openShortcut(route))
.catch((error) => console.warn('读取 Android 快捷入口失败', error))
void syncNativeWidgets()
}
+2
View File
@@ -24,6 +24,7 @@ export const useAuthStore = defineStore('auth', () => {
user.value = data.user
localStorage.setItem('jiaowu_token', data.token)
localStorage.setItem('jiaowu_user', JSON.stringify(data.user))
window.dispatchEvent(new Event('mingxu-auth-changed'))
}
async function refresh() {
@@ -38,6 +39,7 @@ export const useAuthStore = defineStore('auth', () => {
user.value = null
localStorage.removeItem('jiaowu_token')
localStorage.removeItem('jiaowu_user')
window.dispatchEvent(new Event('mingxu-auth-changed'))
}
return { token, user, isLoggedIn, isSuperAdmin, login, refresh, logout }
+74
View File
@@ -0,0 +1,74 @@
export interface SmartGreeting {
title: string
subtitle: string
label: string
}
const dailySubtitles = [
'愿今天的课程与计划都清晰顺利。',
'新的一天,从有序安排开始。',
'把每一次学习,都变成看得见的进步。',
]
function lunarFestival(date: Date) {
try {
const parts = new Intl.DateTimeFormat('zh-CN-u-ca-chinese', {
month: 'long',
day: 'numeric',
}).formatToParts(date)
const month = parts.find((part) => part.type === 'month')?.value ?? ''
const day = parts.find((part) => part.type === 'day')?.value ?? ''
if (month === '正月' && ['1', '2', '3'].includes(day)) return '春节快乐'
if (month === '正月' && day === '15') return '元宵节快乐'
if (month === '五月' && day === '5') return '端午安康'
if (month === '八月' && day === '15') return '中秋快乐'
} catch {
// 少数精简 WebView 不支持中国农历日历,继续使用公历与时段问候。
}
return ''
}
function festivalGreeting(date: Date) {
const month = date.getMonth() + 1
const day = date.getDate()
const lunar = lunarFestival(date)
if (lunar) return lunar
if (month === 1 && day === 1) return '新年快乐'
if (month === 5 && day >= 1 && day <= 5) return '劳动节愉快'
if (month === 9 && day === 10) return '教师节快乐'
if (month === 10 && day >= 1 && day <= 7) return '国庆节快乐'
return ''
}
function timeGreeting(date: Date) {
const hour = date.getHours()
if (hour < 5) return '夜深了'
if (hour < 11) return '早上好'
if (hour < 14) return '中午好'
if (hour < 18) return '下午好'
return '晚上好'
}
export function getSmartGreeting(
date = new Date(),
displayName?: string | null,
): SmartGreeting {
const greeting = festivalGreeting(date) || timeGreeting(date)
const name = displayName?.trim()
const weekday = new Intl.DateTimeFormat('zh-CN', { weekday: 'long' }).format(date)
const label = new Intl.DateTimeFormat('zh-CN', {
month: 'long',
day: 'numeric',
}).format(date)
const index = Math.abs(date.getFullYear() * 372 + date.getMonth() * 31 + date.getDate())
% dailySubtitles.length
return {
title: name ? `${name}${greeting}` : `${greeting},欢迎使用明序教务`,
subtitle: date.getDay() === 0 || date.getDay() === 6
? '周末也要记得放松一下,查看安排后从容出发。'
: dailySubtitles[index],
label: `${label} · ${weekday}`,
}
}