基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
refactor(ui): unify expressive components and remove legacy code (#2533)
Prediditba52a11c53a0
diff --git a/analysis_options.yaml b/analysis_options.yamlindex cbdb82ca..186668a1 100644--- a/analysis_options.yaml+++ b/analysis_options.yaml@@ -1,32 +1,5 @@-# This file configures the analyzer, which statically analyzes Dart code to-# check for errors, warnings, and lints.-#-# The issues identified by the analyzer are surfaced in the UI of Dart-enabled-# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be-# invoked from the command line by running `flutter analyze`.--# The following line activates a set of recommended lints for Flutter apps,-# packages, and plugins designed to encourage good coding practices.include: package:flutter_lints/flutter.yaml-linter:- # The lint rules applied to this project can be customized in the- # section below to disable rules from the `package:flutter_lints/flutter.yaml`- # included above or to enable additional rules. A list of all available lints- # and their documentation is published at https://dart.dev/lints.- #- # Instead of disabling a lint rule for the entire project in the- # section below, it can also be suppressed for a single line of code- # or a specific dart file by using the `// ignore: name_of_lint` and- # `// ignore_for_file: name_of_lint` syntax on the line or in the file- # producing the lint.- rules:- # avoid_print: false # Uncomment to disable the `avoid_print` rule- # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule--# Additional information about this file can be found at-# https://dart.dev/guides/language/analysis-options-analyzer:exclude:- .cache/**diff --git a/lib/bean/appbar/safe_mediaquery_warpper.dart b/lib/bean/appbar/safe_mediaquery_warpper.dartdeleted file mode 100644index 979e02c8..00000000--- a/lib/bean/appbar/safe_mediaquery_warpper.dart+++ /dev/null@@ -1,47 +0,0 @@-import 'package:flutter/material.dart';--/// workaround for padding check error on Xiaomi HyperOS devices-/// caused by flutter/flutter#161086-/// this is a temporary solution, will be removed in the future-class SafeMediaQueryWrapper extends StatelessWidget {- final Widget child;- final double defaultTopPadding;- final double defaultBottomPadding;-- const SafeMediaQueryWrapper({- super.key,- required this.child,- this.defaultTopPadding = 25,- this.defaultBottomPadding = 0,- });-- @override- Widget build(BuildContext context) {- final mediaQuery = MediaQuery.of(context);- final viewPadding = mediaQuery.viewPadding;-- final isPaddingCheckError = viewPadding.top < 0 || viewPadding.top > 50;-- if (!isPaddingCheckError) {- return child;- }-- return MediaQuery(- data: mediaQuery.copyWith(- viewPadding: EdgeInsets.only(- top: defaultTopPadding,- bottom: defaultBottomPadding,- left: viewPadding.left,- right: viewPadding.right,- ),- padding: EdgeInsets.only(- top: defaultTopPadding,- bottom: defaultBottomPadding,- left: mediaQuery.padding.left,- right: mediaQuery.padding.right,- ),- ),- child: child,- );- }-}diff --git a/lib/bean/dialog/adaptive_bottom_sheet.dart b/lib/bean/dialog/adaptive_bottom_sheet.dartindex b3532650..babb3464 100644--- a/lib/bean/dialog/adaptive_bottom_sheet.dart+++ b/lib/bean/dialog/adaptive_bottom_sheet.dart@@ -1,12 +1,16 @@+// Adapted from m3e_core 1.1.2's M3EBottomSheet (MIT).+// Copyright (c) 2026 Mudit Purohit. See licenses/m3e_core.txt.import 'dart:math' as math;import 'package:flutter/material.dart';+import 'package:flutter/physics.dart';+import 'package:kazumi/utils/device.dart';-BoxConstraints adaptiveBottomSheetConstraints(+BoxConstraints _adaptiveBottomSheetConstraints(BuildContext context, {- double maxHeightFactor = 0.75,- double compactLandscapeMaxHeightFactor = 0.9,+ required double maxHeightFactor,+ required double compactLandscapeMaxHeightFactor,}) {final size = MediaQuery.sizeOf(context);final isLandscape = size.width > size.height;@@ -32,24 +36,175 @@ Future<T?> showAdaptiveBottomSheet<T>({required WidgetBuilder builder,double maxHeightFactor = 0.75,double compactLandscapeMaxHeightFactor = 0.9,- Color? backgroundColor,- bool showDragHandle = false,+ bool useRootNavigator = false,}) {- return showModalBottomSheet<T>(+ return _showMaterialBottomSheet<T>(context: context,builder: builder,- isScrollControlled: true,- useSafeArea: true,- showDragHandle: showDragHandle,- constraints: adaptiveBottomSheetConstraints(+ useRootNavigator: useRootNavigator,+ constraints: _adaptiveBottomSheetConstraints(context,maxHeightFactor: maxHeightFactor,compactLandscapeMaxHeightFactor: compactLandscapeMaxHeightFactor,),- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.vertical(top: Radius.circular(28)),+ );+}++const ShapeBorder _materialSheetShape = RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(28)),+);++// Native route motion and the extra surface entrance spring are separate.+const AnimationStyle _materialSheetAnimationStyle = AnimationStyle(+ duration: Duration(milliseconds: 250),+ reverseDuration: Duration(milliseconds: 200),+ curve: Easing.legacyDecelerate,+ reverseCurve: Easing.legacyDecelerate,+);++Future<T?> _showMaterialBottomSheet<T>({+ required BuildContext context,+ required WidgetBuilder builder,+ required BoxConstraints constraints,+ required bool useRootNavigator,+}) {+ return showModalBottomSheet<T>(+ context: context,+ // A single surface owns the handle and background to avoid a second cap.+ backgroundColor: Colors.transparent,+ elevation: 0,+ shape: const RoundedRectangleBorder(),+ clipBehavior: Clip.none,+ constraints: constraints,+ isScrollControlled: true,+ useRootNavigator: useRootNavigator,+ showDragHandle: false,+ useSafeArea: true,+ sheetAnimationStyle: MediaQuery.disableAnimationsOf(context)+ ? AnimationStyle.noAnimation+ : _materialSheetAnimationStyle,+ builder: (context) => _MaterialSheetSurface(+ child: Builder(builder: builder),),- clipBehavior: Clip.antiAlias,- backgroundColor: backgroundColor ?? Theme.of(context).colorScheme.surface,);}++class _MaterialSheetSurface extends StatefulWidget {+ const _MaterialSheetSurface({required this.child});++ final Widget child;++ @override+ State<_MaterialSheetSurface> createState() => _MaterialSheetSurfaceState();+}++class _MaterialSheetSurfaceState extends State<_MaterialSheetSurface>+ with SingleTickerProviderStateMixin {+ late final _entrance = AnimationController.unbounded(vsync: this);+ bool _started = false;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ if (MediaQuery.disableAnimationsOf(context)) {+ _started = true;+ _entrance.value = 1;+ } else if (!_started) {+ _started = true;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || MediaQuery.disableAnimationsOf(context)) return;+ // Preserve the reference spring overshoot.+ _entrance.animateWith(SpringSimulation(+ SpringDescription.withDampingRatio(+ mass: 1,+ stiffness: 380,+ ratio: 0.8,+ ),+ 0,+ 1,+ 0,+ snapToEnd: false,+ ));+ });+ }+ }++ @override+ void dispose() {+ _entrance.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;++ final background = colors.surface;+ final surface = Material(+ color: background,+ elevation: 0,+ shape: _materialSheetShape,+ clipBehavior: Clip.antiAlias,+ child: Theme(+ data: theme.copyWith(+ scaffoldBackgroundColor: Colors.transparent,+ ),+ child: SafeArea(+ top: false,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Semantics(+ label:+ MaterialLocalizations.of(context).modalBarrierDismissLabel,+ onDismiss: () => Navigator.of(context).maybePop(),+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 16),+ child: Center(+ child: Container(+ width: 32,+ height: 4,+ decoration: BoxDecoration(+ color: colors.onSurfaceVariant.withValues(alpha: 0.4),+ borderRadius: BorderRadius.circular(2),+ ),+ ),+ ),+ ),+ ),+ Flexible(child: widget.child),+ ],+ ),+ ),+ ),+ );++ return Stack(+ clipBehavior: Clip.none,+ alignment: Alignment.topCenter,+ children: [+ // Cover the bottom gap during spring overshoot.+ Positioned(+ left: 0,+ right: 0,+ bottom: -400,+ height: 450,+ child: ColoredBox(color: background),+ ),+ AnimatedBuilder(+ animation: _entrance,+ child: surface,+ builder: (context, child) => Transform.translate(+ offset: Offset(0, (1 - _entrance.value) * 200),+ child: Opacity(+ opacity: _entrance.value.clamp(0.0, 1.0),+ child: child,+ ),+ ),+ ),+ ],+ );+ }+}diff --git a/lib/bean/dialog/dialog_helper.dart b/lib/bean/dialog/dialog_helper.dartindex d3a261aa..50594eb4 100644--- a/lib/bean/dialog/dialog_helper.dart+++ b/lib/bean/dialog/dialog_helper.dart@@ -1,14 +1,10 @@import 'package:flutter/material.dart';++import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/navigation.dart';import 'package:kazumi/utils/constants.dart';-// A simple dialog helper class to show dialogs and toasts based on flutter native implementation (replace flutter_smart_dialog)-// flutter_smart_dialog use overlays and self-managed route stack to show dialogs.-// It's powerful but can't behave like the default showDialog, e.g. the lack of mask animation. the lack of snackbar.-// Use the implementation should be careful, because shared route stack with the whole app, it may cause some unexpected behaviors.-// Don't use it in double PopScope widget.class KazumiDialog {- /// The global observer that tracks contexts across the applicationstatic final KazumiDialogObserver observer = KazumiDialogObserver();KazumiDialog._internal();@@ -112,7 +108,7 @@ class KazumiDialog {child: Column(mainAxisSize: MainAxisSize.min,children: [- const CircularProgressIndicator(),+ const LoadingIndicator(),const SizedBox(height: 16),Text(msg ?? 'Loading...',@@ -136,63 +132,6 @@ class KazumiDialog {}}- static Future<T?> showBottomSheet<T>({- BuildContext? context,- required WidgetBuilder builder,- Color? backgroundColor,- double? elevation,- ShapeBorder? shape,- Clip? clipBehavior,- BoxConstraints? constraints,- Color? barrierColor,- bool isScrollControlled = false,- bool useRootNavigator = true,- bool isDismissible = true,- bool enableDrag = true,- RouteSettings? routeSettings,- AnimationController? transitionAnimationController,- Offset? anchorPoint,- bool useSafeArea = false,- }) async {- // Use provided context first, then root context, then fallback to current context- final ctx = context ??- rootNavigatorKey.currentContext ??- observer.rootContext ??- observer.currentContext;- if (ctx != null && ctx.mounted) {- try {- final result = await showModalBottomSheet<T>(- context: ctx,- builder: builder,- backgroundColor: backgroundColor,- elevation: elevation,- shape: shape,- clipBehavior: clipBehavior,- constraints: constraints,- barrierColor: barrierColor,- isScrollControlled: isScrollControlled,- useRootNavigator: useRootNavigator,- isDismissible: isDismissible,- enableDrag: enableDrag,- routeSettings:- routeSettings ?? const RouteSettings(name: 'KazumiBottomSheet'),- transitionAnimationController: transitionAnimationController,- anchorPoint: anchorPoint,- useSafeArea: useSafeArea,- );- return result;- } catch (e) {- debugPrint('Kazumi Dialog Error: Failed to show bottom sheet: $e');- return null;- }- } else {- debugPrint(- 'Kazumi Dialog Error: No context available to show the bottom sheet');- return null;- }- }-- // 在存在返回值时弹出并附带返回值static void dismiss<T>({T? popWith}) {if (observer.hasKazumiDialog && observer.kazumiDialogContext != null) {try {@@ -205,33 +144,6 @@ class KazumiDialog {}}- /// Shows a non-dismissible timed success dialog with a linear progress- /// countdown, then auto-dismisses when the countdown completes.- ///- /// The caller is responsible for dismissing any currently-open dialog- /// BEFORE calling this method.- ///- /// [onComplete] is invoked after the dialog route finishes.- static void showTimedSuccessDialog({- required String title,- required String message,- required VoidCallback onComplete,- Duration duration = const Duration(seconds: 3),- }) {- KazumiDialog.show<bool>(- clickMaskDismiss: false,- builder: (context) => _TimedSuccessDialog(- title: title,- message: message,- duration: duration,- ),- ).then((completed) {- if (completed == true) {- onComplete();- }- });- }-static ScaffoldMessengerState? _resolveScaffoldMessenger(BuildContext? context,) {@@ -256,95 +168,18 @@ class KazumiDialog {}}-class _TimedSuccessDialog extends StatelessWidget {- const _TimedSuccessDialog({- required this.title,- required this.message,- required this.duration,- });-- final String title;- final String message;- final Duration duration;-- @override- Widget build(BuildContext context) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;- return Dialog(- clipBehavior: Clip.antiAlias,- child: Padding(- padding: const EdgeInsets.all(24),- child: SizedBox(- width: 300,- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- Container(- width: 64,- height: 64,- decoration: BoxDecoration(- color: colorScheme.secondaryContainer,- shape: BoxShape.circle,- ),- child: Icon(- Icons.check_rounded,- size: 32,- color: colorScheme.onSecondaryContainer,- ),- ),- const SizedBox(height: 16),- Text(- title,- style: textTheme.headlineSmall,- textAlign: TextAlign.center,- ),- const SizedBox(height: 8),- Text(- message,- style: textTheme.bodyMedium- ?.copyWith(color: colorScheme.onSurfaceVariant),- textAlign: TextAlign.center,- ),- const SizedBox(height: 24),- TweenAnimationBuilder<double>(- tween: Tween(begin: 0.0, end: 1.0),- duration: duration,- onEnd: () => KazumiDialog.dismiss(popWith: true),- builder: (context, value, _) =>- LinearProgressIndicator(value: value),- ),- ],- ),- ),- ),- );- }-}--/// Navigator observer to track contexts and dialog routesclass KazumiDialogObserver extends NavigatorObserver {- /// List of active dialog routesfinal List<Route<dynamic>> _kazumiDialogRoutes = [];bool _snackBarClearScheduled = false;- /// The most recent context from any MaterialPageRoute or PopupRouteBuildContext? _currentContext;- /// The most recent context from any route containing a ScaffoldBuildContext? _scaffoldContext;- /// The root context of the app (for bottom sheets to cover the entire app)- BuildContext? _rootContext;-BuildContext? get currentContext => _currentContext;BuildContext? get scaffoldContext => _scaffoldContext ?? _currentContext;- /// Get the root context for bottom sheets, fallback to scaffold context, then current context- BuildContext? get rootContext =>- _rootContext ?? _scaffoldContext ?? _currentContext;-bool get hasKazumiDialog => _kazumiDialogRoutes.isNotEmpty;BuildContext? get kazumiDialogContext => _kazumiDialogRoutes.isNotEmpty@@ -358,7 +193,7 @@ class KazumiDialogObserver extends NavigatorObserver {_kazumiDialogRoutes.add(route);}if (route.navigator?.context != null) {- _updateContexts(route.navigator!.context, route);+ _updateContexts(route.navigator!.context);}}@@ -370,7 +205,7 @@ class KazumiDialogObserver extends NavigatorObserver {_kazumiDialogRoutes.remove(route);}if (previousRoute?.navigator?.context != null) {- _updateContexts(previousRoute!.navigator!.context, previousRoute);+ _updateContexts(previousRoute!.navigator!.context);}}@@ -378,14 +213,15 @@ class KazumiDialogObserver extends NavigatorObserver {void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {super.didReplace(newRoute: newRoute, oldRoute: oldRoute);_scheduleSnackBarClear();- if (_isKazumiDialogRoute(oldRoute!)) {+ if (_isKazumiDialogRoute(oldRoute)) {_kazumiDialogRoutes.remove(oldRoute);}- if (_isKazumiDialogRoute(newRoute!)) {+ if (newRoute != null && _isKazumiDialogRoute(newRoute)) {_kazumiDialogRoutes.add(newRoute);}- if (newRoute.navigator?.context != null) {- _updateContexts(newRoute.navigator!.context, newRoute);+ final context = newRoute?.navigator?.context;+ if (context != null) {+ _updateContexts(context);}}@@ -399,37 +235,26 @@ class KazumiDialogObserver extends NavigatorObserver {}if (previousRoute?.navigator?.context != null) {- _updateContexts(previousRoute!.navigator!.context, previousRoute);+ _updateContexts(previousRoute!.navigator!.context);}}- void _updateContexts(BuildContext context, Route<dynamic> route) {+ void _updateContexts(BuildContext context) {_currentContext = context;- if (_hasScaffold(context)) {+ if (Scaffold.maybeOf(context) != null) {_scaffoldContext = context;- // Always update root context with scaffold contexts to ensure we have the most recent one- // This helps ensure bottom sheets appear at the app level- _rootContext = context;}}- bool _hasScaffold(BuildContext context) {- return Scaffold.maybeOf(context) != null;- }-- bool _isKazumiDialogRoute(Route<dynamic> route) {- return route.settings.name == 'KazumiDialog' ||- route.settings.name == 'KazumiBottomSheet';- }+ bool _isKazumiDialogRoute(Route<dynamic>? route) =>+ route?.settings.name == 'KazumiDialog';void _scheduleSnackBarClear() {if (_snackBarClearScheduled) return;_snackBarClearScheduled = true;WidgetsBinding.instance.addPostFrameCallback((_) {_snackBarClearScheduled = false;- // Route observer callbacks run while Navigator is reconciling routes.- // Clearing the root messenger after the frame avoids mutating UI state- // in the middle of that reconciliation.+ // Defer snackbar removal until Navigator finishes reconciling routes.rootScaffoldMessengerKey.currentState?.removeCurrentSnackBar();});}diff --git a/lib/bean/dialog/material_bottom_sheet.dart b/lib/bean/dialog/material_bottom_sheet.dartindex 16aa0164..b7c6eb8d 100644--- a/lib/bean/dialog/material_bottom_sheet.dart+++ b/lib/bean/dialog/material_bottom_sheet.dart@@ -1,8 +1,10 @@import 'package:flutter/material.dart';-const double materialBottomSheetRadius = 24;const EdgeInsets materialBottomSheetContentPadding =- EdgeInsets.fromLTRB(16, 16, 16, 24);+ EdgeInsets.fromLTRB(24, 0, 24, 24);++const EdgeInsets materialBottomSheetTabsPadding =+ EdgeInsets.fromLTRB(24, 0, 24, 16);class MaterialBottomSheetHeader extends StatelessWidget {const MaterialBottomSheetHeader({@@ -10,15 +12,15 @@ class MaterialBottomSheetHeader extends StatelessWidget {required this.title,this.description,this.onClose,- this.footer,this.trailing,+ this.compact = false,});final String title;final String? description;final VoidCallback? onClose;- final Widget? footer;final Widget? trailing;+ final bool compact;@overrideWidget build(BuildContext context) {@@ -26,34 +28,24 @@ class MaterialBottomSheetHeader extends StatelessWidget {final colorScheme = theme.colorScheme;return Padding(- padding: const EdgeInsets.fromLTRB(20, 20, 12, 16),+ padding: EdgeInsets.fromLTRB(24, 0, 24, compact ? 8 : 16),child: Column(crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,children: [Row(- crossAxisAlignment: CrossAxisAlignment.start,+ crossAxisAlignment: CrossAxisAlignment.center,children: [Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- title,- style: theme.textTheme.headlineSmall?.copyWith(- color: colorScheme.onSurface,- fontWeight: FontWeight.w700,- ),+ child: Semantics(+ header: true,+ child: Text(+ title,+ style: theme.textTheme.titleLarge?.copyWith(+ color: colorScheme.onSurface,+ fontWeight: FontWeight.w700,),- if (description != null) ...[- const SizedBox(height: 4),- Text(- description!,- style: theme.textTheme.bodyMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- ],- ],+ ),),),if (trailing != null) ...[@@ -61,7 +53,7 @@ class MaterialBottomSheetHeader extends StatelessWidget {trailing!,] else if (onClose != null) ...[const SizedBox(width: 12),- IconButton.filledTonal(+ IconButton(onPressed: onClose,tooltip: '关闭',icon: const Icon(Icons.close_rounded),@@ -69,290 +61,17 @@ class MaterialBottomSheetHeader extends StatelessWidget {],],),- if (footer != null) ...[- const SizedBox(height: 16),- footer!,- ],- ],- ),- );- }-}--// Verbatim ConnectedButtonGroupSmallTokens: ContainerHeight, BetweenSpace,-// InnerCornerCornerSize, PressedInnerCornerCornerSize. Rounding these to the-// app's usual radius vocabulary breaks the group's proportions.--const double _connectedGroupHeight = 40;-const double _connectedGroupGap = 2;-const double _connectedInnerCorner = 8;-const double _connectedPressedInnerCorner = 4;--/// Material 3 Expressive connected button group driving a [TabBarView].-///-/// Outer edges stay `CornerFull`; only the corners facing a sibling move,-/// opening out on selection and tightening under a press. Driven off the-/// [TabController] animation so a drag carries the shape and colour with it.-class MaterialBottomSheetSegmentedTabs extends StatelessWidget {- const MaterialBottomSheetSegmentedTabs({- super.key,- required this.labels,- this.controller,- this.padding = const EdgeInsets.fromLTRB(16, 0, 16, 12),- });-- final List<String> labels;-- /// Falls back to the enclosing [DefaultTabController].- final TabController? controller;-- final EdgeInsetsGeometry padding;-- @override- Widget build(BuildContext context) {- final tabController = controller ?? DefaultTabController.of(context);-- return Padding(- padding: padding,- child: SizedBox(- height: _connectedGroupHeight,- child: AnimatedBuilder(- animation: tabController.animation!,- builder: (context, _) {- final position = tabController.animation!.value;- return Row(- children: [- for (var index = 0; index < labels.length; index++) ...[- if (index != 0) const SizedBox(width: _connectedGroupGap),- Expanded(- child: _ConnectedSegment(- label: labels[index],- selection: (1 - (position - index).abs()).clamp(0.0, 1.0),- isLeading: index == 0,- isTrailing: index == labels.length - 1,- onTap: () => tabController.animateTo(index),- ),- ),- ],- ],- );- },- ),- ),- );- }-}--class _ConnectedSegment extends StatefulWidget {- const _ConnectedSegment({- required this.label,- required this.selection,- required this.isLeading,- required this.isTrailing,- required this.onTap,- });-- final String label;- final double selection;- final bool isLeading;- final bool isTrailing;- final VoidCallback onTap;-- @override- State<_ConnectedSegment> createState() => _ConnectedSegmentState();-}--class _ConnectedSegmentState extends State<_ConnectedSegment> {- bool _pressed = false;-- @override- Widget build(BuildContext context) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;- final selection = widget.selection;- const outerCorner = _connectedGroupHeight / 2;- const outerRadius = Radius.circular(outerCorner);-- return Semantics(- button: true,- inMutuallyExclusiveGroup: true,- selected: selection > 0.5,- // Only the press is tweened. Selection already tracks the tab- // controller, and tweening it too would lag a drag.- child: TweenAnimationBuilder<double>(- tween: Tween<double>(end: _pressed ? 1 : 0),- duration: const Duration(milliseconds: 180),- curve: Curves.easeOutCubic,- builder: (context, press, child) {- // A press only bites on a segment that is not already selected.- var inner = _connectedInnerCorner +- (outerCorner - _connectedInnerCorner) * selection;- inner += (_connectedPressedInnerCorner - inner) *- press *- (1 - selection);- final animated = Radius.circular(inner);- return Material(- // ToggleButtonDefaults fills the selected segment with `primary`,- // too heavy for a sheet this only navigates. `secondaryContainer`- // is the navigation active-indicator role.- color: Color.lerp(- colorScheme.surfaceContainer,- colorScheme.secondaryContainer,- selection,- ),- borderRadius: BorderRadiusDirectional.only(- topStart: widget.isLeading ? outerRadius : animated,- bottomStart: widget.isLeading ? outerRadius : animated,- topEnd: widget.isTrailing ? outerRadius : animated,- bottomEnd: widget.isTrailing ? outerRadius : animated,- ),- clipBehavior: Clip.antiAlias,- child: child,- );- },- child: InkWell(- onTap: widget.onTap,- onHighlightChanged: (value) => setState(() => _pressed = value),- child: Center(- child: Text(- widget.label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: theme.textTheme.labelLarge?.copyWith(- color: Color.lerp(- colorScheme.onSurfaceVariant,- colorScheme.onSecondaryContainer,- selection,- ),+ if (description != null) ...[+ const SizedBox(height: 4),+ Text(+ description!,+ style: theme.textTheme.bodyMedium?.copyWith(+ color: colorScheme.onSurfaceVariant,),),- ),- ),- ),- );- }-}--class MaterialBottomSheetSection extends StatelessWidget {- const MaterialBottomSheetSection({- super.key,- required this.title,- required this.child,- this.description,- this.icon,- this.padding = const EdgeInsets.fromLTRB(18, 16, 18, 18),- });-- final String title;- final String? description;- final IconData? icon;- final Widget child;- final EdgeInsetsGeometry padding;-- @override- Widget build(BuildContext context) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;-- return Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,- child: Padding(- padding: padding,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- if (icon != null) ...[- Icon(icon, color: colorScheme.primary),- const SizedBox(width: 12),- ],- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(- title,- style: theme.textTheme.titleMedium?.copyWith(- color: colorScheme.onSurface,- fontWeight: FontWeight.w700,- ),- ),- if (description != null) ...[- const SizedBox(height: 4),- Text(- description!,- style: theme.textTheme.bodySmall?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- ],- ],- ),- ),- ],- ),- const SizedBox(height: 16),- child,],- ),+ ],),);}}--class MaterialBottomSheetGroup extends StatelessWidget {- const MaterialBottomSheetGroup({- super.key,- required this.title,- required this.children,- this.dividerIndent = 72,- });-- final String title;- final List<Widget> children;- final double dividerIndent;-- @override- Widget build(BuildContext context) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;-- return Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Padding(- padding: const EdgeInsets.fromLTRB(4, 0, 4, 8),- child: Text(- title,- style: theme.textTheme.titleSmall?.copyWith(- color: colorScheme.primary,- fontWeight: FontWeight.w600,- ),- ),- ),- Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,- child: Column(- children: [- for (var index = 0; index < children.length; index++) ...[- children[index],- if (index != children.length - 1)- Divider(- height: 1,- indent: dividerIndent,- color: colorScheme.outlineVariant,- ),- ],- ],- ),- ),- ],- );- }-}diff --git a/lib/bean/settings/settings_list.dart b/lib/bean/settings/settings_list.dartindex 87baad35..5e3734e7 100644--- a/lib/bean/settings/settings_list.dart+++ b/lib/bean/settings/settings_list.dart@@ -1,14 +1,19 @@import 'package:flutter/material.dart';++import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/bean/widget/split_list_row.dart';enum _TileKind { plain, toggle, radio }class SettingsList extends StatelessWidget {- const SettingsList({super.key, required this.sections, this.maxWidth = 1000});+ const SettingsList({+ super.key,+ required this.sections,+ this.maxWidth = 1000,+ });final List<Widget> sections;- /// Defaulted here so a page that says nothing still matches the others.final double maxWidth;@override@@ -52,13 +57,9 @@ class SettingsSection extends StatelessWidget {if (title != null)Padding(padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),- child: DefaultTextStyle.merge(- style:- textTheme.titleSmall?.copyWith(color: colorScheme.primary),- child: title!,- ),+ child: SectionHeader(title: title!),),- SettingsSplitGroup(children: tiles),+ SplitListGroup(children: tiles),if (bottomInfo != null)Padding(padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),@@ -74,45 +75,6 @@ class SettingsSection extends StatelessWidget {}}-/// Rows laid out as an M3 split list: large corners at the group's two ends,-/// small ones in between, and a pressed row morphing out of the group. That-/// morph is what separates the rows, in place of a divider.-class SettingsSplitGroup extends StatelessWidget {- const SettingsSplitGroup({- super.key,- required this.children,- this.outerRadius = splitListOuterRadius,- });-- final List<Widget> children;-- /// The group's two end corners, and the radius a pressed row morphs to.- /// Settings pages take the default; a page whose surrounding cards run at a- /// smaller scale passes theirs so the group sits level with them.- final double outerRadius;-- @override- Widget build(BuildContext context) {- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- for (int i = 0; i < children.length; i++) ...[- if (i > 0) const SizedBox(height: splitListRowGap),- SplitListRow(- topRadius: i == 0 ? outerRadius : splitListInnerRadius,- bottomRadius:- i == children.length - 1 ? outerRadius : splitListInnerRadius,- pressedRadius: outerRadius,- child: children[i],- ),- ],- ],- );- }-}--/// A [SettingsSection] whose tiles form a single radio group, so arrow keys-/// traverse the options and screen readers announce them as one set.class SettingsRadioSection<T> extends StatelessWidget {const SettingsRadioSection({super.key,@@ -140,7 +102,6 @@ class SettingsRadioSection<T> extends StatelessWidget {Color _disabledOn(BuildContext context) =>Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.38);-/// The icon-and-text run every row opens with. Callers wrap it in [Expanded].class _TileLabel extends StatelessWidget {const _TileLabel({required this.title,@@ -192,9 +153,6 @@ class _TileLabel extends StatelessWidget {}}-/// A row that opens a whole category rather than changing one value: the-/// tonal icon badge marks that step down, which is why [SettingsTile] keeps a-/// flat icon. Drop it in a [SettingsSplitGroup] like any other row.class SettingsCategoryTile extends StatelessWidget {const SettingsCategoryTile({super.key,@@ -261,9 +219,6 @@ class SettingsCategoryTile extends StatelessWidget {}}-/// A row whose control is a slider. The label line carries a tonal readout of-/// the current value and the track spans the row beneath it, so the icon, the-/// track and the text never share a line.class SettingsSliderTile extends StatelessWidget {const SettingsSliderTile({super.key,@@ -319,7 +274,6 @@ class SettingsSliderTile extends StatelessWidget {valueLabel,style: textTheme.labelMedium?.copyWith(color: colorScheme.onSecondaryContainer,- // Steady digit widths, so dragging can't jitter the pill.fontFeatures: const [FontFeature.tabularFigures()],),),@@ -332,9 +286,6 @@ class SettingsSliderTile extends StatelessWidget {min: min,max: max,divisions: divisions,- // The pill is the readout, so no bubble rides the thumb; the zero- // inset then measures the track against the row rather than the- // thumb's overlay box.showValueIndicator: ShowValueIndicator.never,padding: EdgeInsets.zero,onChanged: onChanged,@@ -360,7 +311,7 @@ class SettingsTile<T> extends StatelessWidget {initialValue = null,radioValue = null;- /// Tapping the row toggles too, in which case [onToggle] receives null.+ /// Row taps pass null to [onToggle]; switch gestures pass the new value.const SettingsTile.switchTile({super.key,required this.title,@@ -375,8 +326,6 @@ class SettingsTile<T> extends StatelessWidget {onPressed = null,radioValue = null;- /// Selection and change handling come from the enclosing- /// [SettingsRadioSection], so the whole option list is one radio group.const SettingsTile.radioTile({super.key,required this.title,@@ -393,7 +342,6 @@ class SettingsTile<T> extends StatelessWidget {final Widget title;- /// Flat, not a tonal badge — the badge marks a row opening a whole category.final IconData? leading;final Widget? description;final Widget? trailing;diff --git a/lib/bean/widget/connected_tabs.dart b/lib/bean/widget/connected_tabs.dartnew file mode 100644index 00000000..01187a54--- /dev/null+++ b/lib/bean/widget/connected_tabs.dart@@ -0,0 +1,142 @@+import 'package:flutter/material.dart';++// Material 3 connected-button small tokens.++const double _connectedGroupHeight = 40;+const double _connectedGroupGap = 2;+const double _connectedInnerCorner = 8;+const double _connectedPressedInnerCorner = 4;++class ConnectedTabs extends StatelessWidget {+ const ConnectedTabs({+ super.key,+ required this.labels,+ this.controller,+ this.padding = EdgeInsets.zero,+ });++ final List<String> labels;++ final TabController? controller;++ final EdgeInsetsGeometry padding;++ @override+ Widget build(BuildContext context) {+ final tabController = controller ?? DefaultTabController.of(context);+ assert(labels.isNotEmpty && labels.length == tabController.length);++ return Padding(+ padding: padding,+ child: SizedBox(+ height: _connectedGroupHeight,+ child: AnimatedBuilder(+ animation: tabController.animation!,+ builder: (context, _) {+ final position = tabController.animation!.value;+ return Row(+ children: [+ for (var index = 0; index < labels.length; index++) ...[+ if (index != 0) const SizedBox(width: _connectedGroupGap),+ Expanded(+ child: _ConnectedSegment(+ label: labels[index],+ selection: (1 - (position - index).abs()).clamp(0.0, 1.0),+ isLeading: index == 0,+ isTrailing: index == labels.length - 1,+ onTap: () => tabController.animateTo(index),+ ),+ ),+ ],+ ],+ );+ },+ ),+ ),+ );+ }+}++class _ConnectedSegment extends StatefulWidget {+ const _ConnectedSegment({+ required this.label,+ required this.selection,+ required this.isLeading,+ required this.isTrailing,+ required this.onTap,+ });++ final String label;+ final double selection;+ final bool isLeading;+ final bool isTrailing;+ final VoidCallback onTap;++ @override+ State<_ConnectedSegment> createState() => _ConnectedSegmentState();+}++class _ConnectedSegmentState extends State<_ConnectedSegment> {+ bool _pressed = false;++ @override+ Widget build(BuildContext context) {+ final theme = Theme.of(context);+ final colorScheme = theme.colorScheme;+ final selection = widget.selection;+ const outerCorner = _connectedGroupHeight / 2;+ const outerRadius = Radius.circular(outerCorner);++ return Semantics(+ button: true,+ inMutuallyExclusiveGroup: true,+ selected: selection > 0.5,+ // Selection already follows the tab animation; tween only the press.+ child: TweenAnimationBuilder<double>(+ tween: Tween<double>(end: _pressed ? 1 : 0),+ duration: const Duration(milliseconds: 180),+ curve: Curves.easeOutCubic,+ builder: (context, press, child) {+ var inner = _connectedInnerCorner ++ (outerCorner - _connectedInnerCorner) * selection;+ inner +=+ (_connectedPressedInnerCorner - inner) * press * (1 - selection);+ final animated = Radius.circular(inner);+ return Material(+ color: Color.lerp(+ colorScheme.surfaceContainer,+ colorScheme.secondaryContainer,+ selection,+ ),+ borderRadius: BorderRadiusDirectional.only(+ topStart: widget.isLeading ? outerRadius : animated,+ bottomStart: widget.isLeading ? outerRadius : animated,+ topEnd: widget.isTrailing ? outerRadius : animated,+ bottomEnd: widget.isTrailing ? outerRadius : animated,+ ),+ clipBehavior: Clip.antiAlias,+ child: child,+ );+ },+ child: InkWell(+ onTap: widget.onTap,+ onHighlightChanged: (value) => setState(() => _pressed = value),+ child: Center(+ child: Text(+ widget.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: theme.textTheme.labelLarge?.copyWith(+ color: Color.lerp(+ colorScheme.onSurfaceVariant,+ colorScheme.onSecondaryContainer,+ selection,+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/lib/bean/widget/content_section.dart b/lib/bean/widget/content_section.dartnew file mode 100644index 00000000..4d346970--- /dev/null+++ b/lib/bean/widget/content_section.dart@@ -0,0 +1,83 @@+import 'package:flutter/material.dart';++import 'package:kazumi/bean/widget/split_list_row.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';++class SectionHeader extends StatelessWidget {+ const SectionHeader({super.key, required this.title, this.description});++ final Widget title;+ final Widget? description;++ @override+ Widget build(BuildContext context) {+ final theme = Theme.of(context);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Semantics(+ header: true,+ child: DefaultTextStyle.merge(+ style: theme.textTheme.titleSmall?.copyWith(+ color: theme.colorScheme.primary,+ fontWeight: FontWeight.w600,+ ),+ child: title,+ ),+ ),+ if (description != null) ...[+ const SizedBox(height: 4),+ DefaultTextStyle.merge(+ style: theme.textTheme.bodyMedium+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant),+ child: description!,+ ),+ ],+ ],+ );+ }+}++class ContentSection extends StatelessWidget {+ const ContentSection({+ super.key,+ required this.title,+ required Widget child,+ this.description,+ this.padding = const EdgeInsets.all(16),+ }) : _child = child,+ _children = null;++ const ContentSection.group({+ super.key,+ required this.title,+ required List<Widget> children,+ this.description,+ }) : _children = children,+ _child = null,+ padding = EdgeInsets.zero;++ final String title;+ final String? description;+ final EdgeInsetsGeometry padding;+ final Widget? _child;+ final List<Widget>? _children;++ @override+ Widget build(BuildContext context) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),+ child: SectionHeader(+ title: Text(title),+ description: description == null ? null : Text(description!),+ ),+ ),+ if (_children != null)+ SplitListGroup(children: _children)+ else+ TonalCard(padding: padding, child: _child!),+ ],+ );+}diff --git a/lib/bean/widget/image_preview.dart b/lib/bean/widget/image_preview.dartindex 465ce301..918a9512 100644--- a/lib/bean/widget/image_preview.dart+++ b/lib/bean/widget/image_preview.dart@@ -1,11 +1,13 @@import 'package:cached_network_image/cached_network_image.dart';-import 'package:flutter/material.dart';import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';import 'package:flutter_modular/flutter_modular.dart';-import 'package:kazumi/utils/device.dart';import 'package:photo_view/photo_view.dart';import 'package:photo_view/photo_view_gallery.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';+import 'package:kazumi/utils/device.dart';+class ImageViewerRouteArgs {ImageViewerRouteArgs({required List<String> imageUrls,@@ -34,7 +36,6 @@ class ImageViewer extends StatefulWidget {static Object heroTagFor(String imageUrl, int index) => '$imageUrl-$index';- /// 显示图片预览static Future<void> show(BuildContext context, {required List<String> imageUrls,@@ -72,13 +73,10 @@ class _ImageViewerState extends State<ImageViewer> {{};final Map<int, double?> _initialScales = {};- /// 滚轮单次缩放步长static const double _wheelScaleStep = 1.1;- /// 最小缩放倍数static const double _minScaleFactor = 1.0;- /// 最大缩放倍数static const double _maxScaleFactor = 6.0;bool get _isMultiImage => widget.imageUrls.length > 1;@@ -303,7 +301,7 @@ class _ImageViewerState extends State<ImageViewer> {? PhotoViewHeroAttributes(tag: widget.heroTag!): null,loadingBuilder: (context, event) => const Center(- child: CircularProgressIndicator(),+ child: LoadingIndicator(),),errorBuilder: (context, error, stackTrace) =>_buildErrorWidget(context),@@ -323,7 +321,7 @@ class _ImageViewerState extends State<ImageViewer> {onPageChanged: (index) => setState(() => _currentIndex = index),backgroundDecoration: const BoxDecoration(color: Colors.black),loadingBuilder: (context, event) => const Center(- child: CircularProgressIndicator(),+ child: LoadingIndicator(),),builder: (context, index) {final imageUrl = widget.imageUrls[index];diff --git a/lib/bean/widget/loading_indicator.dart b/lib/bean/widget/loading_indicator.dartnew file mode 100644index 00000000..be14edd1--- /dev/null+++ b/lib/bean/widget/loading_indicator.dart@@ -0,0 +1,115 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';+import 'package:material_new_shapes/material_new_shapes.dart';++class LoadingIndicator extends StatefulWidget {+ const LoadingIndicator({+ super.key,+ this.size = 48,+ this.color,+ this.semanticsLabel = '加载中',+ });++ final double size;+ final Color? color;+ final String semanticsLabel;++ @override+ State<LoadingIndicator> createState() => _LoadingIndicatorState();+}++class _LoadingIndicatorState extends State<LoadingIndicator>+ with SingleTickerProviderStateMixin {+ static final _shapes = [+ MaterialShapes.softBurst,+ MaterialShapes.cookie9Sided,+ MaterialShapes.pill,+ MaterialShapes.sunny,+ MaterialShapes.cookie4Sided,+ MaterialShapes.oval,+ MaterialShapes.cookie7Sided,+ ];+ // Share expensive morph matching across indicator instances.+ static final _morphs = List.generate(+ _shapes.length,+ (index) => Morph(_shapes[index], _shapes[(index + 1) % _shapes.length]),+ );++ late final _controller = AnimationController(+ vsync: this,+ duration: Duration(milliseconds: 650 * _shapes.length),+ );++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ if (MediaQuery.disableAnimationsOf(context) ||+ !TickerMode.valuesOf(context).enabled) {+ _controller.stop();+ } else if (!_controller.isAnimating) {+ _controller.repeat();+ }+ }++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ return Semantics(+ label: widget.semanticsLabel,+ child: RepaintBoundary(+ child: SizedBox.square(+ dimension: widget.size,+ child: CustomPaint(+ painter: _LoadingShapePainter(+ animation: _controller,+ morphs: _morphs,+ color: widget.color ?? Theme.of(context).colorScheme.primary,+ ),+ ),+ ),+ ),+ );+ }+}++class _LoadingShapePainter extends CustomPainter {+ _LoadingShapePainter({+ required this.animation,+ required this.morphs,+ required this.color,+ }) : super(repaint: animation);++ final Animation<double> animation;+ final List<Morph> morphs;+ final Color color;+ final Path _path = Path();++ @override+ void paint(Canvas canvas, Size size) {+ final position = animation.value * morphs.length;+ final index = position.floor() % morphs.length;+ final progress = Curves.easeInOutCubicEmphasized.transform(position % 1);+ final path = morphs[index].toPath(progress: progress, path: _path);+ // Fit the diagonal so rotation stays inside small indicator slots.+ final scale = size.shortestSide / math.sqrt2;+ canvas.save();+ canvas.translate(size.width / 2, size.height / 2);+ canvas.rotate(animation.value * math.pi * 2);+ canvas.scale(scale);+ canvas.translate(-0.5, -0.5);+ canvas.drawPath(path, Paint()..color = color);+ canvas.restore();+ }++ @override+ bool shouldRepaint(_LoadingShapePainter oldDelegate) =>+ oldDelegate.color != color ||+ oldDelegate.animation != animation ||+ oldDelegate.morphs != morphs;+}diff --git a/lib/bean/widget/scrollable_wrapper.dart b/lib/bean/widget/scrollable_wrapper.dartdeleted file mode 100644index 926e10ac..00000000--- a/lib/bean/widget/scrollable_wrapper.dart+++ /dev/null@@ -1,46 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter/gestures.dart';--/// 滚动容器-/// 支持鼠标滚轮滚动和拖动滚动-/// 传入ListView的scrollController-class ScrollableWrapper extends StatelessWidget {- final Widget child;- final ScrollController scrollController;-- const ScrollableWrapper({- super.key,- required this.child,- required this.scrollController,- });-- @override- Widget build(BuildContext context) {- return MouseRegion(- child: Listener(- onPointerSignal: (pointerSignal) {- // 鼠标滚轮滚动- if (pointerSignal is PointerScrollEvent &&- scrollController.hasClients) {- scrollController.position.moveTo(- scrollController.offset + pointerSignal.scrollDelta.dy,- curve: Curves.linear,- );- }- },- child: GestureDetector(- onPanUpdate: (details) {- // 拖动滚动- if (scrollController.hasClients) {- scrollController.position.moveTo(- scrollController.offset - details.delta.dx,- curve: Curves.linear,- );- }- },- child: child,- ),- ),- );- }-}diff --git a/lib/bean/widget/split_list_row.dart b/lib/bean/widget/split_list_row.dartindex ae2e04f5..5f71f8f3 100644--- a/lib/bean/widget/split_list_row.dart+++ b/lib/bean/widget/split_list_row.dart@@ -1,24 +1,18 @@import 'package:flutter/material.dart';-/// The M3 Expressive split-list vocabulary: large corners at a group's ends,-/// small ones between rows, and a gap in place of a divider.-const double splitListOuterRadius = 24;+import 'package:kazumi/bean/widget/tonal_card.dart';++const double splitListOuterRadius = tonalCardRadius;const double splitListInnerRadius = 4;const double splitListRowGap = 4;const Duration splitListMotionDuration = Duration(milliseconds: 250);const Curve splitListMotionCurve = Curves.easeInOutCubic;-/// One row of a split list, morphing to [pressedRadius] while held.-///-/// The press is driven by [onTap] here, or, when the row's content owns its-/// own [InkWell], by handing [pressReporterOf] to that-/// [InkWell.onHighlightChanged].class SplitListRow extends StatefulWidget {const SplitListRow({super.key,required this.child,- this.color,this.topRadius = splitListInnerRadius,this.bottomRadius = splitListInnerRadius,this.pressedRadius = splitListOuterRadius,@@ -27,15 +21,12 @@ class SplitListRow extends StatefulWidget {final Widget child;- /// Defaults to `surfaceContainerLow`.- final Color? color;-final double topRadius;final double bottomRadius;final double pressedRadius;final VoidCallback? onTap;- /// Null outside a row, which leaves that row's shape static.+ /// Forward a child InkWell's onHighlightChanged here.static ValueChanged<bool>? pressReporterOf(BuildContext context) {return context.dependOnInheritedWidgetOfExactType<_SplitRowScope>()@@ -53,6 +44,8 @@ class _SplitListRowState extends State<SplitListRow> {@overrideWidget build(BuildContext context) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;final child = widget.onTap == null? widget.child: InkWell(@@ -60,15 +53,13 @@ class _SplitListRowState extends State<SplitListRow> {onHighlightChanged: _reportPress,child: widget.child,);- // An AnimatedContainer rather than Material's implicit animation:- // Material tweens its shape but snaps its colour.+ // Animate color as well as shape; Material alone snaps color changes.return AnimatedContainer(duration: splitListMotionDuration,curve: splitListMotionCurve,clipBehavior: Clip.antiAlias,decoration: BoxDecoration(- color:- widget.color ?? Theme.of(context).colorScheme.surfaceContainerLow,+ color: colors.surfaceContainerLow,borderRadius: BorderRadius.vertical(top: Radius.circular(_pressed ? widget.pressedRadius : widget.topRadius),@@ -78,7 +69,17 @@ class _SplitListRowState extends State<SplitListRow> {),child: Material(type: MaterialType.transparency,- child: _SplitRowScope(onPressChanged: _reportPress, child: child),+ child: ListTileTheme(+ data: theme.listTileTheme.copyWith(+ contentPadding:+ const EdgeInsets.symmetric(horizontal: 16, vertical: 4),+ titleTextStyle:+ theme.textTheme.bodyLarge?.copyWith(color: colors.onSurface),+ subtitleTextStyle: theme.textTheme.bodyMedium+ ?.copyWith(color: colors.onSurfaceVariant),+ ),+ child: _SplitRowScope(onPressChanged: _reportPress, child: child),+ ),),);}@@ -89,8 +90,38 @@ class _SplitRowScope extends InheritedWidget {final ValueChanged<bool> onPressChanged;- // The callback always reaches the same state, so a rebuilt scope never- // obsoletes the one a row already holds.+ // The callback always targets the same state.@overridebool updateShouldNotify(_SplitRowScope oldWidget) => false;}++class SplitListGroup extends StatelessWidget {+ const SplitListGroup({+ super.key,+ required this.children,+ this.outerRadius = splitListOuterRadius,+ });++ final List<Widget> children;++ final double outerRadius;++ @override+ Widget build(BuildContext context) {+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (int i = 0; i < children.length; i++) ...[+ if (i > 0) const SizedBox(height: splitListRowGap),+ SplitListRow(+ topRadius: i == 0 ? outerRadius : splitListInnerRadius,+ bottomRadius:+ i == children.length - 1 ? outerRadius : splitListInnerRadius,+ pressedRadius: outerRadius,+ child: children[i],+ ),+ ],+ ],+ );+ }+}diff --git a/lib/bean/widget/tonal_card.dart b/lib/bean/widget/tonal_card.dartnew file mode 100644index 00000000..f983b803--- /dev/null+++ b/lib/bean/widget/tonal_card.dart@@ -0,0 +1,22 @@+import 'package:flutter/material.dart';++const double tonalCardRadius = 24;++class TonalCard extends StatelessWidget {+ const TonalCard({+ super.key,+ required this.child,+ this.padding = EdgeInsets.zero,+ });++ final Widget child;+ final EdgeInsetsGeometry padding;++ @override+ Widget build(BuildContext context) => Material(+ color: Theme.of(context).colorScheme.surfaceContainerLow,+ borderRadius: BorderRadius.circular(tonalCardRadius),+ clipBehavior: Clip.antiAlias,+ child: Padding(padding: padding, child: child),+ );+}diff --git a/lib/modules/bangumi/weekday_item.dart b/lib/modules/bangumi/weekday_item.dartdeleted file mode 100644index 0d0bb7d4..00000000--- a/lib/modules/bangumi/weekday_item.dart+++ /dev/null@@ -1,17 +0,0 @@-class Weekday {- String? en;- String? cn;- String? ja;- int? id;-- Weekday({this.en, this.cn, this.ja, this.id});-- factory Weekday.fromJson(Map<String, dynamic> json) {- return Weekday(- en: json['en'],- cn: json['cn'],- ja: json['ja'],- id: json['id'],- );- }-}diff --git a/lib/pages/bangumi/bangumi_setting.dart b/lib/pages/bangumi/bangumi_setting.dartindex d0fec0dd..c00892c6 100644--- a/lib/pages/bangumi/bangumi_setting.dart+++ b/lib/pages/bangumi/bangumi_setting.dart@@ -1,11 +1,13 @@-import 'package:kazumi/bean/settings/settings_list.dart';import 'package:flutter/material.dart';+import 'package:url_launcher/url_launcher.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/bangumi/sync_priority.dart';-import 'package:kazumi/services/sync/bangumi_sync_service.dart';import 'package:kazumi/services/storage/storage.dart';-import 'package:url_launcher/url_launcher.dart';+import 'package:kazumi/services/sync/bangumi_sync_service.dart';class BangumiEditorPage extends StatefulWidget {const BangumiEditorPage({super.key});@@ -192,8 +194,7 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {? const SizedBox(width: 20,height: 20,- child:- CircularProgressIndicator(strokeWidth: 2),+ child: LoadingIndicator(),): const Icon(Icons.sync_rounded),onPressed: (_) async {diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dartindex e08f6bdc..b0b343ee 100644--- a/lib/pages/collect/collect_page.dart+++ b/lib/pages/collect/collect_page.dart@@ -1,19 +1,21 @@import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';++import 'package:kazumi/bean/appbar/sys_app_bar.dart';+import 'package:kazumi/bean/card/bangumi_card.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/widget/collect_button.dart';+import 'package:kazumi/bean/widget/empty_state_widget.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/modules/collect/collect_module.dart';+import 'package:kazumi/modules/collect/collect_sync_plan.dart';import 'package:kazumi/modules/collect/collect_type.dart';-import 'package:flutter/material.dart';-import 'package:kazumi/utils/constants.dart';-import 'package:kazumi/bean/card/bangumi_card.dart';import 'package:kazumi/pages/collect/collect_controller.dart';-import 'package:kazumi/bean/appbar/sys_app_bar.dart';-import 'package:kazumi/bean/widget/collect_button.dart';-import 'package:kazumi/bean/widget/empty_state_widget.dart';-import 'package:kazumi/modules/collect/collect_sync_plan.dart';import 'package:kazumi/services/storage/storage.dart';+import 'package:kazumi/utils/constants.dart';class CollectPage extends StatefulWidget {const CollectPage({@@ -149,12 +151,10 @@ class _CollectPageState extends State<CollectPage>super.dispose();}- /// Tab order follows [CollectType.value], so a collectible of type `n`- /// belongs to tab `n - 1`.+ // CollectType values are one-based; tab indices are zero-based.static final List<CollectType> _tabTypes =CollectType.values.where((type) => type.isCollected).toList();- /// Room a counted tab needs before the badge squeezes out the label.static const double _countedTabMinWidth = 104;List<int> get _collectibleCounts {@@ -202,16 +202,13 @@ class _CollectPageState extends State<CollectPage>appBar: SysAppBar(needTopOffset: false,toolbarHeight: 104,- // The app bar sits outside the body observer, so the counts need- // their own one to track the collectibles store.+ // App bar counts need their own Observer, outside the body observer.bottom: PreferredSize(preferredSize: const Size.fromHeight(kTextTabBarHeight),child: Observer(builder: (context) {final List<int>? counts =showAnimeCounter ? _collectibleCounts : null;return LayoutBuilder(builder: (context, constraints) {- // Splitting the bar evenly leaves no room for label and badge- // on a narrow screen, so scroll the tabs instead.final bool scrollable = counts != null &&constraints.maxWidth <MediaQuery.textScalerOf(context)@@ -284,8 +281,7 @@ class _CollectPageState extends State<CollectPage>}},child: syncCollectiblesing- ? const SizedBox(- width: 32, height: 32, child: CircularProgressIndicator())+ ? const SizedBox(width: 32, height: 32, child: LoadingIndicator()): const Icon(Icons.sync_rounded),),body: Observer(builder: (context) {diff --git a/lib/pages/download/download_episode_sheet.dart b/lib/pages/download/download_episode_sheet.dartindex 51bbb4ea..3a892819 100644--- a/lib/pages/download/download_episode_sheet.dart+++ b/lib/pages/download/download_episode_sheet.dart@@ -1,12 +1,15 @@+import 'dart:math' as math;+import 'package:flutter/material.dart';import 'package:flutter_modular/flutter_modular.dart';+import 'package:scrollview_observer/scrollview_observer.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';import 'package:kazumi/modules/download/download_module.dart';import 'package:kazumi/modules/roads/road_module.dart';import 'package:kazumi/pages/download/download_controller.dart';import 'package:kazumi/pages/video/video_controller.dart';-import 'package:scrollview_observer/scrollview_observer.dart';class DownloadEpisodeSheet extends StatefulWidget {final int road;@@ -64,135 +67,140 @@ class _DownloadEpisodeSheetState extends State<DownloadEpisodeSheet> {final allSelected = selectableEpisodes.isNotEmpty &&_selectedEpisodes.length == selectableEpisodes.length;- return DraggableScrollableSheet(- initialChildSize: 0.6,- minChildSize: 0.3,- maxChildSize: 0.9,- expand: false,- builder: (context, scrollController) {- _observerController.controller = scrollController;- if (!_didJumpToPlayingEpisode) {- _didJumpToPlayingEpisode = true;- WidgetsBinding.instance.addPostFrameCallback((_) async {- await Future<void>.delayed(Duration.zero);- final playbackEpisode = videoPageController.playbackEpisode;- if (!mounted ||- playbackEpisode.road != widget.road ||- episodeCount == 0 ||- !scrollController.hasClients) {- return;- }- final index =- (playbackEpisode.episode - 1).clamp(0, episodeCount - 1);- await _observerController.jumpTo(- index: index,- isFixedHeight: true,- );- });- }- return Column(- children: [- MaterialBottomSheetHeader(- title: '下载选集',- description: downloadedCount > 0- ? '共 $episodeCount 集 · $downloadedCount 集已加入下载'- : '共 $episodeCount 集',- onClose: () => Navigator.of(context).pop(),- ),- Expanded(- child: GridViewObserver(- controller: _observerController,- child: GridView.builder(- controller: scrollController,- padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),- gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(- maxCrossAxisExtent: 160,- crossAxisSpacing: 8,- mainAxisSpacing: 8,- mainAxisExtent: 56,+ return LayoutBuilder(builder: (context, constraints) {+ // Reserve header, actions and one episode row even on short windows.+ final textScale = MediaQuery.textScalerOf(context).scale(14) / 14;+ final minSize = (240 * math.max(1.0, textScale) / constraints.maxHeight)+ .clamp(0.3, 1.0);+ return DraggableScrollableSheet(+ initialChildSize: math.max(0.6, minSize),+ minChildSize: minSize,+ maxChildSize: math.max(0.9, minSize),+ expand: false,+ builder: (context, scrollController) {+ _observerController.controller = scrollController;+ if (!_didJumpToPlayingEpisode) {+ _didJumpToPlayingEpisode = true;+ WidgetsBinding.instance.addPostFrameCallback((_) async {+ await Future<void>.delayed(Duration.zero);+ final playbackEpisode = videoPageController.playbackEpisode;+ if (!mounted ||+ playbackEpisode.road != widget.road ||+ episodeCount == 0 ||+ !scrollController.hasClients) {+ return;+ }+ final index =+ (playbackEpisode.episode - 1).clamp(0, episodeCount - 1);+ await _observerController.jumpTo(+ index: index,+ isFixedHeight: true,+ );+ });+ }+ return Column(+ children: [+ MaterialBottomSheetHeader(+ title: '下载选集',+ description: downloadedCount > 0+ ? '$episodeCount 集 · 已下载 $downloadedCount 集'+ : '共 $episodeCount 集',+ onClose: () => Navigator.of(context).pop(),+ ),+ Expanded(+ child: GridViewObserver(+ controller: _observerController,+ child: GridView.builder(+ controller: scrollController,+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 16),+ gridDelegate:+ const SliverGridDelegateWithMaxCrossAxisExtent(+ maxCrossAxisExtent: 160,+ crossAxisSpacing: 8,+ mainAxisSpacing: 8,+ mainAxisExtent: 56,+ ),+ itemCount: episodeCount,+ itemBuilder: (context, index) {+ final episodeNumber = index + 1;+ final episodeUrl = currentRoadData.data[index];+ final isDownloaded = downloadedUrls.contains(episodeUrl);+ final isSelected =+ _selectedEpisodes.contains(episodeNumber);+ return _EpisodeTile(+ identifier: currentRoadData.identifier[index],+ isDownloaded: isDownloaded,+ isSelected: isSelected,+ onTap: isDownloaded+ ? null+ : () {+ setState(() {+ if (isSelected) {+ _selectedEpisodes.remove(episodeNumber);+ } else {+ _selectedEpisodes.add(episodeNumber);+ }+ });+ },+ );+ },),- itemCount: episodeCount,- itemBuilder: (context, index) {- final episodeNumber = index + 1;- final episodeUrl = currentRoadData.data[index];- final isDownloaded = downloadedUrls.contains(episodeUrl);- final isSelected =- _selectedEpisodes.contains(episodeNumber);- return _EpisodeTile(- identifier: currentRoadData.identifier[index],- isDownloaded: isDownloaded,- isSelected: isSelected,- onTap: isDownloaded- ? null- : () {- setState(() {- if (isSelected) {- _selectedEpisodes.remove(episodeNumber);- } else {- _selectedEpisodes.add(episodeNumber);- }- });- },- );- },),),- ),- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),- child: SafeArea(- top: false,- child: Row(- children: [- FilledButton.tonalIcon(- style: FilledButton.styleFrom(- minimumSize: const Size(0, 48),- ),- onPressed: selectableEpisodes.isEmpty- ? null- : () {- setState(() {- _selectedEpisodes.clear();- if (!allSelected) {- _selectedEpisodes.addAll(selectableEpisodes);- }- });- },- icon: Icon(allSelected- ? Icons.deselect_rounded- : Icons.select_all_rounded),- // 用透明的最宽文案占位,切换文本时按钮宽度保持稳定。- label: Stack(- alignment: Alignment.center,- children: [- const Opacity(opacity: 0, child: Text('取消全选')),- Text(allSelected ? '取消全选' : '全选'),- ],- ),- ),- const SizedBox(width: 12),- Expanded(- child: FilledButton.icon(- style: FilledButton.styleFrom(- minimumSize: const Size.fromHeight(48),+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),+ child: SafeArea(+ top: false,+ child: Row(+ children: [+ TextButton(+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 48),),- onPressed: _selectedEpisodes.isEmpty+ onPressed: selectableEpisodes.isEmpty? null- : () => _startBatchDownload(context),- icon: const Icon(Icons.download_rounded),- label: Text(_selectedEpisodes.isEmpty- ? '开始下载'- : '下载 ${_selectedEpisodes.length} 集'),+ : () {+ setState(() {+ _selectedEpisodes.clear();+ if (!allSelected) {+ _selectedEpisodes+ .addAll(selectableEpisodes);+ }+ });+ },+ // Reserve the widest label to keep the action width stable.+ child: Stack(+ alignment: Alignment.center,+ children: [+ const Opacity(opacity: 0, child: Text('取消全选')),+ Text(allSelected ? '取消全选' : '全选'),+ ],+ ),),- ),- ],+ const SizedBox(width: 24),+ Expanded(+ child: FilledButton.icon(+ style: FilledButton.styleFrom(+ minimumSize: const Size.fromHeight(48),+ ),+ onPressed: _selectedEpisodes.isEmpty+ ? null+ : () => _startBatchDownload(context),+ icon: const Icon(Icons.download_rounded),+ label: Text(_selectedEpisodes.isEmpty+ ? '选择集数'+ : '下载 ${_selectedEpisodes.length} 集'),+ ),+ ),+ ],+ ),),),- ),- ],- );- },- );+ ],+ );+ },+ );+ });}void _startBatchDownload(BuildContext context) {@@ -244,7 +252,7 @@ class _EpisodeTile extends StatelessWidget {Widget build(BuildContext context) {final colorScheme = Theme.of(context).colorScheme;final backgroundColor = isDownloaded- ? colorScheme.surfaceContainerHighest.withValues(alpha: 0.5)+ ? colorScheme.surfaceContainerLow: isSelected? colorScheme.secondaryContainer: colorScheme.surfaceContainerLow;@@ -259,13 +267,13 @@ class _EpisodeTile extends StatelessWidget {curve: Curves.easeInOutCubic,decoration: BoxDecoration(color: backgroundColor,- borderRadius: BorderRadius.circular(16),+ borderRadius: BorderRadius.circular(isSelected ? 28 : 16),),clipBehavior: Clip.antiAlias,child: Material(type: MaterialType.transparency,child: InkWell(- borderRadius: BorderRadius.circular(16),+ borderRadius: BorderRadius.circular(isSelected ? 28 : 16),onTap: onTap,child: Stack(children: [@@ -277,10 +285,10 @@ class _EpisodeTile extends StatelessWidget {maxLines: 2,overflow: TextOverflow.ellipsis,textAlign: TextAlign.center,- style: TextStyle(- fontSize: 13,- color: foregroundColor,- ),+ style: Theme.of(context)+ .textTheme+ .bodyMedium+ ?.copyWith(color: foregroundColor),),),),diff --git a/lib/pages/download/download_widgets.dart b/lib/pages/download/download_widgets.dartindex e7b09136..d5953f34 100644--- a/lib/pages/download/download_widgets.dart+++ b/lib/pages/download/download_widgets.dart@@ -1,14 +1,14 @@import 'package:flutter/material.dart';+import 'package:kazumi/bean/card/network_img_layer.dart';import 'package:kazumi/bean/card/rule_card.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/download/download_module.dart';import 'package:kazumi/utils/format.dart';const Duration _kExpandDuration = Duration(milliseconds: 250);const Curve _kExpandCurve = Curves.easeInOutCubic;-/// Rounded tonal card for one bangumi download record: cover, title,-/// source tag, aggregate progress and a collapsible episode list.class DownloadRecordCard extends StatelessWidget {const DownloadRecordCard({super.key,@@ -28,8 +28,6 @@ class DownloadRecordCard extends StatelessWidget {final VoidCallback onDeleteAll;final double totalSpeed;- /// Builds the episode rows; only invoked while [expanded], so collapsed- /// cards skip sorting and tile construction entirely.final List<Widget> Function() episodeTileBuilder;@override@@ -187,8 +185,6 @@ class DownloadRecordCard extends StatelessWidget {}}-/// One episode row inside [DownloadRecordCard]: tonal status badge,-/// episode name, status line, optional full-width progress bar and actions.class DownloadEpisodeTile extends StatelessWidget {const DownloadEpisodeTile({super.key,@@ -202,7 +198,6 @@ class DownloadEpisodeTile extends StatelessWidget {final String statusText;final List<Widget> actions;- /// Non-null only for completed episodes; makes the whole row tappable.final VoidCallback? onPlay;@override@@ -262,7 +257,6 @@ class DownloadEpisodeTile extends StatelessWidget {}}-/// Circular tonal badge showing the episode download status.class _EpisodeStatusBadge extends StatelessWidget {const _EpisodeStatusBadge({required this.episode});@@ -299,7 +293,7 @@ class _EpisodeStatusBadge extends StatelessWidget {child = const SizedBox(width: 22,height: 22,- child: CircularProgressIndicator(strokeWidth: 2.5),+ child: LoadingIndicator(),);break;case DownloadStatus.failed:diff --git a/lib/pages/error/storage_error_page.dart b/lib/pages/error/storage_error_page.dartindex 4f51c218..6a5ba0d1 100644--- a/lib/pages/error/storage_error_page.dart+++ b/lib/pages/error/storage_error_page.dart@@ -1,8 +1,11 @@import 'dart:io';+import 'package:flutter/material.dart';-import 'package:kazumi/bean/widget/error_widget.dart';import 'package:path_provider/path_provider.dart';+import 'package:kazumi/bean/widget/error_widget.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';+class StorageErrorPage extends StatelessWidget {const StorageErrorPage({super.key});@@ -31,7 +34,7 @@ class StorageErrorPage extends StatelessWidget {],);} else {- return const CircularProgressIndicator();+ return const LoadingIndicator();}},),diff --git a/lib/pages/info/character_page.dart b/lib/pages/info/character_page.dartindex bec1cb60..8a7e50ea 100644--- a/lib/pages/info/character_page.dart+++ b/lib/pages/info/character_page.dart@@ -1,60 +1,23 @@-import 'dart:math' as math;import 'dart:ui';+import 'package:flutter/material.dart';-import 'package:kazumi/modules/character/character_full_item.dart';-import 'package:kazumi/modules/comments/comment_item.dart';-import 'package:kazumi/request/apis/bangumi_api.dart';+import 'package:skeletonizer/skeletonizer.dart';+import 'package:kazumi/bean/card/network_img_layer.dart';import 'package:kazumi/bean/card/user_comments_card.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/widget/connected_tabs.dart';+import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/bean/widget/error_widget.dart';import 'package:kazumi/bean/widget/image_preview.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';+import 'package:kazumi/modules/character/character_full_item.dart';+import 'package:kazumi/modules/comments/comment_item.dart';+import 'package:kazumi/request/apis/bangumi_api.dart';import 'package:kazumi/utils/constants.dart';-import 'package:skeletonizer/skeletonizer.dart';--/// Concentric radii: the panel takes the sheet's 24 and insets by this, so the-/// portrait lands on the image token's 12 and both sets of corners stay parallel.-const double _panelPadding = 12;--/// The portrait is a full-body shot, so it spans the panel at roughly a third-/// of its width. On short layouts that third would square the box off and-/// `BoxFit.cover` would crop the head and feet away, hence the ratio ceiling.-const double _portraitMaxAspectRatio = 0.5;-const double _portraitMinWidth = 104;-const double _portraitMaxWidth = 176;--/// Short facts become pills; a key column would spend a whole row on a-/// one-character value in a column this narrow. Longer ones read as paragraphs.-const int _pillMaxValueLength = 12;-const double _pillRadius = 8;-const double _pillGap = 8;-const double _blockGap = 20;-const double _blockLabelGap = 6;const Set<String> _hiddenInfoKeys = {'引用来源'};-const Widget _detailsBone = Skeletonizer.zone(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Wrap(- spacing: _pillGap,- runSpacing: _pillGap,- children: [- Bone.button(uniRadius: _pillRadius, height: 30, width: 76),- Bone.button(uniRadius: _pillRadius, height: 30, width: 60),- Bone.button(uniRadius: _pillRadius, height: 30, width: 92),- Bone.button(uniRadius: _pillRadius, height: 30, width: 68),- ],- ),- SizedBox(height: _blockGap),- Bone.text(width: 48),- SizedBox(height: _blockLabelGap),- Bone.multiText(lines: 8),- ],- ),-);-class CharacterPage extends StatefulWidget {const CharacterPage({super.key,@@ -65,11 +28,7 @@ class CharacterPage extends StatefulWidget {final int characterID;- /// Both header lines come from the tapped list row, never from the request.- /// Whether a header assembled from loaded data has a second line is unknown- /// until the response lands, so it changes line count on arrival and shoves- /// the sheet down a notch; deciding it synchronously is the only shape that- /// cannot shift. The localized name still rides along in the infobox below.+ // Use the tapped name to keep the header height stable while loading.final String characterName;final String characterRelation;@@ -133,7 +92,7 @@ class _CharacterPageState extends State<CharacterPage> {return DefaultTabController(length: 2,child: Scaffold(- backgroundColor: Theme.of(context).colorScheme.surface,+ backgroundColor: Colors.transparent,body: Column(children: [MaterialBottomSheetHeader(@@ -141,7 +100,8 @@ class _CharacterPageState extends State<CharacterPage> {description: _headerDescription,onClose: () => Navigator.of(context).pop(),),- const MaterialBottomSheetSegmentedTabs(+ const ConnectedTabs(+ padding: materialBottomSheetTabsPadding,labels: ['资料', '吐槽'],),Expanded(@@ -180,62 +140,83 @@ class _CharacterPageState extends State<CharacterPage> {);}- return LayoutBuilder(- builder: (context, constraints) {- final portraitHeight = math.max(- 0.0,- constraints.maxHeight -- materialBottomSheetContentPadding.vertical -- _panelPadding * 2,- );- final panelWidth =- constraints.maxWidth - materialBottomSheetContentPadding.horizontal;- final portraitWidth = math.min(- (panelWidth * 0.3)- .clamp(_portraitMinWidth, _portraitMaxWidth)- .toDouble(),- portraitHeight * _portraitMaxAspectRatio,- );-- return Padding(- padding: materialBottomSheetContentPadding,- child: Material(- color: Theme.of(context).colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,+ if (character == null) {+ return const SingleChildScrollView(+ padding: materialBottomSheetContentPadding,+ child: Skeletonizer.zone(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Bone(height: 180, width: 120, uniRadius: 16),+ SizedBox(height: 24),+ Bone.multiText(lines: 5),+ ],+ )),+ );+ }+ final fields = character.infobox+ .where((f) => !_hiddenInfoKeys.contains(f.key))+ .toList();+ return SingleChildScrollView(+ padding: materialBottomSheetContentPadding,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ TonalCard(child: Padding(- padding: const EdgeInsets.all(_panelPadding),+ padding: const EdgeInsets.all(16),child: Row(- crossAxisAlignment: CrossAxisAlignment.stretch,+ crossAxisAlignment: CrossAxisAlignment.start,children: [- character == null- ? Skeletonizer.zone(- child: Bone(- width: portraitWidth,- height: portraitHeight,- uniRadius: StyleString.imgRadius.x,- ),- )- : _buildPortrait(- context,- character,- portraitWidth,- portraitHeight,- ),- const SizedBox(width: 16),+ _buildPortrait(context, character, 104, 176),+ const SizedBox(width: 20),Expanded(- child: SingleChildScrollView(- child: character == null- ? _detailsBone- : _buildDetails(context, character),- ),- ),+ child: SelectionArea(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (final field in fields.take(3)) ...[+ _buildBlock(context, field),+ const SizedBox(height: 12),+ ],+ if (fields.isEmpty)+ Text('暂无资料',+ style: Theme.of(context).textTheme.bodyMedium),+ ],+ ))),],),),),- );- },+ if (character.summary.trim().isNotEmpty) ...[+ const SizedBox(height: 24),+ ContentSection(+ title: '简介',+ child: SelectableText(character.summary.trim(),+ style: Theme.of(context)+ .textTheme+ .bodyMedium+ ?.copyWith(height: 1.6)),+ ),+ ],+ if (fields.length > 3) ...[+ const SizedBox(height: 24),+ ContentSection(+ title: '更多资料',+ child: SelectionArea(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ for (final field in fields.skip(3)) ...[+ _buildBlock(context, field),+ const SizedBox(height: 16),+ ],+ ],+ )),+ ),+ ],+ ],+ ),);}@@ -253,7 +234,7 @@ class _CharacterPageState extends State<CharacterPage> {child: Tooltip(message: '查看原图',child: Material(- color: Theme.of(context).colorScheme.surfaceContainerHigh,+ color: Theme.of(context).colorScheme.surface,borderRadius: const BorderRadius.all(StyleString.imgRadius),clipBehavior: Clip.antiAlias,child: InkWell(@@ -276,95 +257,6 @@ class _CharacterPageState extends State<CharacterPage> {);}- Widget _buildDetails(BuildContext context, CharacterFullItem character) {- final pills = <CharacterInfoField>[];- final blocks = <CharacterInfoField>[];-- for (final field in character.infobox) {- if (_hiddenInfoKeys.contains(field.key)) continue;- if (field.value.length <= _pillMaxValueLength &&- !field.value.contains(' / ')) {- pills.add(field);- } else {- blocks.add(field);- }- }- if (character.summary.trim().isNotEmpty) {- blocks.add(- CharacterInfoField(key: '简介', value: character.summary.trim()),- );- }-- if (pills.isEmpty && blocks.isEmpty) {- final theme = Theme.of(context);- return Text(- '暂无人物资料',- style: theme.textTheme.bodyMedium?.copyWith(- color: theme.colorScheme.onSurfaceVariant,- ),- );- }-- final sections = <Widget>[- if (pills.isNotEmpty)- Wrap(- spacing: _pillGap,- runSpacing: _pillGap,- children: [- for (final field in pills) _buildFactPill(context, field),- ],- ),- for (final block in blocks) _buildBlock(context, block),- ];-- return SelectionArea(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- for (var index = 0; index < sections.length; index++) ...[- if (index != 0) const SizedBox(height: _blockGap),- sections[index],- ],- ],- ),- );- }-- Widget _buildFactPill(BuildContext context, CharacterInfoField field) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;-- return Container(- padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),- decoration: BoxDecoration(- color: colorScheme.surfaceContainerHigh,- borderRadius: BorderRadius.circular(_pillRadius),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Text(- field.key,- style: theme.textTheme.labelSmall?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- const SizedBox(width: 6),- // Wrap bounds its children, so an oversized pill wraps rather than- // overflowing.- Flexible(- child: Text(- field.value,- style: theme.textTheme.labelLarge?.copyWith(- color: colorScheme.onSurface,- ),- ),- ),- ],- ),- );- }-Widget _buildBlock(BuildContext context, CharacterInfoField field) {final theme = Theme.of(context);final colorScheme = theme.colorScheme;@@ -379,7 +271,7 @@ class _CharacterPageState extends State<CharacterPage> {fontWeight: FontWeight.w600,),),- const SizedBox(height: _blockLabelGap),+ const SizedBox(height: 4),Text(field.value,style: theme.textTheme.bodyMedium?.copyWith(@@ -394,9 +286,7 @@ class _CharacterPageState extends State<CharacterPage> {Widget get characterCommentsBody {return CustomScrollView(scrollBehavior: const ScrollBehavior().copyWith(- // Scrollbars' movement is not linear so hide it.scrollbars: false,- // Enable mouse drag to refreshdragDevices: {PointerDeviceKind.mouse,PointerDeviceKind.touch,@@ -404,7 +294,7 @@ class _CharacterPageState extends State<CharacterPage> {),slivers: [SliverPadding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),+ padding: materialBottomSheetContentPadding,sliver: Builder(builder: (context) {if (loadingComments) {return SliverList.builder(@@ -437,8 +327,7 @@ class _CharacterPageState extends State<CharacterPage> {return SliverList(delegate: SliverChildBuilderDelegate((context, index) {- // Fix scroll issue caused by height change of network images- // by keeping loaded cards alive.+ // Keep loaded images alive to prevent scroll jumps.return KeepAlive(keepAlive: true,child: IndexedSemantics(diff --git a/lib/pages/info/info_page.dart b/lib/pages/info/info_page.dartindex fba84c25..dcb383d7 100644--- a/lib/pages/info/info_page.dart+++ b/lib/pages/info/info_page.dart@@ -1,25 +1,27 @@import 'dart:io';import 'dart:ui';-import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:kazumi/pages/info/rating_review_dialog.dart';+import 'package:flutter/material.dart';+import 'package:flutter_mobx/flutter_mobx.dart';import 'package:flutter_modular/flutter_modular.dart';+import 'package:url_launcher/url_launcher.dart';+import 'package:window_manager/window_manager.dart';++import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;+import 'package:kazumi/bean/card/bangumi_info_card.dart';+import 'package:kazumi/bean/card/network_img_layer.dart';+import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/widget/collect_button.dart';import 'package:kazumi/bean/widget/embedded_native_control_area.dart';-import 'package:kazumi/services/storage/storage.dart';+import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/pages/info/info_controller.dart';-import 'package:kazumi/bean/card/bangumi_info_card.dart';+import 'package:kazumi/pages/info/info_tabview.dart';+import 'package:kazumi/pages/info/rating_review_dialog.dart';import 'package:kazumi/pages/info/source_sheet.dart';import 'package:kazumi/plugins/plugins_controller.dart';-import 'package:kazumi/bean/card/network_img_layer.dart';import 'package:kazumi/services/logging/logger.dart';-import 'package:kazumi/pages/info/info_tabview.dart';-import 'package:url_launcher/url_launcher.dart';-import 'package:window_manager/window_manager.dart';-import 'package:flutter_mobx/flutter_mobx.dart';-import 'package:kazumi/modules/bangumi/bangumi_item.dart';-import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;+import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/device.dart';class InfoPage extends StatefulWidget {@@ -215,8 +217,7 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {infoController.staffList.clear();infoController.clearRelations();infoController.pluginSearchResponseList.clear();- // Search results can miss rating distribution or summaries, so fill those- // fields without replacing image URLs that are already rendered.+ // Preserve rendered image URLs when filling missing metadata.if (_needsBangumiInfoRefresh(infoController.bangumiItem)) {_showBangumiInfoSkeleton = true;queryBangumiInfoByID(@@ -426,7 +427,6 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {_isShowingBangumiInfoSkeleton;return Stack(children: [- // No background image when loading to make loading looks betterif (!showBangumiInfoSkeleton)Positioned.fill(bottom: kTextTabBarHeight,@@ -510,9 +510,8 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {tooltip: '开始观看',onPressed: () {showAdaptiveBottomSheet<void>(- backgroundColor:- Theme.of(context).scaffoldBackgroundColor,context: context,+ maxHeightFactor: 0.88,builder: (context) {return SourceSheet(infoController: infoController);},diff --git a/lib/pages/info/rating_review_dialog.dart b/lib/pages/info/rating_review_dialog.dartindex c1a188ff..5caccbdc 100644--- a/lib/pages/info/rating_review_dialog.dart+++ b/lib/pages/info/rating_review_dialog.dart@@ -1,5 +1,7 @@import 'package:flutter/material.dart';import 'package:flutter_rating_bar/flutter_rating_bar.dart';++import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/modules/bangumi/bangumi_tag.dart';import 'package:kazumi/services/logging/logger.dart';@@ -52,13 +54,10 @@ class _RatingReviewDialogState extends State<RatingReviewDialog> {'超神作',];- /// Maximum number of tags that can be submitted.static const int _maxSelectedTags = 10;- /// Maximum length for one custom tag.static const int _maxTagLength = 10;- /// Maximum length for the review text.static const int _maxCommentLength = 380;static const Duration _panelFadeDuration = Duration(milliseconds: 180);@@ -337,14 +336,12 @@ class _RatingReviewDialogState extends State<RatingReviewDialog> {child: Column(children: [_buildMainHeader(theme),-Expanded(child: SingleChildScrollView(padding: const EdgeInsets.fromLTRB(24, 8, 24, 16),child: _buildMainContent(theme),),),-_buildActions(theme),],),@@ -651,8 +648,6 @@ class _RatingReviewDialogState extends State<RatingReviewDialog> {? '最多 $_maxSelectedTags 个标签': null,errorText: _tagErrorText,- // Outlined, not filled: this field floats a label, and- // only the outline can notch around it.border: OutlineInputBorder(borderRadius: BorderRadius.circular(20),),@@ -767,8 +762,7 @@ class _RatingReviewDialogState extends State<RatingReviewDialog> {? SizedBox(width: 16,height: 16,- child: CircularProgressIndicator(- strokeWidth: 2,+ child: LoadingIndicator(color: theme.colorScheme.onPrimary,),)diff --git a/lib/pages/info/source_alias_dialog.dart b/lib/pages/info/source_alias_dialog.dartindex f9bb8d7e..3c960711 100644--- a/lib/pages/info/source_alias_dialog.dart+++ b/lib/pages/info/source_alias_dialog.dart@@ -1,25 +1,30 @@-import 'package:flutter/material.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';+part of 'source_sheet.dart';-/// Deletions edit [aliases] in place and then fire [onAliasesChanged], so the-/// caller can persist the list it passed in.-void showAliasPickerDialog({+void _showAliasPickerDialog({+ required String sourceName,required List<String> aliases,required ValueChanged<String> onAliasSelected,required VoidCallback onAliasesChanged,}) {KazumiDialog.show(builder: (context) => _AliasPickerDialog(+ sourceName: sourceName,aliases: aliases,- onAliasSelected: onAliasSelected,+ onAliasSelected: (alias) {+ KazumiDialog.dismiss();+ onAliasSelected(alias);+ },onAliasesChanged: onAliasesChanged,),);}-/// [onSubmit] never sees a blank keyword.-void showCustomKeywordDialog({required ValueChanged<String> onSubmit}) {- String keyword = '';+void _showCustomKeywordDialog({+ required ValueChanged<String> onSubmit,+ required String initialKeyword,+ required String sourceName,+}) {+ String keyword = initialKeyword;void submit(String value) {final trimmed = value.trim();@@ -30,10 +35,19 @@ void showCustomKeywordDialog({required ValueChanged<String> onSubmit}) {KazumiDialog.show(builder: (context) => AlertDialog(- title: const Text('输入别名'),- content: TextField(+ title: const Text('修改检索词'),+ content: TextFormField(+ initialValue: initialKeyword,+ autofocus: true,+ textInputAction: TextInputAction.search,+ decoration: InputDecoration(+ labelText: '检索关键词',+ helperText: '仅检索来源:$sourceName',+ helperMaxLines: 3,+ border: const OutlineInputBorder(),+ ),onChanged: (value) => keyword = value,- onSubmitted: submit,+ onFieldSubmitted: submit,),actions: [TextButton(@@ -45,7 +59,7 @@ void showCustomKeywordDialog({required ValueChanged<String> onSubmit}) {),TextButton(onPressed: () => submit(keyword),- child: const Text('确认'),+ child: const Text('检索'),),],),@@ -54,11 +68,13 @@ void showCustomKeywordDialog({required ValueChanged<String> onSubmit}) {class _AliasPickerDialog extends StatefulWidget {const _AliasPickerDialog({+ required this.sourceName,required this.aliases,required this.onAliasSelected,required this.onAliasesChanged,});+ final String sourceName;final List<String> aliases;final ValueChanged<String> onAliasSelected;final VoidCallback onAliasesChanged;@@ -68,15 +84,6 @@ class _AliasPickerDialog extends StatefulWidget {}class _AliasPickerDialogState extends State<_AliasPickerDialog> {- late final ValueNotifier<List<String>> _aliasNotifier =- ValueNotifier<List<String>>(List.from(widget.aliases));-- @override- void dispose() {- _aliasNotifier.dispose();- super.dispose();- }-void _confirmDelete(int index) {KazumiDialog.show(builder: (context) => AlertDialog(@@ -93,8 +100,8 @@ class _AliasPickerDialogState extends State<_AliasPickerDialog> {TextButton(onPressed: () {KazumiDialog.dismiss();- widget.aliases.removeAt(index);- _aliasNotifier.value = List.from(widget.aliases);+ // Aliases are shared across source rules.+ setState(() => widget.aliases.removeAt(index));widget.onAliasesChanged();if (widget.aliases.isEmpty) {Navigator.of(this.context).pop();@@ -113,24 +120,35 @@ class _AliasPickerDialogState extends State<_AliasPickerDialog> {clipBehavior: Clip.antiAlias,child: SizedBox(width: 560,- child: ValueListenableBuilder<List<String>>(- valueListenable: _aliasNotifier,- builder: (context, aliasList, child) {- return ListView(- shrinkWrap: true,- children: [- for (var index = 0; index < aliasList.length; index++)- ListTile(- title: Text(aliasList[index]),- trailing: IconButton(- onPressed: () => _confirmDelete(index),- icon: const Icon(Icons.delete),- ),- onTap: () => widget.onAliasSelected(aliasList[index]),+ child: ListView(+ shrinkWrap: true,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 24, 24, 12),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text('别名检索', style: Theme.of(context).textTheme.titleLarge),+ const SizedBox(height: 8),+ Text(+ '仅检索来源:${widget.sourceName}',+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(+ color: Theme.of(context).colorScheme.onSurfaceVariant,+ ),),- ],- );- },+ ],+ ),+ ),+ for (var index = 0; index < widget.aliases.length; index++)+ ListTile(+ title: Text(widget.aliases[index]),+ trailing: IconButton(+ onPressed: () => _confirmDelete(index),+ icon: const Icon(Icons.delete),+ ),+ onTap: () => widget.onAliasSelected(widget.aliases[index]),+ ),+ ],),),);diff --git a/lib/pages/info/source_captcha_flow.dart b/lib/pages/info/source_captcha_flow.dartindex 6b81a98a..f2f10941 100644--- a/lib/pages/info/source_captcha_flow.dart+++ b/lib/pages/info/source_captcha_flow.dart@@ -1,20 +1,10 @@-import 'dart:async';-import 'dart:convert';+part of 'source_sheet.dart';-import 'package:flutter/material.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:kazumi/plugins/anti_crawler_config.dart';-import 'package:kazumi/plugins/plugins.dart';-import 'package:kazumi/services/plugin/captcha_verification_service.dart';--/// Runs one plugin's anti-crawler verification end to end, owning the webview-/// service, its dialog and the timeout that closes it.-class SourceCaptchaFlow {- SourceCaptchaFlow({required this.onVerified, required this.onCancelled});+class _SourceCaptchaFlow {+ _SourceCaptchaFlow({required this.onVerified, required this.onCancelled});final void Function(Plugin plugin, String pageHtml) onVerified;- /// Dismissed before verification landed, so the source is still unresolved.final void Function(Plugin plugin) onCancelled;CaptchaVerificationService? _service;@@ -27,12 +17,9 @@ class SourceCaptchaFlow {case CaptchaType.customJavaScript:_startAutomated(plugin,- searchUrl,- statusText: '${plugin.name} 正在执行验证脚本,请稍候',- detailText: '已加载验证页面并执行自定义脚本,等待验证通过…',- startVerification: (service, url, onVerified) =>+ startVerification: (service, onVerified) =>service.loadForCustomScript(- url: url,+ url: searchUrl,script: plugin.antiCrawlerConfig.captchaScript,pluginName: plugin.name,onVerified: onVerified,@@ -41,12 +28,9 @@ class SourceCaptchaFlow {case CaptchaType.autoClickButton:_startAutomated(plugin,- searchUrl,- statusText: '${plugin.name} 正在自动完成验证,请稍候',- detailText: '已检测到验证按钮并模拟点击,等待验证通过…',- startVerification: (service, url, onVerified) =>+ startVerification: (service, onVerified) =>service.loadForButtonClick(- url: url,+ url: searchUrl,buttonXpath: plugin.antiCrawlerConfig.captchaButton,pluginName: plugin.name,onVerified: onVerified,@@ -64,31 +48,28 @@ class SourceCaptchaFlow {_timer = null;}+ void showSuccess(String pluginName, {required VoidCallback onComplete}) {+ KazumiDialog.show<bool>(+ clickMaskDismiss: false,+ builder: (_) => _VerificationCompleteDialog(pluginName: pluginName),+ ).then((completed) {+ if (completed == true) onComplete();+ });+ }+void _startCaptchaInput(Plugin plugin, String searchUrl) {bool verified = false;-- // Set once the webview reports the captcha gone. The timeout only guards- // "verification was never detected", so it keys off this rather than- // `verified`, which lands seconds later when the harvest finishes.bool finalizing = false;_service?.dispose();final service = _service = CaptchaVerificationService();- service.loadForCaptcha(- searchUrl,- plugin.antiCrawlerConfig.captchaImage,- inputXpath: plugin.antiCrawlerConfig.captchaInput,- );-Future<void> submitCaptcha(String captchaCode) async {await _service?.submitCaptcha(- captchaCode: captchaCode.trim(),+ captchaCode: captchaCode,inputXpath: plugin.antiCrawlerConfig.captchaInput,buttonXpath: plugin.antiCrawlerConfig.captchaButton,pluginName: plugin.name,- // Verification is already confirmed here; the harvest that follows- // takes seconds, so retire the timeout now rather than in onVerified.onFinalizing: () {finalizing = true;_timer?.cancel();@@ -100,8 +81,7 @@ class SourceCaptchaFlow {onVerified(plugin, pageHtml);},);- // submitCaptcha completes once the JS button click is fired; only now- // does the wait for the captcha to disappear begin.+ // Submission finishes on the JS click, before verification completes.if (!finalizing) {_timer?.cancel();_timer = Timer(const Duration(seconds: 8), () {@@ -116,16 +96,12 @@ class SourceCaptchaFlow {onDismiss: () async {_timer?.cancel();_timer = null;- // Capture before the await: an async gap could otherwise let- // [_service] be replaced or cleared, leaving this closure to dispose- // the wrong one.+ // Capture the service before awaiting so a replacement cannot be disposed.final captchaService = _service;_service = null;if (verified) {captchaService?.dispose();} else {- // Saving the earned cookies needs the webview, so it has to- // happen before the service goes.await captchaService?.cancelAndSave(plugin.name);captchaService?.dispose();onCancelled(plugin);@@ -134,19 +110,20 @@ class SourceCaptchaFlow {builder: (context) => _CaptchaDialog(pluginName: plugin.name,captchaImageStream: service.onCaptchaImageUrl,+ onReload: () => service.loadForCaptcha(+ searchUrl,+ plugin.antiCrawlerConfig.captchaImage,+ inputXpath: plugin.antiCrawlerConfig.captchaInput,+ ),onSubmit: submitCaptcha,),);}void _startAutomated(- Plugin plugin,- String searchUrl, {- required String statusText,- required String detailText,+ Plugin plugin, {required Future<void> Function(CaptchaVerificationService service,- String searchUrl,void Function(String pageHtml) onVerified,) startVerification,}) {@@ -155,7 +132,7 @@ class SourceCaptchaFlow {_service?.dispose();final service = _service = CaptchaVerificationService();- unawaited(startVerification(service, searchUrl, (pageHtml) {+ unawaited(startVerification(service, (pageHtml) {verified = true;KazumiDialog.dismiss();onVerified(plugin, pageHtml);@@ -174,8 +151,7 @@ class SourceCaptchaFlow {}},builder: (context) => _AutomatedVerifyDialog(- statusText: statusText,- detailText: detailText,+ pluginName: plugin.name,),);}@@ -183,35 +159,69 @@ class SourceCaptchaFlow {class _VerifyDialogFrame extends StatelessWidget {const _VerifyDialogFrame({+ required this.pluginName,required this.title,- required this.statusText,- required this.children,+ required this.description,+ required this.child,+ this.actions = const [],});+ final String pluginName;final String title;- final String statusText;- final List<Widget> children;+ final String description;+ final Widget child;+ final List<Widget> actions;@overrideWidget build(BuildContext context) {final theme = Theme.of(context);- return Dialog(- clipBehavior: Clip.antiAlias,- child: Padding(- padding: const EdgeInsets.all(24),- child: SizedBox(- width: 400,- child: Column(- mainAxisSize: MainAxisSize.min,+ final colors = theme.colorScheme;+ return AlertDialog(+ scrollable: true,+ backgroundColor: colors.surfaceContainerHigh,+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),+ constraints: const BoxConstraints(maxWidth: 420),+ insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 24),+ titlePadding: const EdgeInsets.fromLTRB(24, 24, 24, 0),+ contentPadding: const EdgeInsets.fromLTRB(24, 12, 24, 0),+ actionsPadding: const EdgeInsets.fromLTRB(24, 16, 24, 16),+ actionsOverflowButtonSpacing: 8,+ title: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(children: [- Text(title, style: theme.textTheme.titleLarge),- const SizedBox(height: 4),- Text(statusText, style: theme.textTheme.bodySmall),- ...children,+ Icon(Icons.verified_user_outlined,+ size: 20, color: colors.onSurfaceVariant),+ const SizedBox(width: 8),+ Expanded(+ child: Text(+ pluginName,+ style: theme.textTheme.labelLarge+ ?.copyWith(color: colors.onSurfaceVariant),+ ),+ ),],),+ const SizedBox(height: 16),+ Text(title, style: theme.textTheme.headlineSmall),+ ],+ ),+ content: SizedBox(+ width: 372,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(description,+ style: theme.textTheme.bodyMedium+ ?.copyWith(color: colors.onSurfaceVariant)),+ const SizedBox(height: 24),+ child,+ if (actions.isEmpty) const SizedBox(height: 24),+ ],),),+ actions: actions,);}}@@ -220,11 +230,13 @@ class _CaptchaDialog extends StatefulWidget {const _CaptchaDialog({required this.pluginName,required this.captchaImageStream,+ required this.onReload,required this.onSubmit,});final String pluginName;final Stream<String?> captchaImageStream;+ final Future<void> Function() onReload;final Future<void> Function(String captchaCode) onSubmit;@override@@ -232,167 +244,283 @@ class _CaptchaDialog extends StatefulWidget {}class _CaptchaDialogState extends State<_CaptchaDialog> {- final ValueNotifier<String?> _captchaImageNotifier =- ValueNotifier<String?>(null);- final ValueNotifier<bool> _submittingNotifier = ValueNotifier<bool>(false);+ final _inputController = TextEditingController();+ final _inputFocus = FocusNode();late final StreamSubscription<String?> _imageSub;- String _captchaCode = '';+ Timer? _loadTimer;+ Uint8List? _imageBytes;+ String? _imageError;+ String? _inputError;+ bool _submitting = false;+ int _imageRevision = 0;@overridevoid initState() {super.initState();- _imageSub = widget.captchaImageStream.listen((url) {- if (!mounted || url == null) return;- _captchaImageNotifier.value = url;- });+ _imageSub = widget.captchaImageStream.listen(_receiveImage);+ _reload();}@overridevoid dispose() {+ _loadTimer?.cancel();_imageSub.cancel();- _captchaImageNotifier.dispose();- _submittingNotifier.dispose();+ _inputController.dispose();+ _inputFocus.dispose();super.dispose();}+ Future<void> _receiveImage(String? data) async {+ if (!mounted || data == null || _submitting) return;+ final revision = ++_imageRevision;+ Uint8List? bytes;+ try {+ bytes = base64Decode(data.split(',').last);+ final codec = await ui.instantiateImageCodec(bytes);+ codec.dispose();+ } catch (_) {+ bytes = null;+ }+ if (!mounted || revision != _imageRevision) return;+ _loadTimer?.cancel();+ setState(() {+ _imageBytes = bytes;+ _imageError = bytes == null ? '验证码图片无法显示' : null;+ });+ }++ Future<void> _reload() async {+ if (_submitting) return;+ final revision = ++_imageRevision;+ _loadTimer?.cancel();+ setState(() {+ _imageBytes = null;+ _imageError = null;+ _inputError = null;+ _inputController.clear();+ });+ _loadTimer = Timer(const Duration(seconds: 15), () {+ if (!mounted || _imageBytes != null) return;+ setState(() => _imageError = '暂时没有获取到验证码');+ });+ try {+ await widget.onReload();+ } catch (_) {+ if (!mounted || revision != _imageRevision) return;+ _loadTimer?.cancel();+ setState(() => _imageError = '验证码加载失败');+ }+ }+Future<void> _submit() async {- if (_submittingNotifier.value) return;- final captchaCode = _captchaCode.trim();- if (captchaCode.isEmpty) {- KazumiDialog.showToast(message: '请输入验证码');+ if (_submitting || _imageBytes == null) return;+ final code = _inputController.text.trim();+ if (code.isEmpty) {+ setState(() => _inputError = '请输入图片中的字符');+ _inputFocus.requestFocus();return;}- _submittingNotifier.value = true;- await widget.onSubmit(captchaCode);+ _inputFocus.unfocus();+ setState(() => _submitting = true);+ try {+ await widget.onSubmit(code);+ } catch (_) {+ if (!mounted) return;+ setState(() {+ _submitting = false;+ _inputError = '未能提交,请重试';+ });+ }}@overrideWidget build(BuildContext context) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;return _VerifyDialogFrame(- title: '验证码验证',- statusText: '${widget.pluginName} 需要验证码验证',- children: [- const SizedBox(height: 20),- ValueListenableBuilder<String?>(- valueListenable: _captchaImageNotifier,- builder: (context, imageUrl, _) {- if (imageUrl == null) {- return const Column(- children: [- CircularProgressIndicator(),- SizedBox(height: 12),- Text('正在加载验证码图片...'),- ],- );- }- return ValueListenableBuilder<bool>(- valueListenable: _submittingNotifier,- builder: (context, isSubmitting, _) {- return Column(- children: [- ClipRRect(- borderRadius: BorderRadius.circular(8),- child: Image.memory(- base64Decode(imageUrl.split(',').last),- height: 80,- fit: BoxFit.contain,- errorBuilder: (context, error, _) =>- const Text('图片解码失败'),- ),- ),- const SizedBox(height: 16),- TextField(- autofocus: true,- enabled: !isSubmitting,- onChanged: (value) => _captchaCode = value,- decoration: const InputDecoration(- labelText: '请输入验证码',- border: OutlineInputBorder(),- ),- onSubmitted: isSubmitting ? null : (_) => _submit(),- ),- ],- );- },- );- },+ pluginName: widget.pluginName,+ title: '输入验证码',+ description: '输入下图中的字符,继续检索此来源。',+ actions: [+ TextButton(+ style: TextButton.styleFrom(minimumSize: const Size(72, 48)),+ onPressed: KazumiDialog.dismiss,+ child: const Text('返回来源'),),- const SizedBox(height: 20),- ListenableBuilder(- listenable: Listenable.merge([- _captchaImageNotifier,- _submittingNotifier,- ]),- builder: (context, _) {- final isSubmitting = _submittingNotifier.value;- final isDisabled =- _captchaImageNotifier.value == null || isSubmitting;- return Row(- mainAxisAlignment: MainAxisAlignment.end,- children: [- TextButton(- onPressed: () => KazumiDialog.dismiss(),- child: Text(- '取消',- style: TextStyle(- color: Theme.of(context).colorScheme.outline,- ),- ),- ),- const SizedBox(width: 8),- FilledButton(- onPressed: isDisabled ? null : _submit,- child: isSubmitting- ? const SizedBox.square(- dimension: 18,- child: CircularProgressIndicator(strokeWidth: 2),- )- : const Text('提交'),- ),- ],- );- },+ FilledButton(+ style: FilledButton.styleFrom(minimumSize: const Size(88, 48)),+ onPressed: _imageBytes == null || _submitting ? null : _submit,+ child: Text(_submitting ? '验证中…' : '验证'),),],+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Container(+ constraints: const BoxConstraints(minHeight: 128),+ padding: const EdgeInsets.all(16),+ decoration: BoxDecoration(+ color: colors.surfaceContainerHighest,+ borderRadius: BorderRadius.circular(20),+ ),+ child: _buildImage(),+ ),+ if (_imageBytes != null) ...[+ Align(+ alignment: Alignment.centerRight,+ child: TextButton.icon(+ style: TextButton.styleFrom(minimumSize: const Size(48, 48)),+ onPressed: _submitting ? null : _reload,+ icon: const Icon(Icons.refresh_rounded, size: 18),+ label: const Text('换一张'),+ ),+ ),+ TextField(+ controller: _inputController,+ focusNode: _inputFocus,+ enabled: !_submitting,+ autocorrect: false,+ enableSuggestions: false,+ textInputAction: TextInputAction.done,+ onChanged: (_) {+ if (_inputError != null) setState(() => _inputError = null);+ },+ onSubmitted: (_) => _submit(),+ decoration: InputDecoration(+ labelText: '验证码',+ floatingLabelBehavior: FloatingLabelBehavior.always,+ errorText: _inputError,+ errorMaxLines: 2,+ border:+ OutlineInputBorder(borderRadius: BorderRadius.circular(12)),+ ),+ ),+ ],+ ],+ ),+ );+ }++ Widget _buildImage() {+ if (_imageError != null) {+ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(Icons.broken_image_outlined,+ color: Theme.of(context).colorScheme.onSurfaceVariant),+ const SizedBox(height: 8),+ Text(_imageError!, textAlign: TextAlign.center),+ TextButton.icon(+ style: TextButton.styleFrom(minimumSize: const Size(48, 48)),+ onPressed: _reload,+ icon: const Icon(Icons.refresh_rounded, size: 18),+ label: const Text('重新加载'),+ ),+ ],+ );+ }+ if (_imageBytes == null || _submitting) {+ return Column(+ mainAxisSize: MainAxisSize.min,+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ LoadingIndicator(+ size: 40, semanticsLabel: _submitting ? '正在验证' : '正在加载验证码'),+ const SizedBox(height: 12),+ Text(_submitting ? '正在等待验证结果…' : '正在加载验证码…',+ textAlign: TextAlign.center),+ ],+ );+ }+ return Center(+ child: ClipRRect(+ borderRadius: BorderRadius.circular(8),+ child: ColoredBox(+ color: Colors.white,+ child: Image.memory(+ _imageBytes!,+ height: 88,+ fit: BoxFit.contain,+ filterQuality: FilterQuality.medium,+ semanticLabel: '验证码图片',+ ),+ ),+ ),);}}class _AutomatedVerifyDialog extends StatelessWidget {- const _AutomatedVerifyDialog({- required this.statusText,- required this.detailText,- });+ const _AutomatedVerifyDialog({required this.pluginName});++ final String pluginName;++ @override+ Widget build(BuildContext context) => _VerifyDialogFrame(+ pluginName: pluginName,+ title: '正在验证',+ description: '正在等待网站响应,通过后会自动继续检索。',+ actions: [+ TextButton(+ style: TextButton.styleFrom(minimumSize: const Size(72, 48)),+ onPressed: KazumiDialog.dismiss,+ child: const Text('返回来源'),+ ),+ ],+ child: const Padding(+ padding: EdgeInsets.symmetric(vertical: 16),+ child:+ Center(child: LoadingIndicator(size: 72, semanticsLabel: '正在验证')),+ ),+ );+}++class _VerificationCompleteDialog extends StatefulWidget {+ const _VerificationCompleteDialog({required this.pluginName});- final String statusText;- final String detailText;+ final String pluginName;++ @override+ State<_VerificationCompleteDialog> createState() =>+ _VerificationCompleteDialogState();+}++class _VerificationCompleteDialogState+ extends State<_VerificationCompleteDialog> {+ late final Timer _closeTimer;++ @override+ void initState() {+ super.initState();+ _closeTimer = Timer(+ const Duration(seconds: 3), () => Navigator.of(context).pop(true));+ }++ @override+ void dispose() {+ _closeTimer.cancel();+ super.dispose();+ }@overrideWidget build(BuildContext context) {+ final colors = Theme.of(context).colorScheme;return _VerifyDialogFrame(- title: '自动验证中',- statusText: statusText,- children: [- const SizedBox(height: 24),- const CircularProgressIndicator(),- const SizedBox(height: 12),- Text(- detailText,- style: Theme.of(context).textTheme.bodyMedium,- textAlign: TextAlign.center,- ),- const SizedBox(height: 20),- Align(- alignment: Alignment.centerRight,- child: TextButton(- onPressed: () => KazumiDialog.dismiss(),- child: Text(- '取消',- style: TextStyle(color: Theme.of(context).colorScheme.outline),- ),+ pluginName: widget.pluginName,+ title: '验证通过',+ description: '即将自动继续检索。',+ child: Center(+ child: Container(+ width: 64,+ height: 64,+ decoration: BoxDecoration(+ color: colors.primaryContainer,+ shape: BoxShape.circle,),+ child: Icon(Icons.check_rounded,+ color: colors.onPrimaryContainer, size: 32),),- ],+ ),);}}diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dartindex 0cc2b694..aeb8411b 100644--- a/lib/pages/info/source_sheet.dart+++ b/lib/pages/info/source_sheet.dart@@ -1,30 +1,36 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';+import 'dart:ui' as ui;+import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';import 'package:flutter_modular/flutter_modular.dart';-import 'package:mobx/mobx.dart' show reaction, ReactionDisposer;-import 'package:kazumi/pages/info/info_controller.dart';-import 'package:kazumi/pages/info/source_alias_dialog.dart';-import 'package:kazumi/pages/info/source_captcha_flow.dart';-import 'package:kazumi/services/logging/logger.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/bean/widget/split_list_row.dart';-import 'package:kazumi/plugins/plugins_controller.dart';-import 'package:kazumi/plugins/plugins.dart';import 'package:kazumi/modules/search/plugin_search_module.dart';+import 'package:kazumi/pages/collect/collect_controller.dart';+import 'package:kazumi/pages/info/info_controller.dart';import 'package:kazumi/pages/video/video_playback_args.dart';+import 'package:kazumi/plugins/anti_crawler_config.dart';+import 'package:kazumi/plugins/plugins.dart';+import 'package:kazumi/plugins/plugins_controller.dart';+import 'package:kazumi/services/logging/logger.dart';+import 'package:kazumi/services/plugin/captcha_verification_service.dart';+import 'package:kazumi/services/plugin/plugin_search_service.dart';import 'package:kazumi/services/plugin/rule_engine_models.dart'show RuleCancelToken;-import 'package:url_launcher/url_launcher.dart';-import 'package:kazumi/services/plugin/plugin_search_service.dart';-import 'package:kazumi/pages/collect/collect_controller.dart';import 'package:kazumi/utils/device.dart';+import 'package:url_launcher/url_launcher.dart';++part 'source_alias_dialog.dart';+part 'source_captcha_flow.dart';+part 'source_sheet_view.dart';class SourceSheet extends StatefulWidget {- const SourceSheet({- super.key,- required this.infoController,- });+ const SourceSheet({super.key, required this.infoController});final InfoController infoController;@@ -35,116 +41,88 @@ class SourceSheet extends StatefulWidget {class _SourceSheetState extends State<SourceSheet> {final CollectController _collectController = inject<CollectController>();final PluginsController _pluginsController = inject<PluginsController>();+ final Map<String, String> _sourceKeywords = {};late final String _keyword;late final PluginSearchService _searchService;- late final SourceCaptchaFlow _captchaFlow;-- String? _expandedSource;- ReactionDisposer? _autoExpandDisposer;+ late final _SourceCaptchaFlow _captchaFlow;+ RuleCancelToken? _chapterCancelToken;@overridevoid initState() {super.initState();- _keyword = widget.infoController.bangumiItem.nameCn == ''- ? widget.infoController.bangumiItem.name- : widget.infoController.bangumiItem.nameCn;+ final item = widget.infoController.bangumiItem;+ _keyword = item.nameCn.isEmpty ? item.name : item.nameCn;_searchService = PluginSearchService(infoController: widget.infoController,pluginsController: _pluginsController,);- _searchService.queryAllSource(_keyword);- _captchaFlow = SourceCaptchaFlow(+ _captchaFlow = _SourceCaptchaFlow(onVerified: _showVerifiedResult,- onCancelled: (plugin) => _querySource(_keyword, plugin.name),- );- // One shot: whichever source reports results first opens, and from then on- // the open card only moves when tapped.- _autoExpandDisposer = reaction<String?>(- (_) => _firstSourceWithResults(),- (name) {- if (name == null) return;- setState(() => _expandedSource = name);- _stopAutoExpand();- },+ onCancelled: (plugin) => _retry(plugin.name),);+ _searchService.queryAllSource(_keyword);}@overridevoid dispose() {- _stopAutoExpand();+ _chapterCancelToken?.cancel();_searchService.cancel();_captchaFlow.dispose();super.dispose();}- void _stopAutoExpand() {- _autoExpandDisposer?.call();- _autoExpandDisposer = null;- }+ String _keywordFor(String name) => _sourceKeywords[name] ?? _keyword;++ Plugin _pluginFor(String name) =>+ _pluginsController.pluginList.firstWhere((plugin) => plugin.name == name);- /// Callbacks can outlive the sheet — a countdown ending after it closes, a- /// dialog dismissed behind it — and a cancelled service still clears the- /// page's results on its way to doing nothing.void _querySource(String keyword, String pluginName) {- if (!mounted) return;- _searchService.querySource(keyword, pluginName);+ final trimmed = keyword.trim();+ if (!mounted || trimmed.isEmpty) return;+ setState(() => _sourceKeywords[pluginName] = trimmed);+ _searchService.querySource(trimmed, pluginName);}+ void _retry(String name) => _querySource(_keywordFor(name), name);+void _showVerifiedResult(Plugin plugin, String pageHtml) {+ if (!mounted) return;if (_searchService.applyHarvestedSearchResult(plugin.name, pageHtml)) {KazumiDialog.showToast(message: '验证成功');return;}- // Counting down before re-querying keeps the retry from tripping the rate- // limit the verification just cleared.- KazumiDialog.showTimedSuccessDialog(- title: '验证成功',- message: '即将重新检索',- onComplete: () => _querySource(_keyword, plugin.name),+ _captchaFlow.showSuccess(+ plugin.name,+ onComplete: () => _retry(plugin.name),);}- /// A plugin can publish more than one response: an alias search adds to what- /// the first pass found.- List<SearchItem> _resultsFor(String pluginName) {- final results = <SearchItem>[];- for (final response in widget.infoController.pluginSearchResponseList) {- if (response.pluginName == pluginName) {- results.addAll(response.data);- }- }- return results;- }-- String? _firstSourceWithResults() {- for (final plugin in _pluginsController.pluginList) {- if (_resultsFor(plugin.name).isNotEmpty) return plugin.name;- }- return null;- }-- void _toggleSource(String pluginName) {- setState(() {- _expandedSource = _expandedSource == pluginName ? null : pluginName;- });- _stopAutoExpand();- }-- void _openInBrowser(Plugin plugin) {+ Future<void> _openInBrowser(String name) async {+ final plugin = _pluginFor(name);final targetUrl = plugin.usesApiSearch? plugin.baseUrl- : plugin.searchURL.replaceFirst(+ : plugin.searchURL.replaceAll('@keyword',- Uri.encodeQueryComponent(_keyword),+ Uri.encodeQueryComponent(_keywordFor(name)),);- launchUrl(Uri.parse(targetUrl), mode: LaunchMode.externalApplication);+ try {+ if (await launchUrl(Uri.parse(targetUrl),+ mode: LaunchMode.externalApplication)) {+ return;+ }+ } catch (error) {+ KazumiLogger().w('SourceSheet: failed to open browser', error: error);+ }+ if (mounted) KazumiDialog.showToast(message: '无法打开浏览器,请稍后重试');}- Future<void> _openSearchItem(Plugin plugin, SearchItem searchItem) async {- final cancelToken = RuleCancelToken();+ Future<void> _openSearchItem(String name, SearchItem searchItem) async {+ if (_chapterCancelToken != null) return;+ final plugin = _pluginFor(name);+ final cancelToken = _chapterCancelToken = RuleCancelToken();KazumiDialog.showLoading(- msg: '获取中',+ msg: '正在获取播放列表',barrierDismissible: isDesktop(),onDismiss: cancelToken.cancel,);@@ -153,11 +131,9 @@ class _SourceSheetState extends State<SourceSheet> {searchItem.src,cancelToken: cancelToken,);- if (roads.isEmpty) {- throw ChapterErrorException(plugin.name);- }+ if (!mounted || cancelToken.isCancelled) return;+ if (roads.isEmpty) throw ChapterErrorException(plugin.name);KazumiDialog.dismiss();- if (!mounted) return;context.pushNamed('/video/',arguments: OnlineVideoPlaybackArgs(@@ -168,314 +144,78 @@ class _SourceSheetState extends State<SourceSheet> {roads: roads,),);- } catch (_) {- KazumiLogger().w("PluginSearchService: failed to query video playlist");+ } catch (error) {+ if (!mounted || cancelToken.isCancelled) return;+ KazumiLogger().w('SourceSheet: failed to query playlist', error: error);KazumiDialog.dismiss();+ KazumiDialog.showToast(message: '未能获取播放列表,请重试或选择其他结果');+ } finally {+ _chapterCancelToken = null;}}- /// Searching under an alias also saves it for the next visit.- void _searchAlias(String pluginName, String alias) {- if (!widget.infoController.bangumiItem.alias.contains(alias)) {- widget.infoController.bangumiItem.alias.add(alias);- _collectController.updateLocalCollect(widget.infoController.bangumiItem);- }- _querySource(alias, pluginName);- }-void _showAliasPicker(String pluginName) {if (widget.infoController.bangumiItem.alias.isEmpty) {- KazumiDialog.showToast(message: '无可用别名,试试手动检索');+ KazumiDialog.showToast(message: '无可用别名,试试修改检索关键词');return;}- showAliasPickerDialog(+ _showAliasPickerDialog(+ sourceName: pluginName,aliases: widget.infoController.bangumiItem.alias,- onAliasSelected: (alias) {- KazumiDialog.dismiss();- _querySource(alias, pluginName);- },+ onAliasSelected: (alias) => _querySource(alias, pluginName),onAliasesChanged: () => _collectController.updateLocalCollect(widget.infoController.bangumiItem),);}- void _showCustomKeyword(String pluginName) => showCustomKeywordDialog(- onSubmit: (keyword) => _searchAlias(pluginName, keyword),+ void _showCustomKeyword(String pluginName) => _showCustomKeywordDialog(+ initialKeyword: _keywordFor(pluginName),+ sourceName: pluginName,+ onSubmit: (keyword) {+ final item = widget.infoController.bangumiItem;+ if (!item.alias.contains(keyword)) {+ item.alias.add(keyword);+ _collectController.updateLocalCollect(item);+ }+ _querySource(keyword, pluginName);+ },);- /// One source, collapsed to a row until opened. The header sits a surface- /// step above its result rows — and shifts to `secondaryContainer` while- /// open — so a rule never reads as one of the titles it returned.- Widget _buildSourceCard(Plugin plugin, List<SearchItem> results, bool open) {- final searching = widget.infoController.pluginSearchStatus[plugin.name] ==- PluginSearchStatus.pending;- final colorScheme = Theme.of(context).colorScheme;-- final body = <({Widget child, VoidCallback? onTap})>[];- if (open && !searching) {- if (results.isEmpty) {- body.add((child: _buildActionsRow(plugin), onTap: null));- } else {- for (final result in results) {- body.add((- child: _buildResultRow(result),- onTap: () => _openSearchItem(plugin, result),- ));- }- }- }-- return Padding(- padding: const EdgeInsets.only(bottom: 12),- child: AnimatedSize(- duration: splitListMotionDuration,- curve: splitListMotionCurve,- alignment: Alignment.topCenter,- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- SplitListRow(- color: open- ? colorScheme.secondaryContainer- : colorScheme.surfaceContainer,- topRadius: splitListOuterRadius,- bottomRadius:- body.isEmpty ? splitListOuterRadius : splitListInnerRadius,- onTap: () => _toggleSource(plugin.name),- child: _buildSourceHeader(plugin, results, searching, open),- ),- for (var i = 0; i < body.length; i++) ...[- const SizedBox(height: splitListRowGap),- SplitListRow(- bottomRadius: i == body.length - 1- ? splitListOuterRadius- : splitListInnerRadius,- onTap: body[i].onTap,- child: body[i].child,- ),- ],- ],- ),- ),- );- }-- /// Status rides in trailing text rather than a leading icon: rows whose- /// siblings lack one end up with misaligned names.- ({String text, Color? color}) _sourceSummary(- Plugin plugin, List<SearchItem> results, bool searching) {- if (searching) return (text: '检索中', color: null);- if (results.isNotEmpty) return (text: '${results.length} 条', color: null);- final error = Theme.of(context).colorScheme.error;- return switch (widget.infoController.pluginSearchStatus[plugin.name]) {- PluginSearchStatus.error => (text: '检索失败', color: error),- PluginSearchStatus.captcha => (text: '需要验证', color: error),- _ => (text: '无结果', color: null),- };- }-- Widget _buildSourceHeader(- Plugin plugin, List<SearchItem> results, bool searching, bool open) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;- final summary = _sourceSummary(plugin, results, searching);- final onColor = open ? colorScheme.onSecondaryContainer : null;- // Buttons under a result list get hit by thumbs reaching for the last row,- // so a source with results keeps its actions up here instead.- final hasMenu = open && !searching && results.isNotEmpty;- return Padding(- // Both branches land on 56dp, matching a result row: the menu's- // IconButton is 48dp on its own.- padding: hasMenu- ? const EdgeInsets.fromLTRB(18, 4, 14, 4)- : const EdgeInsets.fromLTRB(18, 18, 18, 18),- child: Row(- children: [- Expanded(- child: Text(- plugin.name,- style: theme.textTheme.titleSmall?.copyWith(color: onColor),- ),- ),- Text(- summary.text,- style: theme.textTheme.labelMedium?.copyWith(- color: summary.color ?? onColor ?? colorScheme.onSurfaceVariant,- ),- ),- if (searching) ...[- const SizedBox(width: 10),- const SizedBox.square(- dimension: 16,- child: CircularProgressIndicator(strokeWidth: 2),- ),- ] else ...[- if (hasMenu)- PopupMenuButton<VoidCallback>(- tooltip: '${plugin.name} 的更多操作',- icon: Icon(Icons.more_vert_rounded, size: 20, color: onColor),- onSelected: (action) => action(),- itemBuilder: (context) => [- PopupMenuItem(- value: () => _showAliasPicker(plugin.name),- child: const Text('别名检索'),- ),- PopupMenuItem(- value: () => _showCustomKeyword(plugin.name),- child: const Text('手动检索'),- ),- PopupMenuItem(- value: () => _openInBrowser(plugin),- child: const Text('在浏览器中打开'),- ),- ],- )- else- const SizedBox(width: 10),- AnimatedRotation(- turns: open ? 0.5 : 0,- duration: splitListMotionDuration,- curve: splitListMotionCurve,- child: Icon(- Icons.expand_more_rounded,- size: 20,- color: onColor ?? colorScheme.onSurfaceVariant,- ),- ),- ],- ],- ),- );- }-- Widget _buildResultRow(SearchItem searchItem) {- final theme = Theme.of(context);- return Padding(- padding: const EdgeInsets.fromLTRB(18, 18, 16, 18),- child: Row(- children: [- Expanded(- child: Text(searchItem.name, style: theme.textTheme.bodyMedium),- ),- const SizedBox(width: 8),- Icon(- Icons.play_arrow_rounded,- size: 20,- color: theme.colorScheme.primary,- ),- ],- ),- );- }-- Widget _buildActionsRow(Plugin plugin) {- final theme = Theme.of(context);- final actions = <Widget>[];- final String hint;- switch (widget.infoController.pluginSearchStatus[plugin.name]) {- case PluginSearchStatus.captcha:- hint = '这个源要求先完成验证';- actions.add(- _primaryAction('进行验证', () => _captchaFlow.start(plugin, _keyword)));- actions.add(_action('重试', () => _retry(plugin)));- case PluginSearchStatus.error:- hint = '这个源没能返回结果';- actions.add(_primaryAction('重试', () => _retry(plugin)));- default:- hint = '换个关键词再试试';- actions- .add(_primaryAction('别名检索', () => _showAliasPicker(plugin.name)));- actions.add(_action('手动检索', () => _showCustomKeyword(plugin.name)));- }- actions.add(_action('浏览器打开', () => _openInBrowser(plugin)));-- return Padding(- padding: const EdgeInsets.fromLTRB(14, 10, 14, 12),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Padding(- padding: const EdgeInsets.only(left: 4, bottom: 6),- child: Text(- hint,- style: theme.textTheme.bodySmall?.copyWith(- color: theme.colorScheme.onSurfaceVariant,- ),- ),- ),- Wrap(spacing: 8, runSpacing: 4, children: actions),- ],- ),- );- }-- void _retry(Plugin plugin) => _querySource(_keyword, plugin.name);-- Widget _primaryAction(String label, VoidCallback onPressed) =>- FilledButton.tonal(onPressed: onPressed, child: Text(label));-- Widget _action(String label, VoidCallback onPressed) =>- TextButton(onPressed: onPressed, child: Text(label));-- /// Always plugin order, never ranked by what came back: a source can fill- /// up long after the search settles — a captcha source does once verified- /// — and ranking would slide the card someone just acted on out from- /// under them.- List<Widget> _buildSourceCards() {- final cards = <Widget>[];- for (final plugin in _pluginsController.pluginList) {- cards.add(_buildSourceCard(- plugin,- _resultsFor(plugin.name),- _expandedSource == plugin.name,- ));- }- cards.add(const SafeArea(top: false, child: SizedBox(height: 12)));- return cards;- }-- String _progressDescription() {- final plugins = _pluginsController.pluginList;- final done = plugins- .where((plugin) =>- widget.infoController.pluginSearchStatus[plugin.name] !=- PluginSearchStatus.pending)- .length;- final found = plugins.fold<int>(- 0, (sum, plugin) => sum + _resultsFor(plugin.name).length);- if (done < plugins.length) {- return '「$_keyword」· 检索中 $done/${plugins.length}';- }- return '「$_keyword」· $found 条结果';- }-@override- Widget build(BuildContext context) {- return Scaffold(- backgroundColor: Theme.of(context).colorScheme.surface,- body: Observer(+ Widget build(BuildContext context) => Observer(builder: (context) {- // Must be read here, not behind a nested Builder: mobx only tracks- // reads made while the Observer's own builder runs.- final cards = _buildSourceCards();- return Column(- children: [- MaterialBottomSheetHeader(- title: '选择播放源',- description: _progressDescription(),- onClose: () => Navigator.of(context).pop(),- ),- Expanded(- child: ListView.builder(- padding: const EdgeInsets.symmetric(horizontal: 16),- itemCount: cards.length,- itemBuilder: (context, index) => cards[index],- ),- ),- ],+ // Snapshot observable values here; lazy list builders are not tracked.+ final groups = <_SourceSearchGroup>[];+ for (final plugin in _pluginsController.pluginList) {+ final seen = <String>{};+ final results = <SearchItem>[];+ for (final response+ in widget.infoController.pluginSearchResponseList) {+ if (response.pluginName != plugin.name) continue;+ for (final result in response.data) {+ if (seen.add(result.src)) results.add(result);+ }+ }+ groups.add(_SourceSearchGroup(+ name: plugin.name,+ keyword: _keywordFor(plugin.name),+ status: widget.infoController.pluginSearchStatus[plugin.name] ??+ PluginSearchStatus.pending,+ results: results,+ ));+ }+ return _SourceSheetView(+ keyword: _keyword,+ groups: groups,+ onSourceSearch: _showCustomKeyword,+ onSourceAliasSearch: _showAliasPicker,+ onRetry: _retry,+ onVerify: (name) =>+ _captchaFlow.start(_pluginFor(name), _keywordFor(name)),+ onOpenBrowser: _openInBrowser,+ onPlay: _openSearchItem,+ onClose: () => Navigator.of(context).pop(),);},- ),- );- }+ );}diff --git a/lib/pages/info/source_sheet_view.dart b/lib/pages/info/source_sheet_view.dartnew file mode 100644index 00000000..2c70dc5d--- /dev/null+++ b/lib/pages/info/source_sheet_view.dart@@ -0,0 +1,492 @@+part of 'source_sheet.dart';++class _SourceSearchGroup {+ const _SourceSearchGroup({+ required this.name,+ required this.keyword,+ required this.status,+ required this.results,+ });++ final String name;+ final String keyword;+ final PluginSearchStatus status;+ final List<SearchItem> results;++ bool get isSearching => status == PluginSearchStatus.pending;+ bool get hasResults => !isSearching && results.isNotEmpty;+}++enum _SourceDisplay { preview, expanded, collapsed }++class _SourceSheetView extends StatefulWidget {+ const _SourceSheetView({+ required this.keyword,+ required this.groups,+ required this.onSourceSearch,+ required this.onSourceAliasSearch,+ required this.onRetry,+ required this.onVerify,+ required this.onOpenBrowser,+ required this.onPlay,+ required this.onClose,+ });++ final String keyword;+ final List<_SourceSearchGroup> groups;+ final ValueChanged<String> onSourceSearch;+ final ValueChanged<String> onSourceAliasSearch;+ final ValueChanged<String> onRetry;+ final ValueChanged<String> onVerify;+ final ValueChanged<String> onOpenBrowser;+ final void Function(String sourceName, SearchItem result) onPlay;+ final VoidCallback onClose;++ @override+ State<_SourceSheetView> createState() => _SourceSheetViewState();+}++class _SourceSheetViewState extends State<_SourceSheetView> {+ static const _previewCount = 3;+ final _scrollController = ScrollController();+ final _display = <String, _SourceDisplay>{};+ final _headerKeys = <String, GlobalKey>{};++ @override+ void didUpdateWidget(covariant _SourceSheetView oldWidget) {+ super.didUpdateWidget(oldWidget);+ final oldGroups = {for (final group in oldWidget.groups) group.name: group};+ final names = widget.groups.map((group) => group.name).toSet();+ _display.removeWhere((name, _) => !names.contains(name));+ _headerKeys.removeWhere((name, _) => !names.contains(name));+ for (final group in widget.groups) {+ final previous = oldGroups[group.name];+ if (previous?.keyword != group.keyword ||+ (group.isSearching && previous?.isSearching != true)) {+ _display.remove(group.name);+ }+ }+ }++ @override+ void dispose() {+ _scrollController.dispose();+ super.dispose();+ }++ void _setDisplay(String name, _SourceDisplay display,+ {bool fromFooter = false}) {+ if (fromFooter && display == _SourceDisplay.collapsed) {+ final headerContext = _headerKeys[name]?.currentContext;+ if (headerContext != null) {+ // Anchor before shrinking a long group, while its header is laid out.+ Scrollable.ensureVisible(headerContext, alignment: 0);+ }+ }+ setState(() => _display[name] = display);+ }++ Widget _animateSize(Widget child) => MediaQuery.disableAnimationsOf(context)+ ? child+ : AnimatedSize(+ duration: splitListMotionDuration,+ curve: splitListMotionCurve,+ alignment: Alignment.topCenter,+ child: child,+ );++ @override+ Widget build(BuildContext context) {+ final pending = widget.groups.where((group) => group.isSearching).length;+ final resultCount = widget.groups+ .where((group) => group.hasResults)+ .fold(0, (sum, group) => sum + group.results.length);++ return Scaffold(+ backgroundColor: Colors.transparent,+ body: Column(+ children: [+ MaterialBottomSheetHeader(+ title: '播放来源',+ description: pending > 0+ ? '检索中 ${widget.groups.length - pending}/${widget.groups.length} · $resultCount 个结果'+ : '${widget.groups.length} 个来源 · $resultCount 个结果',+ compact: true,+ onClose: widget.onClose,+ ),+ Expanded(+ child: Scrollbar(+ controller: _scrollController,+ child: CustomScrollView(+ controller: _scrollController,+ slivers: [+ if (widget.groups.isEmpty)+ SliverToBoxAdapter(child: _buildNoSources())+ else+ SliverPadding(+ padding: const EdgeInsets.symmetric(horizontal: 24),+ sliver: SliverList.builder(+ itemCount: widget.groups.length,+ findChildIndexCallback: (key) {+ final index = widget.groups.indexWhere(+ (group) => ValueKey(group.name) == key);+ return index < 0 ? null : index;+ },+ itemBuilder: (context, index) {+ final group = widget.groups[index];+ return Padding(+ key: ValueKey(group.name),+ padding: const EdgeInsets.only(bottom: 12),+ child: _buildSourceGroup(group),+ );+ },+ ),+ ),+ const SliverToBoxAdapter(+ child: SafeArea(top: false, child: SizedBox(height: 24)),+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ );+ }++ Widget _buildSourceGroup(_SourceSearchGroup group) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;+ final display = _display[group.name] ?? _SourceDisplay.preview;+ final collapsed = group.hasResults && display == _SourceDisplay.collapsed;+ final showAll = display == _SourceDisplay.expanded;+ final visibleCount = showAll || group.results.length <= _previewCount+ ? group.results.length+ : _previewCount;+ final hasFooter = group.results.length > _previewCount;+ final duration = MediaQuery.disableAnimationsOf(context)+ ? Duration.zero+ : splitListMotionDuration;++ void toggle() => _setDisplay(group.name,+ collapsed ? _SourceDisplay.preview : _SourceDisplay.collapsed);++ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ KeyedSubtree(+ key: _headerKeys.putIfAbsent(group.name, GlobalKey.new),+ child: Row(+ children: [+ Expanded(+ child: Semantics(+ header: true,+ button: group.hasResults,+ expanded: group.hasResults ? !collapsed : null,+ label:+ '来源规则:${group.name}${group.hasResults ? ',${group.results.length} 个结果' : ''}',+ onTap: group.hasResults ? toggle : null,+ excludeSemantics: true,+ child: Material(+ type: MaterialType.transparency,+ child: InkWell(+ borderRadius: BorderRadius.circular(16),+ onTap: group.hasResults ? toggle : null,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 48),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(12, 8, 4, 8),+ child: Row(+ children: [+ Expanded(+ child: Text(+ group.name,+ style: theme.textTheme.labelLarge?.copyWith(+ color: colors.onSurfaceVariant,+ ),+ )),+ if (group.hasResults) ...[+ const SizedBox(width: 8),+ Text(+ '${group.results.length} 个结果',+ style: theme.textTheme.labelMedium?.copyWith(+ color: colors.onSurfaceVariant,+ ),+ ),+ const SizedBox(width: 8),+ AnimatedRotation(+ turns: collapsed ? 0 : 0.5,+ duration: duration,+ curve: splitListMotionCurve,+ child: Icon(Icons.expand_more_rounded,+ size: 20, color: colors.onSurfaceVariant),+ ),+ ],+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ _buildSourceMenu(group),+ ],+ ),+ ),+ if (group.keyword != widget.keyword)+ Padding(+ padding: const EdgeInsets.fromLTRB(12, 0, 12, 8),+ child: Text(+ '检索词:${group.keyword}',+ style: theme.textTheme.bodySmall+ ?.copyWith(color: colors.onSurfaceVariant),+ ),+ ),+ _animateSize(+ Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (group.hasResults) ...[+ if (!collapsed) ...[+ for (var index = 0; index < visibleCount; index++) ...[+ if (index > 0) const SizedBox(height: splitListRowGap),+ _buildResult(group, index,+ isLast: !hasFooter && index == visibleCount - 1),+ ],+ if (hasFooter) ...[+ const SizedBox(height: splitListRowGap),+ SplitListRow(+ bottomRadius: splitListOuterRadius,+ onTap: () => _setDisplay(+ group.name,+ showAll+ ? _SourceDisplay.collapsed+ : _SourceDisplay.expanded,+ fromFooter: true,+ ),+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 48),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 16, vertical: 12),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Flexible(+ child: Text(+ showAll+ ? '收起全部条目'+ : '展开全部 ${group.results.length} 个结果',+ textAlign: TextAlign.center,+ style: theme.textTheme.labelLarge+ ?.copyWith(color: colors.primary),+ )),+ const SizedBox(width: 8),+ Icon(+ showAll+ ? Icons.unfold_less_rounded+ : Icons.expand_more_rounded,+ size: 20,+ color: colors.primary),+ ],+ ),+ ),+ ),+ ),+ ],+ ],+ ] else+ SplitListRow(+ topRadius: splitListOuterRadius,+ bottomRadius: splitListOuterRadius,+ child: group.isSearching+ ? _buildSearching()+ : _buildRecovery(group),+ ),+ ],+ ),+ ),+ ],+ );+ }++ Widget _buildSourceMenu(_SourceSearchGroup group) => TooltipVisibility(+ visible: false,+ child: PopupMenuButton<VoidCallback>(+ tooltip: '${group.name} 的更多操作',+ icon: const Icon(Icons.more_horiz_rounded, size: 20),+ onSelected: (action) => action(),+ itemBuilder: (_) => [+ PopupMenuItem(+ value: () => widget.onSourceSearch(group.name),+ child: const Text('修改此来源的检索词'),+ ),+ PopupMenuItem(+ value: () => widget.onSourceAliasSearch(group.name),+ child: const Text('使用别名检索此来源'),+ ),+ PopupMenuItem(+ value: () => widget.onRetry(group.name),+ child: const Text('重新检索此来源'),+ ),+ PopupMenuItem(+ value: () => widget.onOpenBrowser(group.name),+ child: const Text('在浏览器中打开'),+ ),+ ],+ ),+ );++ Widget _buildResult(_SourceSearchGroup group, int index,+ {required bool isLast}) {+ final theme = Theme.of(context);+ final result = group.results[index];+ return SplitListRow(+ topRadius: index == 0 ? splitListOuterRadius : splitListInnerRadius,+ bottomRadius: isLast ? splitListOuterRadius : splitListInnerRadius,+ onTap: () => widget.onPlay(group.name, result),+ child: Semantics(+ button: true,+ label: '播放 ${result.name},来源 ${group.name}',+ excludeSemantics: true,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 64),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),+ child: Row(+ children: [+ Expanded(+ child: Text(result.name,+ style: theme.textTheme.bodyLarge?.copyWith(+ color: theme.colorScheme.onSurface,+ )),+ ),+ const SizedBox(width: 16),+ Icon(Icons.play_arrow_rounded,+ color: theme.colorScheme.primary),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _buildSearching() => ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 64),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),+ child: Row(+ children: [+ const LoadingIndicator(size: 20, semanticsLabel: '正在检索'),+ const SizedBox(width: 12),+ Expanded(+ child: Text('正在检索…',+ style: Theme.of(context).textTheme.bodyMedium)),+ ],+ ),+ ),+ );++ Widget _buildRecovery(_SourceSearchGroup group) {+ final theme = Theme.of(context);+ final colors = theme.colorScheme;+ final (icon, title, hint, action, onAction, alternative, onAlternative) =+ switch (group.status) {+ PluginSearchStatus.captcha => (+ Icons.verified_user_outlined,+ '需要验证',+ '完成网站验证后继续检索。',+ '进行验证',+ () => widget.onVerify(group.name),+ '打开网站',+ () => widget.onOpenBrowser(group.name),+ ),+ PluginSearchStatus.error => (+ Icons.error_outline_rounded,+ '检索失败',+ '可以重试,或打开网站检查是否可用。',+ '重试',+ () => widget.onRetry(group.name),+ '打开网站',+ () => widget.onOpenBrowser(group.name),+ ),+ _ => (+ Icons.search_off_rounded,+ '没有匹配结果',+ '试试别名或更短的关键词。',+ '修改检索词',+ () => widget.onSourceSearch(group.name),+ '使用别名',+ () => widget.onSourceAliasSearch(group.name),+ ),+ };+ return Padding(+ padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Icon(+ icon,+ size: 20,+ color: group.status == PluginSearchStatus.error+ ? colors.error+ : colors.onSurfaceVariant,+ ),+ ),+ const SizedBox(width: 10),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(title,+ style: theme.textTheme.bodyMedium?.copyWith(+ fontWeight: FontWeight.w500,+ )),+ const SizedBox(height: 2),+ Text(hint,+ style: theme.textTheme.bodySmall?.copyWith(+ color: colors.onSurfaceVariant,+ )),+ ],+ ),+ ),+ ],+ ),+ const SizedBox(height: 8),+ Wrap(+ spacing: 8,+ runSpacing: 4,+ children: [+ FilledButton.tonal(onPressed: onAction, child: Text(action)),+ TextButton(onPressed: onAlternative, child: Text(alternative)),+ ],+ ),+ ],+ ),+ );+ }++ Widget _buildNoSources() => Padding(+ padding: const EdgeInsets.fromLTRB(24, 32, 24, 24),+ child: Column(+ children: [+ Text('还没有来源规则', style: Theme.of(context).textTheme.titleMedium),+ const SizedBox(height: 8),+ Text(+ '请先在「规则管理」中添加来源,再开始播放。',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(+ color: Theme.of(context).colorScheme.onSurfaceVariant,+ ),+ ),+ ],+ ),+ );+}diff --git a/lib/pages/logs/logs_page.dart b/lib/pages/logs/logs_page.dartindex bdf46bb0..1112f2df 100644--- a/lib/pages/logs/logs_page.dart+++ b/lib/pages/logs/logs_page.dart@@ -1,11 +1,14 @@-import 'dart:io';import 'dart:async';+import 'dart:io';+import 'package:flutter/material.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:path_provider/path_provider.dart';import 'package:flutter/services.dart';+import 'package:path_provider/path_provider.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/widget/empty_state_widget.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';class LogsPage extends StatefulWidget {const LogsPage({super.key});@@ -100,7 +103,6 @@ class _LogsPageState extends State<LogsPage> {return;}- // 使用 Future.microtask 避免在构建过程中调用 setStateFuture.microtask(() {if (!mounted) return;@@ -167,7 +169,7 @@ class _LogsPageState extends State<LogsPage> {Widget get buildBody {if (_isLoading) {return const Center(- child: CircularProgressIndicator(),+ child: LoadingIndicator(),);}diff --git a/lib/pages/my/my_page.dart b/lib/pages/my/my_page.dartindex 2458608e..c0932a8b 100644--- a/lib/pages/my/my_page.dart+++ b/lib/pages/my/my_page.dart@@ -1,8 +1,10 @@import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';import 'package:flutter_modular/flutter_modular.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/split_list_row.dart';import 'package:kazumi/modules/collect/collect_type.dart';import 'package:kazumi/modules/my/watch_stats.dart';import 'package:kazumi/pages/menu/route_visibility.dart';@@ -11,8 +13,6 @@ import 'package:kazumi/pages/my/recent_watch_card.dart';import 'package:kazumi/utils/constants.dart';import 'package:kazumi/utils/date_time.dart';-/// Shared by every block on this page, entry group included, so they read as-/// one set of cards.const double _cardRadius = 16;class MyPage extends StatefulWidget {@@ -32,8 +32,7 @@ class _MyPageState extends State<MyPage> {@overridevoid didChangeDependencies() {super.didChangeDependencies();- // This page stays mounted under the player, which rewrites history every- // second. Drop the subscription while covered, re-derive on the way back.+ // Pause history updates while the mounted page is covered by the player._setAttached(!RouteVisibility.isCoveredOf(context));}@@ -193,7 +192,7 @@ class _MyPageState extends State<MyPage> {label: '离线缓存',),];- // Tiles hold different amounts of text; stretch keeps them level.+return IntrinsicHeight(child: Row(crossAxisAlignment: CrossAxisAlignment.stretch,@@ -207,10 +206,8 @@ class _MyPageState extends State<MyPage> {);}- /// The same split list the settings page uses, at this page's card radius so- /// the group sits level with the hero beside it.Widget _entryGroup(WatchStats stats) {- return SettingsSplitGroup(+ return SplitListGroup(outerRadius: _cardRadius,children: [SettingsCategoryTile(@@ -425,4 +422,3 @@ class _StatTile extends StatelessWidget {);}}-diff --git a/lib/pages/onboarding/onboarding_page.dart b/lib/pages/onboarding/onboarding_page.dartindex e634b2b0..58f94c78 100644--- a/lib/pages/onboarding/onboarding_page.dart+++ b/lib/pages/onboarding/onboarding_page.dart@@ -3,8 +3,10 @@ import 'dart:io';import 'package:flutter/material.dart';import 'package:flutter_modular/flutter_modular.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/pages/my/my_controller.dart';import 'package:kazumi/pages/onboarding/steps/disclaimer_step.dart';import 'package:kazumi/pages/onboarding/steps/mirror_settings_step.dart';@@ -181,7 +183,7 @@ class _OnboardingPageState extends State<OnboardingPage> {? const SizedBox(width: 18,height: 18,- child: CircularProgressIndicator(strokeWidth: 2),+ child: LoadingIndicator(),): Text(primaryLabel),),diff --git a/lib/pages/onboarding/steps/disclaimer_step.dart b/lib/pages/onboarding/steps/disclaimer_step.dartindex 9792bf29..482b7771 100644--- a/lib/pages/onboarding/steps/disclaimer_step.dart+++ b/lib/pages/onboarding/steps/disclaimer_step.dart@@ -1,5 +1,8 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart' show rootBundle;++import 'package:kazumi/bean/widget/loading_indicator.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';import 'package:kazumi/pages/onboarding/onboarding_step_layout.dart';import 'package:kazumi/services/logging/logger.dart';@@ -41,19 +44,14 @@ class _DisclaimerStepState extends State<DisclaimerStep> {@overrideWidget build(BuildContext context) {- final colorScheme = Theme.of(context).colorScheme;final textTheme = Theme.of(context).textTheme;return OnboardingStepLayout(leading: const OnboardingStepIcon(icon: Icons.waving_hand_rounded),title: '欢迎使用',subtitle: '请阅读并同意免责声明',- child: Card(- elevation: 0,- margin: EdgeInsets.zero,- color: colorScheme.surfaceContainerLow,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),+ child: TonalCard(child: statementsText == null- ? const Center(child: CircularProgressIndicator())+ ? const Center(child: LoadingIndicator()): SingleChildScrollView(padding: const EdgeInsets.all(20),child: Text(diff --git a/lib/pages/onboarding/steps/mirror_settings_step.dart b/lib/pages/onboarding/steps/mirror_settings_step.dartindex 7f094477..dd35e1a9 100644--- a/lib/pages/onboarding/steps/mirror_settings_step.dart+++ b/lib/pages/onboarding/steps/mirror_settings_step.dart@@ -1,4 +1,6 @@import 'package:flutter/material.dart';++import 'package:kazumi/bean/widget/tonal_card.dart';import 'package:kazumi/pages/onboarding/onboarding_step_layout.dart';import 'package:kazumi/services/storage/storage.dart';@@ -29,13 +31,7 @@ class _MirrorSettingsStepState extends State<MirrorSettingsStep> {subtitle: '中国大陆用户推荐启用,提升访问速度',child: Align(alignment: Alignment.topCenter,- child: Card(- elevation: 0,- margin: EdgeInsets.zero,- color: colorScheme.surfaceContainerLow,- shape:- RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),- clipBehavior: Clip.antiAlias,+ child: TonalCard(child: Column(mainAxisSize: MainAxisSize.min,children: [diff --git a/lib/pages/player/syncplay_sheet.dart b/lib/pages/player/syncplay_sheet.dartindex 0ad62be0..bc54f74d 100644--- a/lib/pages/player/syncplay_sheet.dart+++ b/lib/pages/player/syncplay_sheet.dart@@ -3,18 +3,20 @@ import 'dart:math';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_mobx/flutter_mobx.dart';+import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';+import 'package:kazumi/bean/widget/split_list_row.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';import 'package:kazumi/pages/player/player_controller.dart';import 'package:kazumi/services/player/syncplay_endpoint.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/device.dart';-/// The lobby pops itself with the step to open next, so the framework animates-/// the swap. Steps never route back — dismissing one ends the flow.+// Close each step before opening the next to avoid stacked modal routes.enum _SyncPlayDestination { create, join, server }-/// Single entry point for everything SyncPlay: status, create, join, server.Future<void> showSyncPlaySheet(BuildContext context, {required PlayerController playerController,@@ -56,15 +58,8 @@ Future<T?> _showStep<T>(BuildContext context, WidgetBuilder builder) {String _readEndPoint() =>GStorage.getSetting<String>(SettingsKeys.syncPlayEndPoint);-/// M3 outlined field on the sheet's tonal cards, carrying the cards' radius-/// instead of the 4dp baseline.-///-/// Outlined rather than filled: these fields float a label, and only the-/// outline can notch around it. A fill would slice the label along the-/// container's top edge.InputDecoration _sheetInputDecoration({required String labelText,- required IconData icon,String? hintText,String? helperText,String? errorText,@@ -74,9 +69,6 @@ InputDecoration _sheetInputDecoration({hintText: hintText,helperText: helperText,errorText: errorText,- prefixIcon: Icon(icon),- // Radius only: InputDecorator recolors this border per state from the M3- // defaults, covering hover and disabled as well.border: OutlineInputBorder(borderRadius: BorderRadius.circular(20)),);}@@ -98,73 +90,41 @@ class _SyncPlaySheetScaffold extends StatelessWidget {@overrideWidget build(BuildContext context) {- final ThemeData theme = Theme.of(context);- final ColorScheme colorScheme = theme.colorScheme;final Size size = MediaQuery.sizeOf(context);final double keyboardInset = MediaQuery.viewInsetsOf(context).bottom;- // Phone landscape leaves almost no height once the keyboard is up, so the- // layout collapses to rows and sheds the descriptive copy.+final bool compact =size.width > size.height && !isDesktop() && size.shortestSide < 600;final bool showDescription = !(compact && keyboardInset > 0);return Padding(- // Lifting the sheet by the keyboard inset and letting the body shrink- // keeps the fields reachable instead of covered.padding: EdgeInsets.only(bottom: keyboardInset),child: Column(mainAxisSize: MainAxisSize.min,children: [- Padding(- padding: EdgeInsets.fromLTRB(- 20, compact ? 12 : 20, 12, compact ? 10 : 16),- child: Row(- children: [- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,+ MaterialBottomSheetHeader(+ title: title,+ description: showDescription ? description : null,+ compact: compact,+ onClose: () => Navigator.of(context).pop(),+ trailing: compact && primaryAction != null+ ? Row(mainAxisSize: MainAxisSize.min,children: [- Text(- title,- style: (compact- ? theme.textTheme.titleLarge- : theme.textTheme.headlineSmall)- ?.copyWith(- color: colorScheme.onSurface,- fontWeight: FontWeight.w700,- ),+ primaryAction!,+ const SizedBox(width: 8),+ IconButton(+ onPressed: () => Navigator.of(context).pop(),+ tooltip: '关闭',+ icon: const Icon(Icons.close_rounded),),- if (showDescription) ...[- const SizedBox(height: 4),- Text(- description,- style: theme.textTheme.bodyMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- ],],- ),- ),- // Compact spends its remaining pixels on the fields, so the- // primary action lives here instead of a second button bar.- if (compact && primaryAction != null) ...[- const SizedBox(width: 12),- primaryAction!,- ],- const SizedBox(width: 12),- IconButton.filledTonal(- onPressed: () => Navigator.of(context).pop(),- tooltip: '关闭',- icon: const Icon(Icons.close_rounded),- ),- ],- ),+ )+ : null,),Flexible(child: SingleChildScrollView(- padding: const EdgeInsets.fromLTRB(20, 0, 20, 4),+ padding: const EdgeInsets.symmetric(horizontal: 24),child: bodyBuilder(context, compact),),),@@ -172,7 +132,7 @@ class _SyncPlaySheetScaffold extends StatelessWidget {const SizedBox(height: 12)else if (showCancel || primaryAction != null)Padding(- padding: const EdgeInsets.fromLTRB(20, 16, 20, 20),+ padding: const EdgeInsets.fromLTRB(24, 16, 24, 24),child: Row(children: [if (showCancel)@@ -186,7 +146,7 @@ class _SyncPlaySheetScaffold extends StatelessWidget {),)else- const SizedBox(height: 20),+ const SizedBox(height: 24),],),);@@ -203,20 +163,17 @@ class _SyncPlayHomeSheet extends StatelessWidget {final ColorScheme colorScheme = Theme.of(context).colorScheme;return Observer(builder: (context) {- // Read every observable here and unconditionally: the body builder runs- // from the scaffold's build, where reads are no longer tracked, and a- // short-circuited read would register no dependency.+ // Read all observables here; the deferred body builder is not tracked.final bool hasSession = playerController.syncplay.hasSession;final String room = playerController.syncplay.syncplayRoom;final int rtt = playerController.syncplay.syncplayClientRtt;final bool connected = room.isNotEmpty;- // Connected socket, room not joined yet. The server picker must stay out- // of reach, otherwise the saved address stops matching what we dialed.+ // Lock server selection while connected, even before joining a room.final bool connecting = hasSession && !connected;return _SyncPlaySheetScaffold(title: '一起看',- description: '与好友同步播放、暂停与选集',+ description: '和朋友同步看番',primaryAction: hasSession? FilledButton.tonalIcon(onPressed: () async {@@ -247,17 +204,14 @@ class _SyncPlayHomeSheet extends StatelessWidget {final ThemeData theme = Theme.of(context);final ColorScheme colorScheme = theme.colorScheme;- return Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,+ return TonalCard(child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 20),+ padding: const EdgeInsets.all(16),child: Row(children: [const SizedBox.square(dimension: 22,- child: CircularProgressIndicator(strokeWidth: 2),+ child: LoadingIndicator(),),const SizedBox(width: 16),Expanded(@@ -290,70 +244,38 @@ class _SyncPlayHomeSheet extends StatelessWidget {}Widget _buildLobby(BuildContext context, {required bool compact}) {- final ThemeData theme = Theme.of(context);- final ColorScheme colorScheme = theme.colorScheme;-- final Widget create = _ChoiceCard(- icon: Icons.add_home_outlined,- title: '创建房间',- description: '生成房间号并邀请好友',- emphasized: true,- onTap: () => Navigator.of(context).pop(_SyncPlayDestination.create),- );- final Widget join = _ChoiceCard(- icon: Icons.login_rounded,- title: '加入房间',- description: '已有好友的房间号',- emphasized: false,- onTap: () => Navigator.of(context).pop(_SyncPlayDestination.join),- );-return Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if (compact)- IntrinsicHeight(+ IntrinsicHeight(child: Row(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Expanded(child: create),- const SizedBox(width: 12),- Expanded(child: join),- ],- ),- )- else ...[- create,- const SizedBox(height: 12),- join,- ],+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Expanded(+ child: _ChoiceCard(+ icon: Icons.add_circle_outline_rounded,+ title: '创建房间',+ description: '邀请朋友加入',+ onTap: () =>+ Navigator.of(context).pop(_SyncPlayDestination.create),+ )),+ const SizedBox(width: 12),+ Expanded(+ child: _ChoiceCard(+ icon: Icons.login_rounded,+ title: '加入房间',+ description: '输入房间号',+ onTap: () => Navigator.of(context).pop(_SyncPlayDestination.join),+ )),+ ],+ )),const SizedBox(height: 16),- Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,- child: ListTile(- contentPadding:- const EdgeInsets.symmetric(horizontal: 18, vertical: 4),- leading:- Icon(Icons.dns_outlined, color: colorScheme.onSurfaceVariant),- title: Text(- '同步服务器',- style: theme.textTheme.bodyMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- subtitle: Text(- _readEndPoint(),- overflow: TextOverflow.ellipsis,- style: theme.textTheme.bodyMedium?.copyWith(- color: colorScheme.onSurface,- fontWeight: FontWeight.w600,- ),- ),- trailing: const Icon(Icons.chevron_right_rounded),- onTap: () => Navigator.of(context).pop(_SyncPlayDestination.server),- ),+ ListTile(+ contentPadding: const EdgeInsets.symmetric(horizontal: 8),+ title: const Text('同步服务器'),+ subtitle: Text(_readEndPoint(), overflow: TextOverflow.ellipsis),+ trailing: const Icon(Icons.chevron_right_rounded),+ onTap: () => Navigator.of(context).pop(_SyncPlayDestination.server),),],);@@ -376,10 +298,7 @@ class _SyncPlayHomeSheet extends StatelessWidget {trailing: [_CopyButton(value: room)],),const SizedBox(height: 12),- Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,+ TonalCard(child: Column(children: [_buildInfoRow(@@ -419,7 +338,7 @@ class _SyncPlayHomeSheet extends StatelessWidget {final ColorScheme colorScheme = theme.colorScheme;return Padding(- padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),+ padding: const EdgeInsets.all(16),child: Row(children: [Icon(icon, size: 22, color: colorScheme.onSurfaceVariant),@@ -449,69 +368,34 @@ class _SyncPlayHomeSheet extends StatelessWidget {}class _ChoiceCard extends StatelessWidget {- const _ChoiceCard({- required this.icon,- required this.title,- required this.description,- required this.emphasized,- required this.onTap,- });-+ const _ChoiceCard(+ {required this.icon,+ required this.title,+ required this.description,+ required this.onTap});final IconData icon;final String title;final String description;- final bool emphasized;final VoidCallback onTap;@overrideWidget build(BuildContext context) {- final ThemeData theme = Theme.of(context);- final ColorScheme colorScheme = theme.colorScheme;- final Color background = emphasized- ? colorScheme.primaryContainer- : colorScheme.surfaceContainerHigh;- final Color foreground = emphasized- ? colorScheme.onPrimaryContainer- : colorScheme.onSurfaceVariant;-- return Material(- color: background,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,+ final theme = Theme.of(context);+ return TonalCard(child: InkWell(onTap: onTap,child: Padding(- padding: const EdgeInsets.fromLTRB(18, 16, 16, 16),- child: Row(+ padding: const EdgeInsets.all(20),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,children: [- Icon(icon, color: foreground),- const SizedBox(width: 14),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- mainAxisSize: MainAxisSize.min,- children: [- Text(- title,- style: theme.textTheme.titleMedium?.copyWith(- color: emphasized- ? colorScheme.onPrimaryContainer- : colorScheme.onSurface,- fontWeight: FontWeight.w700,- ),- ),- const SizedBox(height: 2),- Text(- description,- style: theme.textTheme.bodySmall?.copyWith(- color: foreground,- ),- ),- ],- ),- ),- const SizedBox(width: 8),- Icon(Icons.chevron_right_rounded, color: foreground),+ Icon(icon, color: theme.colorScheme.primary, size: 28),+ const SizedBox(height: 20),+ Text(title, style: theme.textTheme.titleMedium),+ const SizedBox(height: 4),+ Text(description,+ style: theme.textTheme.bodyMedium+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),],),),@@ -539,13 +423,9 @@ class _SyncPlayRoomSheet extends StatefulWidget {class _SyncPlayRoomSheetState extends State<_SyncPlayRoomSheet> {static final Random _random = Random();- /// Eight digits keeps accidental collisions with strangers on the public- /// server unlikely while staying inside the 6-10 digit room name rule.static String _generateRoomNumber() =>List.generate(8, (_) => _random.nextInt(10)).join();- /// Alternating consonants and vowels: the field only accepts 4-12 latin- /// letters, and plain random letters out of that alphabet read as noise.static String _generateUserName() {const String consonants = 'bcdfghjklmnpqrstvwxyz';const String vowels = 'aeiou';@@ -590,8 +470,7 @@ class _SyncPlayRoomSheetState extends State<_SyncPlayRoomSheet> {final String room =widget.isCreate ? _createdRoom : _roomController.text.trim();GStorage.putSetting<String>(SettingsKeys.syncPlayUserName, username);- // Close first so the connection toasts land on the page underneath rather- // than behind this sheet.+Navigator.of(context).pop();widget.playerController.createSyncPlayRoom(room, username, widget.changeEpisode);@@ -621,7 +500,7 @@ class _SyncPlayRoomSheetState extends State<_SyncPlayRoomSheet> {onPressed: () =>setState(() => _createdRoom = _generateRoomNumber()),tooltip: '重新生成',- color: Theme.of(context).colorScheme.onPrimaryContainer,+ color: Theme.of(context).colorScheme.onSurface,icon: const Icon(Icons.refresh_rounded),),_CopyButton(value: _createdRoom),@@ -664,7 +543,6 @@ class _SyncPlayRoomSheetState extends State<_SyncPlayRoomSheet> {decoration: _sheetInputDecoration(labelText: '房间号',hintText: '6-10 位数字',- icon: Icons.meeting_room_outlined,),validator: (value) {final String text = (value ?? '').trim();@@ -686,7 +564,6 @@ class _SyncPlayRoomSheetState extends State<_SyncPlayRoomSheet> {autovalidateMode: AutovalidateMode.onUserInteraction,decoration: _sheetInputDecoration(labelText: '昵称',- icon: Icons.person_outline_rounded,helperText: compact ? null : '4-12 位英文字母,房间内可见',),validator: (value) {@@ -712,7 +589,6 @@ class _SyncPlayServerSheet extends StatefulWidget {}class _SyncPlayServerSheetState extends State<_SyncPlayServerSheet> {- /// Stands in for a user supplied address in the otherwise fixed list.static const String _customOption = '自定义服务器';final TextEditingController _customEndPointController =@@ -721,8 +597,7 @@ class _SyncPlayServerSheetState extends State<_SyncPlayServerSheet> {late String _selectedEndPoint;String? _customEndPointError;- /// Only focus the address field when the user picks the custom option, not- /// when the sheet opens with a custom server already saved.+ // Request keyboard focus only after an explicit custom-server selection.bool _focusCustomEndPoint = false;@override@@ -767,7 +642,6 @@ class _SyncPlayServerSheetState extends State<_SyncPlayServerSheet> {child: const Text('保存'),),bodyBuilder: (context, compact) {- final ColorScheme colorScheme = Theme.of(context).colorScheme;final List<String> endPoints = [...officialSyncPlayEndPoints,_customOption,@@ -776,24 +650,10 @@ class _SyncPlayServerSheetState extends State<_SyncPlayServerSheet> {return Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,- child: Column(- children: [- for (int index = 0; index < endPoints.length; index++) ...[- _buildEndPointTile(context, endPoints[index]),- if (index != endPoints.length - 1)- Divider(- height: 1,- indent: 56,- color: colorScheme.outlineVariant,- ),- ],- ],- ),- ),+ SplitListGroup(children: [+ for (final endPoint in endPoints)+ _buildEndPointTile(context, endPoint),+ ]),if (_selectedEndPoint == _customOption) ...[const SizedBox(height: 16),TextField(@@ -805,7 +665,6 @@ class _SyncPlayServerSheetState extends State<_SyncPlayServerSheet> {labelText: '服务器地址',hintText: 'example.com:8996',errorText: _customEndPointError,- icon: Icons.link_rounded,),onChanged: (_) {if (_customEndPointError != null) {@@ -867,12 +726,8 @@ class _RoomNumberCard extends StatelessWidget {final ThemeData theme = Theme.of(context);final ColorScheme colorScheme = theme.colorScheme;- return Container(+ return TonalCard(padding: const EdgeInsets.fromLTRB(20, 14, 8, 14),- decoration: BoxDecoration(- color: colorScheme.primaryContainer,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- ),child: Row(children: [Expanded(@@ -883,13 +738,10 @@ class _RoomNumberCard extends StatelessWidget {Text(label,style: theme.textTheme.labelMedium?.copyWith(- color:- colorScheme.onPrimaryContainer.withValues(alpha: 0.75),+ color: colorScheme.onSurface.withValues(alpha: 0.75),),),const SizedBox(height: 2),- // Compact gives this card half the sheet width, so the- // wide-tracked number scales down instead of overflowing.FittedBox(fit: BoxFit.scaleDown,alignment: Alignment.centerLeft,@@ -897,7 +749,7 @@ class _RoomNumberCard extends StatelessWidget {room,maxLines: 1,style: theme.textTheme.headlineSmall?.copyWith(- color: colorScheme.onPrimaryContainer,+ color: colorScheme.onSurface,fontWeight: FontWeight.w700,letterSpacing: 4,),@@ -913,8 +765,6 @@ class _RoomNumberCard extends StatelessWidget {}}-/// Confirms inline by swapping to a checkmark: a SnackBar raised from inside a-/// modal sheet lands on the page's Scaffold underneath and stays hidden.class _CopyButton extends StatefulWidget {const _CopyButton({required this.value});@@ -950,7 +800,7 @@ class _CopyButtonState extends State<_CopyButton> {return IconButton(onPressed: _copy,tooltip: _copied ? '已复制' : '复制',- color: Theme.of(context).colorScheme.onPrimaryContainer,+ color: Theme.of(context).colorScheme.onSurface,icon: Icon(_copied ? Icons.check_rounded : Icons.copy_rounded),);}diff --git a/lib/pages/player/video_details_sheet.dart b/lib/pages/player/video_details_sheet.dartindex 882c377a..ab5e9bb4 100644--- a/lib/pages/player/video_details_sheet.dart+++ b/lib/pages/player/video_details_sheet.dart@@ -1,12 +1,14 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_mobx/flutter_mobx.dart';+import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';-import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/connected_tabs.dart';+import 'package:kazumi/bean/widget/content_section.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';import 'package:kazumi/pages/player/player_controller.dart';-import 'package:kazumi/utils/device.dart';void showVideoDetailsSheet(BuildContext context, {@@ -16,14 +18,11 @@ void showVideoDetailsSheet(context: context,maxHeightFactor: 0.86,compactLandscapeMaxHeightFactor: 0.95,- builder: (context) => VideoDetailsSheet(playerController: playerController),+ builder: (context) =>+ _VideoDetailsSheet(playerController: playerController),);}-/// Matches the default [SettingsList.maxWidth] so the log card lines up with-/// the status sections on a wide sheet.-const double _contentMaxWidth = 1000;-class _LogEntry {const _LogEntry({required this.raw,@@ -58,16 +57,16 @@ class _LogEntry {bool get isProblem => level == 'fatal' || level == 'error' || level == 'warn';}-class VideoDetailsSheet extends StatefulWidget {- const VideoDetailsSheet({super.key, required this.playerController});+class _VideoDetailsSheet extends StatefulWidget {+ const _VideoDetailsSheet({required this.playerController});final PlayerController playerController;@override- State<VideoDetailsSheet> createState() => _VideoDetailsSheetState();+ State<_VideoDetailsSheet> createState() => _VideoDetailsSheetState();}-class _VideoDetailsSheetState extends State<VideoDetailsSheet>+class _VideoDetailsSheetState extends State<_VideoDetailsSheet>with SingleTickerProviderStateMixin {late final TabController _tabController =TabController(length: 2, vsync: this);@@ -77,12 +76,6 @@ class _VideoDetailsSheetState extends State<VideoDetailsSheet>PlayerController get playerController => widget.playerController;- @override- void initState() {- super.initState();- _tabController.addListener(_handleTabChanged);- }-@overridevoid dispose() {_tabController.dispose();@@ -90,13 +83,6 @@ class _VideoDetailsSheetState extends State<VideoDetailsSheet>super.dispose();}- void _handleTabChanged() {- if (mounted) {- setState(() {});- }- }-- /// [context] must sit below this sheet's ScaffoldMessenger.void _copyToClipboard(BuildContext context, String value) {Clipboard.setData(ClipboardData(text: value));KazumiDialog.showToast(message: '已复制到剪贴板', context: context);@@ -104,183 +90,122 @@ class _VideoDetailsSheetState extends State<VideoDetailsSheet>@overrideWidget build(BuildContext context) {- final size = MediaQuery.sizeOf(context);- final compact =- size.width > size.height && !isDesktop() && size.shortestSide < 600;-- // Own ScaffoldMessenger + Scaffold: the Scaffold hosts toasts inside the- // modal, and the messenger keeps them off the root one, which broadcasts- // every SnackBar to all top-level Scaffolds and would show them twice.return ScaffoldMessenger(- child: Scaffold(- backgroundColor: Colors.transparent,- body: Column(- children: [- if (compact)- _buildCompactHeader(context)- else ...[- MaterialBottomSheetHeader(- title: '视频详情',- description: '实时播放状态与诊断信息',- trailing: Row(- mainAxisSize: MainAxisSize.min,- children: _buildHeaderActions(context),- ),- ),- MaterialBottomSheetSegmentedTabs(- controller: _tabController,- labels: const ['状态', '日志'],- ),- ],- Expanded(- child: TabBarView(- controller: _tabController,- children: [- _buildStatusTab(context),- _buildLogTab(context, compact: compact),- ],- ),- ),- ],- ),- ),- );- }-- /// Folds title, tabs and actions into one row so content keeps the height.- Widget _buildCompactHeader(BuildContext context) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;-- return Padding(- padding: const EdgeInsets.fromLTRB(20, 12, 12, 8),- child: Row(- children: [- Text(- '视频详情',- style: theme.textTheme.titleMedium?.copyWith(- color: colorScheme.onSurface,- fontWeight: FontWeight.w700,- ),- ),- const SizedBox(width: 16),- Expanded(- child: Center(- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 300),- child: MaterialBottomSheetSegmentedTabs(- controller: _tabController,- labels: const ['状态', '日志'],- padding: EdgeInsets.zero,- ),- ),- ),- ),- const SizedBox(width: 8),- ..._buildHeaderActions(context),- ],- ),+ child: Builder(+ builder: (context) => Scaffold(+ backgroundColor: Colors.transparent,+ body: Column(children: [+ MaterialBottomSheetHeader(+ title: '播放信息',+ onClose: () => Navigator.of(context).pop(),+ ),+ ConnectedTabs(+ padding: materialBottomSheetTabsPadding,+ controller: _tabController,+ labels: const ['概览', '日志'],+ ),+ Expanded(+ child: TabBarView(+ controller: _tabController,+ children: [_buildStatusTab(context), _buildLogTab(context)],+ )),+ ]),+ )),);}- /// The copy-all button only applies to the log tab, but holds its slot on- /// both and fades, so the header never reflows.- List<Widget> _buildHeaderActions(BuildContext context) {- final showCopy = _tabController.index == 1;- return [- IgnorePointer(- ignoring: !showCopy,- child: AnimatedOpacity(- opacity: showCopy ? 1 : 0,- duration: const Duration(milliseconds: 250),- curve: Curves.easeInOutCubic,- child: ExcludeSemantics(- excluding: !showCopy,- child: _buildCopyLogsButton(),- ),- ),- ),- const SizedBox(width: 8),- IconButton.filledTonal(- onPressed: () => Navigator.of(context).pop(),- tooltip: '关闭',- icon: const Icon(Icons.close_rounded),- ),- ];- }-- Widget _buildCopyLogsButton() {- return Observer(builder: (context) {- final logs = playerController.debug.playerLog;- return IconButton.filledTonal(- onPressed: logs.isEmpty- ? null- : () => _copyToClipboard(context, logs.join('\n')),- tooltip: '复制全部日志',- icon: const Icon(Icons.copy),- );- });- }-Widget _buildStatusTab(BuildContext context) {return Observer(builder: (context) {final debug = playerController.debug;+ final theme = Theme.of(context);final resolution = debug.playerWidth > 0 && debug.playerHeight > 0? '${debug.playerWidth} × ${debug.playerHeight}'- : '';-- return SettingsList(- sections: [- SettingsSection(- title: const Text('播放源'),- tiles: [- _statusTile(- Icons.link_rounded, '媒体地址', playerController.videoUrl),- _statusTile(- Icons.playlist_play_rounded, '播放列表', debug.playerPlaylist),- ],- ),- SettingsSection(- title: const Text('视频'),- tiles: [- _statusTile(Icons.aspect_ratio_rounded, '分辨率', resolution),- _statusTile(Icons.tune_rounded, '视频参数', debug.playerVideoParams),- _statusTile(- Icons.video_file_rounded, '视频轨道', debug.playerVideoTracks),- _statusTile(- Icons.speed_rounded, '视频码率', debug.playerVideoBitrate),- ],- ),- SettingsSection(- title: const Text('音频'),- tiles: [- _statusTile(- Icons.graphic_eq_rounded, '音频参数', debug.playerAudioParams),- _statusTile(- Icons.audio_file_rounded, '音频轨道', debug.playerAudioTracks),- _statusTile(- Icons.speed_rounded, '音频码率', debug.playerAudioBitrate),- ],+ : '等待画面';+ return ListView(+ key: const PageStorageKey('video-details-overview'),+ padding: materialBottomSheetContentPadding,+ children: [+ ContentSection(+ title: '画面与声音',+ child:+ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(resolution, style: theme.textTheme.headlineSmall),+ const SizedBox(height: 16),+ Row(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Expanded(+ child: _metric(context, '视频码率', debug.playerVideoBitrate)),+ const SizedBox(width: 16),+ Expanded(+ child: _metric(context, '音频码率', debug.playerAudioBitrate)),+ ]),+ ]),),+ const SizedBox(height: 24),+ ContentSection.group(title: '媒体', children: [+ _statusField(context, '媒体地址', playerController.videoUrl,+ compact: true),+ _statusField(context, '播放列表', debug.playerPlaylist, compact: true),+ ]),+ const SizedBox(height: 24),+ ContentSection.group(title: '技术信息', children: [+ ExpansionTile(+ key: const PageStorageKey('video-parameters'),+ title: const Text('视频参数'),+ shape: const Border(),+ collapsedShape: const Border(),+ children: [+ _statusField(context, '编码参数', debug.playerVideoParams),+ _statusField(context, '轨道', debug.playerVideoTracks),+ ],+ ),+ ExpansionTile(+ key: const PageStorageKey('audio-parameters'),+ title: const Text('音频参数'),+ shape: const Border(),+ collapsedShape: const Border(),+ children: [+ _statusField(context, '编码参数', debug.playerAudioParams),+ _statusField(context, '轨道', debug.playerAudioTracks),+ ],+ ),+ ]),],);});}- /// A field the player has not reported yet holds its place as a disabled- /// row, so the list never reflows as the streams fill in.- Widget _statusTile(IconData icon, String label, String value) {- return SettingsTile(- leading: icon,+ Widget _metric(BuildContext context, String label, String value) {+ final theme = Theme.of(context);+ return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(label,+ style: theme.textTheme.labelMedium+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),+ const SizedBox(height: 4),+ Text(value.isEmpty ? '—' : value, style: theme.textTheme.titleMedium),+ ]);+ }++ Widget _statusField(BuildContext context, String label, String value,+ {bool compact = false}) {+ return ListTile(title: Text(label),- description: Text(value.isEmpty ? '暂无数据' : value),- enabled: value.isNotEmpty,- onPressed: (context) => _copyToClipboard(context, value),+ subtitle: Text(+ value.isEmpty ? '尚未获取' : value,+ maxLines: compact ? 2 : null,+ overflow: compact ? TextOverflow.ellipsis : null,+ ),+ trailing: value.isEmpty+ ? null+ : IconButton(+ tooltip: '复制$label',+ icon: const Icon(Icons.content_copy_rounded, size: 18),+ onPressed: () => _copyToClipboard(context, value),+ ),+ onTap: value.isEmpty ? null : () => _copyToClipboard(context, value),);}- /// Jumps to the newest log on first build, then follows new ones only while- /// pinned near the bottom, so reading back through history is never yanked.+ // Follow new logs only while the user stays near the bottom.void _scheduleLogAutoScroll(int logCount) {WidgetsBinding.instance.addPostFrameCallback((_) {if (!mounted || !_logScrollController.hasClients) {@@ -302,74 +227,45 @@ class _VideoDetailsSheetState extends State<VideoDetailsSheet>});}- Widget _buildLogTab(BuildContext context, {required bool compact}) {- final colorScheme = Theme.of(context).colorScheme;-+ Widget _buildLogTab(BuildContext context) {+ final theme = Theme.of(context);return Observer(builder: (context) {final logs = playerController.debug.playerLog;_scheduleLogAutoScroll(logs.length);-- // One card rather than a split group: a console is a continuous surface.- return Center(- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: _contentMaxWidth),- child: Padding(- padding: EdgeInsets.fromLTRB(16, compact ? 4 : 12, 16, 16),- child: Material(- color: colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(materialBottomSheetRadius),- clipBehavior: Clip.antiAlias,- child: logs.isEmpty- ? _buildLogEmptyState(context)- : ListView.builder(- // Preserves the reading position across tab switches.- key: const PageStorageKey('videoDetailsLogList'),- controller: _logScrollController,- padding: const EdgeInsets.symmetric(vertical: 8),- itemCount: logs.length,- itemBuilder: (context, index) =>- _buildLogRow(context, _LogEntry.parse(logs[index])),- ),+ return Padding(+ padding: materialBottomSheetContentPadding,+ child: Column(children: [+ Row(children: [+ Text('${logs.length} 条记录', style: theme.textTheme.labelMedium),+ const Spacer(),+ TextButton.icon(+ onPressed: logs.isEmpty+ ? null+ : () => _copyToClipboard(context, logs.join('\n')),+ icon: const Icon(Icons.content_copy_rounded, size: 18),+ label: const Text('复制全部'),),- ),- ),+ ]),+ const SizedBox(height: 8),+ Expanded(+ child: TonalCard(+ child: logs.isEmpty+ ? Center(+ child: Text('暂无运行日志', style: theme.textTheme.bodyMedium))+ : ListView.builder(+ key: const PageStorageKey('videoDetailsLogList'),+ controller: _logScrollController,+ padding: const EdgeInsets.symmetric(vertical: 12),+ itemCount: logs.length,+ itemBuilder: (context, index) =>+ _buildLogRow(context, _LogEntry.parse(logs[index])),+ ),+ )),+ ]),);});}- Widget _buildLogEmptyState(BuildContext context) {- final theme = Theme.of(context);- final colorScheme = theme.colorScheme;-- return Center(- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- Container(- width: 64,- height: 64,- decoration: BoxDecoration(- color: colorScheme.secondaryContainer,- shape: BoxShape.circle,- ),- child: Icon(- Icons.receipt_long_rounded,- size: 32,- color: colorScheme.onSecondaryContainer,- ),- ),- const SizedBox(height: 12),- Text(- '暂无运行日志',- style: theme.textTheme.titleMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- ],- ),- );- }-Widget _buildLogRow(BuildContext context, _LogEntry entry) {final theme = Theme.of(context);final colorScheme = theme.colorScheme;diff --git a/lib/pages/plugin_editor/editor_form_widgets.dart b/lib/pages/plugin_editor/editor_form_widgets.dartindex 124c332a..757fa5fa 100644--- a/lib/pages/plugin_editor/editor_form_widgets.dart+++ b/lib/pages/plugin_editor/editor_form_widgets.dart@@ -2,145 +2,6 @@ import 'package:flutter/material.dart';const Duration _kSectionAnimationDuration = Duration(milliseconds: 250);-final ShapeBorder _kSectionShape =- RoundedRectangleBorder(borderRadius: BorderRadius.circular(16));--TextStyle? _sectionTitleStyle(ThemeData theme) =>- theme.textTheme.titleMedium?.copyWith(- color: theme.colorScheme.onSurface,- fontWeight: FontWeight.w700,- );--TextStyle? _sectionDescriptionStyle(ThemeData theme) => theme- .textTheme.bodySmall- ?.copyWith(color: theme.colorScheme.onSurfaceVariant);--/// Shared tonal shell of the editor section cards.-class _SectionShell extends StatelessWidget {- const _SectionShell({required this.child});-- final Widget child;-- @override- Widget build(BuildContext context) {- return Card(- elevation: 0,- margin: EdgeInsets.zero,- color: Theme.of(context).colorScheme.surfaceContainerLow,- shape: _kSectionShape,- clipBehavior: Clip.antiAlias,- child: child,- );- }-}--/// Rounded tonal card grouping related editor fields, visually aligned with-/// [MaterialBottomSheetSection] and the onboarding cards: a primary-colored-/// icon, a bold title and an optional supporting description above the fields.-class EditorSectionCard extends StatelessWidget {- const EditorSectionCard({- super.key,- required this.icon,- required this.title,- this.description,- required this.children,- });-- final IconData icon;- final String title;- final String? description;- final List<Widget> children;-- @override- Widget build(BuildContext context) {- final theme = Theme.of(context);- return _SectionShell(- child: Padding(- padding: const EdgeInsets.all(16),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Icon(icon, color: theme.colorScheme.primary),- const SizedBox(width: 12),- Expanded(- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(title, style: _sectionTitleStyle(theme)),- if (description != null) ...[- const SizedBox(height: 4),- Text(- description!,- style: _sectionDescriptionStyle(theme),- ),- ],- ],- ),- ),- ],- ),- const SizedBox(height: 16),- Column(- spacing: 16,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: children,- ),- ],- ),- ),- );- }-}--/// Collapsible variant of [EditorSectionCard] sharing the same tonal shell-/// and header styling, for low-frequency groups like the advanced options.-class EditorExpandableSectionCard extends StatelessWidget {- const EditorExpandableSectionCard({- super.key,- required this.icon,- required this.title,- this.description,- required this.children,- });-- final IconData icon;- final String title;- final String? description;- final List<Widget> children;-- @override- Widget build(BuildContext context) {- final theme = Theme.of(context);- return _SectionShell(- child: ExpansionTile(- maintainState: true,- // Both shapes must drop the default divider border to keep the- // tonal card seamless when expanded.- shape: _kSectionShape,- collapsedShape: _kSectionShape,- tilePadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),- childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),- expandedCrossAxisAlignment: CrossAxisAlignment.stretch,- leading: Icon(icon, color: theme.colorScheme.primary),- title: Text(title, style: _sectionTitleStyle(theme)),- subtitle: description == null- ? null- : Text(description!, style: _sectionDescriptionStyle(theme)),- children: children,- ),- );- }-}--/// M3 outlined text field used inside [EditorSectionCard], carrying the card's-/// radius instead of the 4dp baseline.-///-/// Outlined rather than filled: these fields float a label, and only the-/// outline can notch around it. A fill would slice the label along the-/// container's top edge.class EditorTextField extends StatelessWidget {const EditorTextField({super.key,@@ -168,17 +29,12 @@ class EditorTextField extends StatelessWidget {helperText: helper,helperMaxLines: 3,alignLabelWithHint: maxLines > 1,- // Radius only: InputDecorator recolors this border per state from the- // M3 defaults, covering hover and disabled as well.border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),),);}}-/// Labeled full-width [SegmentedButton] with an optional supporting line that-/// follows the selected value. Replaces the dropdown form fields for the-/// small fixed enums of the editor (mode, method, body type, ...).class EditorSegmentedField<T> extends StatelessWidget {const EditorSegmentedField({super.key,@@ -194,7 +50,6 @@ class EditorSegmentedField<T> extends StatelessWidget {final List<ButtonSegment<T>> segments;final ValueChanged<T> onChanged;- /// Supporting text for the selected value, shown under the button.final String Function(T value)? description;@override@@ -234,8 +89,6 @@ class EditorSegmentedField<T> extends StatelessWidget {}}-/// Smooth transition for field groups that swap with [activeKey]: the old-/// group fades out while the container height eases to the new group.class EditorAnimatedSection extends StatelessWidget {const EditorAnimatedSection({super.key,@@ -254,8 +107,7 @@ class EditorAnimatedSection extends StatelessWidget {alignment: Alignment.topCenter,child: AnimatedSwitcher(duration: _kSectionAnimationDuration,- // Default layout centers entries, which makes tall groups jump- // vertically mid-transition; pin both to the top instead.+ // Pin both transition entries to the top to prevent vertical jumps.layoutBuilder: (currentChild, previousChildren) => Stack(alignment: Alignment.topCenter,children: [@@ -272,7 +124,6 @@ class EditorAnimatedSection extends StatelessWidget {}}-/// Small primary-colored group header inside the advanced options card.class EditorSubheader extends StatelessWidget {const EditorSubheader({super.key, required this.label});diff --git a/lib/pages/plugin_editor/plugin_catalog_view.dart b/lib/pages/plugin_editor/plugin_catalog_view.dartindex d317fd5a..cfc60d9d 100644--- a/lib/pages/plugin_editor/plugin_catalog_view.dart+++ b/lib/pages/plugin_editor/plugin_catalog_view.dart@@ -2,8 +2,10 @@ import 'dart:async';import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';+import 'package:kazumi/bean/card/rule_card.dart';import 'package:kazumi/bean/widget/error_widget.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/plugin/plugin_http_module.dart';import 'package:kazumi/pages/plugin_editor/plugin_update_actions.dart';import 'package:kazumi/plugins/plugins_controller.dart';@@ -180,7 +182,7 @@ class PluginCatalogViewState extends State<PluginCatalogView> {Widget _buildBody() {if (_loading) {- return const Center(child: CircularProgressIndicator());+ return const Center(child: LoadingIndicator());}if (_loadFailed) {return _buildLoadError();diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dartindex e9838ba0..eebacc85 100644--- a/lib/pages/plugin_editor/plugin_editor_page.dart+++ b/lib/pages/plugin_editor/plugin_editor_page.dart@@ -2,12 +2,15 @@ import 'dart:convert';import 'package:flutter/material.dart';import 'package:flutter_modular/flutter_modular.dart';-import 'package:kazumi/plugins/plugins.dart';-import 'package:kazumi/plugins/api_rule_config.dart';-import 'package:kazumi/plugins/anti_crawler_config.dart';-import 'package:kazumi/plugins/plugins_controller.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';+import 'package:kazumi/bean/widget/content_section.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';import 'package:kazumi/pages/plugin_editor/editor_form_widgets.dart';+import 'package:kazumi/plugins/anti_crawler_config.dart';+import 'package:kazumi/plugins/api_rule_config.dart';+import 'package:kazumi/plugins/plugins.dart';+import 'package:kazumi/plugins/plugins_controller.dart';import 'package:kazumi/request/config/api_endpoints.dart';import 'package:kazumi/services/plugin/api_rule_engine.dart';@@ -214,7 +217,7 @@ class _PluginEditorPageState extends State<PluginEditorPage> {String chapterApiMethod = 'GET';String chapterApiBodyType = ApiBodyType.none;String chapterApiFormat = ApiChapterFormat.nested;- // Legacy schema values retained on save but no longer exposed as settings.+ // Preserve legacy schema values on save, even when no longer editable.late String _api;late String _type;late bool _muliSources;@@ -224,7 +227,6 @@ class _PluginEditorPageState extends State<PluginEditorPage> {bool useLegacyParser = false;bool adBlocker = false;- // AntiCrawler fieldsfinal TextEditingController captchaImageController = TextEditingController();final TextEditingController captchaInputController = TextEditingController();final TextEditingController captchaButtonController = TextEditingController();@@ -426,70 +428,78 @@ class _PluginEditorPageState extends State<PluginEditorPage> {spacing: 16,crossAxisAlignment: CrossAxisAlignment.stretch,children: [- EditorSectionCard(- icon: Icons.badge_rounded,+ ContentSection(title: _RuleEditorText.sectionBasic,description: _RuleEditorText.sectionBasicDesc,- children: [- EditorTextField(- controller: nameController,- label: _RuleEditorText.ruleName,- ),- EditorTextField(- controller: versionController,- label: _RuleEditorText.ruleVersion,- ),- EditorTextField(- controller: baseURLController,- label: _RuleEditorText.baseUrl,- ),- ],+ child: Column(+ spacing: 16,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ EditorTextField(+ controller: nameController,+ label: _RuleEditorText.ruleName,+ ),+ EditorTextField(+ controller: versionController,+ label: _RuleEditorText.ruleVersion,+ ),+ EditorTextField(+ controller: baseURLController,+ label: _RuleEditorText.baseUrl,+ ),+ ]),),- EditorSectionCard(- icon: Icons.search_rounded,+ ContentSection(title: _RuleEditorText.sectionSearch,description: _RuleEditorText.sectionSearchDesc,- children: [- EditorSegmentedField<String>(- label: _RuleEditorText.searchRuleType,- value: searchMode,- segments: _ruleModeSegments,- onChanged: (value) => setState(() => searchMode = value),- ),- EditorAnimatedSection(- activeKey: searchMode,- child: Column(- spacing: 16,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: searchMode == RuleMode.xpath- ? _buildXPathSearchFields()- : _buildApiSearchFields(),- ),- ),- ],+ child: Column(+ spacing: 16,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ EditorSegmentedField<String>(+ label: _RuleEditorText.searchRuleType,+ value: searchMode,+ segments: _ruleModeSegments,+ onChanged: (value) =>+ setState(() => searchMode = value),+ ),+ EditorAnimatedSection(+ activeKey: searchMode,+ child: Column(+ spacing: 16,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: searchMode == RuleMode.xpath+ ? _buildXPathSearchFields()+ : _buildApiSearchFields(),+ ),+ ),+ ]),),- EditorSectionCard(- icon: Icons.playlist_play_rounded,+ ContentSection(title: _RuleEditorText.sectionChapter,description: _RuleEditorText.sectionChapterDesc,- children: [- EditorSegmentedField<String>(- label: _RuleEditorText.chapterRuleType,- value: chapterMode,- segments: _ruleModeSegments,- onChanged: (value) => setState(() => chapterMode = value),- ),- EditorAnimatedSection(- activeKey: chapterMode,- child: Column(- spacing: 16,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: chapterMode == RuleMode.xpath- ? _buildXPathChapterFields()- : _buildApiChapterFields(),- ),- ),- ],+ child: Column(+ spacing: 16,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ EditorSegmentedField<String>(+ label: _RuleEditorText.chapterRuleType,+ value: chapterMode,+ segments: _ruleModeSegments,+ onChanged: (value) =>+ setState(() => chapterMode = value),+ ),+ EditorAnimatedSection(+ activeKey: chapterMode,+ child: Column(+ spacing: 16,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: chapterMode == RuleMode.xpath+ ? _buildXPathChapterFields()+ : _buildApiChapterFields(),+ ),+ ),+ ]),),_buildAdvancedOptionsCard(),],@@ -518,62 +528,71 @@ class _PluginEditorPageState extends State<PluginEditorPage> {}Widget _buildAdvancedOptionsCard() {- return EditorExpandableSectionCard(- icon: Icons.tune_rounded,- title: _RuleEditorText.advancedOptions,- description: _RuleEditorText.advancedOptionsDesc,- children: [- const EditorSubheader(label: _RuleEditorText.groupBehavior),- SwitchListTile(- contentPadding: EdgeInsets.zero,- title: const Text(_RuleEditorText.legacyParser),- subtitle: const Text(_RuleEditorText.legacyParserDesc),- value: useLegacyParser,- onChanged: (value) => setState(() => useLegacyParser = value),- ),- SwitchListTile(- contentPadding: EdgeInsets.zero,- title: const Text(_RuleEditorText.adBlocker),- subtitle: const Text(_RuleEditorText.adBlockerDesc),- value: adBlocker,- onChanged: (value) => setState(() => adBlocker = value),+ return TonalCard(+ child: ExpansionTile(+ maintainState: true,+ shape: const Border(),+ collapsedShape: const Border(),+ tilePadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),+ childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),+ expandedCrossAxisAlignment: CrossAxisAlignment.stretch,+ title: const SectionHeader(+ title: Text(_RuleEditorText.advancedOptions),+ description: Text(_RuleEditorText.advancedOptionsDesc),),- const EditorSubheader(label: _RuleEditorText.groupNetwork),- EditorTextField(- controller: userAgentController,- label: _RuleEditorText.userAgent,- helper: _RuleEditorText.userAgentHelper,- ),- const SizedBox(height: 16),- EditorTextField(- controller: refererController,- label: _RuleEditorText.referer,- helper: _RuleEditorText.refererHelper,- ),- if (searchMode == RuleMode.xpath) ...[- const EditorSubheader(label: _RuleEditorText.groupAntiCrawler),+ children: [+ const EditorSubheader(label: _RuleEditorText.groupBehavior),SwitchListTile(contentPadding: EdgeInsets.zero,- title: const Text(_RuleEditorText.antiCrawlerEnable),- subtitle: const Text(_RuleEditorText.antiCrawlerEnableDesc),- value: antiCrawlerEnabled,- onChanged: (value) => setState(() => antiCrawlerEnabled = value),+ title: const Text(_RuleEditorText.legacyParser),+ subtitle: const Text(_RuleEditorText.legacyParserDesc),+ value: useLegacyParser,+ onChanged: (value) => setState(() => useLegacyParser = value),),- EditorAnimatedSection(- activeKey: antiCrawlerEnabled,- child: antiCrawlerEnabled- ? Padding(- padding: const EdgeInsets.only(top: 8),- child: Column(- spacing: 16,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: _buildAntiCrawlerFields(),- ),- )- : const SizedBox.shrink(),+ SwitchListTile(+ contentPadding: EdgeInsets.zero,+ title: const Text(_RuleEditorText.adBlocker),+ subtitle: const Text(_RuleEditorText.adBlockerDesc),+ value: adBlocker,+ onChanged: (value) => setState(() => adBlocker = value),+ ),+ const EditorSubheader(label: _RuleEditorText.groupNetwork),+ EditorTextField(+ controller: userAgentController,+ label: _RuleEditorText.userAgent,+ helper: _RuleEditorText.userAgentHelper,),+ const SizedBox(height: 16),+ EditorTextField(+ controller: refererController,+ label: _RuleEditorText.referer,+ helper: _RuleEditorText.refererHelper,+ ),+ if (searchMode == RuleMode.xpath) ...[+ const EditorSubheader(label: _RuleEditorText.groupAntiCrawler),+ SwitchListTile(+ contentPadding: EdgeInsets.zero,+ title: const Text(_RuleEditorText.antiCrawlerEnable),+ subtitle: const Text(_RuleEditorText.antiCrawlerEnableDesc),+ value: antiCrawlerEnabled,+ onChanged: (value) => setState(() => antiCrawlerEnabled = value),+ ),+ EditorAnimatedSection(+ activeKey: antiCrawlerEnabled,+ child: antiCrawlerEnabled+ ? Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Column(+ spacing: 16,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: _buildAntiCrawlerFields(),+ ),+ )+ : const SizedBox.shrink(),+ ),+ ],],- ],+ ),);}@@ -881,8 +900,6 @@ class _PluginEditorPageState extends State<PluginEditorPage> {),];- /// Builds the edited plugin, surfacing build/validation errors to the- /// user. Returns null when the current input does not form a valid rule.Plugin? _tryBuildEditedPlugin() {try {return _buildEditedPlugin();diff --git a/lib/pages/plugin_editor/plugin_test_page.dart b/lib/pages/plugin_editor/plugin_test_page.dartindex eb5d012b..6fbbc32d 100644--- a/lib/pages/plugin_editor/plugin_test_page.dart+++ b/lib/pages/plugin_editor/plugin_test_page.dart@@ -1,20 +1,20 @@import 'dart:convert';+import '../../modules/roads/road_module.dart';+import '../../plugins/api_rule_config.dart';+import '../../plugins/plugins.dart';import 'package:dio/dio.dart';import 'package:flutter/material.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/search/plugin_search_module.dart';import 'package:kazumi/services/logging/logger.dart';-import '../../modules/roads/road_module.dart';-import '../../plugins/api_rule_config.dart';-import '../../plugins/plugins.dart';-const _h8 = SizedBox(height: 8.0);const _h12 = SizedBox(height: 12.0);-// 简化配色映射:仅三类核心色enum CoreColorType { error, success, waiting }extension CoreColorExtension on ThemeData {@@ -295,9 +295,8 @@ class _PluginTestPageState extends State<PluginTestPage> {);Widget _buildLoading(ThemeData theme) => Center(- child: CircularProgressIndicator.adaptive(- valueColor: AlwaysStoppedAnimation<Color>(- theme.getCoreColor(CoreColorType.success)),+ child: LoadingIndicator(+ color: theme.getCoreColor(CoreColorType.success),),);@@ -322,7 +321,6 @@ class _PluginTestPageState extends State<PluginTestPage> {return '${plugin.searchMode == RuleMode.api ? 'JSON' : 'HTML'}长度:${searchRaw.length} 字符';}- // 简化副标题颜色逻辑:仅三类Color _getSubtitleColor(String subtitle, ThemeData theme) {if (subtitle.contains('测试中') ||subtitle.contains('获取中') ||@@ -388,7 +386,6 @@ class _PluginTestPageState extends State<PluginTestPage> {]);}- /// Nodes the rule skipped during parsing; empty when every node matched.Widget _buildDiagnosticsWidget(List<String> diagnostics, ThemeData theme) {if (diagnostics.isEmpty) return const SizedBox.shrink();return Container(@@ -417,8 +414,8 @@ class _PluginTestPageState extends State<PluginTestPage> {(message) => Padding(padding: const EdgeInsets.only(bottom: 4.0),child: SelectableText(message,- style: theme.textTheme.bodySmall?.copyWith(- color: theme.colorScheme.onErrorContainer)),+ style: theme.textTheme.bodySmall+ ?.copyWith(color: theme.colorScheme.onErrorContainer)),),),],diff --git a/lib/pages/search/image_search_page.dart b/lib/pages/search/image_search_page.dartindex 596d1628..7a3b898c 100644--- a/lib/pages/search/image_search_page.dart+++ b/lib/pages/search/image_search_page.dart@@ -5,13 +5,15 @@ import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';import 'package:flutter_modular/flutter_modular.dart';import 'package:image_picker/image_picker.dart';+import 'package:url_launcher/url_launcher.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/bean/card/network_img_layer.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/search/image_search_module.dart';import 'package:kazumi/pages/search/search_controller.dart';import 'package:kazumi/utils/constants.dart';-import 'package:url_launcher/url_launcher.dart';import 'package:kazumi/utils/format.dart';class ImageSearchPage extends StatefulWidget {@@ -211,8 +213,7 @@ class _ImageSearchPageState extends State<ImageSearchPage> {? SizedBox(width: 18,height: 18,- child: CircularProgressIndicator(- strokeWidth: 2,+ child: LoadingIndicator(color: colorScheme.onPrimary,),)@@ -509,7 +510,7 @@ class _ImageSearchPageState extends State<ImageSearchPage> {icon: const SizedBox(width: 28,height: 28,- child: CircularProgressIndicator(strokeWidth: 2.5),+ child: LoadingIndicator(),),title: '正在识别图片',description: '请稍候,正在从截图中匹配番剧信息',diff --git a/lib/pages/search/search_page.dart b/lib/pages/search/search_page.dartindex c9dcbf2d..1b72b7e6 100644--- a/lib/pages/search/search_page.dart+++ b/lib/pages/search/search_page.dart@@ -1,11 +1,15 @@import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';import 'package:flutter_modular/flutter_modular.dart';-import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';-import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/bean/card/bangumi_card.dart';+import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';+import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/widget/connected_tabs.dart';+import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/bean/widget/error_widget.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';import 'package:kazumi/pages/search/search_controller.dart';import 'package:kazumi/services/logging/logger.dart';@@ -104,10 +108,9 @@ class _SearchPageState extends State<SearchPage> {}}- Future<void> showWorkbench() async {+ Future<void> _showWorkbench() async {final result = await showAdaptiveBottomSheet<_SearchWorkbenchResult>(maxHeightFactor: 0.86,- backgroundColor: Theme.of(context).scaffoldBackgroundColor,context: context,builder: (context) {return _SearchWorkbenchSheet(@@ -234,7 +237,7 @@ class _SearchPageState extends State<SearchPage> {title: const Text("搜索"),),floatingActionButton: FloatingActionButton.extended(- onPressed: showWorkbench,+ onPressed: _showWorkbench,icon: const Icon(Icons.tune),label: const Text("筛选"),),@@ -356,7 +359,7 @@ class _SearchPageState extends State<SearchPage> {if (searchPageController.isLoading &&searchPageController.bangumiList.isEmpty) {- return const Center(child: CircularProgressIndicator());+ return const Center(child: LoadingIndicator());}int crossCount = 3;if (MediaQuery.sizeOf(context).width >@@ -582,323 +585,306 @@ class _SearchWorkbenchSheetState extends State<_SearchWorkbenchSheet> {@overrideWidget build(BuildContext context) {- return SafeArea(- child: Column(- children: [- MaterialBottomSheetHeader(- title: '筛选条件',- description: '组合标签、季度和评分等条件,更快找到想看的番剧。',- onClose: () => Navigator.pop(context),- ),- Expanded(- child: ListView(- padding: const EdgeInsets.fromLTRB(16, 4, 16, 24),- children: [- MaterialBottomSheetSection(- title: '排序',- description: '选择列表优先展示的内容。',- icon: Icons.sort_rounded,- child: SingleChildScrollView(- scrollDirection: Axis.horizontal,- child: SegmentedButton<String>(- selected: {draft.sort},- onSelectionChanged: (value) {- setState(() {- draft = draft.copyWith(sort: value.first);- });- },- segments: const [- ButtonSegment(value: 'heat', label: Text('热度')),- ButtonSegment(value: 'rank', label: Text('排名')),- ButtonSegment(value: 'score', label: Text('评分')),- ButtonSegment(value: 'match', label: Text('匹配')),- ],- ),- ),+ final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;+ return Padding(+ padding: EdgeInsets.only(bottom: keyboardInset),+ child: DefaultTabController(+ length: 2,+ child: LayoutBuilder(builder: (context, constraints) {+ final editingInShortWindow =+ keyboardInset > 0 && constraints.maxHeight < 280;+ return Column(+ children: [+ if (!editingInShortWindow)+ MaterialBottomSheetHeader(+ title: '筛选番剧',+ onClose: () => Navigator.pop(context),),- const SizedBox(height: 12),- MaterialBottomSheetSection(- title: '标签',- description: '选择多个标签时,会优先寻找同时包含这些标签的番剧。',- icon: Icons.sell_outlined,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,+ if (!editingInShortWindow)+ const ConnectedTabs(+ padding: materialBottomSheetTabsPadding,+ labels: ['常用', '进阶']),+ Expanded(+ child: TabBarView(children: [+ ListView(+ key: const PageStorageKey('search-basic-filters'),+ padding: materialBottomSheetContentPadding,children: [- Wrap(- spacing: 8,- runSpacing: 8,- children: [- for (final tag in defaultAnimeTags)- FilterChip(- label: Text(tag),- selected: draft.tags.contains(tag),- showCheckmark: false,- onSelected: (selected) {- setState(() {- draft = draft.copyWith(- tags: selected- ? [...draft.tags, tag]- : draft.tags- .where((item) => item != tag)- .toList(),- );- });- },- ),- ],+ ContentSection(+ title: '排序',+ child: Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final sort in [+ 'heat',+ 'rank',+ 'score',+ 'match'+ ])+ ChoiceChip(+ label: Text(_sortLabel(sort)),+ selected: draft.sort == sort,+ onSelected: (_) => setState(() {+ draft = draft.copyWith(sort: sort);+ }),+ ),+ ],+ ),),- const SizedBox(height: 14),- Row(- children: [- Expanded(- child: TextField(+ const SizedBox(height: 24),+ ContentSection(+ title: '题材标签',+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final tag in {+ ...defaultAnimeTags,+ ...draft.tags+ })+ FilterChip(+ label: Text(tag),+ selected: draft.tags.contains(tag),+ onSelected: (selected) => setState(() {+ draft = draft.copyWith(+ tags: selected+ ? [...draft.tags, tag]+ : draft.tags+ .where((item) => item != tag)+ .toList());+ }),+ ),+ ],+ ),+ const SizedBox(height: 12),+ TextField(controller: tagController,- decoration: const InputDecoration(- labelText: '自定义标签',- prefixIcon: Icon(Icons.add_circle_outline),+ decoration: InputDecoration(+ hintText: '添加自定义标签',+ filled: true,+ fillColor:+ Theme.of(context).colorScheme.surface,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(20),+ borderSide: BorderSide.none,+ ),+ suffixIcon: IconButton(+ tooltip: '添加标签',+ onPressed: () => addTag(tagController.text),+ icon: const Icon(Icons.add_rounded),+ ),),onSubmitted: addTag,),- ),- const SizedBox(width: 8),- IconButton.filledTonal(- tooltip: '添加标签',- onPressed: () => addTag(tagController.text),- icon: const Icon(Icons.add),- ),- ],+ ],+ ),),- if (draft.tags.isNotEmpty) ...[- const SizedBox(height: 12),- Wrap(- spacing: 8,- runSpacing: 8,+ const SizedBox(height: 24),+ ContentSection(+ title: '收藏状态',+ child: Column(children: [- for (final tag in draft.tags)- InputChip(- label: Text(tag),- onDeleted: () {- setState(() {- draft = draft.copyWith(- tags: draft.tags- .where((item) => item != tag)- .toList(),- );- });- },- ),+ _SearchSwitchTile(+ title: '隐藏看过的番剧',+ value: notShowWatched,+ onChanged: (value) {+ setState(() => notShowWatched = value);+ },+ ),+ _SearchSwitchTile(+ title: '隐藏抛弃的番剧',+ value: notShowAbandoned,+ onChanged: (value) {+ setState(() => notShowAbandoned = value);+ },+ ),],),- TextButton.icon(- onPressed: () {- setState(() => draft = draft.copyWith(tags: []));- },- icon: const Icon(Icons.clear_all),- label: const Text('清空标签'),- ),- ],+ ),],),- ),- const SizedBox(height: 12),- MaterialBottomSheetSection(- title: '季度与日期',- description: '按播出季度查找,也可以指定更精确的日期范围。',- icon: Icons.calendar_month,- child: Column(+ ListView(+ key: const PageStorageKey('search-advanced-filters'),+ padding: materialBottomSheetContentPadding,children: [- DropdownButtonFormField<String>(- initialValue:- draft.season.isEmpty ? null : draft.season,- decoration: const InputDecoration(- labelText: '季度',- prefixIcon: Icon(Icons.event_available_outlined),- ),- items: [- for (final season in seasonOptions)- DropdownMenuItem(- value: season.value,- child: Text(season.label),+ ContentSection(+ title: '放送日期',+ child: Column(+ children: [+ DropdownButtonFormField<String>(+ initialValue:+ draft.season.isEmpty ? null : draft.season,+ decoration: const InputDecoration(+ labelText: '季度',+ prefixIcon:+ Icon(Icons.event_available_outlined),+ ),+ items: [+ for (final season in seasonOptions)+ DropdownMenuItem(+ value: season.value,+ child: Text(season.label),+ ),+ ],+ onChanged: (value) {+ setState(() {+ draft = draft.copyWith(+ season: value ?? '',+ dateRange: null,+ );+ });+ },+ ),+ const SizedBox(height: 12),+ Align(+ alignment: Alignment.centerLeft,+ child: Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ OutlinedButton.icon(+ onPressed: pickCustomDateRange,+ icon: const Icon(Icons.date_range),+ label: Text(draft.dateRange == null+ ? '自定义日期'+ : '${draft.dateRange!.start}..${draft.dateRange!.end}'),+ ),+ if (draft.season.isNotEmpty ||+ draft.dateRange != null)+ TextButton.icon(+ onPressed: () {+ setState(() {+ draft = draft.copyWith(+ season: '',+ dateRange: null,+ );+ });+ },+ icon: const Icon(Icons.clear),+ label: const Text('不限日期'),+ ),+ ],+ ),),- ],- onChanged: (value) {- setState(() {- draft = draft.copyWith(- season: value ?? '',- dateRange: null,- );- });- },+ ],+ ),),- const SizedBox(height: 12),- Align(- alignment: Alignment.centerLeft,+ const SizedBox(height: 24),+ ContentSection(+ title: '放送星期',child: Wrap(spacing: 8,runSpacing: 8,children: [- OutlinedButton.icon(- onPressed: pickCustomDateRange,- icon: const Icon(Icons.date_range),- label: Text(draft.dateRange == null- ? '自定义日期'- : '${draft.dateRange!.start}..${draft.dateRange!.end}'),- ),- if (draft.season.isNotEmpty ||- draft.dateRange != null)- TextButton.icon(- onPressed: () {+ for (int weekday = 1; weekday <= 7; weekday++)+ FilterChip(+ label: Text('周${[+ '一',+ '二',+ '三',+ '四',+ '五',+ '六',+ '日'+ ][weekday - 1]}'),+ selected: draft.weekdays.contains(weekday),+ showCheckmark: false,+ onSelected: (selected) {+ final weekdays = draft.weekdays.toSet();+ if (selected) {+ weekdays.add(weekday);+ } else {+ weekdays.remove(weekday);+ }+ final next = weekdays.toList()..sort();setState(() {- draft = draft.copyWith(- season: '',- dateRange: null,- );+ draft = draft.copyWith(weekdays: next);});},- icon: const Icon(Icons.clear),- label: const Text('不限日期'),),],),),- ],- ),- ),- const SizedBox(height: 12),- MaterialBottomSheetSection(- title: '数值范围',- description: '只显示符合评分或排名范围的番剧。',- icon: Icons.tune_rounded,- child: Column(- children: [- _SearchSwitchTile(- title: '启用评分范围',- value: draft.scoreRange?.isValid == true,- onChanged: (value) {- setState(() {- draft = draft.copyWith(- scoreRange: value- ? const SearchDoubleRange(- min: 7.0,- max: 10.0,- )- : null,- );- });- },- ),- if (draft.scoreRange?.isValid == true)- _buildScoreRangeSlider(draft.scoreRange!),- _SearchSwitchTile(- title: '启用排名范围',- value: draft.rankRange?.isValid == true,- onChanged: (value) {- setState(() {- draft = draft.copyWith(- rankRange: value- ? const SearchIntRange(min: 1, max: 5000)- : null,- );- });- },- ),- if (draft.rankRange?.isValid == true)- _buildRankRangeSlider(draft.rankRange!),- ],- ),- ),- const SizedBox(height: 12),- MaterialBottomSheetSection(- title: '星期',- description: '按放送星期过滤,多个星期按任一匹配处理。',- icon: Icons.today_outlined,- child: Wrap(- spacing: 8,- runSpacing: 8,- children: [- for (int weekday = 1; weekday <= 7; weekday++)- FilterChip(- label: Text('周$weekday'),- selected: draft.weekdays.contains(weekday),- showCheckmark: false,- onSelected: (selected) {- final weekdays = draft.weekdays.toSet();- if (selected) {- weekdays.add(weekday);- } else {- weekdays.remove(weekday);- }- final next = weekdays.toList()..sort();- setState(() {- draft = draft.copyWith(weekdays: next);- });- },+ const SizedBox(height: 24),+ ContentSection(+ title: '评分与排名',+ child: Column(+ children: [+ _SearchSwitchTile(+ title: '限定评分',+ value: draft.scoreRange?.isValid == true,+ onChanged: (value) {+ setState(() {+ draft = draft.copyWith(+ scoreRange: value+ ? const SearchDoubleRange(+ min: 7.0,+ max: 10.0,+ )+ : null,+ );+ });+ },+ ),+ if (draft.scoreRange?.isValid == true)+ _buildScoreRangeSlider(draft.scoreRange!),+ _SearchSwitchTile(+ title: '限定排名',+ value: draft.rankRange?.isValid == true,+ onChanged: (value) {+ setState(() {+ draft = draft.copyWith(+ rankRange: value+ ? const SearchIntRange(+ min: 1, max: 5000)+ : null,+ );+ });+ },+ ),+ if (draft.rankRange?.isValid == true)+ _buildRankRangeSlider(draft.rankRange!),+ ],),- ],- ),- ),- const SizedBox(height: 12),- MaterialBottomSheetSection(- title: '过滤',- description: '控制是否隐藏已经看过或放弃的番剧。',- icon: Icons.filter_alt_outlined,- child: Column(- children: [- _SearchSwitchTile(- title: '隐藏已看',- value: notShowWatched,- onChanged: (value) {- setState(() => notShowWatched = value);- },- ),- _SearchSwitchTile(- title: '隐藏已弃',- value: notShowAbandoned,- onChanged: (value) {- setState(() => notShowAbandoned = value);- },),],),+ ]),+ ),+ if (!editingInShortWindow)+ Padding(+ padding: const EdgeInsets.fromLTRB(24, 12, 24, 24),+ child: Row(children: [+ TextButton(+ onPressed: () => setState(() {+ draft = resetAdvancedFilters();+ notShowWatched = false;+ notShowAbandoned = false;+ tagController.clear();+ }),+ child: const Text('重置'),+ ),+ const Spacer(),+ FilledButton(+ onPressed: () => Navigator.pop(+ context,+ _SearchWorkbenchResult(+ filterState: draft,+ notShowWatched: notShowWatched,+ notShowAbandoned: notShowAbandoned,+ shouldSearch: true,+ )),+ child: const Text('查看结果'),+ ),+ ]),),- ],- ),- ),- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),- child: Row(- children: [- TextButton.icon(- onPressed: () {- setState(() {- draft = resetAdvancedFilters();- notShowWatched = false;- notShowAbandoned = false;- });- },- icon: const Icon(Icons.restart_alt),- label: const Text('重置'),- ),- const Spacer(),- FilledButton.icon(- onPressed: () {- Navigator.pop(- context,- _SearchWorkbenchResult(- filterState: draft,- notShowWatched: notShowWatched,- notShowAbandoned: notShowAbandoned,- shouldSearch: true,- ),- );- },- icon: const Icon(Icons.check),- label: const Text('应用'),- ),- ],- ),- ),- ],+ ],+ );+ }),),);}diff --git a/lib/pages/settings/danmaku/danmaku_settings_sheet.dart b/lib/pages/settings/danmaku/danmaku_settings_sheet.dartindex add0870b..930b94b4 100644--- a/lib/pages/settings/danmaku/danmaku_settings_sheet.dart+++ b/lib/pages/settings/danmaku/danmaku_settings_sheet.dart@@ -1,15 +1,19 @@import 'package:canvas_danmaku/canvas_danmaku.dart';import 'package:flutter/material.dart';+import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';-import 'package:kazumi/services/storage/storage.dart';+import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/connected_tabs.dart';+import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/pages/settings/danmaku/danmaku_shield_settings_sheet.dart';import 'package:kazumi/pages/settings/danmaku/danmaku_time_offset_sheet.dart';-import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/device.dart';enum _DanmakuSettingsDestination {timeOffset,+ shield,}Future<void> showDanmakuSettingsSheet({@@ -29,17 +33,14 @@ Future<void> showDanmakuSettingsSheet({},);- if (!context.mounted ||- destination != _DanmakuSettingsDestination.timeOffset) {- return;- }-+ if (!context.mounted || destination == null) return;await showAdaptiveBottomSheet<void>(context: context,- builder: (context) {- return DanmakuTimeOffsetSheet(- onTimelineOffsetChanged: onTimelineOffsetChanged,- );+ builder: (context) => switch (destination) {+ _DanmakuSettingsDestination.shield => const DanmakuShieldSettingsSheet(),+ _DanmakuSettingsDestination.timeOffset => DanmakuTimeOffsetSheet(+ onTimelineOffsetChanged: onTimelineOffsetChanged,+ ),},);}@@ -58,8 +59,7 @@ class _DanmakuSettingsSheet extends StatefulWidget {}class _DanmakuSettingsSheetState extends State<_DanmakuSettingsSheet> {- /// The stored duration, before playback speed scales it. The running option- /// carries the scaled value, so it can't back this slider.+ // The slider uses stored duration, before playback speed scales it.late double _duration;DanmakuOption get _option => widget.danmakuController.option;@@ -74,196 +74,165 @@ class _DanmakuSettingsSheetState extends State<_DanmakuSettingsSheet> {setState(() => widget.danmakuController.updateOption(option));}- void _showDanmakuShieldSheet() {- showAdaptiveBottomSheet<void>(- context: context,- builder: (context) => const DanmakuShieldSettingsSheet(),- );- }-@overrideWidget build(BuildContext context) {- return SafeArea(- bottom: false,- child: Scaffold(- body: Column(- children: [- MaterialBottomSheetHeader(- title: '弹幕设置',- description: '调整弹幕显示、样式与屏蔽规则',- onClose: () => Navigator.of(context).pop(),+ return DefaultTabController(+ length: 2,+ child: Column(+ children: [+ MaterialBottomSheetHeader(+ title: '弹幕设置',+ onClose: () => Navigator.of(context).pop(),+ ),+ const ConnectedTabs(+ padding: materialBottomSheetTabsPadding, labels: ['外观', '播放']),+ Expanded(+ child: TabBarView(children: [+ ListView(+ key: const PageStorageKey('danmaku-appearance'),+ padding: materialBottomSheetContentPadding,+ children: [+ ContentSection.group(title: '显示效果', children: [+ SettingsSliderTile(+ title: Text('字体大小'),+ value: _option.fontSize,+ min: 10,+ max: isCompact() ? 32 : 48,+ valueLabel: '${_option.fontSize.floor()}',+ onChanged: (value) {+ final fontSize = value.floorToDouble();+ _applyOption(_option.copyWith(fontSize: fontSize));+ GStorage.putSetting<double>(+ SettingsKeys.danmakuFontSize, fontSize);+ },+ ),+ SettingsSliderTile(+ title: Text('不透明度'),+ value: _option.opacity,+ min: 0.1,+ max: 1,+ valueLabel: '${(_option.opacity * 100).round()}%',+ onChanged: (value) {+ _applyOption(_option.copyWith(opacity: value));+ GStorage.putSetting<double>(SettingsKeys.danmakuOpacity,+ double.parse(value.toStringAsFixed(2)));+ },+ ),+ SettingsSliderTile(+ title: Text('显示区域'),+ value: _option.area,+ min: 0,+ max: 1,+ divisions: 8,+ valueLabel: '${(_option.area * 100).round()}%',+ onChanged: (value) {+ _applyOption(_option.copyWith(area: value));+ GStorage.putSetting<double>(+ SettingsKeys.danmakuArea, value);+ },+ ),+ SettingsSliderTile(+ title: Text('行间距'),+ value: _option.lineHeight,+ min: 0,+ max: 3,+ divisions: 30,+ valueLabel: _option.lineHeight.toStringAsFixed(1),+ onChanged: (value) {+ final lineHeight = double.parse(value.toStringAsFixed(1));+ _applyOption(_option.copyWith(lineHeight: lineHeight));+ GStorage.putSetting<double>(+ SettingsKeys.danmakuLineHeight, lineHeight);+ },+ ),+ ]),+ const SizedBox(height: 24),+ ContentSection(+ title: '弹幕类型',+ child: Wrap(spacing: 8, runSpacing: 8, children: [+ _typeChip('滚动', !_option.hideScroll, (show) {+ _applyOption(_option.copyWith(hideScroll: !show));+ GStorage.putSetting<bool>(+ SettingsKeys.danmakuScroll, show);+ }),+ _typeChip('顶部', !_option.hideTop, (show) {+ _applyOption(_option.copyWith(hideTop: !show));+ GStorage.putSetting<bool>(SettingsKeys.danmakuTop, show);+ }),+ _typeChip('底部', !_option.hideBottom, (show) {+ _applyOption(_option.copyWith(hideBottom: !show));+ GStorage.putSetting<bool>(+ SettingsKeys.danmakuBottom, show);+ }),+ ]),+ ),+ ],),- Expanded(- child: SettingsList(- sections: [- SettingsSection(- title: Text('弹幕屏蔽'),- tiles: [- SettingsTile(- leading: Icons.block_rounded,- onPressed: (_) {- _showDanmakuShieldSheet();- },- title: Text('关键词屏蔽'),- ),- ],+ ListView(+ key: const PageStorageKey('danmaku-playback'),+ padding: materialBottomSheetContentPadding,+ children: [+ ContentSection.group(title: '速度', children: [+ SettingsSliderTile(+ title: Text('停留时间'),+ value: _duration,+ min: 2,+ max: 16,+ divisions: 14,+ valueLabel: '${_duration.round()} 秒',+ onChanged: (value) {+ final duration = value.roundToDouble();+ setState(() => _duration = duration);+ GStorage.putSetting<double>(+ SettingsKeys.danmakuDuration, duration);+ widget.onUpdateDanmakuSpeed();+ },+ ),+ SettingsTile.switchTile(+ onToggle: (value) {+ bool followSpeed = value ??+ !GStorage.getSetting<bool>(+ SettingsKeys.danmakuFollowSpeed);+ GStorage.putSetting<bool>(+ SettingsKeys.danmakuFollowSpeed, followSpeed);+ widget.onUpdateDanmakuSpeed();+ setState(() {});+ },+ title: Text('跟随视频倍速'),+ initialValue: GStorage.getSetting<bool>(+ SettingsKeys.danmakuFollowSpeed),),- SettingsSection(- title: Text('弹幕样式'),- tiles: [- SettingsSliderTile(- leading: Icons.format_size_rounded,- title: Text('字体大小'),- value: _option.fontSize,- min: 10,- max: isCompact() ? 32 : 48,- valueLabel: '${_option.fontSize.floor()}',- onChanged: (value) {- final fontSize = value.floorToDouble();- _applyOption(_option.copyWith(fontSize: fontSize));- GStorage.putSetting<double>(- SettingsKeys.danmakuFontSize, fontSize);- },- ),- SettingsSliderTile(- leading: Icons.opacity_rounded,- title: Text('弹幕不透明度'),- value: _option.opacity,- min: 0.1,- max: 1,- valueLabel: '${(_option.opacity * 100).round()}%',- onChanged: (value) {- _applyOption(_option.copyWith(opacity: value));- GStorage.putSetting<double>(- SettingsKeys.danmakuOpacity,- double.parse(value.toStringAsFixed(2)));- },- ),- ],+ ]),+ const SizedBox(height: 24),+ ContentSection.group(title: '校准与过滤', children: [+ SettingsTile(+ leading: Icons.sync_rounded,+ title: const Text('时间校准'),+ description: Text(formatDanmakuTimeOffset(+ normalizeDanmakuTimeOffset(GStorage.getSetting<double>(+ SettingsKeys.danmakuTimeOffset)),+ )),+ onPressed: (context) => Navigator.of(context)+ .pop(_DanmakuSettingsDestination.timeOffset),),- SettingsSection(- title: Text('弹幕显示'),- tiles: [- SettingsTile(- leading: Icons.schedule_rounded,- onPressed: (context) {- Navigator.of(context)- .pop(_DanmakuSettingsDestination.timeOffset);- },- title: Text('时间轴偏移'),- value: Text(- formatDanmakuTimeOffset(- normalizeDanmakuTimeOffset(- GStorage.getSetting<double>(- SettingsKeys.danmakuTimeOffset),- ),- ),- ),- ),- SettingsSliderTile(- leading: Icons.crop_free_rounded,- title: Text('弹幕区域'),- value: _option.area,- min: 0,- max: 1,- divisions: 8,- valueLabel: '${(_option.area * 100).round()}%',- onChanged: (value) {- _applyOption(_option.copyWith(area: value));- GStorage.putSetting<double>(- SettingsKeys.danmakuArea, value);- },- ),- SettingsSliderTile(- leading: Icons.timer_rounded,- title: Text('持续时间'),- value: _duration,- min: 2,- max: 16,- divisions: 14,- valueLabel: '${_duration.round()} 秒',- onChanged: (value) {- final duration = value.roundToDouble();- setState(() => _duration = duration);- GStorage.putSetting<double>(- SettingsKeys.danmakuDuration, duration);- widget.onUpdateDanmakuSpeed();- },- ),- SettingsSliderTile(- leading: Icons.format_line_spacing_rounded,- title: Text('行高'),- value: _option.lineHeight,- min: 0,- max: 3,- divisions: 30,- valueLabel: _option.lineHeight.toStringAsFixed(1),- onChanged: (value) {- final lineHeight =- double.parse(value.toStringAsFixed(1));- _applyOption(- _option.copyWith(lineHeight: lineHeight));- GStorage.putSetting<double>(- SettingsKeys.danmakuLineHeight, lineHeight);- },- ),- SettingsTile.switchTile(- leading: Icons.vertical_align_top_rounded,- onToggle: (value) {- final show = value ?? _option.hideTop;- _applyOption(_option.copyWith(hideTop: !show));- GStorage.putSetting<bool>(- SettingsKeys.danmakuTop, show);- },- title: Text('顶部弹幕'),- initialValue: !_option.hideTop,- ),- SettingsTile.switchTile(- leading: Icons.vertical_align_bottom_rounded,- onToggle: (value) {- final show = value ?? _option.hideBottom;- _applyOption(_option.copyWith(hideBottom: !show));- GStorage.putSetting<bool>(- SettingsKeys.danmakuBottom, show);- },- title: Text('底部弹幕'),- initialValue: !_option.hideBottom,- ),- SettingsTile.switchTile(- leading: Icons.swap_horiz_rounded,- onToggle: (value) {- final show = value ?? _option.hideScroll;- _applyOption(_option.copyWith(hideScroll: !show));- GStorage.putSetting<bool>(- SettingsKeys.danmakuScroll, show);- },- title: Text('滚动弹幕'),- initialValue: !_option.hideScroll,- ),- SettingsTile.switchTile(- leading: Icons.speed_rounded,- onToggle: (value) {- bool followSpeed = value ??- !GStorage.getSetting<bool>(- SettingsKeys.danmakuFollowSpeed);- GStorage.putSetting<bool>(- SettingsKeys.danmakuFollowSpeed, followSpeed);- widget.onUpdateDanmakuSpeed();- setState(() {});- },- title: Text('跟随视频倍速'),- description: Text('弹幕速度随视频倍速变化'),- initialValue: GStorage.getSetting<bool>(- SettingsKeys.danmakuFollowSpeed),- ),- ],+ SettingsTile(+ leading: Icons.filter_alt_outlined,+ title: const Text('屏蔽规则'),+ description: const Text('关键词与正则表达式'),+ onPressed: (context) => Navigator.of(context)+ .pop(_DanmakuSettingsDestination.shield),),- ],- ),+ ]),+ ],),- ],- ),+ ])),+ ],),);}++ Widget _typeChip(String label, bool selected, ValueChanged<bool> onSelected) {+ return FilterChip(+ label: Text(label), selected: selected, onSelected: onSelected);+ }}diff --git a/lib/pages/settings/danmaku/danmaku_shield_editor.dart b/lib/pages/settings/danmaku/danmaku_shield_editor.dartnew file mode 100644index 00000000..2ecfd8b3--- /dev/null+++ b/lib/pages/settings/danmaku/danmaku_shield_editor.dart@@ -0,0 +1,103 @@+import 'package:flutter/material.dart';+import 'package:flutter_mobx/flutter_mobx.dart';++import 'package:kazumi/bean/widget/content_section.dart';+import 'package:kazumi/pages/my/my_controller.dart';++class DanmakuShieldEditor extends StatefulWidget {+ const DanmakuShieldEditor({+ super.key,+ required this.controller,+ this.padding = const EdgeInsets.fromLTRB(24, 0, 24, 24),+ });++ final MyController controller;+ final EdgeInsetsGeometry padding;++ @override+ State<DanmakuShieldEditor> createState() => _DanmakuShieldEditorState();+}++class _DanmakuShieldEditorState extends State<DanmakuShieldEditor> {+ MyController get myController => widget.controller;+ final TextEditingController textEditingController = TextEditingController();++ @override+ void dispose() {+ textEditingController.dispose();+ super.dispose();+ }++ void _addRule() {+ final rule = textEditingController.text.trim();+ if (rule.isEmpty) return;+ final previousCount = myController.shieldList.length;+ myController.addShieldList(rule);+ if (myController.shieldList.length > previousCount) {+ textEditingController.clear();+ }+ }++ @override+ Widget build(BuildContext context) {+ return ListView(+ padding: widget.padding,+ children: [+ ContentSection(+ title: '添加规则',+ child:+ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ TextField(+ controller: textEditingController,+ decoration: InputDecoration(+ hintText: '关键词或 /正则表达式/',+ border:+ OutlineInputBorder(borderRadius: BorderRadius.circular(16)),+ suffixIcon: IconButton(+ tooltip: '添加规则',+ onPressed: _addRule,+ icon: const Icon(Icons.add_rounded),+ ),+ ),+ onSubmitted: (_) => _addRule(),+ ),+ const SizedBox(height: 8),+ Text('包含关键词的弹幕会被隐藏。用 / / 包裹正则表达式。',+ style: Theme.of(context).textTheme.bodySmall?.copyWith(+ color: Theme.of(context).colorScheme.onSurfaceVariant,+ )),+ ]),+ ),+ const SizedBox(height: 24),+ Observer(builder: (context) {+ final rules = myController.shieldList.toList();+ if (rules.isEmpty) {+ return Padding(+ padding: const EdgeInsets.all(24),+ child: Text('还没有屏蔽规则',+ textAlign: TextAlign.center,+ style: Theme.of(context).textTheme.bodyMedium),+ );+ }+ return ContentSection.group(+ title: '已添加 · ${rules.length}',+ children: [+ for (final rule in rules)+ ListTile(+ title: Text(rule),+ subtitle: rule.startsWith('/') && rule.endsWith('/')+ ? const Text('正则表达式')+ : null,+ trailing: IconButton(+ tooltip: '删除规则',+ icon: const Icon(Icons.close_rounded, size: 20),+ onPressed: () => myController.removeShieldList(rule),+ ),+ ),+ ],+ );+ }),+ ],+ );+ }+}diff --git a/lib/pages/settings/danmaku/danmaku_shield_settings.dart b/lib/pages/settings/danmaku/danmaku_shield_settings.dartindex afd0a7b0..5be547a5 100644--- a/lib/pages/settings/danmaku/danmaku_shield_settings.dart+++ b/lib/pages/settings/danmaku/danmaku_shield_settings.dart@@ -1,98 +1,24 @@import 'package:flutter/material.dart';-import 'package:kazumi/pages/my/my_controller.dart';-import 'package:flutter_mobx/flutter_mobx.dart';import 'package:flutter_modular/flutter_modular.dart';-import 'package:kazumi/bean/appbar/sys_app_bar.dart';--class DanmakuShieldSettings extends StatefulWidget {- const DanmakuShieldSettings({super.key});-- @override- State<DanmakuShieldSettings> createState() => _DanmakuShieldSettingsState();-}-class _DanmakuShieldSettingsState extends State<DanmakuShieldSettings> {- final MyController myController = inject<MyController>();- final TextEditingController textEditingController = TextEditingController();+import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';+import 'package:kazumi/pages/my/my_controller.dart';+import 'package:kazumi/pages/settings/danmaku/danmaku_shield_editor.dart';- @override- void dispose() {- textEditingController.dispose();- super.dispose();- }+class DanmakuShieldSettings extends StatelessWidget {+ const DanmakuShieldSettings({super.key});@override- Widget build(BuildContext context) {- return Scaffold(- appBar: SysAppBar(- title: const Text("弹幕屏蔽"),- ),- body: ListView(- padding: EdgeInsets.all(12),- children: [- TextField(- controller: textEditingController,- decoration: InputDecoration(- border: const OutlineInputBorder(),- hintText: "输入关键词或正则表达式",- suffixIcon: TextButton.icon(- onPressed: () {- myController.addShieldList(- textEditingController.text.trim(),- );- },- icon: const Icon(Icons.add),- label: const Text("添加"),- ),+ Widget build(BuildContext context) => SettingsDetailScaffold(+ title: const Text('屏蔽规则'),+ body: Center(+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 1000),+ child: DanmakuShieldEditor(+ controller: inject<MyController>(),+ padding: const EdgeInsets.all(16),),- onSubmitted: (_) {- myController.addShieldList(- textEditingController.text.trim(),- );- },- ),- SizedBox(height: 12),- Text(- '以"/"开头和结尾将视作正则表达式, 如"/\\d+/"表示屏蔽所有数字',),- Observer(builder: (context) {- return Text(- "已添加${myController.shieldList.length}个关键词",- );- }),- SizedBox(height: 12),- Observer(builder: (context) {- return Wrap(- runSpacing: 12,- spacing: 12,- children: myController.shieldList- .map(- (item) => Chip(- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(32)),- backgroundColor:- Theme.of(context).colorScheme.secondaryContainer,- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,- side: BorderSide.none,- label: Text(- item,- style: TextStyle(- fontSize: 14,- ),- ),- padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),- deleteIcon: Icon(Icons.close, size: 18),- deleteButtonTooltipMessage: '',- onDeleted: () {- myController.removeShieldList(item);- },- ),- )- .toList(),- );- })- ],- ),- );- }+ ),+ );}diff --git a/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart b/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dartindex beec42bb..893583b7 100644--- a/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart+++ b/lib/pages/settings/danmaku/danmaku_shield_settings_sheet.dart@@ -1,112 +1,26 @@import 'package:flutter/material.dart';+import 'package:flutter_modular/flutter_modular.dart';+import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';import 'package:kazumi/pages/my/my_controller.dart';-import 'package:flutter_mobx/flutter_mobx.dart';-import 'package:flutter_modular/flutter_modular.dart';+import 'package:kazumi/pages/settings/danmaku/danmaku_shield_editor.dart';-class DanmakuShieldSettingsSheet extends StatefulWidget {+class DanmakuShieldSettingsSheet extends StatelessWidget {const DanmakuShieldSettingsSheet({super.key});@override- State<DanmakuShieldSettingsSheet> createState() =>- _DanmakuShieldSettingsSheetState();-}--class _DanmakuShieldSettingsSheetState- extends State<DanmakuShieldSettingsSheet> {- final MyController myController = inject<MyController>();- final TextEditingController textEditingController = TextEditingController();-- @override- void dispose() {- textEditingController.dispose();- super.dispose();- }-- @override- Widget build(BuildContext context) {- return Scaffold(- body: Column(- children: [- MaterialBottomSheetHeader(- title: '弹幕屏蔽',- description: '使用关键词或正则表达式过滤弹幕',- onClose: () => Navigator.of(context).pop(),- ),- Expanded(- child: ListView(- padding: materialBottomSheetContentPadding,- children: [- MaterialBottomSheetSection(- title: '添加屏蔽规则',- description: '以“/”开头和结尾将视作正则表达式,如“/\\d+/”表示屏蔽所有数字',- icon: Icons.add_circle_outline_rounded,- child: TextField(- controller: textEditingController,- decoration: InputDecoration(- border: const OutlineInputBorder(),- hintText: '输入关键词或正则表达式',- suffixIcon: TextButton.icon(- onPressed: () {- myController.addShieldList(- textEditingController.text.trim(),- );- },- icon: const Icon(Icons.add),- label: const Text('添加'),- ),- ),- onSubmitted: (_) {- myController.addShieldList(- textEditingController.text.trim(),- );- },- ),- ),- const SizedBox(height: 16),- Observer(builder: (context) {- return MaterialBottomSheetSection(- title: '已添加${myController.shieldList.length}个关键词',- icon: Icons.shield_outlined,- child: Wrap(- runSpacing: 12,- spacing: 12,- children: myController.shieldList- .map(- (item) => Chip(- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(32),- ),- backgroundColor: Theme.of(context)- .colorScheme- .secondaryContainer,- materialTapTargetSize:- MaterialTapTargetSize.shrinkWrap,- side: BorderSide.none,- label: Text(- item,- style: const TextStyle(fontSize: 14),- ),- padding: const EdgeInsets.symmetric(- horizontal: 8,- vertical: 4,- ),- deleteIcon: const Icon(Icons.close, size: 18),- deleteButtonTooltipMessage: '',- onDeleted: () {- myController.removeShieldList(item);- },- ),- )- .toList(),- ),- );- }),- ],+ Widget build(BuildContext context) => Scaffold(+ backgroundColor: Colors.transparent,+ body: Column(+ children: [+ MaterialBottomSheetHeader(+ title: '屏蔽规则',+ onClose: () => Navigator.of(context).pop(),+ ),+ Expanded(+ child: DanmakuShieldEditor(controller: inject<MyController>()),),- ),- ],- ),- );- }+ ],+ ),+ );}diff --git a/lib/pages/settings/danmaku/danmaku_time_offset_sheet.dart b/lib/pages/settings/danmaku/danmaku_time_offset_sheet.dartindex 42dc0173..75a2ebab 100644--- a/lib/pages/settings/danmaku/danmaku_time_offset_sheet.dart+++ b/lib/pages/settings/danmaku/danmaku_time_offset_sheet.dart@@ -1,5 +1,7 @@import 'package:flutter/material.dart';+import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/widget/tonal_card.dart';import 'package:kazumi/services/storage/storage.dart';const double _minDanmakuTimeOffset = -180;@@ -74,144 +76,78 @@ class _DanmakuTimeOffsetSheetState extends State<DanmakuTimeOffsetSheet> {@overrideWidget build(BuildContext context) {final theme = Theme.of(context);- final colorScheme = theme.colorScheme;- final direction = _offset == 0 ? '无偏移' : (_offset > 0 ? '延后' : '提前');-- return SafeArea(- top: false,- child: Scaffold(- body: Column(- children: [- MaterialBottomSheetHeader(- title: '弹幕时间轴偏移',- description: '校准弹幕相对于视频画面的显示时间',- onClose: () => Navigator.of(context).pop(),- ),- Expanded(- child: SingleChildScrollView(- padding: materialBottomSheetContentPadding,- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Container(- width: double.infinity,- padding: const EdgeInsets.symmetric(- horizontal: 24, vertical: 20),- decoration: BoxDecoration(- color: colorScheme.secondaryContainer,- borderRadius: BorderRadius.circular(28),- ),- child: Column(- children: [- Text(- direction,- style: theme.textTheme.titleMedium?.copyWith(- color: colorScheme.onSecondaryContainer,- fontWeight: FontWeight.w600,- ),- ),- const SizedBox(height: 4),- Text(- _formatDanmakuOffsetDuration(_offset),- style: theme.textTheme.displaySmall?.copyWith(- color: colorScheme.onSecondaryContainer,- fontFeatures: const [- FontFeature.tabularFigures()- ],- fontWeight: FontWeight.w500,- ),- ),- ],- ),- ),- const SizedBox(height: 24),- Row(- children: [- Text(- '提前 3:00',- style: theme.textTheme.labelMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- const Spacer(),- Text(- '延后 3:00',- style: theme.textTheme.labelMedium?.copyWith(- color: colorScheme.onSurfaceVariant,- ),- ),- ],- ),- Slider(- value: _offset,- min: _minDanmakuTimeOffset,- max: _maxDanmakuTimeOffset,- divisions: _danmakuTimeOffsetDivisions,- label: formatDanmakuTimeOffset(_offset),- onChanged: _updateOffset,- ),- const SizedBox(height: 12),- LayoutBuilder(- builder: (context, constraints) {- final advanceButton = SizedBox(- width: double.infinity,- height: 56,- child: FilledButton.tonalIcon(- onPressed: _offset > _minDanmakuTimeOffset- ? () => _updateOffset(_offset - 1)- : null,- icon: const Icon(Icons.remove_rounded),- label: const Text('提前 1 秒'),- ),- );- final delayButton = SizedBox(- width: double.infinity,- height: 56,- child: FilledButton.tonalIcon(- onPressed: _offset < _maxDanmakuTimeOffset- ? () => _updateOffset(_offset + 1)- : null,- icon: const Icon(Icons.add_rounded),- label: const Text('延后 1 秒'),- ),- );-- if (constraints.maxWidth < 360) {- return Column(- children: [- advanceButton,- const SizedBox(height: 12),- delayButton,- ],- );- }- return Row(- children: [- Expanded(child: advanceButton),- const SizedBox(width: 12),- Expanded(child: delayButton),- ],- );- },+ final colors = theme.colorScheme;+ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ MaterialBottomSheetHeader(+ title: '弹幕时间校准',+ description: '弹幕出现太早就延后,太晚就提前。',+ onClose: () => Navigator.of(context).pop(),+ ),+ Flexible(+ child: SingleChildScrollView(+ padding: materialBottomSheetContentPadding,+ child: Column(children: [+ TonalCard(+ child: Padding(+ padding: const EdgeInsets.all(16),+ child: Column(children: [+ Text(_offset == 0 ? '与视频同步' : (_offset > 0 ? '延后' : '提前'),+ style: theme.textTheme.labelLarge+ ?.copyWith(color: colors.onSurfaceVariant)),+ const SizedBox(height: 8),+ Row(children: [+ IconButton.filledTonal(+ tooltip: '提前 1 秒',+ onPressed: _offset > _minDanmakuTimeOffset+ ? () => _updateOffset(_offset - 1)+ : null,+ icon: const Icon(Icons.remove_rounded),),- const SizedBox(height: 12),- SizedBox(- width: double.infinity,- height: 52,- child: OutlinedButton.icon(- onPressed: _offset != 0 ? () => _updateOffset(0) : null,- icon: const Icon(Icons.restart_alt_rounded),- label: const Text('恢复无偏移'),- ),+ Expanded(+ child: FittedBox(+ fit: BoxFit.scaleDown,+ child: Text(_formatDanmakuOffsetDuration(_offset),+ style: theme.textTheme.displaySmall?.copyWith(+ color: colors.onSurface,+ fontFeatures: const [FontFeature.tabularFigures()],+ )),+ )),+ IconButton.filledTonal(+ tooltip: '延后 1 秒',+ onPressed: _offset < _maxDanmakuTimeOffset+ ? () => _updateOffset(_offset + 1)+ : null,+ icon: const Icon(Icons.add_rounded),),- ],- ),+ ]),+ const SizedBox(height: 16),+ Slider(+ value: _offset,+ min: _minDanmakuTimeOffset,+ max: _maxDanmakuTimeOffset,+ divisions: _danmakuTimeOffsetDivisions,+ label: formatDanmakuTimeOffset(_offset),+ onChanged: _updateOffset,+ ),+ Row(+ mainAxisAlignment: MainAxisAlignment.spaceBetween,+ children: [+ Text('提前 3 分钟', style: theme.textTheme.labelSmall),+ Text('延后 3 分钟', style: theme.textTheme.labelSmall),+ ]),+ ]),),),- ],- ),- ),+ const SizedBox(height: 12),+ TextButton(+ onPressed: _offset != 0 ? () => _updateOffset(0) : null,+ child: const Text('恢复同步'),+ ),+ ]),+ )),+ ],);}}diff --git a/lib/pages/settings/displaymode_settings.dart b/lib/pages/settings/displaymode_settings.dartindex 46d3a38e..feb7ab39 100644--- a/lib/pages/settings/displaymode_settings.dart+++ b/lib/pages/settings/displaymode_settings.dart@@ -2,8 +2,10 @@ import 'package:flutter/material.dart';import 'package:flutter/scheduler.dart';import 'package:flutter/services.dart';import 'package:flutter_displaymode/flutter_displaymode.dart';-import 'package:kazumi/services/storage/storage.dart';+import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';+import 'package:kazumi/services/storage/storage.dart';class SetDisplayMode extends StatefulWidget {const SetDisplayMode({super.key});@@ -70,7 +72,7 @@ class _SetDisplayModeState extends State<SetDisplayMode> {return Scaffold(appBar: AppBar(title: const Text('屏幕帧率设置')),body: (modes.isEmpty)- ? const CircularProgressIndicator()+ ? const LoadingIndicator(): SettingsList(sections: [SettingsRadioSection<DisplayMode>(diff --git a/lib/pages/settings/download_settings.dart b/lib/pages/settings/download_settings.dartindex 3fd8eebd..78a23dd4 100644--- a/lib/pages/settings/download_settings.dart+++ b/lib/pages/settings/download_settings.dart@@ -1,13 +1,15 @@import 'dart:io';+import 'package:file_picker/file_picker.dart';import 'package:flutter/material.dart';-import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';+import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/services/platform/secure_bookmark_service.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/file_system.dart';-import 'package:kazumi/bean/settings/settings_list.dart';-import 'package:file_picker/file_picker.dart';class DownloadSettingsPage extends StatefulWidget {const DownloadSettingsPage({super.key});@@ -180,7 +182,7 @@ class _DownloadSettingsPageState extends State<DownloadSettingsPage> {? const SizedBox(width: 20,height: 20,- child: CircularProgressIndicator(strokeWidth: 2),+ child: LoadingIndicator(),): _hasCustomDirectory? IconButton(diff --git a/lib/pages/settings/keyboard_settings.dart b/lib/pages/settings/keyboard_settings.dartindex 5c1bedcf..a02f63d8 100644--- a/lib/pages/settings/keyboard_settings.dart+++ b/lib/pages/settings/keyboard_settings.dart@@ -1,29 +1,26 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';++import 'package:kazumi/bean/dialog/dialog_helper.dart';+import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';+import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/constants.dart';-import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-/// Display group for the shortcut list. Functions missing from every group-/// fall back to a trailing "其他" group so new shortcuts never disappear.class _ShortcutGroup {- const _ShortcutGroup(this.title, this.icon, this.functions);+ const _ShortcutGroup(this.title, this.functions);final String title;- final IconData icon;final List<String> functions;}const List<_ShortcutGroup> _shortcutGroups = [- _ShortcutGroup('播放控制', Icons.play_arrow_rounded,- ['playorpause', 'forward', 'rewind', 'skip', 'next', 'prev']),_ShortcutGroup(- '音量', Icons.volume_up_rounded, ['volumeup', 'volumedown', 'togglemute']),- _ShortcutGroup('画面与弹幕', Icons.fullscreen_rounded,- ['fullscreen', 'exitfullscreen', 'screenshot', 'toggledanmaku']),- _ShortcutGroup('倍速', Icons.speed_rounded,- ['speed1', 'speed2', 'speed3', 'speedup', 'speeddown']),+ '播放控制', ['playorpause', 'forward', 'rewind', 'skip', 'next', 'prev']),+ _ShortcutGroup('音量', ['volumeup', 'volumedown', 'togglemute']),+ _ShortcutGroup(+ '画面与弹幕', ['fullscreen', 'exitfullscreen', 'screenshot', 'toggledanmaku']),+ _ShortcutGroup('倍速', ['speed1', 'speed2', 'speed3', 'speedup', 'speeddown']),];class KeyboardSettingsPage extends StatefulWidget {@@ -37,8 +34,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {String? listeningFunction;int? listeningIndex;- /// Value the listening slot held before recording started; empty means the- /// slot was newly added and should be dropped when recording is cancelled.+ // An empty original value marks a new, uncommitted binding.String originalValue = '';late Map<String, List<String>> shortcuts;@@ -50,10 +46,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {@overridevoid initState() {super.initState();- // 根据默认快捷键生成可用快捷键列表,并读取已设置值。- // 旧版实现可能把 '' / '...' 占位符持久化过,甚至把配置存成空列表- // (单绑定进入录制后直接退出页面);界面保证每个功能至少保留一个- // 真实绑定,读入时清理占位符、空配置恢复默认,有变化则回写+ // Repair persisted placeholders and keep at least one binding per action.shortcuts = {};for (final key in defaultShortcuts.keys) {final stored = GStorage.getStringListSettingByName(@@ -81,9 +74,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {super.dispose();}- /// Restores or removes the pending slot so no '...' placeholder is left- /// behind when recording moves elsewhere. Pure state mutation: build-path- /// callers wrap it in setState, dispose calls it bare.+ // Also called during dispose; do not setState here.void cancelListening() {if (!isListening) return;final func = listeningFunction!;@@ -120,7 +111,6 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {final func = listeningFunction!;final index = listeningIndex!;- // 冲突规避for (final entry in shortcuts.entries) {final otherFunc = entry.key;final otherKeys = entry.value;@@ -145,7 +135,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {return true;}- // 新槽位不落盘:录制成功或取消时才持久化,storage 里永远没有占位符+ // Persist a new binding only after recording or cancellation.void onAddKey(String func) {setState(() {cancelListening();@@ -163,7 +153,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {final keyValue = shortcuts[func]![index];setState(() {cancelListening();- // 取消可能移除了同列表中的待录制项,按值重新定位(同一功能内按键唯一)+ // Cancellation can shift indices; locate the binding again by value.final idx = shortcuts[func]!.indexOf(keyValue);if (idx >= 0) {beginListening(func, idx);@@ -201,13 +191,13 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {final funcs = group.functions.where(shortcuts.containsKey).toList();covered.addAll(funcs);if (funcs.isNotEmpty) {- groups.add(_ShortcutGroup(group.title, group.icon, funcs));+ groups.add(_ShortcutGroup(group.title, funcs));}}final leftovers =shortcuts.keys.where((func) => !covered.contains(func)).toList();if (leftovers.isNotEmpty) {- groups.add(_ShortcutGroup('其他', Icons.keyboard_rounded, leftovers));+ groups.add(_ShortcutGroup('其他', leftovers));}return groups;}@@ -276,51 +266,18 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {);}- Widget _buildGroupCard(_ShortcutGroup group) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;-- return Card(- elevation: 0,- margin: const EdgeInsets.only(bottom: 12),- color: colorScheme.surfaceContainerLow,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),- clipBehavior: Clip.antiAlias,- child: Padding(- padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- children: [- Container(- width: 36,- height: 36,- decoration: BoxDecoration(- color: colorScheme.secondaryContainer,- shape: BoxShape.circle,- ),- child: Icon(- group.icon,- size: 18,- color: colorScheme.onSecondaryContainer,- ),- ),- const SizedBox(width: 12),- Text(- group.title,- style: textTheme.titleMedium- ?.copyWith(fontWeight: FontWeight.w700),- ),- ],- ),- const SizedBox(height: 8),- for (final func in group.functions) _buildShortcutRow(func),- ],+ Widget _buildGroupCard(_ShortcutGroup group) => Padding(+ padding: const EdgeInsets.only(bottom: 24),+ child: ContentSection(+ title: group.title,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final func in group.functions) _buildShortcutRow(func),+ ],+ ),),- ),- );- }+ );Widget _buildShortcutRow(String func) {final textTheme = Theme.of(context).textTheme;@@ -352,8 +309,7 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {Widget _buildKeyCap(String func, List<String> keys, int i) {final listening = listeningFunction == func && listeningIndex == i;- // 删除入口只按真实绑定数判定,待录制占位符不算数——- // 否则单绑定时点「添加」会让原按键出现删除按钮,可被误删成空绑定+ // Pending placeholders must not count toward the last-binding safeguard.final realCount = keys.where((value) => value != '...').length;return _KeyCap(label: listening ? '按任意键' : keyAliases[keys[i]] ?? keys[i],@@ -365,8 +321,6 @@ class _KeyboardSettingsPageState extends State<KeyboardSettingsPage> {}}-/// Tonal keycap pill for one bound key; tap to re-record, tap again to-/// cancel. Shows a close icon when the function has spare bindings.class _KeyCap extends StatelessWidget {const _KeyCap({required this.label,@@ -427,7 +381,6 @@ class _KeyCap extends StatelessWidget {}}-/// Outlined pill that appends a new binding slot and starts recording.class _AddKeyButton extends StatelessWidget {const _AddKeyButton({required this.onTap});diff --git a/lib/pages/settings/settings_page.dart b/lib/pages/settings/settings_page.dartindex 1634c354..9432c2bb 100644--- a/lib/pages/settings/settings_page.dart+++ b/lib/pages/settings/settings_page.dart@@ -1,8 +1,10 @@import 'package:flutter/material.dart';import 'package:flutter_modular/flutter_modular.dart';+import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';import 'package:kazumi/bean/settings/settings_list.dart';+import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/pages/about/about_page.dart';import 'package:kazumi/pages/my/my_controller.dart';import 'package:kazumi/pages/plugin_editor/plugin_view_page.dart';@@ -133,8 +135,7 @@ final List<_SettingsGroup> _settingsGroups = [),];-/// Adds and removes pages without a transition, so a breakpoint reflow is-/// carried by the rail animation alone instead of two animations at once.+// Breakpoint changes use only the rail animation, without a page transition.class _InstantTransitionDelegate extends TransitionDelegate<dynamic> {const _InstantTransitionDelegate();@@ -182,13 +183,9 @@ class _SettingsPageState extends State<SettingsPage> {static const ValueKey<String> _listPageKey =ValueKey<String>('settings-list');- /// Single-pane detail rides a real route so it keeps the platform transition.final GlobalKey<NavigatorState> _detailNavigatorKey =GlobalKey<NavigatorState>();- /// Single source of truth for the layout: it picks the right pane's content- /// in two-pane mode and whether the detail route is pushed in single-pane,- /// so resizing across the breakpoint reflows without losing the selection._SettingsCategory? _selected;bool? _lastTwoPane;@@ -205,8 +202,7 @@ class _SettingsPageState extends State<SettingsPage> {@overrideWidget build(BuildContext context) {final twoPane = _useTwoPane(context);- // Falls back to the first category without writing it back, otherwise- // narrowing the window would jump into a category never picked.+ // Do not persist the fallback category during a layout change.final shown = _selected ?? _settingsGroups.first.categories.first;final detail = twoPane ? null : _selected;final layoutChanged = _lastTwoPane != null && _lastTwoPane != twoPane;@@ -220,7 +216,7 @@ class _SettingsPageState extends State<SettingsPage> {? const _InstantTransitionDelegate(): const DefaultTransitionDelegate<dynamic>(),onDidRemovePage: (page) {- // A layout-driven removal keeps the selection for the right pane.+ // Keep the selection when layout changes remove the detail route.if (page.key != _listPageKey && !_useTwoPane(context)) {_backToCategoryList();}@@ -252,7 +248,7 @@ class _SettingsPageState extends State<SettingsPage> {return Scaffold(appBar: SysAppBar(title: const Text('设置'),- // First route of the nested Navigator, so back must pop the outer one.+ // The nested root route delegates back navigation to the outer navigator.leading: IconButton(onPressed: () => context.maybePop(),icon: const Icon(Icons.arrow_back),@@ -294,8 +290,6 @@ class _SettingsPageState extends State<SettingsPage> {);}- /// Left unfilled so the pane shares the page surface; a fill would either- /// match the cards inside it or stack another tone step onto them.Widget _detailPane(BuildContext context, _SettingsCategory shown) {return Padding(key: ValueKey<String>('pane:${shown.id}'),@@ -310,7 +304,6 @@ class _SettingsPageState extends State<SettingsPage> {);}- /// Scoped so the lists inside each embedded settings page are covered too.Widget _withoutScrollbar(BuildContext context, Widget child) {return ScrollConfiguration(behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),@@ -319,8 +312,6 @@ class _SettingsPageState extends State<SettingsPage> {}Widget _rail(BuildContext context, _SettingsCategory shown) {- final textTheme = Theme.of(context).textTheme;- final colorScheme = Theme.of(context).colorScheme;return _withoutScrollbar(context,ListView(@@ -329,11 +320,7 @@ class _SettingsPageState extends State<SettingsPage> {for (final group in _settingsGroups) ...[Padding(padding: const EdgeInsets.fromLTRB(28, 16, 28, 8),- child: Text(- group.title,- style:- textTheme.titleSmall?.copyWith(color: colorScheme.primary),- ),+ child: SectionHeader(title: Text(group.title)),),for (final category in group.categories)_RailDestination(@@ -347,35 +334,27 @@ class _SettingsPageState extends State<SettingsPage> {);}- Widget _singlePaneBody(BuildContext context) {- final textTheme = Theme.of(context).textTheme;- final colorScheme = Theme.of(context).colorScheme;- return ListView(- padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),- children: [- for (final group in _settingsGroups) ...[- Padding(- padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),- child: Text(- group.title,- style: textTheme.titleSmall?.copyWith(color: colorScheme.primary),+ Widget _singlePaneBody(BuildContext context) => ListView(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),+ children: [+ for (final group in _settingsGroups)+ Padding(+ padding: const EdgeInsets.only(top: 16),+ child: ContentSection.group(+ title: group.title,+ children: [+ for (final category in group.categories)+ SettingsCategoryTile(+ icon: category.icon,+ title: category.label,+ description: category.description,+ onTap: () => setState(() => _selected = category),+ ),+ ],+ ),),- ),- SettingsSplitGroup(- children: [- for (final category in group.categories)- SettingsCategoryTile(- icon: category.icon,- title: category.label,- description: category.description,- onTap: () => setState(() => _selected = category),- ),- ],- ),],- ],- );- }+ );}class _RailDestination extends StatelessWidget {diff --git a/lib/pages/timeline/timeline_page.dart b/lib/pages/timeline/timeline_page.dartindex 15fbec08..c5339a7c 100644--- a/lib/pages/timeline/timeline_page.dart+++ b/lib/pages/timeline/timeline_page.dart@@ -1,16 +1,18 @@import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';-import 'package:kazumi/modules/bangumi/bangumi_item.dart';-import 'package:kazumi/pages/timeline/timeline_controller.dart';++import 'package:kazumi/bean/appbar/sys_app_bar.dart';+import 'package:kazumi/bean/card/bangumi_timeline_card.dart';import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';-import 'package:kazumi/bean/card/bangumi_timeline_card.dart';-import 'package:kazumi/utils/constants.dart';+import 'package:kazumi/bean/widget/bangumi_mirror_error_widget.dart';+import 'package:kazumi/bean/widget/content_section.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';+import 'package:kazumi/modules/bangumi/bangumi_item.dart';+import 'package:kazumi/pages/timeline/timeline_controller.dart';import 'package:kazumi/services/storage/storage.dart';-import 'package:kazumi/bean/appbar/sys_app_bar.dart';import 'package:kazumi/utils/anime_season.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:kazumi/bean/widget/bangumi_mirror_error_widget.dart';+import 'package:kazumi/utils/constants.dart';import 'package:kazumi/utils/device.dart';class TimelinePage extends StatefulWidget {@@ -30,7 +32,6 @@ class _TimelinePageState extends State<TimelinePage>TimelineController get timelineController => widget.controller;TabController? tabController;late bool showRating;- final GlobalKey filterSectionKey = GlobalKey();@overridevoid initState() {@@ -50,7 +51,7 @@ class _TimelinePageState extends State<TimelinePage>super.dispose();}- DateTime generateDateTime(int year, String season) {+ DateTime _generateDateTime(int year, String season) {switch (season) {case '冬':return DateTime(year, 1, 1);@@ -75,258 +76,84 @@ class _TimelinePageState extends State<TimelinePage>Tab(text: '日'),];- final seasons = ['秋', '夏', '春', '冬'];-- String getStringByDateTime(DateTime d) {+ String _getStringByDateTime(DateTime d) {return d.year.toString() + getSeasonStringByMonth(d.month);}- Future<void> scrollToFilterSection() async {- final filterContext = filterSectionKey.currentContext;- if (filterContext == null) {- return;- }-- await Scrollable.ensureVisible(- filterContext,- duration: const Duration(milliseconds: 280),- curve: Curves.easeOutCubic,- alignment: 0.04,- );- }-- BoxConstraints buildTimelineBottomSheetConstraints(- BuildContext context, {- double? compactHeightFactor,- }) {- final mediaSize = MediaQuery.sizeOf(context);- final adaptiveConstraints = adaptiveBottomSheetConstraints(context);- final maxHeight = compactHeightFactor != null- ? (mediaSize.height >= LayoutBreakpoint.compact['height']!- ? mediaSize.height * compactHeightFactor- : mediaSize.height)- : double.infinity;-- return BoxConstraints(- maxWidth: adaptiveConstraints.maxWidth,- maxHeight: maxHeight,- );- }-- Widget buildTimelineBottomSheetShell(- BuildContext context, {- required Widget header,- required Widget body,- }) {- final colorScheme = Theme.of(context).colorScheme;-- return Container(- decoration: BoxDecoration(- color: colorScheme.surface,- borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),- ),- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- header,- Flexible(child: body),- ],- ),- );- }-- void showSeasonBottomSheet(BuildContext context) {- final currDate = DateTime.now();- final years = List.generate(20, (index) => currDate.year - index);-- // 按年份分组生成可用季节- final yearSeasons = <int, List<DateTime>>{};- for (final year in years) {- final availableSeasons = <DateTime>[];- for (final season in seasons) {- final date = generateDateTime(year, season);- if (currDate.isAfter(date)) {- availableSeasons.add(date);- }- }- if (availableSeasons.isNotEmpty) {- yearSeasons[year] = availableSeasons;- }- }-- KazumiDialog.showBottomSheet(+ void _showSeasonBottomSheet(BuildContext context) {+ final now = DateTime.now();+ final years = List.generate(20, (i) => now.year - i);+ showAdaptiveBottomSheet<void>(context: context,- backgroundColor: Theme.of(context).colorScheme.surface,- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.vertical(top: Radius.circular(28)),- ),- clipBehavior: Clip.antiAlias,- useSafeArea: true,- constraints: buildTimelineBottomSheetConstraints(context),- isScrollControlled: true,- builder: (BuildContext sheetContext) {- return DraggableScrollableSheet(- initialChildSize: 0.72,- minChildSize: 0.4,- maxChildSize: 0.92,- expand: false,- builder: (context, scrollController) {- return buildTimelineBottomSheetShell(- sheetContext,- header: buildSeasonSheetHeader(sheetContext),- body: ListView.separated(- controller: scrollController,- padding: const EdgeInsets.fromLTRB(16, 8, 16, 28),- itemCount: yearSeasons.keys.length,- separatorBuilder: (_, __) => const SizedBox(height: 12),- itemBuilder: (context, index) {- final year = yearSeasons.keys.elementAt(index);- final availableSeasons = yearSeasons[year]!;-- return buildSeasonYearSection(- context,- year,- availableSeasons,- );- },- ),- );- },- );- },- );- }-- Widget buildSeasonSheetHeader(BuildContext context) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;-- return MaterialBottomSheetHeader(- title: '时间机器',- description: '按季度回到任意放送季,时间线会立即切换。',- onClose: KazumiDialog.dismiss,- footer: Container(- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),- decoration: BoxDecoration(- color: colorScheme.secondaryContainer,- borderRadius: BorderRadius.circular(16),- ),- child: Text(- '当前查看 ${getStringByDateTime(timelineController.selectedDate)}',- style: textTheme.labelLarge?.copyWith(- color: colorScheme.onSecondaryContainer,- fontWeight: FontWeight.w600,- ),- ),- ),- );- }-- DateTime? getSelectedSeason(List<DateTime> availableSeasons) {- for (final season in availableSeasons) {- if (isSameSeason(timelineController.selectedDate, season)) {- return season;- }- }-- return null;- }-- Widget buildSeasonYearSection(- BuildContext context, int year, List<DateTime> availableSeasons) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;- final hasSelectedSeason = getSelectedSeason(availableSeasons) != null;-- return Container(- padding: const EdgeInsets.fromLTRB(20, 18, 20, 20),- decoration: BoxDecoration(- color: hasSelectedSeason- ? colorScheme.secondaryContainer.withValues(alpha: 0.5)- : colorScheme.surfaceContainerLow,- borderRadius: BorderRadius.circular(20),- border: Border.all(- color: hasSelectedSeason- ? colorScheme.secondary.withValues(alpha: 0.24)- : colorScheme.outlineVariant.withValues(alpha: 0.5),- ),- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,+ useRootNavigator: true,+ maxHeightFactor: .86,+ builder: (context) => Column(children: [- Text(- '$year年',- style: textTheme.titleMedium?.copyWith(- color: colorScheme.onSurface,- fontWeight: FontWeight.w700,- ),+ MaterialBottomSheetHeader(+ title: '放送季度',+ description:+ '正在查看 ${_getStringByDateTime(timelineController.selectedDate)}',+ onClose: () => Navigator.of(context).pop(),),- if (!hasSelectedSeason) ...[- const SizedBox(height: 4),- Text(- '共 ${availableSeasons.length} 个季度可选',- style: textTheme.bodySmall?.copyWith(- color: colorScheme.onSurfaceVariant,- ),+ Expanded(+ child: ListView.separated(+ padding: materialBottomSheetContentPadding,+ itemCount: years.length,+ separatorBuilder: (_, __) => const SizedBox(height: 24),+ itemBuilder: (context, index) {+ final year = years[index];+ return ContentSection(+ title: '$year',+ padding: const EdgeInsets.all(8),+ child: LayoutBuilder(builder: (context, constraints) {+ final columns =+ MediaQuery.textScalerOf(context).scale(14) > 21 ? 2 : 4;+ return Wrap(+ spacing: 4,+ runSpacing: 4,+ children: [+ for (final season in ['冬', '春', '夏', '秋'])+ SizedBox(+ width: (constraints.maxWidth - 4 * (columns - 1)) /+ columns,+ child: _seasonButton(+ context, _generateDateTime(year, season), now),+ ),+ ],+ );+ }),+ );+ },),- ],- const SizedBox(height: 16),- buildSeasonChoiceChips(context, availableSeasons),+ ),],),);}- Widget buildSeasonChoiceChips(- BuildContext context, List<DateTime> availableSeasons) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;- final selectedSeason = getSelectedSeason(availableSeasons);-- return Wrap(- spacing: 12,- runSpacing: 12,- children: availableSeasons.map((date) {- final seasonName = getSeasonStringByMonth(date.month);- final isSelected =- selectedSeason != null && isSameSeason(selectedSeason, date);-- return ChoiceChip(- label: Text(seasonName),- selected: isSelected,- onSelected: (selected) {- if (!selected) {- return;+ Widget _seasonButton(BuildContext context, DateTime date, DateTime now) {+ final selected = isSameSeason(timelineController.selectedDate, date);+ final colors = Theme.of(context).colorScheme;+ return TextButton(+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 48),+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),+ backgroundColor:+ selected ? colors.secondaryContainer : Colors.transparent,+ foregroundColor:+ selected ? colors.onSecondaryContainer : colors.onSurface,+ ),+ onPressed: now.isAfter(date)+ ? () {+ Navigator.of(context).pop();+ _onSeasonSelected(date);}- KazumiDialog.dismiss();- onSeasonSelected(date);- },- showCheckmark: false,- labelStyle: textTheme.labelLarge?.copyWith(- color: isSelected- ? colorScheme.onSecondaryContainer- : colorScheme.onSurface,- fontWeight: FontWeight.w600,- ),- backgroundColor: colorScheme.surfaceContainerHigh,- selectedColor: colorScheme.secondaryContainer,- side: BorderSide(- color: isSelected- ? Colors.transparent- : colorScheme.outlineVariant.withValues(alpha: 0.4),- width: 1,- ),- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(18),- ),- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,- );- }).toList(),+ : null,+ child: Text('${getSeasonStringByMonth(date.month)}季'),);}- void onSeasonSelected(DateTime date) async {+ void _onSeasonSelected(DateTime date) async {final currDate = DateTime.now();timelineController.tryEnterSeason(date);@@ -340,337 +167,70 @@ class _TimelinePageState extends State<TimelinePage>AnimeSeason(timelineController.selectedDate).toString();}- String getSortTypeLabel(int sortType) {- switch (sortType) {- case 1:- return '时间优先';- case 2:- return '评分优先';- case 3:- return '热度优先';- default:- return '热度优先';- }- }-- int getEnabledTimelineFilterCount() {- var enabledCount = 0;- if (timelineController.notShowAbandonedBangumis) {- enabledCount++;- }- if (timelineController.notShowWatchedBangumis) {- enabledCount++;- }- if (timelineController.onlyShowWatchingBangumis) {- enabledCount++;- }- return enabledCount;- }-- Widget buildTimelineOptionSummaryChip(- BuildContext context, {- required String label,- bool highlighted = false,- VoidCallback? onTap,- IconData? trailingIcon,- }) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;- final foregroundColor =- highlighted ? colorScheme.onSecondaryContainer : colorScheme.onSurface;-- return Material(- color: Colors.transparent,- child: InkWell(- onTap: onTap,- borderRadius: BorderRadius.circular(16),- child: Ink(- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),- decoration: BoxDecoration(- color: highlighted- ? colorScheme.secondaryContainer- : colorScheme.surfaceContainerHigh,- borderRadius: BorderRadius.circular(16),+ Widget _buildTimelineOptionsSheet(BuildContext context) {+ return StatefulBuilder(builder: (context, updateSheet) {+ return Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ MaterialBottomSheetHeader(+ title: '时间线选项',+ onClose: () => Navigator.of(context).pop(),),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Text(- label,- style: textTheme.labelLarge?.copyWith(- color: foregroundColor,- fontWeight: FontWeight.w600,- ),- ),- if (trailingIcon != null) ...[- const SizedBox(width: 6),- Icon(- trailingIcon,- size: 18,- color: foregroundColor,+ Flexible(+ child: ListView(+ shrinkWrap: true,+ padding: materialBottomSheetContentPadding,+ children: [+ ContentSection(+ title: '排序',+ child: Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ for (final option in [(3, '热度'), (2, '评分'), (1, '播出时间')])+ ChoiceChip(+ label: Text(option.$2),+ selected: timelineController.sortType == option.$1,+ onSelected: (_) => updateSheet(() {+ timelineController.changeSortType(option.$1);+ }),+ ),+ ],+ ),),+ const SizedBox(height: 24),+ Observer(+ builder: (context) => ContentSection.group(+ title: '显示范围',+ children: [+ SwitchListTile(+ title: const Text('隐藏看过的番剧'),+ value: timelineController.notShowWatchedBangumis,+ onChanged:+ timelineController.setNotShowWatchedBangumis,+ ),+ SwitchListTile(+ title: const Text('隐藏抛弃的番剧'),+ value:+ timelineController.notShowAbandonedBangumis,+ onChanged: timelineController+ .setNotShowAbandonedBangumis,+ ),+ SwitchListTile(+ title: const Text('只看正在追的番剧'),+ value:+ timelineController.onlyShowWatchingBangumis,+ onChanged: timelineController+ .setOnlyShowWatchingBangumis,+ ),+ ],+ )),],- ],- ),- ),- ),- );- }-- Widget buildTimelineOptionsSheetHeader(BuildContext context) {- return MaterialBottomSheetHeader(- title: '时间线选项',- description: '调整排序和过滤条件,结果会立即应用到当前时间线。',- onClose: KazumiDialog.dismiss,- footer: Observer(- builder: (context) {- final enabledFilterCount = getEnabledTimelineFilterCount();- return Wrap(- spacing: 8,- runSpacing: 8,- children: [- buildTimelineOptionSummaryChip(- context,- label: '当前排序 ${getSortTypeLabel(timelineController.sortType)}',- highlighted: true,- ),- buildTimelineOptionSummaryChip(- context,- label: enabledFilterCount == 0- ? '未启用过滤条件'- : '已启用 $enabledFilterCount 个过滤条件',- onTap: scrollToFilterSection,- ),- ],- );- },- ),- );- }-- Widget buildSortOptionTile(- BuildContext context, {- required int sortType,- required String title,- required String description,- required IconData icon,- }) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;- final isSelected = timelineController.sortType == sortType;-- return Ink(- decoration: BoxDecoration(- color: isSelected- ? colorScheme.secondaryContainer- : colorScheme.surfaceContainerHigh,- borderRadius: BorderRadius.circular(20),- border: Border.all(- color: isSelected- ? colorScheme.secondary.withValues(alpha: 0.3)- : colorScheme.outlineVariant.withValues(alpha: 0.4),- ),- ),- child: ListTile(- contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),- leading: Icon(- icon,- color: isSelected- ? colorScheme.onSecondaryContainer- : colorScheme.onSurfaceVariant,- ),- title: Text(- title,- style: textTheme.titleMedium?.copyWith(- color: isSelected- ? colorScheme.onSecondaryContainer- : colorScheme.onSurface,- fontWeight: FontWeight.w600,- ),- ),- subtitle: Text(- description,- style: textTheme.bodySmall?.copyWith(- color: isSelected- ? colorScheme.onSecondaryContainer.withValues(alpha: 0.82)- : colorScheme.onSurfaceVariant,- ),- ),- trailing: Icon(- isSelected- ? Icons.check_circle_rounded- : Icons.radio_button_unchecked_rounded,- color: isSelected- ? colorScheme.onSecondaryContainer- : colorScheme.onSurfaceVariant,- ),- onTap: () {- KazumiDialog.dismiss();- timelineController.changeSortType(sortType);- },- ),- );- }-- Widget buildFilterOptionTile(- BuildContext context, {- required String title,- required String description,- required bool value,- required ValueChanged<bool> onChanged,- required IconData icon,- }) {- final colorScheme = Theme.of(context).colorScheme;- final textTheme = Theme.of(context).textTheme;-- return Ink(- decoration: BoxDecoration(- color: value- ? colorScheme.secondaryContainer.withValues(alpha: 0.5)- : colorScheme.surfaceContainerHigh,- borderRadius: BorderRadius.circular(20),- border: Border.all(- color: value- ? colorScheme.secondary.withValues(alpha: 0.24)- : colorScheme.outlineVariant.withValues(alpha: 0.4),- ),- ),- child: ListTile(- contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),- leading: Icon(- icon,- color: value- ? colorScheme.onSecondaryContainer- : colorScheme.onSurfaceVariant,- ),- title: Text(- title,- style: textTheme.titleMedium?.copyWith(- color: value- ? colorScheme.onSecondaryContainer- : colorScheme.onSurface,- fontWeight: FontWeight.w600,- ),- ),- subtitle: Text(- description,- style: textTheme.bodySmall?.copyWith(- color: value- ? colorScheme.onSecondaryContainer.withValues(alpha: 0.82)- : colorScheme.onSurfaceVariant,- ),- ),- trailing: Switch(- value: value,- onChanged: onChanged,- ),- onTap: () {- onChanged(!value);- },- ),- );- }-- Widget showFilterSwitcher() {- return MaterialBottomSheetSection(- key: filterSectionKey,- title: '过滤器',- description: '按收藏状态收起不需要显示的条目,支持连续调整。',- child: Column(- children: [- Observer(- builder: (context) => buildFilterOptionTile(- context,- title: '不显示已抛弃的番剧',- description: '隐藏已经标记为抛弃的条目。',- value: timelineController.notShowAbandonedBangumis,- onChanged: (value) {- timelineController.setNotShowAbandonedBangumis(value);- },- icon: Icons.heart_broken_rounded,- ),- ),- const SizedBox(height: 12),- Observer(- builder: (context) => buildFilterOptionTile(- context,- title: '不显示已看过的番剧',- description: '把已经看完的条目从时间线中移除。',- value: timelineController.notShowWatchedBangumis,- onChanged: (value) {- timelineController.setNotShowWatchedBangumis(value);- },- icon: Icons.task_alt_rounded,- ),- ),- const SizedBox(height: 12),- Observer(- builder: (context) => buildFilterOptionTile(- context,- title: '只显示在看的番剧',- description: '聚焦当前正在追更的条目。',- value: timelineController.onlyShowWatchingBangumis,- onChanged: (value) {- timelineController.setOnlyShowWatchingBangumis(value);- },- icon: Icons.live_tv_rounded,),),],- ),- );- }-- Widget showSortSwitcher() {- return MaterialBottomSheetSection(- title: '排序方式',- description: '选择每一天内番剧卡片的排列方式。',- child: Column(- children: [- buildSortOptionTile(- context,- sortType: 3,- title: '按热度排序',- description: '优先展示讨论度和关注度更高的条目。',- icon: Icons.local_fire_department_rounded,- ),- const SizedBox(height: 12),- buildSortOptionTile(- context,- sortType: 2,- title: '按评分排序',- description: '优先展示评分更高的条目。',- icon: Icons.star_rounded,- ),- const SizedBox(height: 12),- buildSortOptionTile(- context,- sortType: 1,- title: '按时间排序',- description: '恢复默认时间顺序,方便按播出节奏查看。',- icon: Icons.schedule_rounded,- ),- ],- ),- );- }-- Widget buildTimelineOptionsSheet(BuildContext context) {- return buildTimelineBottomSheetShell(- context,- header: buildTimelineOptionsSheetHeader(context),- body: ListView(- shrinkWrap: true,- padding: const EdgeInsets.fromLTRB(16, 8, 16, 28),- children: [- showSortSwitcher(),- const SizedBox(height: 12),- showFilterSwitcher(),- ],- ),- );+ );+ });}@override@@ -690,27 +250,22 @@ class _TimelinePageState extends State<TimelinePage>return Text(timelineController.seasonString);}),onTap: () {- showSeasonBottomSheet(context);+ _showSeasonBottomSheet(context);},),),floatingActionButton: FloatingActionButton(onPressed: () {- KazumiDialog.showBottomSheet(- backgroundColor: Theme.of(context).colorScheme.surface,- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.vertical(top: Radius.circular(28)),- ),- isScrollControlled: true,- constraints: buildTimelineBottomSheetConstraints(- context,- compactHeightFactor: 2 / 3,- ),- clipBehavior: Clip.antiAlias,- useSafeArea: true,+ showAdaptiveBottomSheet<void>(+ useRootNavigator: true,+ maxHeightFactor: MediaQuery.sizeOf(context).height >=+ LayoutBreakpoint.compact['height']!+ ? 2 / 3+ : 1,+ compactLandscapeMaxHeightFactor: 1,context: context,builder: (context) {- return buildTimelineOptionsSheet(context);+ return _buildTimelineOptionsSheet(context);},);},@@ -720,7 +275,7 @@ class _TimelinePageState extends State<TimelinePage>if (timelineController.isLoading &&timelineController.bangumiCalendar.isEmpty) {return const Center(- child: CircularProgressIndicator(),+ child: LoadingIndicator(),);}if (timelineController.isTimeOut) {@@ -729,7 +284,7 @@ class _TimelinePageState extends State<TimelinePage>height: 400,child: BangumiMirrorErrorWidget(onRetry: () {- onSeasonSelected(timelineController.selectedDate);+ _onSeasonSelected(timelineController.selectedDate);},onSettingsReturned: () {if (mounted) {@@ -759,7 +314,6 @@ class _TimelinePageState extends State<TimelinePage>}double cardHeight = isDesktop() ? 160 : (isTablet() ? 140 : 120);for (var bangumiList in bangumiCalendar) {- // 根据过滤器设置过滤番剧var filteredList = bangumiList;if (timelineController.notShowAbandonedBangumis) {diff --git a/lib/pages/video/danmaku_destination_sheet.dart b/lib/pages/video/danmaku_destination_sheet.dartnew file mode 100644index 00000000..96212e17--- /dev/null+++ b/lib/pages/video/danmaku_destination_sheet.dart@@ -0,0 +1,44 @@+import 'package:flutter/material.dart';++import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';+import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:kazumi/bean/widget/split_list_row.dart';+import 'package:kazumi/pages/player/controller/player_models.dart';++Future<DanmakuDestination?> showDanmakuDestinationSheet(BuildContext context) {+ return showAdaptiveBottomSheet<DanmakuDestination>(+ context: context,+ builder: (context) => Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ MaterialBottomSheetHeader(+ title: '发送到',+ onClose: () => Navigator.of(context).pop(),+ ),+ Flexible(+ child: SingleChildScrollView(+ padding: materialBottomSheetContentPadding,+ child: SplitListGroup(+ children: [+ ListTile(+ leading: const Icon(Icons.groups_rounded),+ title: const Text('一起看聊天室'),+ subtitle: const Text('与同房间的朋友聊天'),+ onTap: () =>+ Navigator.of(context).pop(DanmakuDestination.chatRoom),+ ),+ ListTile(+ leading: const Icon(Icons.subtitles_outlined),+ title: const Text('视频弹幕'),+ subtitle: const Text('发送至远程弹幕库'),+ onTap: () => Navigator.of(context)+ .pop(DanmakuDestination.remoteDanmaku),+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ );+}diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dartindex f37c85d1..49df8ba1 100644--- a/lib/pages/video/video_page.dart+++ b/lib/pages/video/video_page.dart@@ -1,33 +1,36 @@import 'dart:async';+import 'package:canvas_danmaku/models/danmaku_content_item.dart';import 'package:flutter/material.dart';-import 'package:flutter_modular/flutter_modular.dart';-import 'package:kazumi/pages/player/player_controller.dart';-import 'package:kazumi/pages/video/video_controller.dart';-import 'package:kazumi/pages/video/danmaku_send_sheet.dart';-import 'package:kazumi/pages/video/video_playback_args.dart';-import 'package:kazumi/pages/history/history_controller.dart';-import 'package:kazumi/services/logging/logger.dart';-import 'package:kazumi/pages/player/player_item.dart';import 'package:flutter_mobx/flutter_mobx.dart';-import 'package:kazumi/services/storage/storage.dart';-import 'package:kazumi/services/player/pip_utils.dart';-import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;-import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';+import 'package:flutter_modular/flutter_modular.dart';+import 'package:mobx/mobx.dart' as mobx;import 'package:screen_brightness_platform_interface/screen_brightness_platform_interface.dart';import 'package:scrollview_observer/scrollview_observer.dart';-import 'package:kazumi/pages/player/episode_comments_sheet.dart';import 'package:window_manager/window_manager.dart';++import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;+import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';+import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/widget/embedded_native_control_area.dart';+import 'package:kazumi/bean/widget/loading_indicator.dart';+import 'package:kazumi/modules/download/download_module.dart';import 'package:kazumi/pages/download/download_controller.dart';import 'package:kazumi/pages/download/download_episode_sheet.dart';-import 'package:kazumi/modules/download/download_module.dart';+import 'package:kazumi/pages/history/history_controller.dart';+import 'package:kazumi/pages/player/episode_comments_sheet.dart';+import 'package:kazumi/pages/player/player_controller.dart';+import 'package:kazumi/pages/player/player_item.dart';+import 'package:kazumi/pages/video/danmaku_destination_sheet.dart';+import 'package:kazumi/pages/video/danmaku_send_sheet.dart';+import 'package:kazumi/pages/video/video_controller.dart';+import 'package:kazumi/pages/video/video_playback_args.dart';+import 'package:kazumi/services/logging/logger.dart';+import 'package:kazumi/services/platform/display_mode_service.dart';+import 'package:kazumi/services/player/pip_utils.dart';import 'package:kazumi/services/player/timed_shutdown_service.dart';+import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/device.dart';-import 'package:kazumi/services/platform/display_mode_service.dart';-import 'package:mobx/mobx.dart' as mobx;class VideoPage extends StatefulWidget {const VideoPage({@@ -88,7 +91,7 @@ class _VideoPageState extends State<VideoPage>super.initState();videoPageController.applyPlaybackArgs(widget.args);windowManager.addListener(this);- // Window fullscreen can be changed outside this page through system chrome.+videoPageController.isDesktopFullscreen();tabController = TabController(length: 2, vsync: this);observerController = GridObserverController(controller: scrollController);@@ -125,9 +128,7 @@ class _VideoPageState extends State<VideoPage>return window.width > window.height;}- /// The fullscreen switch has two inputs, the window shape and the picture in- /// picture state, and they arrive over different channels in either order, so- /// it settles on both. A picture in picture window is not an orientation.+ // Fullscreen and picture-in-picture events can arrive in either order.void _syncFullscreenWithWindowShape() {if (isDesktop() || videoPageController.isPip) {return;@@ -265,8 +266,7 @@ class _VideoPageState extends State<VideoPage>_logSubscription?.cancel();} catch (_) {}_pipModeListener();- // Cancellation and log-stream teardown happen in VideoPageController's- // own dispose when Modular releases the route scope.+ // Modular disposes the controller and its log subscription with the route.if (!isDesktop()) {try {ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();@@ -329,8 +329,7 @@ class _VideoPageState extends State<VideoPage>void menuJumpToCurrentEpisode() {WidgetsBinding.instance.addPostFrameCallback((_) async {- // GridViewObserver binds its sliver context in its own post-frame callback.- // Wait until the current frame's callbacks have all completed first.+ // Wait for GridViewObserver to bind its sliver in the post-frame callback.await Future<void>.delayed(Duration.zero);if (!mounted || !scrollController.hasClients) {return;@@ -510,8 +509,7 @@ class _VideoPageState extends State<VideoPage>unawaited(playerController.sendSyncPlayChatMessage(msg));} else {- // The remote danmaku provider does not expose a send API here; render the- // local echo so the user still sees their message immediately.+ // This provider has no send API; display a local echo.playerController.danmaku.canvasController.addDanmaku(DanmakuContentItem(msg, selfSend: true));}@@ -534,52 +532,7 @@ class _VideoPageState extends State<VideoPage>return false;}- final DanmakuDestination? result =- await showAdaptiveBottomSheet<DanmakuDestination>(- context: context,- builder: (context) {- return Padding(- padding: const EdgeInsets.only(bottom: 16),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- MaterialBottomSheetHeader(- title: '发送弹幕至',- description: '选择这条弹幕的发送位置',- onClose: () => Navigator.of(context).pop(),- ),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 16),- child: MaterialBottomSheetGroup(- title: '发送位置',- children: [- ListTile(- contentPadding:- const EdgeInsets.symmetric(horizontal: 16),- leading: const Icon(Icons.groups_rounded),- title: const Text('发送到聊天室'),- subtitle: const Text('同步观看成员均可看到'),- onTap: () => Navigator.of(context)- .pop(DanmakuDestination.chatRoom),- ),- ListTile(- contentPadding:- const EdgeInsets.symmetric(horizontal: 16),- leading: const Icon(Icons.cloud_upload_rounded),- title: const Text('发送到远程弹幕库'),- subtitle: const Text('作为视频弹幕发送'),- onTap: () => Navigator.of(context)- .pop(DanmakuDestination.remoteDanmaku),- ),- ],- ),- ),- ],- ),- );- },- );+ final result = await showDanmakuDestinationSheet(context);if (result == null || !mounted) {return false;@@ -615,7 +568,6 @@ class _VideoPageState extends State<VideoPage>appBar: null,body: SafeArea(top: !videoPageController.isFullscreen && !isPip,- // set iOS and Android navigation bar to immersivebottom: false,left: !videoPageController.isFullscreen && !isPip,right: !videoPageController.isFullscreen && !isPip,@@ -748,7 +700,7 @@ class _VideoPageState extends State<VideoPage>: Column(mainAxisAlignment: MainAxisAlignment.center,children: [- CircularProgressIndicator(+ LoadingIndicator(color: Theme.of(context).colorScheme.tertiaryContainer),@@ -995,7 +947,7 @@ class _VideoPageState extends State<VideoPage>return SizedBox(width: 16,height: 16,- child: CircularProgressIndicator(strokeWidth: 2),+ child: LoadingIndicator(),);default:return const SizedBox.shrink();diff --git a/lib/services/sync/history_sync_service.dart b/lib/services/sync/history_sync_service.dartindex ea2a0395..6e067bb0 100644--- a/lib/services/sync/history_sync_service.dart+++ b/lib/services/sync/history_sync_service.dart@@ -3,13 +3,14 @@ import 'dart:io';import 'dart:isolate';import 'package:flutter/foundation.dart';+import 'package:path_provider/path_provider.dart';+import 'package:kazumi/modules/history/history_module.dart';import 'package:kazumi/modules/history/history_sync.dart';import 'package:kazumi/services/logging/logger.dart';import 'package:kazumi/services/storage/history_storage_coordinator.dart';import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/utils/async_serial_queue.dart';-import 'package:path_provider/path_provider.dart';class HistorySyncService {static const int checkpointLogThresholdBytes = 1024 * 1024;@@ -211,11 +212,7 @@ class HistorySyncService {await GStorage.histories.flush();}- /// Creates a stable set of local logs for one sync attempt.- ///- /// A checkpoint attempt renames the active log to a pending file, allowing- /// playback to continue appending to a fresh log. Pending files survive- /// failed or interrupted syncs and are picked up by the next attempt.+ /// Rotate active logs for concurrent appends; retain pending files until sync commits.Future<HistorySyncLogBatch> prepareLocalLogs({required Directory runDirectory,required bool forceCheckpoint,@@ -270,10 +267,7 @@ class HistorySyncService {});}- /// Copies the active log for upload, dropping lines other devices could- /// not merge. When malformed lines are found the active log itself is- /// rewritten from the sanitized copy so the damage does not resurface on- /// every following sync. Returns null when nothing valid is left to upload.+ /// Sanitize the upload and active log so corrupt lines do not keep propagating.Future<File?> copyActiveLogForUpload(Directory runDirectory) {return _localLogQueue.run(() async {final activeFile = await localChangeLogFile();@@ -303,9 +297,7 @@ class HistorySyncService {});}- /// Replaces the active log with its sanitized copy. Must be called while- /// holding [_localLogQueue] so no append interleaves. Best-effort: on- /// failure the damaged log stays and the next sync retries.+ /// Requires [_localLogQueue] to prevent appends during replacement.Future<void> _repairActiveLog(File activeFile, File sanitizedFile) async {try {final tempFile = File('${activeFile.path}.repair');@@ -342,13 +334,7 @@ class HistorySyncService {return HistorySyncSnapshot.fromJson(json);}- /// Merges event files into [snapshot].- ///- /// With [tolerateMalformedLines] each unparsable line is skipped and- /// reported through a warning log instead of failing the whole merge. This- /// keeps sync alive when a crash mid-append leaves a truncated line in a- /// locally-owned log; the local Hive box remains the source of truth for- /// anything a skipped line described.+ /// Optionally skip malformed lines while logging each failure.Future<HistorySyncSnapshot> mergeEventFiles({required HistorySyncSnapshot snapshot,required Iterable<File> eventFiles,@@ -374,9 +360,7 @@ class HistorySyncService {);}- /// Merges independently-owned remote logs without letting one invalid file- /// block every device. Each file is transactional: none of its events are- /// applied if parsing fails.+ /// Merge each remote file atomically so one invalid log cannot block other devices.Future<HistorySyncSnapshot> mergeRemoteEventFiles({required HistorySyncSnapshot snapshot,required Iterable<File> eventFiles,@@ -545,8 +529,7 @@ Future<Map<String, dynamic>> _mergeHistoryEventFiles(};}-/// Runs [_copyValidEventLines] in an isolate. Top-level so the isolate-/// closure captures only the paths, not the service instance.+// Keep the isolate entry point top-level to avoid capturing the service.Future<Map<String, int>> _sanitizeEventLogCopy({required String sourcePath,required String targetPath,@@ -558,8 +541,7 @@ Future<Map<String, int>> _sanitizeEventLogCopy({return Isolate.run(() => _copyValidEventLines(request));}-/// Copies only the lines other devices can merge, so one corrupt local line-/// cannot get this device's remote log quarantined by every peer.+// Drop corrupt lines before other devices can quarantine the entire log.Future<Map<String, int>> _copyValidEventLines(Map<String, String> request,) async {diff --git a/lib/utils/anime_season.dart b/lib/utils/anime_season.dartindex 8ee07653..278285f4 100644--- a/lib/utils/anime_season.dart+++ b/lib/utils/anime_season.dart@@ -60,5 +60,5 @@ String getSeasonStringByMonth(int month) {}bool isSameSeason(DateTime d1, DateTime d2) {- return d1.year == d2.year && (d1.month - d2.month).abs() <= 2;+ return d1.year == d2.year && (d1.month - 1) ~/ 3 == (d2.month - 1) ~/ 3;}diff --git a/licenses/m3e_core.txt b/licenses/m3e_core.txtnew file mode 100644index 00000000..90830cf7--- /dev/null+++ b/licenses/m3e_core.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Mudit Purohit++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/pubspec.lock b/pubspec.lockindex 345de3a4..22c6b82d 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -952,6 +952,14 @@ packages:url: "https://pub.dev"source: hostedversion: "0.13.0"+ material_new_shapes:+ dependency: "direct main"+ description:+ name: material_new_shapes+ sha256: e4bc375205e187e8fb232573387112dd8c0dd45b03af8aa2b3c79eb4b9e3e0dc+ url: "https://pub.dev"+ source: hosted+ version: "1.0.0"maybe_just_nothing:dependency: transitivedescription:diff --git a/pubspec.yaml b/pubspec.yamlindex af11484f..f6a334ba 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,41 +1,17 @@name: kazumidescription: "A new Flutter project."-# The following line prevents the package from being accidentally published to-# pub.dev using `flutter pub publish`. This is preferred for private packages.-publish_to: "none" # Remove this line if you wish to publish to pub.dev--# The following defines the version and build number for your application.-# A version number is three numbers separated by dots, like 1.2.43-# followed by an optional build number separated by a +.-# Both the version and the builder number may be overridden in flutter-# build by specifying --build-name and --build-number, respectively.-# In Android, build-name is used as versionName while build-number used as versionCode.-# Read more about Android versioning at https://developer.android.com/studio/publish/versioning-# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.-# Read more about iOS versioning at-# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html-# In Windows, build-name is used as the major, minor, and patch parts-# of the product and file versions while build-number is used as the build suffix.+publish_to: "none"version: 2.3.0+20300environment:sdk: ">=3.3.4 <4.0.0"flutter: 3.47.2-# Dependencies specify other packages that your package needs in order to work.-# To automatically upgrade your package dependencies to the latest versions-# consider running `flutter pub upgrade --major-versions`. Alternatively,-# dependencies can be manually updated by changing the version numbers below to-# the latest version available on pub.dev. To see which dependencies have newer-# versions available, run `flutter pub outdated`.dependencies:flutter:sdk: flutterflutter_localizations:sdk: flutter-- # The following adds the Cupertino Icons font to your application.- # Use with the CupertinoIcons class for iOS style icons.cupertino_icons: ^1.0.6flutter_modular: ^7.1.0mobx: ^2.6.0@@ -51,12 +27,8 @@ dependencies:cached_network_image: ^3.4.1flutter_cache_manager: ^3.4.1image: ^4.8.0- # cached_network_image_ce: ^4.6.4file_picker: ^10.3.7- # fvp: ^0.28.0- # video_player: ^2.9.1-flutter_volume_controller: ^2.0.1audio_video_progress_bar: ^2.0.2audio_service: ^0.18.15@@ -104,6 +76,7 @@ dependencies:open_filex: ^4.7.0html: anymaterial_color_utilities: any+ material_new_shapes: ^1.0.0path: anyphoto_view: ^0.15.0win32: ^5.15.0@@ -172,11 +145,6 @@ dev_dependencies:flutter_test:sdk: flutter- # The "flutter_lints" package below contains a set of recommended lints to- # encourage good coding practices. The lint set provided by the package is- # activated in the `analysis_options.yaml` file located at the root of your- # package. See that file for information about deactivating specific lint- # rules and activating additional ones.flutter_lints: ^6.0.0build_runner: ^2.15.0mobx_codegen: ^2.7.5@@ -185,9 +153,6 @@ dev_dependencies:flutter_native_splash: ^2.4.3msix: ^3.16.12-# For information on the generic Dart part of this file, see the-# following page: https://dart.dev/tools/pub/pubspec-flutter_launcher_icons:android: trueios: true@@ -204,7 +169,7 @@ flutter_launcher_icons:windows:generate: trueimage_path: assets/images/logo/logo_rounded.png- icon_size: 256 # min:48, max:256, default: 48+ icon_size: 256flutter_native_splash:android: false@@ -223,49 +188,14 @@ msix_config:install_certificate: falsebuild_windows: false-# The following section is specific to Flutter packages.flutter:- # The following line ensures that the Material Icons font is- # included with your application, so that you can use the icons in- # the material Icons class.uses-material-design: true-- # To add assets to your application, add an assets section, like this:- # assets:- # - images/a_dot_burr.jpeg- # - images/a_dot_ham.jpegassets:- assets/images/- assets/plugins/- assets/shaders/- assets/images/logo/- assets/statements/-- # An image asset can refer to one or more resolution-specific "variants", see- # https://flutter.dev/assets-and-images/#resolution-aware-- # For details regarding adding assets from package dependencies, see- # https://flutter.dev/assets-and-images/#from-packages-- # To add custom fonts to your application, add a fonts section here,- # in this "flutter" section. Each entry in this list should have a- # "family" key with the font family name, and a "fonts" key with a- # list giving the asset and other descriptors for the font. For- # example:- # fonts:- # - family: Schyler- # fonts:- # - asset: fonts/Schyler-Regular.ttf- # - asset: fonts/Schyler-Italic.ttf- # style: italic- # - family: Trajan Pro- # fonts:- # - asset: fonts/TrajanPro.ttf- # - asset: fonts/TrajanPro_Bold.ttf- # weight: 700- #- # For details regarding fonts from package dependencies,- # see https://flutter.dev/custom-fonts/#from-packagesfonts:- family: MI_Sans_Regularfonts: