feat: select school terms and smooth refractive Dock motion

This commit is contained in:
Codex
2026-10-13 19:08:36 +08:00
parent 3e2d8864af
commit 50fcc70e8e
33 changed files with 1245 additions and 94 deletions
+2 -2
View File
@@ -35,7 +35,7 @@ class ExamsPage extends StatelessWidget {
builder: (context) => AlertDialog(
title: const Text('导入考试信息'),
content: Text(
'${draft.semesterLabel} · ${draft.records.length} 门课程\n将更新本机考试列表,尚未公布的字段显示为“尚未安排”。',
'${draft.semesterLabel} · ${draft.records.length} 门课程\n文件仅包含这个学期;其他学期请从学校查询。将更新本机考试列表,尚未公布的字段显示为“尚未安排”。',
),
actions: [
TextButton(
@@ -78,7 +78,7 @@ class ExamsPage extends StatelessWidget {
),
children: [
const Text(
'RSchedule',
'考试',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
const SizedBox(height: 18),
@@ -41,6 +41,14 @@ class _ImportPreviewState extends State<ImportPreview> {
style: const TextStyle(color: river),
),
if (draft.semesterLabel != null) Text('学期:${draft.semesterLabel}'),
if (draft.schoolTerm != null)
const Padding(
padding: EdgeInsets.only(top: 8),
child: Text(
'文件仅包含这个学期;查询其他学期请使用学校连接中的“更新学期”。',
style: TextStyle(fontSize: 12, height: 1.6),
),
),
const SizedBox(height: 18),
if (empty)
Text(draft.explicitlyEmpty ? '此操作会清空当前课表。' : '没有识别到课程,当前课表保持不变。'),
@@ -18,10 +18,12 @@ class ProfilePage extends StatelessWidget {
this.authStatus = '未登录',
this.onLogout,
this.logoutLabel = '退出学校登录',
this.onUpdateTerm,
});
final AppController controller;
final VoidCallback onLogin;
final VoidCallback? onLogout;
final VoidCallback? onUpdateTerm;
final String authStatus, logoutLabel;
Future<void> _import(BuildContext context) async {
try {
@@ -190,6 +192,13 @@ class ProfilePage extends StatelessWidget {
),
),
Divider(height: 1, color: ink.withValues(alpha: 0.06)),
_tile(
Icons.date_range_rounded,
'更新学期',
controller.snapshot.schoolTerm?.label ?? '选择学校查询学期',
onUpdateTerm ?? onLogin,
),
Divider(height: 1, color: ink.withValues(alpha: 0.06)),
_tile(
Icons.file_download_outlined,
'从文件导入',
+16 -1
View File
@@ -8,8 +8,13 @@ import '../../domain/semester.dart';
import '../../services/notification_service.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key, required this.controller});
const SettingsPage({
super.key,
required this.controller,
this.focusSemester = false,
});
final AppController controller;
final bool focusSemester;
@override
State<SettingsPage> createState() => _SettingsPageState();
}
@@ -20,6 +25,7 @@ class _SettingsPageState extends State<SettingsPage> {
double? _courseHeightDraft;
bool _savingHeight = false;
String? _weeksError, _dateError;
final _scroll = ScrollController();
@override
void initState() {
super.initState();
@@ -27,11 +33,19 @@ class _SettingsPageState extends State<SettingsPage> {
_weeks = TextEditingController(
text: '${widget.controller.snapshot.settings.semester?.totalWeeks ?? 20}',
);
if (widget.focusSemester) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
}
@override
void dispose() {
_weeks.dispose();
_scroll.dispose();
super.dispose();
}
@@ -132,6 +146,7 @@ class _SettingsPageState extends State<SettingsPage> {
),
),
body: ListView(
controller: _scroll,
padding: const EdgeInsets.fromLTRB(20, 12, 20, 40),
children: [
if (c.isDemo)
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../app/app_controller.dart';
import '../../domain/school_term.dart';
import 'school_session.dart';
class SchoolAuthPage extends StatefulWidget {
@@ -18,6 +19,7 @@ class SchoolAuthPage extends StatefulWidget {
class _SchoolAuthPageState extends State<SchoolAuthPage> {
bool _saving = false;
SchoolTerm? _termChoice;
@override
void initState() {
super.initState();
@@ -36,7 +38,9 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
final courses = s.pendingDraft, exams = s.pendingExams;
final generation = s.pageGeneration;
final route = ModalRoute.of(context);
if (_saving || (courses == null && exams == null)) return;
if (s.needsTermSelection || _saving || (courses == null && exams == null)) {
return;
}
_saving = true;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) {
@@ -102,7 +106,9 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
),
IconButton(
tooltip: '读取当前页面',
onPressed: _saving ? null : s.readCurrentPage,
onPressed: _saving || s.needsTermSelection
? null
: s.readCurrentPage,
icon: const Icon(Icons.sync_rounded),
),
],
@@ -123,7 +129,9 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
child: Stack(
children: [
WebViewWidget(controller: s.web),
if (s.finding || _saving)
if (s.needsTermSelection)
Positioned.fill(child: _termPicker(s)),
if (!s.needsTermSelection && (s.finding || _saving))
Positioned.fill(
child: ColoredBox(
color: const Color(0xFFF5F9FE),
@@ -152,4 +160,62 @@ class _SchoolAuthPageState extends State<SchoolAuthPage> {
),
);
}
Widget _termPicker(SchoolSession session) {
final choices = session.termChoices;
final preferred =
_termChoice ??
session.selectedTerm ??
widget.controller.snapshot.schoolTerm ??
choices.first;
final selected = choices.contains(preferred) ? preferred : choices.first;
return Material(
color: const Color(0xFFF5F9FE),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'选择学校学期',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
const SizedBox(height: 8),
Text(session.requestingExams ? '将读取这个学期的考试安排。' : '将读取这个学期的课程表。'),
const SizedBox(height: 12),
Expanded(
child: ListView.builder(
itemCount: choices.length,
itemBuilder: (context, index) {
final term = choices[index];
final isSelected = term == selected;
return ListTile(
title: Text(term.label),
selected: isSelected,
leading: Icon(
isSelected
? Icons.radio_button_checked
: Icons.radio_button_off,
),
onTap: () => setState(() => _termChoice = term),
);
},
),
),
const SizedBox(height: 12),
FilledButton(
onPressed: () => session.selectTerm(selected),
child: const Text('导入所选学期'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消'),
),
],
),
),
),
);
}
}
@@ -25,7 +25,11 @@ class SchoolLoginFlow {
_requested = false;
return null;
}
if (uri.path == _target!.path ||
final atTarget =
uri.path == _target!.path &&
(!_target!.queryParameters.containsKey('xq') ||
uri.queryParameters['xq'] == _target!.queryParameters['xq']);
if (atTarget ||
_requested ||
_attempts >= 2 ||
!authenticated ||
@@ -5,6 +5,7 @@ import 'package:html/parser.dart' as html;
import '../../data/json_schedule_import.dart';
import '../../domain/course.dart';
import '../../domain/school_term.dart';
import 'school_navigation_policy.dart';
class UnsupportedSchoolLayout implements Exception {
@@ -112,6 +113,7 @@ class SchoolPageAdapter {
source: source,
parserVersion: 'uestc-graduate-html-v1',
semesterLabel: selected.text.trim(),
schoolTerm: SchoolTerm(int.parse(term)),
);
} on UnsupportedSchoolLayout {
rethrow;
@@ -1,5 +1,6 @@
import 'dart:convert';
import '../../domain/school_term.dart';
import 'school_navigation_policy.dart';
/// Only serialize recognized table fragments, never a login document.
@@ -14,7 +15,7 @@ const schoolPageProbeScript = r'''(() => {
} catch (_) { return false; }
};
const topUrl = location.href;
const result = {topUrl, authenticated: false, pages: []};
const result = {topUrl, authenticated: false, pages: [], terms: []};
if (!trusted(topUrl) || document.querySelector('input[type="password"]')) {
return JSON.stringify(result);
}
@@ -34,6 +35,13 @@ const schoolPageProbeScript = r'''(() => {
['timetable', '#tbl', '#drpxq'], ['exams', '#sample-table-1', '#xqbh']
]) {
const table = doc.querySelector(tableId), term = doc.querySelector(termId);
if (term && term.options && term.options.length <= 146) {
for (const option of Array.from(term.options)) {
const id = Number(option.value);
if (/^[1-9]\d*$/.test(option.value) && id <= 9999 &&
!result.terms.includes(id) && result.terms.length < 146) result.terms.push(id);
}
}
if (!table || !term || !term.options || term.selectedIndex < 0) continue;
const selected = term.cloneNode(true);
Array.from(selected.options).forEach((option, index) => {
@@ -59,9 +67,14 @@ class SchoolTableFragment {
}
class SchoolPageEvidence {
const SchoolPageEvidence(this.authenticated, this.pages);
const SchoolPageEvidence(
this.authenticated,
this.pages, {
this.terms = const [],
});
final bool authenticated;
final List<SchoolTableFragment> pages;
final List<SchoolTerm> terms;
static SchoolPageEvidence decode(Object raw, Uri current) {
dynamic value = raw;
@@ -92,6 +105,22 @@ class SchoolPageEvidence {
pages.add(SchoolTableFragment(page['kind'] as String, uri, content));
}
}
return SchoolPageEvidence(value['authenticated'] == true, pages);
final terms = <SchoolTerm>[];
final candidatesTerms = value['terms'];
if (candidatesTerms is List && candidatesTerms.length <= 146) {
final ids =
candidatesTerms
.whereType<int>()
.where((id) => id >= 1 && id <= 9999)
.toSet()
.toList()
..sort((a, b) => b.compareTo(a));
terms.addAll(ids.map(SchoolTerm.new));
}
return SchoolPageEvidence(
value['authenticated'] == true,
pages,
terms: terms,
);
}
}
+114 -17
View File
@@ -5,6 +5,7 @@ import 'package:webview_flutter/webview_flutter.dart';
import '../../data/json_schedule_import.dart';
import '../../domain/exam_schedule.dart';
import '../../domain/school_term.dart';
import 'school_navigation_policy.dart';
import 'school_page_adapter.dart';
import 'school_exam_adapter.dart';
@@ -114,6 +115,23 @@ class SchoolSession extends ChangeNotifier {
int _openSerial = 0;
ImportDraft? pendingDraft;
ExamSchedule? pendingExams;
SchoolTerm? selectedTerm;
bool _termSelectionRequested = true;
bool _termSelectionReady = false;
List<SchoolTerm> _liveTerms = const [];
bool get needsTermSelection =>
hasOpened &&
connectionState == SchoolConnectionState.connected &&
_termSelectionRequested &&
_termSelectionReady;
List<SchoolTerm> get termChoices {
final terms = [...(_liveTerms.isEmpty ? SchoolTerm.choices : _liveTerms)];
if (selectedTerm != null && !terms.contains(selectedTerm)) {
terms.add(selectedTerm!);
}
return terms..sort((a, b) => b.id.compareTo(a.id));
}
String message = '请在学校网页中完成登录与验证码。';
String get statusLabel => logoutFailed
? '学校退出未完成,请重试'
@@ -130,18 +148,31 @@ class SchoolSession extends ChangeNotifier {
'https://yjsjy.uestc.edu.cn/pyxx/jzsso/login',
);
static final timetableUrl = Uri.parse(
'https://yjsjy.uestc.edu.cn/pyxx/pygl/xskbcx/index/1',
'https://yjsjy.uestc.edu.cn/pyxx/pygl/xskbcx/index/73',
);
static final examUrl = Uri.parse(
'https://yjsjy.uestc.edu.cn/pyxx/pygl/kskcxx/index',
'https://yjsjy.uestc.edu.cn/pyxx/pygl/kskcxx/index?xq=73',
);
Uri get _target => requestingExams ? examUrl : timetableUrl;
Uri get _target => requestingExams
? (selectedTerm?.examUri ?? examUrl)
: (selectedTerm?.timetableUri ?? timetableUrl);
Future<void> open() => _open(exams: false);
Future<void> openTimetable() => _open(exams: false);
Future<void> openExams() => _open(exams: true);
Future<void> openAuthentication() =>
_open(exams: requestingExams, forceAuth: true);
Future<void> _open({required bool exams, bool forceAuth = false}) async {
Future<void> openTimetable({SchoolTerm? term, bool chooseTerm = false}) =>
_open(exams: false, term: term, chooseTerm: chooseTerm);
Future<void> openExams({SchoolTerm? term, bool chooseTerm = false}) =>
_open(exams: true, term: term, chooseTerm: chooseTerm);
Future<void> openAuthentication() => _open(
exams: requestingExams,
term: selectedTerm,
chooseTerm: _termSelectionRequested,
forceAuth: true,
);
Future<void> _open({
required bool exams,
SchoolTerm? term,
bool chooseTerm = false,
bool forceAuth = false,
}) async {
final serial = ++_openSerial;
final closing = _logoutFuture;
if (closing != null) await closing;
@@ -154,6 +185,9 @@ class SchoolSession extends ChangeNotifier {
final generation = _pageGeneration;
pendingDraft = null;
pendingExams = null;
selectedTerm = term;
_termSelectionRequested = chooseTerm || term == null;
_termSelectionReady = false;
requestingExams = exams;
logoutFailed = false;
hasOpened = true;
@@ -161,10 +195,17 @@ class SchoolSession extends ChangeNotifier {
_flow.begin(_target);
final connected =
connectionState == SchoolConnectionState.connected && !forceAuth;
finding = connected;
message = connected ? _findingMessage : '请在学校网页中完成登录与验证码。';
if (connected) _armTimeout();
_termSelectionReady = connected;
finding = connected && !needsTermSelection;
_loading = !needsTermSelection;
message = needsTermSelection
? '请选择要导入的学校学期。'
: connected
? _findingMessage
: '请在学校网页中完成登录与验证码。';
if (finding) _armTimeout();
notifyListeners();
if (needsTermSelection) return;
try {
await web.loadRequest(connected ? _target : authUrl);
} catch (_) {
@@ -174,6 +215,39 @@ class SchoolSession extends ChangeNotifier {
}
}
Future<void> selectTerm(SchoolTerm term) async {
if (!hasOpened ||
!needsTermSelection ||
connectionState != SchoolConnectionState.connected ||
!termChoices.contains(term)) {
return;
}
final serial = ++_openSerial;
_poll?.cancel();
_timeout?.cancel();
_pageGeneration++;
_reader.invalidate();
final generation = _pageGeneration;
pendingDraft = null;
pendingExams = null;
selectedTerm = term;
_termSelectionRequested = false;
_manualRead = false;
_flow.begin(_target);
finding = true;
_loading = true;
message = _findingMessage;
_armTimeout();
notifyListeners();
try {
await web.loadRequest(_target);
} catch (_) {
if (serial == _openSerial && generation == _pageGeneration) {
_failure('学校学期查询页面暂时无法打开,请重试。');
}
}
}
String get _findingMessage => requestingExams ? '正在查找考试安排,请稍候' : '正在查找课表,请稍候';
void _armTimeout() {
_timeout?.cancel();
@@ -223,6 +297,7 @@ class SchoolSession extends ChangeNotifier {
if (!_readingActive ||
!hasOpened ||
generation != _pageGeneration ||
needsTermSelection ||
pendingDraft != null ||
pendingExams != null) {
return;
@@ -258,6 +333,7 @@ class SchoolSession extends ChangeNotifier {
_loading = false;
if (pendingDraft != null || pendingExams != null) return;
if (uri.host == 'idas.uestc.edu.cn') {
_termSelectionReady = false;
_timeout?.cancel();
finding = false;
connectionState = SchoolConnectionState.authenticating;
@@ -275,7 +351,7 @@ class SchoolSession extends ChangeNotifier {
final targetPage = requestingExams
? SchoolNavigationPolicy.isExam(uri)
: SchoolNavigationPolicy.isTimetable(uri);
if (targetPage || _manualRead) {
if (!_termSelectionRequested && (targetPage || _manualRead)) {
finding = true;
message = _findingMessage;
notifyListeners();
@@ -288,21 +364,33 @@ class SchoolSession extends ChangeNotifier {
await web.currentUrl() != url) {
return;
}
if (evidence.terms.isNotEmpty) _liveTerms = evidence.terms;
if (_termSelectionRequested) {
if (evidence.authenticated || evidence.pages.isNotEmpty) {
connectionState = SchoolConnectionState.connected;
_termSelectionReady = true;
_timeout?.cancel();
_poll?.cancel();
finding = false;
message = '请选择要导入的学校学期。';
notifyListeners();
}
return;
}
for (final page in evidence.pages) {
if (page.kind != (requestingExams ? 'exams' : 'timetable')) continue;
try {
if (requestingExams) {
final draft = SchoolExamAdapter.extract(page.html);
if (generation != _pageGeneration) return;
if (draft.termId != selectedTerm?.id.toString()) continue;
pendingExams = draft;
} else {
// The probe validates the live document's origin. The strict parser
// gets only its recognized fragment with the canonical table path.
final draft = await _reader.read(
timetableUrl,
() async => page.html,
);
final draft = await _reader.read(_target, () async => page.html);
if (!hasOpened || generation != _pageGeneration) return;
if (draft.schoolTerm != selectedTerm) continue;
pendingDraft = draft;
}
_timeout?.cancel();
@@ -347,6 +435,9 @@ class SchoolSession extends ChangeNotifier {
}
Future<ImportDraft> readTimetable() async {
if (_termSelectionRequested || selectedTerm == null) {
throw UnsupportedSchoolLayout();
}
final generation = _pageGeneration;
final uri = Uri.tryParse(await web.currentUrl() ?? '');
if (uri == null || !SchoolNavigationPolicy.isGraduatePage(uri)) {
@@ -360,7 +451,12 @@ class SchoolSession extends ChangeNotifier {
for (final page in evidence.pages) {
if (page.kind != 'timetable') continue;
try {
return await _reader.read(timetableUrl, () async => page.html);
final draft = await _reader.read(
selectedTerm!.timetableUri,
() async => page.html,
);
if (draft.schoolTerm != selectedTerm) continue;
return draft;
} on UnsupportedSchoolLayout {
if (generation != _pageGeneration) rethrow;
}
@@ -369,6 +465,7 @@ class SchoolSession extends ChangeNotifier {
}
Future<void> readCurrentPage() async {
if (needsTermSelection) return;
_poll?.cancel();
_timeout?.cancel();
_pageGeneration++;
@@ -3,11 +3,13 @@ import 'package:flutter/material.dart';
import '../../app/app_controller.dart';
import '../../app/app_theme.dart';
import '../../domain/schedule_engine.dart';
import '../profile/settings_page.dart';
import 'week_grid.dart';
class TimetablePage extends StatefulWidget {
const TimetablePage({super.key, required this.controller});
const TimetablePage({super.key, required this.controller, this.onSync});
final AppController controller;
final VoidCallback? onSync;
@override
State<TimetablePage> createState() => _TimetablePageState();
}
@@ -40,13 +42,32 @@ class _TimetablePageState extends State<TimetablePage> {
140 + MediaQuery.paddingOf(context).bottom,
),
children: [
const Padding(
Padding(
padding: EdgeInsets.symmetric(horizontal: 14),
child: Text(
'RSchedule',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
child: Row(
children: [
const Expanded(
child: Text(
'课表',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
),
IconButton(
tooltip: '刷新课表',
onPressed: widget.onSync,
icon: const Icon(Icons.sync_rounded),
),
],
),
),
if (!c.isDemo && c.snapshot.schoolTerm != null)
Padding(
padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
child: Text(
c.snapshot.schoolTerm!.label,
style: TextStyle(fontSize: 12, color: ink.withValues(alpha: 0.5)),
),
),
const SizedBox(height: 10),
SurfaceCard(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 0),
@@ -142,6 +163,51 @@ class _TimetablePageState extends State<TimetablePage> {
textAlign: TextAlign.center,
style: TextStyle(fontSize: 11, color: ink.withValues(alpha: 0.35)),
),
] else if (c.visibleCourses.isNotEmpty) ...[
const SizedBox(height: 36),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: SurfaceCard(
child: Column(
children: [
const Icon(
Icons.event_available_rounded,
size: 44,
color: river,
),
const SizedBox(height: 18),
const Text(
'课表已导入,请设置学期开始日',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
const SizedBox(height: 10),
Text(
'${c.visibleCourses.length} 条课程安排已保存',
style: const TextStyle(fontSize: 13, color: river),
),
const SizedBox(height: 10),
const Text(
'课程按教学周保存。设置真实的学期开始日后,\n才能显示每周课表并安排课前提醒。',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12, height: 1.8),
),
const SizedBox(height: 20),
FilledButton.icon(
onPressed: () => Navigator.push(
context,
MaterialPageRoute<void>(
builder: (_) =>
SettingsPage(controller: c, focusSemester: true),
),
),
icon: const Icon(Icons.edit_calendar_rounded, size: 18),
label: const Text('设置学期开始日'),
),
],
),
),
),
] else ...[
const SizedBox(height: 38),
const Icon(