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
+28 -1
View File
@@ -9,6 +9,7 @@ import '../services/calendar_service.dart';
import '../domain/schedule_engine.dart';
import '../data/demo_schedule.dart';
import '../domain/exam_schedule.dart';
import '../domain/school_term.dart';
class AppController extends ChangeNotifier {
AppController(this.store, this.notifications, this.calendar, this.clock);
@@ -145,6 +146,11 @@ class AppController extends ChangeNotifier {
await _save(
snapshot.copyWith(
courses: draft.courses,
schoolTerm: draft.schoolTerm,
clearExams: _differentTerm(draft.schoolTerm),
settings: _differentTerm(draft.schoolTerm)
? snapshot.settings.copyWith(clearSemester: true)
: snapshot.settings,
importMetadata: ImportMetadata(
source: draft.source,
importedAt: clock(),
@@ -177,8 +183,29 @@ class AppController extends ChangeNotifier {
});
Future<void> applyExams(ExamSchedule value) => _run(() async {
final validated = ExamSchedule.fromJson(value.toJson());
await _save(snapshot.copyWith(examSchedule: validated));
final term = SchoolTerm(int.parse(validated.termId));
final changed = _differentTerm(term);
await _save(
snapshot.copyWith(
examSchedule: validated,
schoolTerm: term,
courses: changed ? [] : null,
clearMetadata: changed,
settings: changed
? snapshot.settings.copyWith(clearSemester: true)
: null,
),
);
if (changed) {
isDemo = false;
await _reconcile();
}
});
bool _differentTerm(SchoolTerm? next) =>
next != null &&
((snapshot.schoolTerm != null && snapshot.schoolTerm != next) ||
(snapshot.schoolTerm == null &&
(snapshot.courses.isNotEmpty || snapshot.examSchedule != null)));
Future<void> clearExams() => _run(() async {
await _save(snapshot.copyWith(clearExams: true));
});
+15 -4
View File
@@ -136,12 +136,19 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
}
}
void _school({bool exams = false}) {
void _school({bool exams = false, bool chooseTerm = false}) {
if (widget.schoolBuilder != null) {
final term = widget.controller.snapshot.schoolTerm;
if (exams) {
widget.school?.openExams();
widget.school?.openExams(
term: term,
chooseTerm: chooseTerm || term == null,
);
} else {
widget.school?.openTimetable();
widget.school?.openTimetable(
term: term,
chooseTerm: chooseTerm || term == null,
);
}
Navigator.push(
context,
@@ -272,7 +279,10 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
child: TabDeck(
index: _tab,
children: [
TimetablePage(controller: widget.controller),
TimetablePage(
controller: widget.controller,
onSync: _school,
),
ExamsPage(
controller: widget.controller,
onSync: () {
@@ -282,6 +292,7 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
ProfilePage(
controller: widget.controller,
onLogin: _school,
onUpdateTerm: () => _school(chooseTerm: true),
authStatus: widget.school?.statusLabel ?? '未登录',
logoutLabel: widget.school?.logoutFailed == true
? '重试退出学校登录'
+20
View File
@@ -1,4 +1,5 @@
import '../domain/course.dart';
import '../domain/school_term.dart';
import 'dart:convert';
@@ -9,12 +10,14 @@ class ImportDraft {
required this.source,
required this.parserVersion,
this.semesterLabel,
this.schoolTerm,
});
final List<Course> courses;
final bool explicitlyEmpty;
final CourseSource source;
final String parserVersion;
final String? semesterLabel;
final SchoolTerm? schoolTerm;
}
class JsonScheduleImport {
@@ -46,11 +49,28 @@ class JsonScheduleImport {
if (courses.map((c) => c.id).toSet().length != courses.length) {
throw const FormatException('课程标识重复');
}
final termIds = courses
.map((c) => RegExp(r'^uestc-(\d+)-').firstMatch(c.id)?.group(1))
.whereType<String>()
.toSet();
final term = json['schoolTerm'] != null
? SchoolTerm.fromJson(
Map<String, dynamic>.from(json['schoolTerm'] as Map),
)
: termIds.length == 1
? SchoolTerm(int.parse(termIds.single))
: null;
if (termIds.length > 1 ||
(term != null && termIds.any((id) => id != term.id.toString()))) {
throw const FormatException('文件中包含不同学期的课程');
}
return ImportDraft(
courses: List.unmodifiable(courses),
explicitlyEmpty: json['explicitlyEmpty'] == true,
source: source,
parserVersion: 'json-v1',
schoolTerm: source == CourseSource.demo ? null : term,
semesterLabel: term?.label,
);
} on FormatException {
rethrow;
+2 -1
View File
@@ -24,6 +24,7 @@ class AppSettings {
final String? calendarId;
AppSettings copyWith({
Semester? semester,
bool clearSemester = false,
bool? remindersEnabled,
int? reminderMinutes,
ColorMode? colorMode,
@@ -32,7 +33,7 @@ class AppSettings {
String? calendarId,
double? courseHeightScale,
}) => AppSettings(
semester: semester ?? this.semester,
semester: clearSemester ? null : semester ?? this.semester,
remindersEnabled: remindersEnabled ?? this.remindersEnabled,
reminderMinutes: reminderMinutes ?? this.reminderMinutes,
colorMode: colorMode ?? this.colorMode,
+26 -1
View File
@@ -2,6 +2,7 @@ import 'app_settings.dart';
import 'course.dart';
import 'semester.dart';
import 'exam_schedule.dart';
import 'school_term.dart';
class ImportMetadata {
const ImportMetadata({
@@ -20,16 +21,32 @@ class AppSnapshot {
List<Course> courses = const [],
this.importMetadata,
this.examSchedule,
SchoolTerm? schoolTerm,
this.calendarCleanupPending = false,
Map<String, String> calendarEventIds = const {},
}) : courses = List.unmodifiable(courses),
}) : schoolTerm = schoolTerm ?? _legacyTerm(courses, examSchedule),
courses = List.unmodifiable(courses),
calendarEventIds = Map.unmodifiable(calendarEventIds);
final AppSettings settings;
final List<Course> courses;
final ImportMetadata? importMetadata;
final ExamSchedule? examSchedule;
final SchoolTerm? schoolTerm;
final Map<String, String> calendarEventIds;
final bool calendarCleanupPending;
static SchoolTerm? _legacyTerm(List<Course> courses, ExamSchedule? exams) {
final ids = courses
.map(
(course) => RegExp(r'^uestc-(\d+)-').firstMatch(course.id)?.group(1),
)
.whereType<String>()
.toSet();
if (exams != null) ids.add(exams.termId);
if (ids.length != 1) return null;
final id = int.tryParse(ids.single);
return id != null && id >= 1 && id <= 9999 ? SchoolTerm(id) : null;
}
AppSnapshot copyWith({
AppSettings? settings,
List<Course>? courses,
@@ -38,6 +55,7 @@ class AppSnapshot {
bool clearMetadata = false,
ExamSchedule? examSchedule,
bool clearExams = false,
SchoolTerm? schoolTerm,
bool? calendarCleanupPending,
}) => AppSnapshot(
settings: settings ?? this.settings,
@@ -46,6 +64,7 @@ class AppSnapshot {
? null
: importMetadata ?? this.importMetadata,
examSchedule: clearExams ? null : examSchedule ?? this.examSchedule,
schoolTerm: schoolTerm ?? this.schoolTerm,
calendarEventIds: calendarEventIds ?? this.calendarEventIds,
calendarCleanupPending:
calendarCleanupPending ?? this.calendarCleanupPending,
@@ -53,6 +72,7 @@ class AppSnapshot {
Map<String, dynamic> toJson() => {
'schemaVersion': 1,
'examSchedule': examSchedule?.toJson(),
'schoolTerm': schoolTerm?.toJson(),
'courses': courses.map((c) => c.toJson()).toList(),
'settings': {
'semester': settings.semester == null
@@ -116,6 +136,11 @@ class AppSnapshot {
);
final metadata = json['importMetadata'];
return AppSnapshot(
schoolTerm: json['schoolTerm'] == null
? null
: SchoolTerm.fromJson(
Map<String, dynamic>.from(json['schoolTerm'] as Map),
),
examSchedule: json['examSchedule'] == null
? null
: ExamSchedule.fromJson(
+27
View File
@@ -0,0 +1,27 @@
/// The graduate system's term number, independent of teaching-week dates.
class SchoolTerm {
SchoolTerm(this.id) {
if (id < 1 || id > 9999) throw ArgumentError('学校学期编号无效');
}
final int id;
String get label {
final year = 1990 + ((id - 1) ~/ 2);
return '$year-${year + 1}年${id.isOdd ? '秋' : '春'}';
}
static List<SchoolTerm> get choices =>
List.generate(73, (index) => SchoolTerm(73 - index));
Uri get timetableUri =>
Uri.https('yjsjy.uestc.edu.cn', '/pyxx/pygl/xskbcx/index/$id');
Uri get examUri =>
Uri.https('yjsjy.uestc.edu.cn', '/pyxx/pygl/kskcxx/index', {'xq': '$id'});
Map<String, dynamic> toJson() => {'id': id};
factory SchoolTerm.fromJson(Map<String, dynamic> json) {
if (json['id'] is! int) throw const FormatException('学校学期无效');
return SchoolTerm(json['id'] as int);
}
@override
bool operator ==(Object other) => other is SchoolTerm && other.id == id;
@override
int get hashCode => id.hashCode;
}
+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(
+51 -25
View File
@@ -30,6 +30,14 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
value: 0,
);
bool _reduceMotion = false;
late int _targetIndex;
bool _elasticMotion = false;
@override
void initState() {
super.initState();
_targetIndex = widget.selectedIndex;
}
double get _pressure => _press.value.clamp(0.0, 1.18);
void _pressTo(double target) {
if (_reduceMotion) {
@@ -38,7 +46,7 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
}
_press.animateWith(
SpringSimulation(
const SpringDescription(mass: 1, stiffness: 440, damping: 20),
const SpringDescription(mass: 1, stiffness: 440, damping: 17),
_press.value,
target,
_press.velocity,
@@ -55,26 +63,36 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
double? _drag;
double _dragSpeed = 0;
double get _position => _drag ?? _motion.value.clamp(-0.12, 2.12);
void _spring(int index, [double velocity = 0]) {
void _moveTo(int index, {bool elastic = false, double velocity = 0}) {
_targetIndex = index;
_elasticMotion = elastic && !_reduceMotion;
if (_reduceMotion) {
_motion.value = index.toDouble();
return;
}
_motion.animateWith(
SpringSimulation(
const SpringDescription(mass: 1, stiffness: 380, damping: 23),
_position,
if (elastic) {
_motion.animateWith(
SpringSimulation(
const SpringDescription(mass: 1, stiffness: 380, damping: 19),
_position,
index.toDouble(),
velocity.clamp(-8, 8),
),
);
} else {
_motion.animateTo(
index.toDouble(),
velocity.clamp(-8, 8),
),
);
duration: const Duration(milliseconds: 320),
curve: Curves.easeOutCubic,
);
}
}
void _select(int index, [double velocity = 0]) {
void _select(int index, {bool elastic = false, double velocity = 0}) {
final position = _position;
setState(() => _drag = null);
_motion.value = position;
_spring(index, velocity);
_moveTo(index, elastic: elastic, velocity: velocity);
_pressTo(0);
widget.onSelected(index);
}
@@ -82,8 +100,10 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
@override
void didUpdateWidget(GlassDock oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selectedIndex != widget.selectedIndex && _drag == null) {
_spring(widget.selectedIndex);
// The parent acknowledges onSelected with a rebuild. Restarting here used
// to erase the release velocity and start a second spring for the same tab.
if (widget.selectedIndex != _targetIndex && _drag == null) {
_moveTo(widget.selectedIndex);
}
}
@@ -124,12 +144,10 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
);
return ClipRRect(
borderRadius: BorderRadius.circular(40),
child: lens
? GlassRefraction(strength: 0.25 + pressure * 0.95, child: content)
: BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: 1.0, sigmaY: 1.0),
child: content,
),
child: GlassRefraction(
strength: lens ? 0.25 + pressure * 0.95 : 0.32,
child: content,
),
);
}
@@ -138,12 +156,19 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
animation: Listenable.merge([_motion, _press]),
builder: (context, _) {
final press = _pressure;
final speed = (_drag != null ? _dragSpeed : _motion.velocity).abs();
final stretch = (speed / 16).clamp(0.0, 0.12) + press * 0.18;
final speed = _reduceMotion
? 0.0
: (_drag != null
? _dragSpeed
: _elasticMotion
? _motion.velocity
: 0.0)
.abs();
final stretch = (speed / 16).clamp(0.0, 0.14) + press * 0.30;
final lensWidth = _travel * (1 + stretch);
final lensHeight =
(_height - _inset * 2) *
(1 + press * 0.19 - (speed / 16).clamp(0.0, 0.07));
(1 + press * 0.31 - (speed / 16).clamp(0.0, 0.07));
return SizedBox(
width: _width,
height: _height,
@@ -201,7 +226,7 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
child: GestureDetector(
key: index == widget.selectedIndex ? const Key('dock-cursor') : null,
behavior: HitTestBehavior.opaque,
onTapDown: (_) => _pressTo(1),
onTapDown: index == widget.selectedIndex ? (_) => _pressTo(1) : null,
onTapCancel: () {
if (_drag == null) _pressTo(0);
},
@@ -229,7 +254,8 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
onHorizontalDragEnd: index == widget.selectedIndex
? (details) => _select(
_position.round().clamp(0, 2),
details.velocity.pixelsPerSecond.dx / _travel,
elastic: true,
velocity: details.velocity.pixelsPerSecond.dx / _travel,
)
: null,
onHorizontalDragCancel: index == widget.selectedIndex
@@ -238,7 +264,7 @@ class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
final position = _position;
setState(() => _drag = null);
_motion.value = position;
_spring(widget.selectedIndex);
_moveTo(widget.selectedIndex, elastic: true);
_pressTo(0);
}
: null,