feat: deliver RSchedule service login exams and elastic glass navigation

This commit is contained in:
Codex
2026-10-13 17:06:50 +08:00
parent 9193fd8e43
commit 8f20a341c4
35 changed files with 1742 additions and 453 deletions
+8
View File
@@ -8,6 +8,7 @@ import '../services/notification_service.dart';
import '../services/calendar_service.dart';
import '../domain/schedule_engine.dart';
import '../data/demo_schedule.dart';
import '../domain/exam_schedule.dart';
class AppController extends ChangeNotifier {
AppController(this.store, this.notifications, this.calendar, this.clock);
@@ -174,6 +175,13 @@ class AppController extends ChangeNotifier {
}
await _cleanupCalendar();
});
Future<void> applyExams(ExamSchedule value) => _run(() async {
final validated = ExamSchedule.fromJson(value.toJson());
await _save(snapshot.copyWith(examSchedule: validated));
});
Future<void> clearExams() => _run(() async {
await _save(snapshot.copyWith(clearExams: true));
});
Future<void> disableCalendar({required bool deleteEvents}) => _run(() async {
await _save(
snapshot.copyWith(
+88 -21
View File
@@ -7,6 +7,8 @@ import '../features/timetable/course_details.dart';
import 'app_controller.dart';
import 'app_theme.dart';
import '../widgets/glass_dock.dart';
import '../widgets/tab_deck.dart';
import '../features/exams/exams_page.dart';
import '../features/timetable/timetable_page.dart';
import '../features/profile/profile_page.dart';
import '../features/school/school_session.dart';
@@ -26,7 +28,7 @@ class HepanApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Riverside Schedule',
title: 'RSchedule',
theme: hepanTheme(),
locale: const Locale('zh', 'CN'),
supportedLocales: const [Locale('zh', 'CN')],
@@ -57,6 +59,33 @@ class _Shell extends StatefulWidget {
class _ShellState extends State<_Shell> with WidgetsBindingObserver {
int _tab = 0;
bool _dockHidden = false;
double _scrollTravel = 0;
void _selectTab(int index) {
if (index == _tab) return;
setState(() {
_tab = index;
_dockHidden = false;
_scrollTravel = 0;
});
}
bool _scroll(ScrollNotification notification) {
if (_tab == 2 || notification.metrics.axis != Axis.vertical) return false;
if (notification is ScrollUpdateNotification &&
notification.dragDetails != null) {
final delta = notification.scrollDelta ?? 0;
if (delta.sign != _scrollTravel.sign) _scrollTravel = 0;
_scrollTravel += delta;
final hide = notification.metrics.pixels > 0 && _scrollTravel > 24;
final reveal = notification.metrics.pixels <= 0 || _scrollTravel < -16;
if ((hide && !_dockHidden) || (reveal && _dockHidden)) {
setState(() => _dockHidden = hide);
}
}
return false;
}
@override
void initState() {
super.initState();
@@ -107,8 +136,13 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
}
}
void _school() {
void _school({bool exams = false}) {
if (widget.schoolBuilder != null) {
if (exams) {
widget.school?.openExams();
} else {
widget.school?.openTimetable();
}
Navigator.push(
context,
MaterialPageRoute<void>(builder: (_) => widget.schoolBuilder!()),
@@ -135,7 +169,7 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
context: context,
builder: (context) => AlertDialog(
title: const Text('退出学校登录'),
content: const Text('已导入的课表是否保留在手机中?'),
content: const Text('已导入的课表和考试信息是否保留在手机中?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, 0),
@@ -143,11 +177,11 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
),
TextButton(
onPressed: () => Navigator.pop(context, 1),
child: const Text('保留课表'),
child: const Text('保留课表和考试'),
),
TextButton(
onPressed: () => Navigator.pop(context, 2),
child: const Text('清除课表'),
child: const Text('清除课表和考试'),
),
],
),
@@ -156,6 +190,7 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
await widget.school?.logout();
if (choice == 2) {
await widget.controller.clearCourses();
await widget.controller.clearExams();
}
}
@@ -232,19 +267,31 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
),
),
Expanded(
child: IndexedStack(
index: _tab,
children: [
TimetablePage(controller: widget.controller),
ProfilePage(
controller: widget.controller,
onLogin: _school,
authStatus: widget.school?.statusLabel ?? '未登录',
onLogout: widget.school?.hasOpened == true
? _logout
: null,
),
],
child: NotificationListener<ScrollNotification>(
onNotification: _scroll,
child: TabDeck(
index: _tab,
children: [
TimetablePage(controller: widget.controller),
ExamsPage(
controller: widget.controller,
onSync: () {
_school(exams: true);
},
),
ProfilePage(
controller: widget.controller,
onLogin: _school,
authStatus: widget.school?.statusLabel ?? '未登录',
logoutLabel: widget.school?.logoutFailed == true
? '重试退出学校登录'
: '退出学校登录',
onLogout: widget.school?.canLogout == true
? _logout
: null,
),
],
),
),
),
],
@@ -255,9 +302,29 @@ class _ShellState extends State<_Shell> with WidgetsBindingObserver {
right: 0,
bottom: 16 + MediaQuery.paddingOf(context).bottom,
child: Center(
child: GlassDock(
selectedIndex: _tab,
onSelected: (index) => setState(() => _tab = index),
child: IgnorePointer(
ignoring: _dockHidden,
child: ExcludeSemantics(
excluding: _dockHidden,
child: AnimatedSlide(
key: const Key('floating-dock'),
offset: _dockHidden
? const Offset(0, 1.8)
: Offset.zero,
duration: MediaQuery.disableAnimationsOf(context)
? Duration.zero
: const Duration(milliseconds: 240),
curve: Curves.easeOutCubic,
child: AnimatedOpacity(
opacity: _dockHidden ? 0 : 1,
duration: const Duration(milliseconds: 180),
child: GlassDock(
selectedIndex: _tab,
onSelected: _selectTab,
),
),
),
),
),
),
),
+12
View File
@@ -1,6 +1,7 @@
import 'app_settings.dart';
import 'course.dart';
import 'semester.dart';
import 'exam_schedule.dart';
class ImportMetadata {
const ImportMetadata({
@@ -18,6 +19,7 @@ class AppSnapshot {
this.settings = const AppSettings(),
List<Course> courses = const [],
this.importMetadata,
this.examSchedule,
this.calendarCleanupPending = false,
Map<String, String> calendarEventIds = const {},
}) : courses = List.unmodifiable(courses),
@@ -25,6 +27,7 @@ class AppSnapshot {
final AppSettings settings;
final List<Course> courses;
final ImportMetadata? importMetadata;
final ExamSchedule? examSchedule;
final Map<String, String> calendarEventIds;
final bool calendarCleanupPending;
AppSnapshot copyWith({
@@ -33,6 +36,8 @@ class AppSnapshot {
ImportMetadata? importMetadata,
Map<String, String>? calendarEventIds,
bool clearMetadata = false,
ExamSchedule? examSchedule,
bool clearExams = false,
bool? calendarCleanupPending,
}) => AppSnapshot(
settings: settings ?? this.settings,
@@ -40,12 +45,14 @@ class AppSnapshot {
importMetadata: clearMetadata
? null
: importMetadata ?? this.importMetadata,
examSchedule: clearExams ? null : examSchedule ?? this.examSchedule,
calendarEventIds: calendarEventIds ?? this.calendarEventIds,
calendarCleanupPending:
calendarCleanupPending ?? this.calendarCleanupPending,
);
Map<String, dynamic> toJson() => {
'schemaVersion': 1,
'examSchedule': examSchedule?.toJson(),
'courses': courses.map((c) => c.toJson()).toList(),
'settings': {
'semester': settings.semester == null
@@ -109,6 +116,11 @@ class AppSnapshot {
);
final metadata = json['importMetadata'];
return AppSnapshot(
examSchedule: json['examSchedule'] == null
? null
: ExamSchedule.fromJson(
Map<String, dynamic>.from(json['examSchedule'] as Map),
),
calendarCleanupPending:
(json['calendarCleanupPending'] ?? false) as bool,
courses: values,
+82
View File
@@ -0,0 +1,82 @@
class ExamRecord {
const ExamRecord({
required this.code,
required this.name,
this.assessment = '',
this.candidate = '',
this.sequence = '',
this.room = '',
this.seat = '',
this.time = '',
});
final String code, name, assessment, candidate, sequence, room, seat, time;
Map<String, dynamic> toJson() => {
'code': code,
'name': name,
'assessment': assessment,
'candidate': candidate,
'sequence': sequence,
'room': room,
'seat': seat,
'time': time,
};
factory ExamRecord.fromJson(Map<String, dynamic> json) {
String field(String key) {
final value = json[key];
if (value is! String || value.length > 1000) {
throw const FormatException('考试信息无效');
}
return value;
}
final record = ExamRecord(
code: field('code'),
name: field('name'),
assessment: field('assessment'),
candidate: field('candidate'),
sequence: field('sequence'),
room: field('room'),
seat: field('seat'),
time: field('time'),
);
if (record.code.isEmpty || record.name.isEmpty) {
throw const FormatException('考试课程无效');
}
return record;
}
}
class ExamSchedule {
ExamSchedule({
required this.semesterLabel,
required this.termId,
required List<ExamRecord> records,
}) : records = List.unmodifiable(records);
final String semesterLabel, termId;
final List<ExamRecord> records;
Map<String, dynamic> toJson() => {
'semesterLabel': semesterLabel,
'termId': termId,
'records': records.map((r) => r.toJson()).toList(),
};
factory ExamSchedule.fromJson(Map<String, dynamic> json) {
final label = json['semesterLabel'],
id = json['termId'],
rows = json['records'];
if (label is! String ||
label.trim().isEmpty ||
id is! String ||
!RegExp(r'^\d+$').hasMatch(id) ||
rows is! List ||
rows.length > 500) {
throw const FormatException('考试列表无效');
}
final records = rows
.map((r) => ExamRecord.fromJson(Map<String, dynamic>.from(r as Map)))
.toList();
if (records.map((r) => r.code).toSet().length != records.length) {
throw const FormatException('考试课程重复');
}
return ExamSchedule(semesterLabel: label, termId: id, records: records);
}
}
+202
View File
@@ -0,0 +1,202 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../../app/app_controller.dart';
import '../../app/app_theme.dart';
import '../school/school_exam_adapter.dart';
class ExamsPage extends StatelessWidget {
const ExamsPage({super.key, required this.controller, required this.onSync});
final AppController controller;
final VoidCallback onSync;
Future<void> _import(BuildContext context) async {
try {
final file = await FilePicker.pickFile(
type: FileType.custom,
allowedExtensions: ['html', 'htm'],
);
if (file == null) return;
final bytes = BytesBuilder(copy: false);
var length = 0;
await for (final chunk in file.readAsByteStream()) {
length += chunk.length;
if (length > 2 * 1024 * 1024) {
throw const FormatException('文件不能超过 2 MB');
}
bytes.add(chunk);
}
final draft = SchoolExamAdapter.extract(utf8.decode(bytes.takeBytes()));
if (!context.mounted) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('导入考试信息'),
content: Text(
'${draft.semesterLabel} · ${draft.records.length} 门课程\n将更新本机考试列表,尚未公布的字段显示为“尚未安排”。',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('确认导入'),
),
],
),
);
if (confirmed == true) {
await controller.applyExams(draft);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(controller.lastError ?? '考试信息已导入')),
);
}
}
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('导入未完成:$error')));
}
}
}
@override
Widget build(BuildContext context) {
final schedule = controller.snapshot.examSchedule;
return ListView(
key: const PageStorageKey('exams-scroll'),
padding: EdgeInsets.fromLTRB(
22,
10,
22,
140 + MediaQuery.paddingOf(context).bottom,
),
children: [
const Text(
'RSchedule',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
const SizedBox(height: 18),
Row(
children: [
const Expanded(
child: Text(
'考试安排',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w700),
),
),
IconButton(
tooltip: '从学校更新考试',
onPressed: onSync,
icon: const Icon(Icons.sync_rounded),
),
IconButton(
tooltip: '导入考试 HTML',
onPressed: () => _import(context),
icon: const Icon(Icons.file_download_outlined),
),
],
),
const SizedBox(height: 8),
if (schedule == null) ...[
const SizedBox(height: 54),
const Icon(
Icons.assignment_outlined,
size: 64,
color: Color(0xFF9ABBE8),
),
const SizedBox(height: 20),
const Text(
'等待学校公布考试安排',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
const SizedBox(height: 12),
const Text(
'连接研究生系统,或导入学校考试页面的 HTML。',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, height: 1.8),
),
const SizedBox(height: 24),
Center(
child: FilledButton.icon(
onPressed: onSync,
icon: const Icon(Icons.school_outlined),
label: const Text('连接学校考试查询'),
),
),
] else ...[
Text(
'${schedule.semesterLabel} · ${schedule.records.length} 门课程',
style: TextStyle(fontSize: 13, color: ink.withValues(alpha: 0.55)),
),
const SizedBox(height: 18),
if (schedule.records.isEmpty) const Text('该学期暂无考试课程'),
for (final exam in schedule.records)
Padding(
padding: const EdgeInsets.only(bottom: 14),
child: SurfaceCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
exam.name,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 14),
_field(Icons.schedule_rounded, '考试时间', exam.time),
_field(Icons.location_on_outlined, '考场', exam.room),
_field(Icons.event_seat_outlined, '座位号', exam.seat),
if (exam.assessment.isNotEmpty)
_field(
Icons.assignment_outlined,
'考核方式',
exam.assessment,
),
if (exam.candidate.isNotEmpty)
_field(Icons.badge_outlined, '考生编号', exam.candidate),
if (exam.sequence.isNotEmpty)
_field(
Icons.format_list_numbered,
'考场顺序号',
exam.sequence,
),
],
),
),
),
const Text(
'排考信息以学校最新公布为准。',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 11, color: Color(0xFF8493A5)),
),
],
],
);
}
Widget _field(IconData icon, String label, String value) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 17, color: const Color(0xFF007AFF)),
const SizedBox(width: 9),
Expanded(
child: Text(
'$label:${value.isEmpty ? '尚未安排' : value}',
style: const TextStyle(fontSize: 13, height: 1.5),
),
),
],
),
);
}
@@ -17,11 +17,12 @@ class ProfilePage extends StatelessWidget {
required this.onLogin,
this.authStatus = '未登录',
this.onLogout,
this.logoutLabel = '退出学校登录',
});
final AppController controller;
final VoidCallback onLogin;
final VoidCallback? onLogout;
final String authStatus;
final String authStatus, logoutLabel;
Future<void> _import(BuildContext context) async {
try {
final file = await FilePicker.pickFile(
@@ -67,7 +68,7 @@ class ProfilePage extends StatelessWidget {
),
children: [
const Text(
'Riverside Schedule',
'RSchedule',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
const SizedBox(height: 16),
@@ -114,7 +115,7 @@ class ProfilePage extends StatelessWidget {
Center(
child: TextButton(
onPressed: onLogout,
child: const Text('退出学校登录'),
child: Text(logoutLabel),
),
),
],
@@ -210,7 +211,7 @@ class ProfilePage extends StatelessWidget {
child: Column(
children: [
const Text(
'Riverside Schedule',
'RSchedule',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
),
const SizedBox(height: 6),
+80 -151
View File
@@ -2,8 +2,6 @@ import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../app/app_controller.dart';
import '../../app/app_theme.dart';
import '../profile/import_preview.dart';
import 'school_session.dart';
class SchoolAuthPage extends StatefulWidget {
@@ -19,202 +17,133 @@ class SchoolAuthPage extends StatefulWidget {
}
class _SchoolAuthPageState extends State<SchoolAuthPage> {
final _username = TextEditingController(),
_password = TextEditingController();
bool _showWeb = false, _previewing = false;
bool _saving = false;
@override
void initState() {
super.initState();
widget.session.addListener(_changed);
if (!widget.session.hasOpened) {
widget.session.open();
}
WidgetsBinding.instance.addPostFrameCallback((_) => _changed());
}
void _changed() {
if (!mounted) return;
setState(() {});
final draft = widget.session.pendingDraft;
if (draft != null && !_previewing) {
_previewing = true;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) return;
await showModalBottomSheet<bool>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (_) =>
ImportPreview(draft: draft, controller: widget.controller),
final s = widget.session;
final courses = s.pendingDraft, exams = s.pendingExams;
final generation = s.pageGeneration;
final route = ModalRoute.of(context);
if (_saving || (courses == null && exams == null)) return;
_saving = true;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) {
_saving = false;
return;
}
// The session draft must still belong to the same page after navigation.
if (generation != s.pageGeneration ||
courses != s.pendingDraft ||
exams != s.pendingExams) {
_saving = false;
_changed();
return;
}
if (courses != null) {
await widget.controller.applyImport(courses, confirmedEmpty: false);
}
if (exams != null) await widget.controller.applyExams(exams);
final success = widget.controller.lastError == null;
final acknowledged = s.saved(
success: success,
generation: generation,
draft: courses,
exams: exams,
);
_saving = false;
if (!mounted) return;
if (!acknowledged) {
_changed();
return;
}
if (success && route?.isCurrent == true) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(exams == null ? '课表已导入;请核对学期开始日。' : '考试信息已更新'),
),
);
widget.session.pendingDraft = null;
_previewing = false;
});
}
} else {
setState(() {});
}
});
}
@override
void dispose() {
widget.session.removeListener(_changed);
_password.clear();
_username.clear();
_password.dispose();
_username.dispose();
super.dispose();
}
Future<void> _submit() async {
if (_username.text.trim().isEmpty || _password.text.isEmpty) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('请输入学号和密码')));
return;
}
try {
await widget.session.submitCredentials(
_username.text.trim(),
_password.text,
);
} finally {
_password.clear();
if (mounted) {
setState(() => _showWeb = true);
}
}
}
@override
Widget build(BuildContext context) {
final s = widget.session;
return Scaffold(
appBar: AppBar(
title: const Text(
'学校认证',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700),
),
title: const Text('学校认证'),
actions: [
IconButton(
tooltip: _showWeb ? '应用登录界面' : '学校页面',
onPressed: () => setState(() => _showWeb = !_showWeb),
icon: Icon(
_showWeb ? Icons.person_outline : Icons.language_rounded,
),
tooltip: '重新认证',
onPressed: _saving ? null : s.openAuthentication,
icon: const Icon(Icons.refresh_rounded),
),
IconButton(
tooltip: '打开学校课表',
onPressed: () {
setState(() => _showWeb = true);
s.openTimetable();
},
icon: const Icon(Icons.calendar_month_outlined),
tooltip: '重试读取',
onPressed: _saving
? null
: (s.requestingExams ? s.openExams : s.openTimetable),
icon: const Icon(Icons.sync_rounded),
),
],
),
body: Column(
children: [
if (s.busy) const LinearProgressIndicator(minHeight: 2),
if (s.busy || _saving) const LinearProgressIndicator(minHeight: 2),
Container(
width: double.infinity,
padding: const EdgeInsets.all(13),
color: river.withValues(alpha: 0.07),
padding: const EdgeInsets.all(12),
color: const Color(0xFFEFF6FF),
child: Text(
s.message,
style: const TextStyle(fontSize: 12, height: 1.5, color: ink),
style: const TextStyle(fontSize: 12, height: 1.5),
),
),
Expanded(
child: _showWeb
? WebViewWidget(controller: s.web)
: ListView(
padding: const EdgeInsets.all(24),
children: [
const SizedBox(height: 20),
const Icon(Icons.school_outlined, size: 48, color: river),
const SizedBox(height: 20),
const Text(
'登录,连接你的每一天。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 23,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Text(
'电子科技大学统一身份认证',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13,
color: ink.withValues(alpha: 0.5),
),
),
const SizedBox(height: 30),
SurfaceCard(
child: Stack(
children: [
WebViewWidget(controller: s.web),
if (s.finding || _saving)
Positioned.fill(
child: ColoredBox(
color: const Color(0xFFF5F9FE),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _username,
textInputAction: TextInputAction.next,
autocorrect: false,
decoration: const InputDecoration(
labelText: '学号/工号',
prefixIcon: Icon(Icons.person_outline),
),
),
const SizedBox(height: 16),
TextField(
controller: _password,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: const InputDecoration(
labelText: '学校密码',
prefixIcon: Icon(Icons.lock_outline),
),
onSubmitted: (_) => _submit(),
),
const CircularProgressIndicator(),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: !s.busy && s.formReady
? _submit
: null,
child: Text(s.busy ? '正在准备学校认证…' : '登录并打开课表'),
),
),
const SizedBox(height: 10),
TextButton(
onPressed: () {
_password.clear();
setState(() => _showWeb = true);
s.openAuthentication();
},
child: const Text('使用学校页面登录'),
Text(
_saving
? '正在保存,请稍候'
: (s.requestingExams
? '正在查找考试安排,请稍候'
: '正在查找课表,请稍候'),
),
],
),
),
const SizedBox(height: 20),
Text(
'密码仅交给学校处理,不在应用中保存。需要验证码或其他验证时,将由学校页面继续处理。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
height: 1.7,
color: ink.withValues(alpha: 0.45),
),
),
const SizedBox(height: 14),
Text(
'学校课表识别待登录后联调;也可通过「我的」导入课表文件。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 11,
height: 1.6,
color: ink.withValues(alpha: 0.45),
),
),
],
),
),
],
),
),
],
),
@@ -0,0 +1,91 @@
import 'dart:convert';
import 'package:html/parser.dart' as html;
import '../../domain/exam_schedule.dart';
class SchoolExamAdapter {
static ExamSchedule extract(String content) {
try {
if (utf8.encode(content).length > 2 * 1024 * 1024) {
throw const FormatException();
}
final document = html.parse(content);
final selected = document.querySelector('#xqbh option[selected]');
final term = selected?.attributes['value'];
final table = document.querySelector('#sample-table-1');
const headers = [
'id',
'序号',
'学号',
'姓名',
'课程代码',
'课程名称',
'考核方式',
'考生编号',
'考场顺序号',
'考场',
'座位号',
'考试时间',
];
if (selected == null ||
term == null ||
table == null ||
!RegExp(r'^\d+$').hasMatch(term)) {
throw const FormatException();
}
final rows = table.querySelectorAll('tr');
if (rows.isEmpty || rows.first.children.length != headers.length) {
throw const FormatException();
}
for (var i = 0; i < headers.length; i++) {
if (rows.first.children[i].text.trim() != headers[i]) {
throw const FormatException();
}
}
final records = <ExamRecord>[];
var explicitlyEmpty = false;
for (final row in rows.skip(1)) {
// DataTables can insert a single explicit no-data placeholder.
if (row.children.length == 1 &&
row.children.first.attributes['colspan'] == '12' &&
const [
'没有数据',
'暂无数据',
'无数据',
'No data available in table',
].contains(row.text.trim())) {
explicitlyEmpty = true;
continue;
}
if (row.children.length != 12 ||
row.querySelector('script,style') != null) {
throw const FormatException();
}
final cells = row.children.map((c) => c.text.trim()).toList();
records.add(
ExamRecord(
code: cells[4],
name: cells[5],
assessment: cells[6],
candidate: cells[7],
sequence: cells[8],
room: cells[9],
seat: cells[10],
time: cells[11],
),
);
}
if (records.isEmpty && !explicitlyEmpty) throw const FormatException();
return ExamSchedule.fromJson(
ExamSchedule(
semesterLabel: selected.text.trim(),
termId: term,
records: records,
).toJson(),
);
} catch (_) {
throw const FormatException('未识别到完整的考试查询表,已有考试信息保持不变。');
}
}
}
@@ -0,0 +1,34 @@
import 'school_navigation_policy.dart';
/// Only the authenticated graduate system may advance the service handshake.
class SchoolLoginFlow {
Uri? _target;
bool _requested = false;
void begin(Uri target) {
_target = target;
_requested = false;
}
void reset() {
_target = null;
_requested = false;
}
Uri? onLoaded(Uri uri, {required bool authenticated}) {
if (_target == null || !SchoolNavigationPolicy.isSchoolPage(uri)) {
return null;
}
if (uri.host == 'idas.uestc.edu.cn') {
_requested = false;
return null;
}
if (uri.path == _target!.path ||
_requested ||
!authenticated ||
!uri.path.startsWith('/pyxx/')) {
return null;
}
_requested = true;
return _target;
}
}
@@ -1,4 +1,21 @@
class SchoolNavigationPolicy {
static Uri? secureIdentityRedirect(Uri uri) {
if (uri.scheme != 'http' ||
uri.port != 80 ||
uri.userInfo.isNotEmpty ||
uri.host != 'idas.uestc.edu.cn' ||
uri.path != '/authserver/login') {
return null;
}
return Uri(
scheme: 'https',
host: uri.host,
path: uri.path,
query: uri.hasQuery ? uri.query : null,
fragment: uri.hasFragment ? uri.fragment : null,
);
}
static bool canNavigate(Uri uri, {required bool isMainFrame}) => isMainFrame
? isSchoolPage(uri)
: (uri.scheme == 'https' && uri.userInfo.isEmpty) ||
@@ -17,6 +34,18 @@ class SchoolNavigationPolicy {
r'$',
).hasMatch(uri.path);
static bool isSchoolPage(Uri uri) =>
(_https(uri) &&
const {
'idas.uestc.edu.cn',
'yjsjy.uestc.edu.cn',
}.contains(uri.host)) ||
(uri.scheme == 'http' &&
uri.port == 80 &&
uri.userInfo.isEmpty &&
uri.host == 'yjsjy.uestc.edu.cn' &&
uri.path.startsWith('/pyxx/'));
static bool isExam(Uri uri) =>
_https(uri) &&
const {'idas.uestc.edu.cn', 'yjsjy.uestc.edu.cn'}.contains(uri.host);
uri.host == 'yjsjy.uestc.edu.cn' &&
uri.path == '/pyxx/pygl/kskcxx/index';
}
+253 -171
View File
@@ -1,11 +1,15 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../data/json_schedule_import.dart';
import '../../domain/exam_schedule.dart';
import 'school_navigation_policy.dart';
import 'school_page_adapter.dart';
import 'school_exam_adapter.dart';
import 'school_login_flow.dart';
enum SchoolConnectionState {
signedOut,
@@ -21,15 +25,30 @@ class SchoolSession extends ChangeNotifier {
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (request) {
onNavigationRequest: (request) async {
final uri = Uri.tryParse(request.url);
final upgrade = uri == null || !request.isMainFrame
? null
: SchoolNavigationPolicy.secureIdentityRedirect(uri);
if (upgrade != null) {
try {
await web.loadRequest(upgrade);
} catch (_) {
_failure('学校身份认证暂时无法打开,请重试。');
}
return NavigationDecision.prevent;
}
if (uri == null ||
!SchoolNavigationPolicy.canNavigate(
uri,
isMainFrame: request.isMainFrame,
)) {
message = '学校跳转到了其他地址,已停止自动交接登录信息。';
notifyListeners();
if (kDebugMode && request.isMainFrame) {
debugPrint(
'Blocked school navigation origin: ${uri?.scheme}://${uri?.host}',
);
}
if (request.isMainFrame) _failure('学校跳转到了其他地址,请返回学校认证入口重试。');
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
@@ -38,230 +57,293 @@ class SchoolSession extends ChangeNotifier {
_pageGeneration++;
_reader.invalidate();
pendingDraft = null;
if (!hasOpened) {
return;
}
pendingExams = null;
if (!hasOpened) return;
_loading = true;
formReady = false;
notifyListeners();
},
onPageFinished: _loaded,
onWebResourceError: (error) {
if (error.isForMainFrame == true) {
_loading = false;
message = '学校页面暂时未能加载,请检查网络或使用统一认证入口。';
notifyListeners();
onWebResourceError: (error) async {
if (error.isForMainFrame != true || error.url == null) return;
final generation = _pageGeneration;
final current = await web.currentUrl();
if (hasOpened &&
generation == _pageGeneration &&
error.url == current) {
_failure('学校页面暂时未能加载,请检查网络后重试。');
}
},
onHttpError: (error) async {
final generation = _pageGeneration;
final current = Uri.tryParse(await web.currentUrl() ?? '');
if (!hasOpened ||
error.request == null ||
error.request!.uri != current) {
return;
if (hasOpened &&
generation == _pageGeneration &&
error.request != null &&
error.request!.uri == current) {
_failure('学校请求未完成,请稍后重试。');
}
_loading = false;
message = '学校页面请求未完成,可稍后重试。';
notifyListeners();
},
),
);
}
late final WebViewController web;
final _reader = SchoolReader(SchoolPageAdapter());
final _flow = SchoolLoginFlow();
Timer? _timeout;
SchoolConnectionState connectionState = SchoolConnectionState.signedOut;
bool _loading = false,
_submitting = false,
hasOpened = false,
formReady = false;
bool get busy => _loading || _submitting || _reader.busy;
finding = false,
requestingExams = false;
bool logoutFailed = false;
bool get canLogout => hasOpened || logoutFailed;
bool get busy => _loading || _reader.busy;
int _pageGeneration = 0;
int get pageGeneration => _pageGeneration;
Future<void>? _logoutFuture;
int _openSerial = 0;
ImportDraft? pendingDraft;
String message = '请通过学校统一身份认证登录。';
String get statusLabel => switch (connectionState) {
SchoolConnectionState.signedOut => '未登录',
SchoolConnectionState.authenticating => '请在学校页面完成认证',
SchoolConnectionState.connected => '学校认证已确认',
SchoolConnectionState.expired => '学校登录已过期',
SchoolConnectionState.unknown => '学校页面已打开 · 等待完整课表',
};
ExamSchedule? pendingExams;
String message = '请在学校网页中完成登录与验证码。';
String get statusLabel => logoutFailed
? '学校退出未完成,请重试'
: switch (connectionState) {
SchoolConnectionState.signedOut => '未登录',
SchoolConnectionState.authenticating => '请在学校页面完成认证',
SchoolConnectionState.connected => '研究生系统已连接',
SchoolConnectionState.expired => '学校登录已过期',
SchoolConnectionState.unknown => '学校连接未确认',
};
// HTTPS entry produces the same official HTTP service callback. Do not drop
// the graduate-service query by opening a generic identity login page.
static final authUrl = Uri.parse(
'https://idas.uestc.edu.cn/authserver/login',
'https://yjsjy.uestc.edu.cn/pyxx/jzsso/login',
);
static final timetableUrl = Uri.parse(
'https://yjsjy.uestc.edu.cn/pyxx/pygl/xskbcx/index/1',
);
Future<void> open() => openTimetable();
Future<void> openTimetable() async {
hasOpened = true;
_loading = true;
static final examUrl = Uri.parse(
'https://yjsjy.uestc.edu.cn/pyxx/pygl/kskcxx/index',
);
Uri get _target => requestingExams ? examUrl : 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 {
final serial = ++_openSerial;
final closing = _logoutFuture;
if (closing != null) await closing;
if (serial != _openSerial) return;
_timeout?.cancel();
_pageGeneration++;
_reader.invalidate();
pendingDraft = null;
message = '正在打开研究生课表页面…';
notifyListeners();
try {
await web.loadRequest(timetableUrl);
} catch (_) {
_loading = false;
message = '学校课表页面无法打开,请检查校园网络。';
notifyListeners();
}
}
Future<void> openAuthentication() async {
pendingExams = null;
requestingExams = exams;
logoutFailed = false;
hasOpened = true;
_loading = true;
message = '正在准备学校认证…';
_flow.begin(_target);
final connected =
connectionState == SchoolConnectionState.connected && !forceAuth;
finding = connected;
message = connected ? _findingMessage : '请在学校网页中完成登录与验证码。';
if (connected) _armTimeout();
notifyListeners();
try {
await web.loadRequest(authUrl);
await web.loadRequest(connected ? _target : authUrl);
} catch (_) {
_loading = false;
message = '学校认证页面暂时不可用。';
notifyListeners();
if (serial == _openSerial) _failure('学校入口无法打开,请检查校园网络后重试。');
}
}
String get _findingMessage => requestingExams ? '正在查找考试安排,请稍候' : '正在查找课表,请稍候';
void _armTimeout() {
_timeout?.cancel();
_timeout = Timer(
const Duration(seconds: 45),
() => _failure('查找超时,请检查学校页面后重试。已有数据保持不变。'),
);
}
void _failure(String text) {
if (!hasOpened) return;
_pageGeneration++;
_reader.invalidate();
_timeout?.cancel();
finding = false;
_loading = false;
message = text;
notifyListeners();
}
Future<String> _html() async {
final raw = await web.runJavaScriptReturningResult(
'JSON.stringify(document.documentElement.outerHTML)',
);
final value = raw is String ? raw : raw.toString();
try {
final decoded = jsonDecode(value);
return decoded is String ? decoded : value;
} catch (_) {
return value;
}
}
static const _readyScript = """(() => {
if (location.origin !== 'https://idas.uestc.edu.cn' || location.pathname !== '/authserver/login') return false;
const f = document.querySelector('.login-main #pwdFromId');
if (!f || f.method.toLowerCase() !== 'post') return false;
const action = new URL(f.action, location.href);
return action.origin === location.origin && action.pathname === '/authserver/login'
&& !!f.querySelector('#username') && !!f.querySelector('#password')
&& !!f.querySelector('#saltPassword') && !!f.querySelector('#pwdEncryptSalt')
&& !!f.querySelector('#login_submit') && typeof window.startLogin === 'function'
&& typeof window.encryptPassword === 'function' && typeof window.checkUserCaptcha === 'function';
})()""";
bool _truth(Object value) => value == true || value.toString() == 'true';
Future<void> _loaded(String url) async {
if (!hasOpened) {
if (!hasOpened) return;
final generation = _pageGeneration;
final uri = Uri.tryParse(url);
final current = await web.currentUrl();
if (!hasOpened ||
generation != _pageGeneration ||
current != url ||
uri == null ||
!SchoolNavigationPolicy.isSchoolPage(uri)) {
return;
}
_loading = false;
final generation = _pageGeneration;
final uri = Uri.tryParse(url);
if (uri != null && SchoolNavigationPolicy.canInjectCredentials(uri)) {
connectionState = connectionState == SchoolConnectionState.connected
? SchoolConnectionState.expired
: SchoolConnectionState.authenticating;
if (uri.host == 'idas.uestc.edu.cn') {
_timeout?.cancel();
finding = false;
connectionState = SchoolConnectionState.authenticating;
_flow.onLoaded(uri, authenticated: false);
message = '请在学校网页中完成登录与验证码。';
notifyListeners();
return;
}
final targetPage = requestingExams
? SchoolNavigationPolicy.isExam(uri)
: SchoolNavigationPolicy.isTimetable(uri);
if (targetPage) {
finding = true;
message = _findingMessage;
notifyListeners();
try {
final ready = _truth(
await web.runJavaScriptReturningResult(_readyScript),
);
if (!hasOpened || generation != _pageGeneration) return;
formReady = ready;
if (requestingExams) {
final text = await _html();
if (!hasOpened || generation != _pageGeneration) return;
final draft = SchoolExamAdapter.extract(text);
pendingExams = draft;
} else {
final draft = await readTimetable();
if (!hasOpened || generation != _pageGeneration) return;
pendingDraft = draft;
}
_timeout?.cancel();
connectionState = SchoolConnectionState.connected;
message = '读取成功,正在保存…';
} catch (_) {
if (!hasOpened || generation != _pageGeneration) return;
formReady = false;
}
message = formReady ? '可以使用应用界面登录;验证码会在学校页面完成。' : '请使用学校原页面完成认证。';
} else if (uri != null && SchoolNavigationPolicy.isTimetable(uri)) {
connectionState = SchoolConnectionState.unknown;
message = '已打开课表页面,正在核对课程结构。';
try {
final draft = await readTimetable();
if (!hasOpened || generation != _pageGeneration) return;
pendingDraft = draft;
connectionState = SchoolConnectionState.connected;
} catch (error) {
if (!hasOpened || generation != _pageGeneration) return;
message = error is UnsupportedSchoolLayout
? error.toString()
: '课表读取未完成,已有课表保持不变。';
}
} else {
connectionState = SchoolConnectionState.unknown;
message = '可点击右上角日历打开学校课表。';
}
notifyListeners();
}
Future<void> submitCredentials(String username, String password) async {
if (busy) return;
_submitting = true;
message = '正在交接学校认证…';
notifyListeners();
try {
final url = Uri.tryParse(await web.currentUrl() ?? '');
if (url == null ||
!SchoolNavigationPolicy.canInjectCredentials(url) ||
!_truth(await web.runJavaScriptReturningResult(_readyScript))) {
throw StateError('学校表单尚未准备好,请使用学校页面登录');
}
final result = await web.runJavaScriptReturningResult('''(() => {
if (!($_readyScript)) return false;
const f = document.querySelector('.login-main #pwdFromId');
const u = f.querySelector('#username'), p = f.querySelector('#password');
u.value = ${jsonEncode(username)}; p.value = ${jsonEncode(password)};
p.removeAttribute('readonly');
u.dispatchEvent(new Event('input', {bubbles:true}));
p.dispatchEvent(new Event('input', {bubbles:true}));
window.checkUserCaptcha(); return true;
})()''');
if (!_truth(result)) throw StateError('学校表单已变化,请使用学校页面登录');
var settled = false;
for (var i = 0; i < 20; i++) {
if (_truth(
await web.runJavaScriptReturningResult(
'!!window.jQuery && window.jQuery.active === 0',
),
)) {
settled = true;
break;
}
await Future<void>.delayed(const Duration(milliseconds: 200));
}
final current = Uri.tryParse(await web.currentUrl() ?? '');
if (!settled ||
current == null ||
!SchoolNavigationPolicy.canInjectCredentials(current)) {
message = '请在学校页面继续完成验证。';
_failure(
'没有读取到完整${requestingExams ? '考试信息' : '课表'},请检查学校页面后重试。已有数据保持不变。',
);
return;
}
await web.runJavaScript('''(() => {
if (!($_readyScript)) return;
window.startLogin(document.querySelector('.login-main #pwdFromId #login_submit'));
})()''');
message = '已交给学校处理;如有验证码,请在学校页面完成。';
} catch (_) {
message = '登录交接未完成,请使用学校页面继续。';
} finally {
_submitting = false;
notifyListeners();
} else {
// A logout link is evidence of a graduate-system session, unlike simply
// returning to a callback URL or the identity administration dashboard.
bool authenticated = false;
try {
authenticated = _truth(
await web.runJavaScriptReturningResult("""(() => {
return Array.from(document.querySelectorAll('a[href]')).some(a => {
try { const u = new URL(a.href, location.href); return u.hostname === 'yjsjy.uestc.edu.cn' && u.pathname === '/pyxx/home/exit'; } catch (_) { return false; }
});
})()"""),
);
} catch (_) {
/* Keep the school page available for manual recovery. */
}
if (!hasOpened || generation != _pageGeneration) return;
final next = _flow.onLoaded(uri, authenticated: authenticated);
if (next != null) {
finding = true;
_loading = true;
message = _findingMessage;
_armTimeout();
notifyListeners();
try {
await web.loadRequest(next);
} catch (_) {
_failure('课表查询页面暂时无法打开,请重试。');
}
return;
}
finding = false;
message = '请在学校网页完成认证;进入研究生系统后会自动读取。';
}
notifyListeners();
}
Future<ImportDraft> readTimetable() async {
final uri = Uri.tryParse(await web.currentUrl() ?? '');
if (uri == null) throw UnsupportedSchoolLayout();
return _reader.read(uri, () async {
final raw = await web.runJavaScriptReturningResult(
'JSON.stringify(document.documentElement.outerHTML)',
);
final value = raw is String ? raw : raw.toString();
try {
final decoded = jsonDecode(value);
return decoded is String ? decoded : value;
} catch (_) {
return value;
}
});
return _reader.read(uri, _html);
}
Future<void> logout() async {
bool saved({
required bool success,
required int generation,
ImportDraft? draft,
ExamSchedule? exams,
}) {
if (generation != _pageGeneration ||
draft != pendingDraft ||
exams != pendingExams) {
return false;
}
pendingDraft = null;
pendingExams = null;
finding = false;
message = success
? '${requestingExams ? '考试安排' : '课表'}已导入并在本机保存。'
: '保存未完成,请重试。';
notifyListeners();
return true;
}
Future<void> logout() {
if (_logoutFuture != null) return _logoutFuture!;
final future = _performLogout();
_logoutFuture = future;
return future.whenComplete(() => _logoutFuture = null);
}
Future<void> _performLogout() async {
_openSerial++;
_pageGeneration++;
_reader.invalidate();
hasOpened = false;
await WebViewCookieManager().clearCookies();
await web.clearCache();
await web.clearLocalStorage();
await web.loadHtmlString('<html></html>');
_loading = false;
_flow.reset();
_timeout?.cancel();
hasOpened = false;
pendingDraft = null;
formReady = false;
connectionState = SchoolConnectionState.signedOut;
message = '已退出学校登录。';
pendingExams = null;
finding = false;
var failed = false;
try {
await WebViewCookieManager().clearCookies();
await web.clearCache();
await web.clearLocalStorage();
await web.loadHtmlString('<html></html>');
} catch (_) {
failed = true;
}
_loading = false;
logoutFailed = failed;
connectionState = failed
? SchoolConnectionState.unknown
: SchoolConnectionState.signedOut;
message = failed ? '学校退出未完成,请重试;重新连接会再次经过学校认证。' : '已退出学校登录。';
notifyListeners();
}
@override
void dispose() {
_timeout?.cancel();
super.dispose();
}
}
@@ -32,6 +32,7 @@ class _TimetablePageState extends State<TimetablePage> {
: term.firstMonday.add(Duration(days: (week - 1) * 7));
final sunday = monday.add(const Duration(days: 6));
return ListView(
key: const PageStorageKey('timetable-scroll'),
padding: EdgeInsets.fromLTRB(
8,
10,
@@ -40,7 +41,7 @@ class _TimetablePageState extends State<TimetablePage> {
),
children: [
const Text(
'Riverside Schedule',
'RSchedule',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
@@ -157,7 +158,7 @@ class _TimetablePageState extends State<TimetablePage> {
),
const SizedBox(height: 12),
Text(
'在「我的」设置学期并导入课程,\n或先看看示例课表。',
'在「个人设置」设置学期并导入课程,\n或先看看示例课表。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13,
+142 -60
View File
@@ -2,6 +2,7 @@ import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
class GlassDock extends StatefulWidget {
const GlassDock({
@@ -15,16 +16,59 @@ class GlassDock extends StatefulWidget {
State<GlassDock> createState() => _GlassDockState();
}
class _GlassDockState extends State<GlassDock> {
static const _width = 192.0, _travel = 88.0;
class _GlassDockState extends State<GlassDock> with TickerProviderStateMixin {
static const _width = 280.0, _travel = 88.0;
static const _blue = Color(0xFF007AFF);
late final AnimationController _motion = AnimationController.unbounded(
vsync: this,
value: widget.selectedIndex.toDouble(),
);
late final AnimationController _press = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 140),
);
double? _drag;
double get _position => _drag ?? widget.selectedIndex.toDouble();
void _select(int index) {
double _dragSpeed = 0;
double get _position => _drag ?? _motion.value.clamp(-0.12, 2.12);
void _spring(int index, [double velocity = 0]) {
if (MediaQuery.disableAnimationsOf(context)) {
_motion.value = index.toDouble();
return;
}
_motion.animateWith(
SpringSimulation(
const SpringDescription(mass: 1, stiffness: 380, damping: 23),
_position,
index.toDouble(),
velocity.clamp(-8, 8),
),
);
}
void _select(int index, [double velocity = 0]) {
final position = _position;
setState(() => _drag = null);
_motion.value = position;
_spring(index, velocity);
_press.reverse();
widget.onSelected(index);
}
@override
void didUpdateWidget(GlassDock oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selectedIndex != widget.selectedIndex && _drag == null) {
_spring(widget.selectedIndex);
}
}
@override
void dispose() {
_motion.dispose();
_press.dispose();
super.dispose();
}
Widget _glass({required Widget child, bool lens = false}) => ClipRRect(
borderRadius: BorderRadius.circular(lens ? 36 : 40),
child: BackdropFilter(
@@ -61,50 +105,60 @@ class _GlassDockState extends State<GlassDock> {
);
@override
Widget build(BuildContext context) => SizedBox(
width: _width,
height: 70,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
boxShadow: [
BoxShadow(
color: _blue.withValues(alpha: 0.035),
blurRadius: 12,
offset: const Offset(0, 5),
Widget build(BuildContext context) => AnimatedBuilder(
animation: Listenable.merge([_motion, _press]),
builder: (context, _) {
final press = Curves.easeOut.transform(_press.value);
final speed = (_drag != null ? _dragSpeed : _motion.velocity).abs();
final stretch = (speed / 16).clamp(0.0, 0.14) + press * 0.04;
final lensWidth = 88 * (1 + stretch);
final lensHeight = 56 + press * 5 - stretch * 9;
return SizedBox(
width: _width,
height: 70,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(40),
boxShadow: [
BoxShadow(
color: _blue.withValues(alpha: 0.035),
blurRadius: 12,
offset: const Offset(0, 5),
),
],
),
],
),
child: _glass(
child: Stack(
children: [
AnimatedPositioned(
duration: Duration(milliseconds: _drag == null ? 260 : 0),
curve: Curves.easeOutCubic,
left: 7 + _position * _travel,
top: _drag == null ? 7 : 5,
width: _drag == null ? 90 : 94,
height: _drag == null ? 56 : 60,
child: IgnorePointer(
child: _glass(lens: true, child: const SizedBox.expand()),
),
child: _glass(
child: Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: 8 + _position * _travel - (lensWidth - 88) / 2,
top: (70 - lensHeight) / 2,
width: lensWidth,
height: lensHeight,
child: IgnorePointer(
child: _glass(lens: true, child: const SizedBox.expand()),
),
),
Positioned(
left: 8,
right: 8,
top: 7,
bottom: 7,
child: Row(
children: [
_item(0, Icons.calendar_month_rounded, '课表'),
_item(1, Icons.assignment_outlined, '考试'),
_item(2, Icons.person_rounded, '个人设置'),
],
),
),
],
),
Positioned(
left: 8,
right: 8,
top: 7,
bottom: 7,
child: Row(
children: [
_item(0, Icons.calendar_month_rounded, '课表'),
_item(1, Icons.person_rounded, '我的'),
],
),
),
],
),
),
),
),
);
},
);
Widget _item(int index, IconData icon, String label) => Expanded(
child: Semantics(
@@ -116,31 +170,59 @@ class _GlassDockState extends State<GlassDock> {
child: GestureDetector(
key: index == widget.selectedIndex ? const Key('dock-cursor') : null,
behavior: HitTestBehavior.opaque,
onTapDown: (_) => _press.forward(),
onTapCancel: () {
if (_drag == null) _press.reverse();
},
onTap: () => _select(index),
onHorizontalDragStart: index == widget.selectedIndex
? (_) => setState(() => _drag = widget.selectedIndex.toDouble())
? (_) {
final start = _position.clamp(0.0, 2.0);
_motion.stop();
_press.forward();
setState(() {
_drag = start;
_dragSpeed = 0;
});
}
: null,
onHorizontalDragUpdate: index == widget.selectedIndex
? (details) => setState(
() => _drag = (_position + details.delta.dx / _travel).clamp(
0,
1,
),
)
? (details) => setState(() {
_dragSpeed = details.delta.dx / _travel * 60;
_drag = (_position + details.delta.dx / _travel).clamp(
0.0,
2.0,
);
})
: null,
onHorizontalDragEnd: index == widget.selectedIndex
? (_) => _select(_position >= 0.5 ? 1 : 0)
? (details) => _select(
_position.round().clamp(0, 2),
details.velocity.pixelsPerSecond.dx / _travel,
)
: null,
onHorizontalDragCancel: index == widget.selectedIndex
? () => setState(() => _drag = null)
? () {
final position = _position;
setState(() => _drag = null);
_motion.value = position;
_spring(widget.selectedIndex);
_press.reverse();
}
: null,
child: Center(
child: Icon(
icon,
size: 27,
color: index == (_position >= 0.5 ? 1 : 0)
? _blue
: _blue.withValues(alpha: 0.48),
child: AnimatedScale(
scale: index == _position.round().clamp(0, 2)
? 1 + _press.value * 0.08
: 1,
duration: const Duration(milliseconds: 130),
child: Icon(
icon,
size: 27,
color: index == _position.round().clamp(0, 2)
? _blue
: _blue.withValues(alpha: 0.48),
),
),
),
),
+78
View File
@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
/// Retains all tab states and scroll positions, with no page-swipe recognizer.
class TabDeck extends StatefulWidget {
const TabDeck({super.key, required this.index, required this.children});
final int index;
final List<Widget> children;
@override
State<TabDeck> createState() => _TabDeckState();
}
class _TabDeckState extends State<TabDeck> with SingleTickerProviderStateMixin {
late final AnimationController _motion = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 330),
value: 1,
);
int? _outgoing;
int _direction = 1;
@override
void didUpdateWidget(TabDeck oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.index != widget.index) {
_outgoing = oldWidget.index;
_direction = widget.index > oldWidget.index ? 1 : -1;
if (MediaQuery.disableAnimationsOf(context)) {
_motion.value = 1;
} else {
_motion.forward(from: 0);
}
}
}
@override
void dispose() {
_motion.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: _motion,
builder: (context, _) {
final t = Curves.easeOutCubic.transform(_motion.value);
return Stack(
fit: StackFit.expand,
children: [
for (var i = 0; i < widget.children.length; i++)
Offstage(
offstage:
i != widget.index && (i != _outgoing || _motion.isCompleted),
child: TickerMode(
enabled: i == widget.index,
child: IgnorePointer(
ignoring: i != widget.index,
child: ExcludeSemantics(
excluding: i != widget.index,
child: Opacity(
opacity: i == widget.index
? t
: (i == _outgoing ? 1 - t : 0),
child: Transform.translate(
offset: Offset(
(i == widget.index ? 1 - t : -t) * 22 * _direction,
0,
),
child: widget.children[i],
),
),
),
),
),
),
],
);
},
);
}