Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat(rules): redesign rule management

Predidit1aa66d9bee4e
diff --git a/lib/bean/card/rule_card.dart b/lib/bean/card/rule_card.dart
index dbfb69f4..da6f16a2 100644
--- a/lib/bean/card/rule_card.dart
+++ b/lib/bean/card/rule_card.dart
@@ -1,97 +1,161 @@
import 'package:flutter/material.dart';
-/// Rounded tonal card for a rule entry, shared by the rule manage page,
-/// the rule shop page and the onboarding rule step.
class RuleCard extends StatelessWidget {
const RuleCard({
super.key,
required this.title,
this.tags = const [],
this.caption,
+ this.subtitle,
this.trailing,
this.onTap,
this.onLongPress,
this.selected = false,
+ this.installed = false,
});
final String title;
final List<Widget> tags;
-
- /// Plain text shown after [tags], e.g. the last update date.
final String? caption;
+ final String? subtitle;
final Widget? trailing;
final VoidCallback? onTap;
final VoidCallback? onLongPress;
final bool selected;
+ final bool installed;
@override
Widget build(BuildContext context) {
- final colorScheme = Theme.of(context).colorScheme;
- final textTheme = Theme.of(context).textTheme;
- return Card(
- elevation: 0,
- margin: const EdgeInsets.only(bottom: 8),
- color: selected
- ? colorScheme.primaryContainer
- : colorScheme.surfaceContainerLow,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
- clipBehavior: Clip.antiAlias,
- child: ListTile(
- onTap: onTap,
- onLongPress: onLongPress,
+ final colors = Theme.of(context).colorScheme;
+ final text = Theme.of(context).textTheme;
+ // Keep menu focus from activating the enclosing InkWell's highlight.
+ final actions = trailing == null
+ ? null
+ : Focus(
+ parentNode: Focus.maybeOf(context, scopeOk: true),
+ canRequestFocus: false,
+ skipTraversal: true,
+ child: trailing!,
+ );
+ final duration = MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 220);
+ return Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Semantics(
selected: selected,
- title: Text(title, style: textTheme.titleMedium),
- subtitle: tags.isEmpty && caption == null
- ? null
- : Padding(
- padding: const EdgeInsets.only(top: 4),
- child: Wrap(
- spacing: 6,
- runSpacing: 4,
- crossAxisAlignment: WrapCrossAlignment.center,
- children: [
- ...tags,
- if (caption != null)
- Text(
- caption!,
- style: textTheme.bodySmall
- ?.copyWith(color: colorScheme.onSurfaceVariant),
+ child: AnimatedContainer(
+ duration: duration,
+ curve: Curves.easeInOutCubicEmphasized,
+ decoration: BoxDecoration(
+ color: selected
+ ? colors.secondaryContainer
+ : colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(selected ? 20 : 28),
+ border: Border.all(
+ color: selected ? colors.secondary : Colors.transparent,
+ width: 2,
+ ),
+ ),
+ child: Material(
+ type: MaterialType.transparency,
+ borderRadius: BorderRadius.circular(selected ? 18 : 26),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: onTap,
+ onLongPress: onLongPress,
+ child: Padding(
+ padding: const EdgeInsets.all(14),
+ child: LayoutBuilder(builder: (context, constraints) {
+ final stacked = constraints.maxWidth < 300 ||
+ MediaQuery.textScalerOf(context).scale(14) > 20;
+ final identity = Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ AnimatedContainer(
+ duration: duration,
+ width: 48,
+ height: 48,
+ decoration: BoxDecoration(
+ color: selected || installed
+ ? colors.secondaryContainer
+ : colors.primaryContainer,
+ borderRadius:
+ BorderRadius.circular(installed ? 24 : 16),
+ ),
+ child: Icon(
+ selected
+ ? Icons.check_rounded
+ : Icons.extension_rounded,
+ color: selected || installed
+ ? colors.onSecondaryContainer
+ : colors.onPrimaryContainer,
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title,
+ style: text.titleMedium
+ ?.copyWith(fontWeight: FontWeight.w700),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis),
+ if (subtitle != null && subtitle!.isNotEmpty) ...[
+ const SizedBox(height: 3),
+ Text(subtitle!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: text.bodySmall?.copyWith(
+ color: colors.onSurfaceVariant)),
+ ],
+ if (tags.isNotEmpty) ...[
+ const SizedBox(height: 8),
+ Wrap(spacing: 6, runSpacing: 6, children: tags),
+ ],
+ if (caption != null) ...[
+ const SizedBox(height: 6),
+ Text(caption!,
+ style: text.bodySmall?.copyWith(
+ color: colors.onSurfaceVariant)),
+ ],
+ ],
+ ),
),
- ],
- ),
+ ],
+ );
+ if (stacked) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ identity,
+ if (actions != null) ...[
+ const SizedBox(height: 8),
+ Align(
+ alignment: AlignmentDirectional.centerEnd,
+ child: actions),
+ ],
+ ],
+ );
+ }
+ return Row(children: [
+ Expanded(child: identity),
+ if (actions != null) ...[
+ const SizedBox(width: 12),
+ actions
+ ],
+ ]);
+ }),
),
- trailing: trailing,
- ),
- );
- }
-}
-
-/// Fixed-width tonal action button for [RuleCard] trailing slots, so the
-/// button edge stays aligned across rows regardless of label length
-/// (e.g. 安装 / 更新 / 已安装). Pass null [onPressed] for the disabled state.
-class RuleCardActionButton extends StatelessWidget {
- const RuleCardActionButton({
- super.key,
- required this.label,
- this.onPressed,
- });
-
- final String label;
- final VoidCallback? onPressed;
-
- @override
- Widget build(BuildContext context) {
- return SizedBox(
- width: 96,
- child: FilledButton.tonal(
- onPressed: onPressed,
- child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
+ ),
+ ),
+ ),
),
);
}
}
-/// Small tonal label used inside [RuleCard], e.g. version or captcha tags.
class RuleTag extends StatelessWidget {
const RuleTag({
super.key,
@@ -105,18 +169,16 @@ class RuleTag extends StatelessWidget {
final Color foreground;
@override
- Widget build(BuildContext context) {
- return Container(
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
- decoration: BoxDecoration(
- color: background,
- borderRadius: BorderRadius.circular(8),
- ),
- child: Text(
- label,
- style:
- Theme.of(context).textTheme.labelSmall?.copyWith(color: foreground),
- ),
- );
- }
+ Widget build(BuildContext context) => Container(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
+ decoration: BoxDecoration(
+ color: background,
+ borderRadius: BorderRadius.circular(8),
+ ),
+ child: Text(label,
+ style: Theme.of(context)
+ .textTheme
+ .labelSmall
+ ?.copyWith(color: foreground, fontWeight: FontWeight.w600)),
+ );
}
diff --git a/lib/pages/onboarding/steps/plugin_shop_step.dart b/lib/pages/onboarding/steps/plugin_shop_step.dart
index f4862365..8fc423fc 100644
--- a/lib/pages/onboarding/steps/plugin_shop_step.dart
+++ b/lib/pages/onboarding/steps/plugin_shop_step.dart
@@ -12,17 +12,10 @@ class PluginShopStep extends StatelessWidget {
final PluginsController controller;
@override
- Widget build(BuildContext context) {
- return OnboardingStepLayout(
- leading: const OnboardingStepIcon(icon: Icons.travel_explore_rounded),
- title: '添加规则',
- subtitle: '规则提供番剧搜索源,可稍后在 设置 → 规则管理 中调整',
- child: PluginCatalogView(
- controller: controller,
- listPadding: EdgeInsets.zero,
- showRefreshButton: true,
- compactLastUpdate: true,
- ),
- );
- }
+ Widget build(BuildContext context) => OnboardingStepLayout(
+ leading: const OnboardingStepIcon(icon: Icons.travel_explore_rounded),
+ title: '添加规则',
+ subtitle: '规则提供番剧搜索源,可稍后在 设置 → 规则管理 中调整',
+ child: PluginCatalogView(controller: controller, onboarding: true),
+ );
}
diff --git a/lib/pages/plugin_editor/editor_form_widgets.dart b/lib/pages/plugin_editor/editor_form_widgets.dart
index 757fa5fa..fe1038f9 100644
--- a/lib/pages/plugin_editor/editor_form_widgets.dart
+++ b/lib/pages/plugin_editor/editor_form_widgets.dart
@@ -1,6 +1,5 @@
import 'package:flutter/material.dart';
-
-const Duration _kSectionAnimationDuration = Duration(milliseconds: 250);
+import 'package:kazumi/pages/plugin_editor/rule_management_widgets.dart';
class EditorTextField extends StatelessWidget {
const EditorTextField({
@@ -20,21 +19,101 @@ class EditorTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
- return TextField(
- controller: controller,
- maxLines: maxLines,
- decoration: InputDecoration(
- labelText: label,
- hintText: hint,
- helperText: helper,
- helperMaxLines: 3,
- alignLabelWithHint: maxLines > 1,
- border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
+ final theme = Theme.of(context);
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Text(label, style: theme.textTheme.labelLarge),
+ const SizedBox(height: 8),
+ Semantics(
+ label: label,
+ child: TextField(
+ controller: controller,
+ maxLines: maxLines,
+ autocorrect: false,
+ enableSuggestions: false,
+ style: maxLines > 1
+ ? theme.textTheme.bodyMedium?.copyWith(fontFamily: 'monospace')
+ : null,
+ decoration: ruleInputDecoration(context, hint: hint),
+ ),
),
- );
+ if (helper != null) ...[
+ const SizedBox(height: 6),
+ Text(helper!,
+ style: theme.textTheme.bodySmall
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),
+ ],
+ ]);
}
}
+class EditorChoiceGroup<T> extends StatelessWidget {
+ const EditorChoiceGroup({
+ super.key,
+ required this.value,
+ required this.segments,
+ required this.onChanged,
+ });
+
+ final T value;
+ final List<ButtonSegment<T>> segments;
+ final ValueChanged<T> onChanged;
+
+ @override
+ Widget build(BuildContext context) =>
+ LayoutBuilder(builder: (context, constraints) {
+ final colors = Theme.of(context).colorScheme;
+ final wrap = constraints.maxWidth <
+ segments.length * MediaQuery.textScalerOf(context).scale(76);
+ Widget button(int index) {
+ final segment = segments[index];
+ final selected = segment.value == value;
+ final outer = const Radius.circular(24);
+ final inner = Radius.circular(selected ? 24 : 8);
+ return Semantics(
+ selected: selected,
+ inMutuallyExclusiveGroup: true,
+ child: FilledButton(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(64, 48),
+ padding:
+ const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
+ backgroundColor: selected
+ ? colors.secondaryContainer
+ : colors.surfaceContainerHighest,
+ foregroundColor: selected
+ ? colors.onSecondaryContainer
+ : colors.onSurfaceVariant,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadiusDirectional.only(
+ topStart: index == 0 || wrap ? outer : inner,
+ bottomStart: index == 0 || wrap ? outer : inner,
+ topEnd: index == segments.length - 1 || wrap ? outer : inner,
+ bottomEnd:
+ index == segments.length - 1 || wrap ? outer : inner,
+ )),
+ ),
+ onPressed:
+ segment.enabled ? () => onChanged(segment.value) : null,
+ child: segment.label ?? segment.icon ?? const SizedBox.shrink(),
+ ),
+ );
+ }
+
+ if (wrap) {
+ return Wrap(
+ spacing: 4,
+ runSpacing: 4,
+ children: List.generate(segments.length, button));
+ }
+ return Row(children: [
+ for (var index = 0; index < segments.length; index++) ...[
+ if (index > 0) const SizedBox(width: 4),
+ Expanded(child: button(index)),
+ ],
+ ]);
+ });
+}
+
class EditorSegmentedField<T> extends StatelessWidget {
const EditorSegmentedField({
super.key,
@@ -49,96 +128,53 @@ class EditorSegmentedField<T> extends StatelessWidget {
final T value;
final List<ButtonSegment<T>> segments;
final ValueChanged<T> onChanged;
-
final String Function(T value)? description;
@override
- Widget build(BuildContext context) {
- final theme = Theme.of(context);
- final colorScheme = theme.colorScheme;
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- label,
- style: theme.textTheme.labelLarge
- ?.copyWith(color: colorScheme.onSurfaceVariant),
- ),
- const SizedBox(height: 8),
- SegmentedButton<T>(
- segments: segments,
- selected: {value},
- showSelectedIcon: false,
- expandedInsets: EdgeInsets.zero,
- onSelectionChanged: (selection) => onChanged(selection.first),
- ),
- if (description != null) ...[
- const SizedBox(height: 6),
- AnimatedSwitcher(
- duration: _kSectionAnimationDuration,
- child: Text(
- description!(value),
- key: ValueKey<T>(value),
- style: theme.textTheme.bodySmall
- ?.copyWith(color: colorScheme.onSurfaceVariant),
- ),
- ),
+ Widget build(BuildContext context) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(label, style: Theme.of(context).textTheme.labelLarge),
+ const SizedBox(height: 8),
+ EditorChoiceGroup<T>(
+ value: value, segments: segments, onChanged: onChanged),
+ if (description != null) ...[
+ const SizedBox(height: 8),
+ Text(description!(value),
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant)),
+ ],
],
- ],
- );
- }
+ );
}
class EditorAnimatedSection extends StatelessWidget {
- const EditorAnimatedSection({
- super.key,
- required this.activeKey,
- required this.child,
- });
-
+ const EditorAnimatedSection(
+ {super.key, required this.activeKey, required this.child});
final Object activeKey;
final Widget child;
@override
- Widget build(BuildContext context) {
- return AnimatedSize(
- duration: _kSectionAnimationDuration,
- curve: Curves.easeInOutCubic,
- alignment: Alignment.topCenter,
- child: AnimatedSwitcher(
- duration: _kSectionAnimationDuration,
- // Pin both transition entries to the top to prevent vertical jumps.
- layoutBuilder: (currentChild, previousChildren) => Stack(
- alignment: Alignment.topCenter,
- children: [
- ...previousChildren,
- if (currentChild != null) currentChild,
- ],
- ),
- child: KeyedSubtree(
- key: ValueKey<Object>(activeKey),
- child: child,
- ),
- ),
- );
- }
+ Widget build(BuildContext context) => AnimatedSize(
+ duration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 250),
+ curve: Curves.easeInOutCubicEmphasized,
+ alignment: Alignment.topCenter,
+ child: KeyedSubtree(key: ValueKey<Object>(activeKey), child: child),
+ );
}
class EditorSubheader extends StatelessWidget {
const EditorSubheader({super.key, required this.label});
-
final String label;
@override
- Widget build(BuildContext context) {
- final theme = Theme.of(context);
- return Padding(
- padding: const EdgeInsets.only(top: 16, bottom: 8),
- child: Text(
- label,
- style: theme.textTheme.labelLarge
- ?.copyWith(color: theme.colorScheme.primary),
- ),
- );
- }
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(top: 24, bottom: 12),
+ child: Text(label,
+ style: Theme.of(context).textTheme.titleMedium?.copyWith(
+ color: Theme.of(context).colorScheme.primary,
+ fontWeight: FontWeight.w600)),
+ );
}
diff --git a/lib/pages/plugin_editor/plugin_catalog_view.dart b/lib/pages/plugin_editor/plugin_catalog_view.dart
index cfc60d9d..64905d21 100644
--- a/lib/pages/plugin_editor/plugin_catalog_view.dart
+++ b/lib/pages/plugin_editor/plugin_catalog_view.dart
@@ -2,40 +2,38 @@ 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/dialog/dialog_helper.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/pages/plugin_editor/rule_management_widgets.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/services/storage/storage.dart';
-enum PluginCatalogSort { lastUpdate, name }
+enum _CatalogSort { lastUpdate, name }
+
+enum _CatalogFilter { all, installed, updates }
class PluginCatalogView extends StatefulWidget {
const PluginCatalogView({
super.key,
required this.controller,
- this.sort = PluginCatalogSort.lastUpdate,
- this.listPadding = const EdgeInsets.symmetric(horizontal: 8),
- this.showRefreshButton = false,
- this.compactLastUpdate = false,
- this.errorMessage = '无法访问规则仓库',
+ this.onboarding = false,
});
final PluginsController controller;
- final PluginCatalogSort sort;
- final EdgeInsetsGeometry listPadding;
- final bool showRefreshButton;
- final bool compactLastUpdate;
- final String errorMessage;
+ final bool onboarding;
@override
- State<PluginCatalogView> createState() => PluginCatalogViewState();
+ State<PluginCatalogView> createState() => _PluginCatalogViewState();
}
-class PluginCatalogViewState extends State<PluginCatalogView> {
+class _PluginCatalogViewState extends State<PluginCatalogView> {
+ final _search = TextEditingController();
+ final Set<String> _installing = {};
+ _CatalogSort _sort = _CatalogSort.lastUpdate;
+ _CatalogFilter _filter = _CatalogFilter.all;
bool _loading = true;
bool _loadFailed = false;
@@ -51,6 +49,12 @@ class PluginCatalogViewState extends State<PluginCatalogView> {
}
}
+ @override
+ void dispose() {
+ _search.dispose();
+ super.dispose();
+ }
+
Future<void> _loadPluginCatalog({bool forceRefresh = false}) async {
try {
if (forceRefresh) {
@@ -58,21 +62,23 @@ class PluginCatalogViewState extends State<PluginCatalogView> {
} else {
await _controller.ensurePluginCatalog();
}
- if (!mounted) return;
- setState(() {
- _loading = false;
- _loadFailed = false;
- });
+ if (mounted) {
+ setState(() {
+ _loading = false;
+ _loadFailed = false;
+ });
+ }
} catch (_) {
- if (!mounted) return;
- setState(() {
- _loading = false;
- _loadFailed = true;
- });
+ if (mounted) {
+ setState(() {
+ _loading = false;
+ _loadFailed = true;
+ });
+ }
}
}
- void refresh() {
+ void _refresh() {
if (_loading) return;
setState(() {
_loading = true;
@@ -82,137 +88,274 @@ class PluginCatalogViewState extends State<PluginCatalogView> {
}
Future<void> _toggleGitProxyAndRefresh() async {
- final enableGitProxy = GStorage.getSetting(SettingsKeys.enableGitProxy);
- await GStorage.putSetting(SettingsKeys.enableGitProxy, !enableGitProxy);
- if (!mounted) return;
- refresh();
+ try {
+ final enabled = GStorage.getSetting(SettingsKeys.enableGitProxy);
+ await GStorage.putSetting(SettingsKeys.enableGitProxy, !enabled);
+ if (mounted) _refresh();
+ } catch (_) {
+ KazumiDialog.showToast(message: '切换规则镜像失败,请重试');
+ }
+ }
+
+ Future<void> _install(
+ PluginHTTPItem item, PluginCatalogItemStatus status) async {
+ if (!_installing.add(item.name)) return;
+ setState(() {});
+ try {
+ await updatePluginWithFeedback(_controller, item.name,
+ installing: status == PluginCatalogItemStatus.install);
+ } finally {
+ if (mounted) setState(() => _installing.remove(item.name));
+ }
}
- List<PluginHTTPItem> _sortedItems() {
- final items = _controller.pluginHTTPList.toList();
- switch (widget.sort) {
- case PluginCatalogSort.lastUpdate:
+ List<PluginHTTPItem> _visibleItems() {
+ final query = _search.text.trim().toLowerCase();
+ final items = _controller.pluginHTTPList.where((item) {
+ final status = _controller.pluginStatus(item);
+ return (item.name.toLowerCase().contains(query) ||
+ item.author.toLowerCase().contains(query)) &&
+ switch (_filter) {
+ _CatalogFilter.all => true,
+ _CatalogFilter.installed =>
+ status != PluginCatalogItemStatus.install,
+ _CatalogFilter.updates => status == PluginCatalogItemStatus.update,
+ };
+ }).toList();
+ switch (_sort) {
+ case _CatalogSort.lastUpdate:
items.sort((a, b) => b.lastUpdate.compareTo(a.lastUpdate));
- case PluginCatalogSort.name:
+ case _CatalogSort.name:
items.sort(
- (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()),
- );
+ (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
}
return items;
}
- Widget _buildPluginList() {
- return Observer(builder: (context) {
- final colorScheme = Theme.of(context).colorScheme;
- final items = _sortedItems();
-
- return ListView.builder(
- padding: widget.listPadding,
- itemCount: items.length,
- itemBuilder: (context, index) {
- final item = items[index];
- final status = _controller.pluginStatus(item);
- return RuleCard(
- title: item.name,
- tags: [
- RuleTag(
- label: item.version,
- background: colorScheme.secondaryContainer,
- foreground: colorScheme.onSecondaryContainer,
- ),
- if (item.antiCrawlerEnabled)
- RuleTag(
- label: 'captcha',
- background: colorScheme.tertiaryContainer,
- foreground: colorScheme.onTertiaryContainer,
- ),
- ],
- caption:
- item.lastUpdate > 0 ? _formatLastUpdate(item.lastUpdate) : null,
- trailing: RuleCardActionButton(
- label: switch (status) {
- PluginCatalogItemStatus.install => '安装',
- PluginCatalogItemStatus.installed => '已安装',
- PluginCatalogItemStatus.update => '更新',
- },
- onPressed: status == PluginCatalogItemStatus.installed
- ? null
- : () async {
- final result = await updatePluginWithFeedback(
- _controller,
- item.name,
- installing: status == PluginCatalogItemStatus.install,
- );
- if (result == PluginUpdateResult.updated && mounted) {
- setState(() {});
- }
- },
+ Widget _sortButton() => MenuAnchor(
+ builder: (context, controller, _) => TextButton.icon(
+ onPressed: () =>
+ controller.isOpen ? controller.close() : controller.open(),
+ icon: const Icon(Icons.sort_rounded, size: 20),
+ label: Text(_sort == _CatalogSort.name ? '名称排序' : '最近更新'),
+ ),
+ menuChildren: [
+ for (final sort in _CatalogSort.values)
+ MenuItemButton(
+ leadingIcon: Icon(
+ _sort == sort ? Icons.check_rounded : Icons.sort_rounded),
+ onPressed: () => setState(() => _sort = sort),
+ child: Text(sort == _CatalogSort.name ? '按名称排序' : '按更新时间排序'),
),
- );
- },
+ ],
);
- });
- }
-
- String _formatLastUpdate(int millisecondsSinceEpoch) {
- final value =
- DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch).toString();
- if (widget.compactLastUpdate) {
- return value.split(' ')[0];
- }
- return '更新时间: ${value.split('.')[0]}';
- }
- Widget _buildLoadError() {
- final enableGitProxy = GStorage.getSetting(SettingsKeys.enableGitProxy);
- return Center(
- child: GeneralErrorWidget(
- errMsg:
- '${widget.errorMessage}\n${enableGitProxy ? '规则仓库镜像已启用' : '规则仓库镜像已禁用'}',
- actions: [
- GeneralErrorButton(
- onPressed: () => unawaited(_toggleGitProxyAndRefresh()),
- text: enableGitProxy ? '禁用规则镜像' : '启用规则镜像',
- ),
- GeneralErrorButton(onPressed: refresh, text: '刷新'),
- ],
- ),
- );
+ Widget _header(int total, int installed, int updates) {
+ final theme = Theme.of(context);
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ if (!widget.onboarding) ...[
+ const RulePageIntro(
+ title: '发现更多来源',
+ description: '浏览社区规则,为你的番剧搜索添加更多选择。',
+ icon: Icons.travel_explore_rounded,
+ ),
+ const SizedBox(height: 20),
+ TextField(
+ controller: _search,
+ onChanged: (_) => setState(() {}),
+ decoration: ruleInputDecoration(context,
+ hint: '搜索规则或作者',
+ prefix: const Icon(Icons.search_rounded),
+ suffix: _search.text.isEmpty
+ ? null
+ : IconButton(
+ tooltip: '清除搜索',
+ onPressed: () => setState(_search.clear),
+ icon: const Icon(Icons.close_rounded))),
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ runSpacing: 4,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ for (final entry in [
+ (_CatalogFilter.all, '全部 $total'),
+ (_CatalogFilter.installed, '已安装 $installed'),
+ (_CatalogFilter.updates, '可更新 $updates'),
+ ])
+ FilterChip(
+ label: Text(entry.$2),
+ selected: _filter == entry.$1,
+ onSelected: (_) => setState(() => _filter = entry.$1)),
+ ],
+ ),
+ ],
+ Row(children: [
+ if (!widget.onboarding) _sortButton(),
+ const Spacer(),
+ IconButton.filledTonal(
+ tooltip: '刷新规则列表',
+ onPressed: _loading ? null : _refresh,
+ icon: const Icon(Icons.refresh_rounded)),
+ ]),
+ if (_loading && total > 0)
+ const Padding(
+ padding: EdgeInsets.symmetric(vertical: 8),
+ child: LinearProgressIndicator()),
+ if (_loadFailed && total > 0)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Text('刷新失败,正在显示上次获取的规则。', style: theme.textTheme.bodySmall)),
+ const SizedBox(height: 8),
+ ]);
}
- Widget _buildBody() {
+ Widget _emptyBody() {
if (_loading) {
- return const Center(child: LoadingIndicator());
- }
- if (_loadFailed) {
- return _buildLoadError();
+ return const Padding(
+ padding: EdgeInsets.all(48),
+ child: Center(child: LoadingIndicator()));
}
- if (_controller.pluginHTTPList.isEmpty) {
- return const Center(child: Text('规则仓库中暂无规则'));
+ if (_loadFailed && _controller.pluginHTTPList.isEmpty) {
+ final enabled = GStorage.getSetting(SettingsKeys.enableGitProxy);
+ return RuleEmptyState(
+ title: '无法访问规则仓库',
+ description: '请检查网络连接,或切换规则仓库镜像后重试。',
+ icon: Icons.cloud_off_rounded,
+ action: Wrap(
+ alignment: WrapAlignment.center,
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ TextButton(
+ onPressed: _toggleGitProxyAndRefresh,
+ child: Text(enabled ? '关闭规则镜像' : '启用规则镜像')),
+ FilledButton.tonalIcon(
+ onPressed: _refresh,
+ icon: const Icon(Icons.refresh_rounded),
+ label: const Text('重新加载')),
+ ]),
+ );
}
- return _buildPluginList();
+ return RuleEmptyState(
+ title: _controller.pluginHTTPList.isEmpty ? '仓库暂时没有规则' : '没有符合条件的规则',
+ description:
+ _controller.pluginHTTPList.isEmpty ? '稍后刷新再来看看。' : '试试其他关键词,或切换筛选。',
+ icon: Icons.search_off_rounded,
+ );
}
@override
- Widget build(BuildContext context) {
- if (!widget.showRefreshButton) {
- return _buildBody();
- }
- return Column(
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- IconButton(
- onPressed: refresh,
- tooltip: '刷新规则列表',
- icon: const Icon(Icons.refresh_rounded),
+ Widget build(BuildContext context) => Observer(builder: (context) {
+ final colors = Theme.of(context).colorScheme;
+ final catalog = _controller.pluginHTTPList.toList();
+ final installed = catalog
+ .where((p) =>
+ _controller.pluginStatus(p) != PluginCatalogItemStatus.install)
+ .length;
+ final updates = catalog
+ .where((p) =>
+ _controller.pluginStatus(p) == PluginCatalogItemStatus.update)
+ .length;
+ final items = _visibleItems();
+ return CustomScrollView(
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ slivers: [
+ SliverPadding(
+ padding: widget.onboarding
+ ? EdgeInsets.zero
+ : const EdgeInsets.fromLTRB(16, 12, 16, 24),
+ sliver: SliverMainAxisGroup(slivers: [
+ SliverToBoxAdapter(
+ child: _header(catalog.length, installed, updates)),
+ if (items.isEmpty)
+ SliverToBoxAdapter(child: _emptyBody())
+ else
+ SliverList.builder(
+ itemCount: items.length,
+ itemBuilder: (context, index) {
+ final item = items[index];
+ final status = _controller.pluginStatus(item);
+ final busy = _installing.contains(item.name);
+ return RuleCard(
+ key: ValueKey(item.name),
+ title: item.name,
+ installed: status == PluginCatalogItemStatus.installed,
+ subtitle:
+ item.author.isEmpty ? null : '作者 · ${item.author}',
+ tags: [
+ RuleTag(
+ label: item.version,
+ background: colors.surfaceContainerHighest,
+ foreground: colors.onSurfaceVariant),
+ if (item.antiCrawlerEnabled)
+ RuleTag(
+ label: '含验证支持',
+ background: colors.tertiaryContainer,
+ foreground: colors.onTertiaryContainer),
+ ],
+ caption: item.lastUpdate > 0
+ ? '更新于 ${DateTime.fromMillisecondsSinceEpoch(item.lastUpdate).toString().split(' ').first}'
+ : null,
+ trailing: _CatalogRuleAction(
+ status: status,
+ busy: busy,
+ onPressed: () => _install(item, status),
+ ),
+ );
+ },
+ ),
+ ]),
),
],
- ),
- const SizedBox(height: 4),
- Expanded(child: _buildBody()),
- ],
+ );
+ });
+}
+
+class _CatalogRuleAction extends StatelessWidget {
+ const _CatalogRuleAction({
+ required this.status,
+ required this.busy,
+ required this.onPressed,
+ });
+
+ final PluginCatalogItemStatus status;
+ final bool busy;
+ final VoidCallback onPressed;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ if (!busy && status == PluginCatalogItemStatus.installed) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.check_rounded, size: 18, color: colors.onSurfaceVariant),
+ const SizedBox(width: 6),
+ Text('已安装',
+ style: Theme.of(context)
+ .textTheme
+ .labelLarge
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ ]),
+ );
+ }
+ final installing = status == PluginCatalogItemStatus.install;
+ return FilledButton.tonal(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(108, 48),
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ ),
+ onPressed: busy ? null : onPressed,
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ if (busy)
+ const LoadingIndicator(size: 20)
+ else
+ Icon(installing ? Icons.add_rounded : Icons.sync_rounded, size: 18),
+ const SizedBox(width: 6),
+ Text(installing ? (busy ? '安装中' : '安装') : (busy ? '更新中' : '更新')),
+ ]),
);
}
}
diff --git a/lib/pages/plugin_editor/plugin_editor_page.dart b/lib/pages/plugin_editor/plugin_editor_page.dart
index eebacc85..20c21a82 100644
--- a/lib/pages/plugin_editor/plugin_editor_page.dart
+++ b/lib/pages/plugin_editor/plugin_editor_page.dart
@@ -4,8 +4,8 @@ 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/widget/content_section.dart';
-import 'package:kazumi/bean/widget/tonal_card.dart';
+import 'package:kazumi/bean/widget/loading_indicator.dart';
+import 'package:kazumi/pages/plugin_editor/rule_management_widgets.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';
@@ -154,6 +154,10 @@ class PluginEditorPage extends StatefulWidget {
class _PluginEditorPageState extends State<PluginEditorPage> {
PluginsController get pluginsController => widget.controller;
+ final _formScroll = ScrollController();
+ int _section = 0;
+ bool _saving = false;
+ String? _editorError;
final TextEditingController nameController = TextEditingController();
final TextEditingController versionController = TextEditingController();
final TextEditingController userAgentController = TextEditingController();
@@ -350,6 +354,7 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
@override
void dispose() {
+ _formScroll.dispose();
nameController.dispose();
versionController.dispose();
userAgentController.dispose();
@@ -399,147 +404,206 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
return const JsonEncoder.withIndent(' ').convert(value);
}
+ void _testRule() {
+ final editedPlugin = _tryBuildEditedPlugin();
+ if (editedPlugin == null) return;
+ context.pushNamed('/settings/plugin/test', arguments: editedPlugin);
+ }
+
+ Future<void> _save() async {
+ if (_saving) return;
+ final editedPlugin = _tryBuildEditedPlugin();
+ if (editedPlugin == null) return;
+ setState(() {
+ _saving = true;
+ _editorError = null;
+ });
+ try {
+ await pluginsController.updatePlugin(editedPlugin);
+ if (mounted) context.pop();
+ } catch (error) {
+ _showEditorError(error);
+ } finally {
+ if (mounted) setState(() => _saving = false);
+ }
+ }
+
@override
Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
return Scaffold(
- appBar: SysAppBar(
- title: const Text(_RuleEditorText.pageTitle),
- actions: [
- IconButton(
- tooltip: _RuleEditorText.testRule,
- icon: const Icon(Icons.bug_report_outlined),
- onPressed: () {
- final editedPlugin = _tryBuildEditedPlugin();
- if (editedPlugin == null) return;
- context.pushNamed(
- '/settings/plugin/test',
- arguments: editedPlugin,
- );
- },
+ appBar: const SysAppBar(title: Text(_RuleEditorText.pageTitle)),
+ body: SafeArea(
+ top: false,
+ bottom: false,
+ child: SingleChildScrollView(
+ controller: _formScroll,
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 900),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ RulePageIntro(
+ title: widget.plugin.name.isEmpty
+ ? '编写新规则'
+ : widget.plugin.name,
+ description: '从站点信息到搜索与选集,逐步配置你的番剧来源。',
+ icon: Icons.edit_note_rounded,
+ ),
+ const SizedBox(height: 20),
+ if (_editorError != null) ...[
+ Semantics(
+ liveRegion: true,
+ child: Container(
+ padding: const EdgeInsets.all(16),
+ decoration: BoxDecoration(
+ color: colors.errorContainer,
+ borderRadius: BorderRadius.circular(20)),
+ child: Text(_editorError!,
+ style: TextStyle(color: colors.onErrorContainer)),
+ ),
+ ),
+ const SizedBox(height: 16),
+ ],
+ EditorChoiceGroup<int>(
+ value: _section,
+ segments: const [
+ ButtonSegment(value: 0, label: Text('基本')),
+ ButtonSegment(value: 1, label: Text('搜索')),
+ ButtonSegment(value: 2, label: Text('选集')),
+ ButtonSegment(value: 3, label: Text('高级')),
+ ],
+ onChanged: (value) => setState(() => _section = value),
+ ),
+ const SizedBox(height: 16),
+ _buildCurrentSection(),
+ ],
+ ),
+ ),
),
- ],
+ ),
),
- body: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
- child: Center(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 1000),
- child: Column(
- spacing: 16,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- ContentSection(
- title: _RuleEditorText.sectionBasic,
- description: _RuleEditorText.sectionBasicDesc,
- 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,
- ),
- ]),
- ),
- ContentSection(
- title: _RuleEditorText.sectionSearch,
- description: _RuleEditorText.sectionSearchDesc,
- 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(),
- ),
- ),
- ]),
- ),
- ContentSection(
- title: _RuleEditorText.sectionChapter,
- description: _RuleEditorText.sectionChapterDesc,
- 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(),
- ],
+ bottomNavigationBar: Material(
+ color: colors.surfaceContainerLow,
+ child: SafeArea(
+ top: false,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Align(
+ heightFactor: 1,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 900),
+ child: Row(children: [
+ Expanded(
+ child: FilledButton.tonalIcon(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(0, 48)),
+ onPressed: _saving ? null : _testRule,
+ icon: const Icon(Icons.science_outlined),
+ label: Text(
+ MediaQuery.textScalerOf(context).scale(14) > 20
+ ? '测试'
+ : _RuleEditorText.testRule))),
+ const SizedBox(width: 12),
+ Expanded(
+ child: FilledButton.icon(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(0, 48)),
+ onPressed: _saving ? null : _save,
+ icon: _saving
+ ? const LoadingIndicator(size: 20)
+ : const Icon(Icons.check_rounded),
+ label: Text(_saving ? '保存中' : _RuleEditorText.save))),
+ ]),
+ ),
),
),
),
),
- floatingActionButton: FloatingActionButton.extended(
- heroTag: null,
- icon: const Icon(Icons.save_rounded),
- label: const Text(_RuleEditorText.save),
- onPressed: () async {
- final editedPlugin = _tryBuildEditedPlugin();
- if (editedPlugin == null) return;
- try {
- await pluginsController.updatePlugin(editedPlugin);
- } catch (error) {
- _showEditorError(error);
- return;
- }
- if (!context.mounted) return;
- context.pop();
- },
+ );
+ }
+
+ Widget _buildCurrentSection() {
+ if (_section == 3) return _buildAdvancedOptionsCard();
+ final isSearch = _section == 1;
+ return RuleSection(
+ key: ValueKey(_section),
+ title: switch (_section) {
+ 0 => _RuleEditorText.sectionBasic,
+ 1 => _RuleEditorText.sectionSearch,
+ _ => _RuleEditorText.sectionChapter,
+ },
+ description: switch (_section) {
+ 0 => _RuleEditorText.sectionBasicDesc,
+ 1 => _RuleEditorText.sectionSearchDesc,
+ _ => _RuleEditorText.sectionChapterDesc,
+ },
+ icon: switch (_section) {
+ 0 => Icons.info_outline_rounded,
+ 1 => Icons.search_rounded,
+ _ => Icons.video_library_outlined,
+ },
+ child: Column(
+ spacing: 20,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: _section == 0
+ ? [
+ EditorTextField(
+ controller: nameController,
+ label: _RuleEditorText.ruleName),
+ EditorTextField(
+ controller: versionController,
+ label: _RuleEditorText.ruleVersion),
+ EditorTextField(
+ controller: baseURLController,
+ label: _RuleEditorText.baseUrl),
+ ]
+ : [
+ EditorSegmentedField<String>(
+ label: isSearch
+ ? _RuleEditorText.searchRuleType
+ : _RuleEditorText.chapterRuleType,
+ value: isSearch ? searchMode : chapterMode,
+ segments: _ruleModeSegments,
+ description: (mode) => mode == RuleMode.api
+ ? '请求接口并从 JSON 响应中提取数据。'
+ : '从网页 HTML 中定位并提取内容。',
+ onChanged: (value) => setState(() {
+ if (isSearch) {
+ searchMode = value;
+ } else {
+ chapterMode = value;
+ }
+ }),
+ ),
+ EditorAnimatedSection(
+ activeKey: isSearch ? searchMode : chapterMode,
+ child: Column(
+ spacing: 20,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: isSearch
+ ? (searchMode == RuleMode.xpath
+ ? _buildXPathSearchFields()
+ : _buildApiSearchFields())
+ : (chapterMode == RuleMode.xpath
+ ? _buildXPathChapterFields()
+ : _buildApiChapterFields()),
+ ),
+ ),
+ ],
),
);
}
Widget _buildAdvancedOptionsCard() {
- 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),
- ),
+ return RuleSection(
+ title: _RuleEditorText.advancedOptions,
+ description: _RuleEditorText.advancedOptionsDesc,
+ icon: Icons.tune_rounded,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const EditorSubheader(label: _RuleEditorText.groupBehavior),
SwitchListTile(
@@ -1068,8 +1132,11 @@ class _PluginEditorPageState extends State<PluginEditorPage> {
void _showEditorError(Object error) {
if (!mounted) return;
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(content: Text(error.toString())),
- );
+ setState(() => _editorError = error.toString());
+ if (_formScroll.hasClients) {
+ _formScroll.animateTo(0,
+ duration: const Duration(milliseconds: 250),
+ curve: Curves.easeOutCubic);
+ }
}
}
diff --git a/lib/pages/plugin_editor/plugin_shop_page.dart b/lib/pages/plugin_editor/plugin_shop_page.dart
index f1a39569..d1f31ad8 100644
--- a/lib/pages/plugin_editor/plugin_shop_page.dart
+++ b/lib/pages/plugin_editor/plugin_shop_page.dart
@@ -3,51 +3,22 @@ import 'package:kazumi/bean/appbar/sys_app_bar.dart';
import 'package:kazumi/pages/plugin_editor/plugin_catalog_view.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
-class PluginShopPage extends StatefulWidget {
- const PluginShopPage({
- super.key,
- required this.controller,
- });
-
+class PluginShopPage extends StatelessWidget {
+ const PluginShopPage({super.key, required this.controller});
final PluginsController controller;
@override
- State<PluginShopPage> createState() => _PluginShopPageState();
-}
-
-class _PluginShopPageState extends State<PluginShopPage> {
- final catalogKey = GlobalKey<PluginCatalogViewState>();
- bool sortByName = false;
-
- void _toggleSort() {
- setState(() {
- sortByName = !sortByName;
- });
- }
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: SysAppBar(
- title: const Text('规则仓库'),
- actions: [
- IconButton(
- onPressed: _toggleSort,
- tooltip: sortByName ? '按名称排序' : '按更新时间排序',
- icon: Icon(sortByName ? Icons.sort_by_alpha : Icons.access_time)),
- IconButton(
- onPressed: () => catalogKey.currentState?.refresh(),
- tooltip: '刷新规则列表',
- icon: const Icon(Icons.refresh))
- ],
- ),
- body: PluginCatalogView(
- key: catalogKey,
- controller: widget.controller,
- sort:
- sortByName ? PluginCatalogSort.name : PluginCatalogSort.lastUpdate,
- errorMessage: '啊咧(⊙.⊙) 无法访问规则仓库',
- ),
- );
- }
+ Widget build(BuildContext context) => Scaffold(
+ appBar: const SysAppBar(title: Text('规则仓库')),
+ body: SafeArea(
+ top: false,
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1000),
+ child: PluginCatalogView(controller: controller),
+ ),
+ ),
+ ),
+ );
}
diff --git a/lib/pages/plugin_editor/plugin_test_page.dart b/lib/pages/plugin_editor/plugin_test_page.dart
index 6fbbc32d..bbde1a3c 100644
--- a/lib/pages/plugin_editor/plugin_test_page.dart
+++ b/lib/pages/plugin_editor/plugin_test_page.dart
@@ -1,35 +1,21 @@
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:flutter/services.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/roads/road_module.dart';
import 'package:kazumi/modules/search/plugin_search_module.dart';
+import 'package:kazumi/pages/plugin_editor/rule_management_widgets.dart';
+import 'package:kazumi/plugins/api_rule_config.dart';
+import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/services/logging/logger.dart';
const _h8 = SizedBox(height: 8.0);
const _h12 = SizedBox(height: 12.0);
-enum CoreColorType { error, success, waiting }
-
-extension CoreColorExtension on ThemeData {
- Color getCoreColor(CoreColorType type) {
- switch (type) {
- case CoreColorType.error:
- return colorScheme.error;
- case CoreColorType.success:
- return colorScheme.primary;
- case CoreColorType.waiting:
- return colorScheme.onSurfaceVariant;
- }
- }
-}
-
class PluginTestPage extends StatefulWidget {
const PluginTestPage({
super.key,
@@ -54,6 +40,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
PluginSearchResponse? searchRes;
List<Road>? chapters;
bool isTesting = false;
+ bool _hasRun = false;
+ int _runId = 0;
String errorMsg = "";
List<String> searchDiagnostics = [];
List<String> chapterDiagnostics = [];
@@ -69,8 +57,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
bool get _needChapterParse =>
plugin.chapterMode == RuleMode.api || plugin.chapterRoads.isNotEmpty;
- CancelToken? _testSearchRequestCancelToken;
- CancelToken? _testRoadsCancelToken;
+ CancelToken? _testCancelToken;
@override
void initState() {
@@ -82,8 +69,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
@override
void dispose() {
- _testSearchRequestCancelToken?.cancel();
- _testRoadsCancelToken?.cancel();
+ _testCancelToken?.cancel();
testKeywordController.dispose();
searchRawScrollController.dispose();
chapterScrollController.dispose();
@@ -91,14 +77,12 @@ class _PluginTestPageState extends State<PluginTestPage> {
super.dispose();
}
- void _onBackPressed() =>
- KazumiDialog.observer.hasKazumiDialog ? KazumiDialog.dismiss() : null;
-
void _resetState() => setState(() {
- _testSearchRequestCancelToken?.cancel();
- _testSearchRequestCancelToken = null;
- _testRoadsCancelToken?.cancel();
- _testRoadsCancelToken = null;
+ _runId++;
+ isTesting = false;
+ _hasRun = false;
+ _testCancelToken?.cancel();
+ _testCancelToken = null;
searchRaw = "";
chapterRaw = "";
searchRes = null;
@@ -110,109 +94,148 @@ class _PluginTestPageState extends State<PluginTestPage> {
_shownFragmentIndex = null;
});
- void _toggleFragment(int index) {
- if (_shownFragmentIndex == index) {
- return setState(() => _shownFragmentIndex = null);
- }
- setState(() => _shownFragmentIndex = index);
- }
+ void _toggleFragment(int index) => setState(
+ () => _shownFragmentIndex = _shownFragmentIndex == index ? null : index);
- Future<void> startTest() async {
+ Future<void> _startTest() async {
+ if (isTesting) return;
final keyword = testKeywordController.text.trim();
+ if (keyword.isEmpty) {
+ setState(() => errorMsg = '请输入一个番剧名称作为测试关键词。');
+ return;
+ }
_resetState();
- setState(() => isTesting = true);
+ // Ignore late responses from requests that do not honor cancellation.
+ final runId = _runId;
+ final cancelToken = _testCancelToken = CancelToken();
+ setState(() {
+ isTesting = true;
+ _hasRun = true;
+ });
try {
- _testSearchRequestCancelToken?.cancel();
- _testSearchRequestCancelToken = CancelToken();
- final searchTrace = await plugin.traceSearch(
- keyword,
- cancelToken: _testSearchRequestCancelToken,
- );
- searchRaw = searchTrace.rawResponse;
- searchRes = searchTrace.response;
- searchDiagnostics = searchTrace.diagnostics;
- _itemFragmentMap.addAll(searchTrace.matchedFragments.asMap());
+ final searchTrace =
+ await plugin.traceSearch(keyword, cancelToken: cancelToken);
+ if (!mounted || runId != _runId) return;
+ setState(() {
+ searchRaw = searchTrace.rawResponse;
+ searchRes = searchTrace.response;
+ searchDiagnostics = searchTrace.diagnostics;
+ _itemFragmentMap.addAll(searchTrace.matchedFragments.asMap());
+ });
if (_hasSearchData && _needChapterParse) {
final firstItem = searchRes!.data.first;
if (firstItem.src.isNotEmpty) {
- _testRoadsCancelToken?.cancel();
- _testRoadsCancelToken = CancelToken();
- final chapterTrace = await plugin.traceChapters(
- firstItem.src,
- cancelToken: _testRoadsCancelToken,
- );
- chapterRaw = chapterTrace.rawResponse;
- chapters = chapterTrace.roads;
- chapterDiagnostics = chapterTrace.diagnostics;
+ final chapterTrace = await plugin.traceChapters(firstItem.src,
+ cancelToken: cancelToken);
+ if (!mounted || runId != _runId) return;
+ setState(() {
+ chapterRaw = chapterTrace.rawResponse;
+ chapters = chapterTrace.roads;
+ chapterDiagnostics = chapterTrace.diagnostics;
+ });
}
}
- } catch (e, stack) {
- KazumiLogger().e("PluginTest: test failed", error: e, stackTrace: stack);
- if (mounted) {
- setState(() => errorMsg = e.toString());
- }
+ } catch (error, stack) {
+ if (!mounted || runId != _runId) return;
+ KazumiLogger()
+ .e('PluginTest: test failed', error: error, stackTrace: stack);
+ setState(() => errorMsg = error.toString());
} finally {
- if (mounted) setState(() => isTesting = false);
+ if (mounted && runId == _runId) setState(() => isTesting = false);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
- return PopScope(
- canPop: true,
- onPopInvokedWithResult: (didPop, _) => !didPop ? _onBackPressed() : null,
- child: Scaffold(
- appBar: SysAppBar(
- title: Text('${plugin.name} 测试'),
- actions: [
- IconButton(
- onPressed: isTesting ? null : startTest,
- icon: const Icon(Icons.bug_report_outlined),
- tooltip: '开始测试',
- ),
- IconButton(
- onPressed: _resetState,
- icon: const Icon(Icons.refresh),
- tooltip: '重置',
- ),
- ],
- ),
- body: SingleChildScrollView(
- padding: const EdgeInsets.all(16.0),
+ return Scaffold(
+ appBar: SysAppBar(
+ title: const Text('规则测试'),
+ actions: [
+ IconButton(
+ onPressed: _resetState,
+ icon: const Icon(Icons.restart_alt_rounded),
+ tooltip: '重置测试',
+ ),
+ const SizedBox(width: 8),
+ ],
+ ),
+ body: SafeArea(
+ top: false,
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 32),
child: Center(
child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 1000),
+ constraints: const BoxConstraints(maxWidth: 900),
child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _buildKeywordInput(theme),
- _h12,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ RulePageIntro(
+ title: plugin.name,
+ description: '一次测试,检查搜索请求、结果解析和播放线路。',
+ icon: Icons.science_outlined,
+ ),
+ const SizedBox(height: 20),
+ RuleSection(
+ title: '试着搜索一部番剧',
+ description: '选集测试会使用第一条搜索结果。',
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _buildKeywordInput(),
+ const SizedBox(height: 16),
+ Align(
+ alignment: AlignmentDirectional.centerEnd,
+ child: FilledButton.icon(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(132, 48)),
+ onPressed: isTesting ? _resetState : _startTest,
+ icon: Icon(isTesting
+ ? Icons.stop_rounded
+ : Icons.play_arrow_rounded),
+ label: Text(isTesting ? '停止测试' : '开始测试'),
+ ),
+ ),
+ if (isTesting) ...[
+ const SizedBox(height: 16),
+ const LinearProgressIndicator(),
+ ],
+ ],
+ ),
+ ),
+ if (errorMsg.isNotEmpty && !isTesting) ...[
+ const SizedBox(height: 16),
_buildErrorWidget(theme),
- _buildExpansionTile(
+ ],
+ const SizedBox(height: 20),
+ _buildExpansionTile(
theme: theme,
- title: '1. 搜索请求测试',
+ number: 1,
+ title: '搜索请求',
subtitle: _getSearchSubtitle(),
+ completed: _hasSearchRaw,
expanded: false,
- child: _buildSearchContent(theme),
- ),
- _h12,
- _buildExpansionTile(
+ child: _buildSearchContent(theme)),
+ _h12,
+ _buildExpansionTile(
theme: theme,
- title: '2. 搜索解析测试',
+ number: 2,
+ title: '结果解析',
subtitle: _getParseSubtitle(),
- expanded: false,
- child: _buildParseContent(theme),
- ),
- _h12,
- _buildExpansionTile(
+ completed: _hasSearchData,
+ expanded: _hasSearchData,
+ child: _buildParseContent(theme)),
+ _h12,
+ _buildExpansionTile(
theme: theme,
- title: '3. 章节列表测试',
+ number: 3,
+ title: '播放线路',
subtitle: _getChapterSubtitle(),
- expanded: _hasSearchData,
- child: _buildChapterContent(theme),
- ),
- ]),
+ completed: _hasChapters,
+ expanded: _hasChapters,
+ child: _buildChapterContent(theme)),
+ ],
+ ),
),
),
),
@@ -222,81 +245,112 @@ class _PluginTestPageState extends State<PluginTestPage> {
Widget _buildExpansionTile({
required ThemeData theme,
+ required int number,
required String title,
required String subtitle,
+ required bool completed,
required bool expanded,
required Widget child,
}) {
- return ExpansionTile(
- title: Text(title, style: theme.textTheme.titleMedium),
- subtitle: Text(subtitle,
- style: TextStyle(
- fontSize: 12.0, color: _getSubtitleColor(subtitle, theme))),
- initiallyExpanded: expanded,
- shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
- iconColor: theme.getCoreColor(CoreColorType.success),
- collapsedIconColor: theme.getCoreColor(CoreColorType.waiting),
- children: [_h8, child, _h8],
+ final colors = theme.colorScheme;
+ final failed = _hasRun &&
+ !isTesting &&
+ !completed &&
+ switch (number) {
+ 1 => true,
+ 2 => _hasSearchRaw,
+ _ => _hasSearchData && _needChapterParse,
+ };
+ final foreground = completed
+ ? colors.onTertiaryContainer
+ : failed
+ ? colors.onErrorContainer
+ : colors.onSurfaceVariant;
+ return Material(
+ color: colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(28),
+ clipBehavior: Clip.antiAlias,
+ child: ExpansionTile(
+ key: ValueKey('$number-$_hasRun-$completed'),
+ tilePadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
+ childrenPadding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
+ leading: Container(
+ width: 40,
+ height: 40,
+ decoration: BoxDecoration(
+ color: completed
+ ? colors.tertiaryContainer
+ : failed
+ ? colors.errorContainer
+ : colors.surfaceContainerHighest,
+ borderRadius: BorderRadius.circular(completed ? 20 : 12)),
+ child: Center(
+ child: completed
+ ? Icon(Icons.check_rounded, color: foreground)
+ : failed
+ ? Icon(Icons.error_outline_rounded, color: foreground)
+ : Text('$number',
+ style: theme.textTheme.titleMedium
+ ?.copyWith(color: foreground))),
+ ),
+ title: Text(title,
+ style: theme.textTheme.titleMedium
+ ?.copyWith(fontWeight: FontWeight.w600)),
+ subtitle: Text(subtitle,
+ style: theme.textTheme.bodySmall
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ initiallyExpanded: expanded,
+ shape: const Border(),
+ collapsedShape: const Border(),
+ children: [child],
+ ),
);
}
- Widget _buildKeywordInput(ThemeData theme) => TextField(
+ Widget _buildKeywordInput() => TextField(
controller: testKeywordController,
- decoration: InputDecoration(
- labelText: '测试关键词',
- border: OutlineInputBorder(
- borderSide:
- BorderSide(color: theme.getCoreColor(CoreColorType.waiting))),
- focusedBorder: OutlineInputBorder(
- borderSide:
- BorderSide(color: theme.getCoreColor(CoreColorType.success))),
- labelStyle:
- TextStyle(color: theme.getCoreColor(CoreColorType.waiting)),
- ),
+ decoration: ruleInputDecoration(context,
+ label: '测试关键词',
+ hint: '输入番剧名称',
+ prefix: const Icon(Icons.search_rounded)),
enabled: !isTesting,
- onSubmitted: (_) => startTest(),
- style: theme.textTheme.bodyLarge,
+ textInputAction: TextInputAction.search,
+ onSubmitted: (_) => _startTest(),
);
- Widget _buildErrorWidget(ThemeData theme) => errorMsg.isEmpty || isTesting
- ? const SizedBox.shrink()
- : Container(
- padding: const EdgeInsets.all(12.0),
- decoration: BoxDecoration(
- color: theme.colorScheme.errorContainer,
- border: Border.all(color: theme.getCoreColor(CoreColorType.error)),
- borderRadius: BorderRadius.circular(8),
+ Widget _buildErrorWidget(ThemeData theme) => Container(
+ padding: const EdgeInsets.all(12.0),
+ decoration: BoxDecoration(
+ color: theme.colorScheme.errorContainer,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Icon(Icons.error_outline, color: theme.colorScheme.error, size: 20),
+ const SizedBox(width: 12),
+ Expanded(
+ child:
+ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(errorMsg,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: theme.colorScheme.onErrorContainer)),
+ _h8,
+ TextButton(
+ onPressed: _startTest,
+ style: TextButton.styleFrom(
+ backgroundColor:
+ theme.colorScheme.error.withValues(alpha: 0.1)),
+ child: Text('重试测试',
+ style:
+ TextStyle(color: theme.colorScheme.onErrorContainer)),
+ ),
+ ]),
),
- child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
- Icon(Icons.error_outline,
- color: theme.getCoreColor(CoreColorType.error), size: 20),
- _h8,
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(errorMsg,
- style: theme.textTheme.bodyMedium?.copyWith(
- color: theme.colorScheme.onErrorContainer)),
- _h8,
- TextButton(
- onPressed: startTest,
- style: TextButton.styleFrom(
- backgroundColor: theme
- .getCoreColor(CoreColorType.error)
- .withValues(alpha: 0.1)),
- child: Text('重试测试',
- style: TextStyle(
- color: theme.colorScheme.onErrorContainer)),
- ),
- ]),
- ),
- ]),
- );
+ ]),
+ );
Widget _buildLoading(ThemeData theme) => Center(
child: LoadingIndicator(
- color: theme.getCoreColor(CoreColorType.success),
+ color: theme.colorScheme.primary,
),
);
@@ -308,60 +362,81 @@ class _PluginTestPageState extends State<PluginTestPage> {
text,
style: theme.textTheme.bodyMedium?.copyWith(
color: isError
- ? theme.getCoreColor(CoreColorType.error)
- : theme.getCoreColor(CoreColorType.waiting),
+ ? theme.colorScheme.error
+ : theme.colorScheme.onSurfaceVariant,
),
),
),
);
String _getSearchSubtitle() {
- if (isTesting) return '测试中...';
- if (!_hasSearchRaw) return '未执行测试';
+ if (isTesting && !_hasSearchRaw) return '正在请求站点…';
+ if (!_hasSearchRaw) return _hasRun ? '没有收到响应' : '等待开始';
return '${plugin.searchMode == RuleMode.api ? 'JSON' : 'HTML'}长度:${searchRaw.length} 字符';
}
- Color _getSubtitleColor(String subtitle, ThemeData theme) {
- if (subtitle.contains('测试中') ||
- subtitle.contains('获取中') ||
- subtitle.contains('解析中')) {
- return theme.getCoreColor(CoreColorType.waiting);
- }
- if (subtitle.contains('失败') ||
- subtitle.contains('无可用') ||
- subtitle.contains('无有效') ||
- subtitle.contains('跳过')) {
- return theme.getCoreColor(CoreColorType.error);
- }
- return theme.getCoreColor(CoreColorType.success);
- }
-
- Widget _buildSearchContent(ThemeData theme) {
- if (isTesting) return _buildLoading(theme);
- if (!_hasSearchRaw) return _buildEmpty('点击顶部「开始测试」按钮执行', theme);
+ Widget _codePanel(String raw, ThemeData theme,
+ {ScrollController? controller}) {
return Container(
- margin: const EdgeInsets.only(bottom: 8.0),
- padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(8),
- border: Border.all(color: theme.getCoreColor(CoreColorType.waiting)),
- color: theme.colorScheme.surface,
- ),
- height: 250,
- child: SingleChildScrollView(
- controller: searchRawScrollController,
- physics: const ClampingScrollPhysics(),
- child: SelectableText(
- _formattedRaw(searchRaw, isJson: plugin.searchMode == RuleMode.api),
- style: theme.textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
- ),
+ color: theme.colorScheme.surfaceContainerHighest,
+ borderRadius: BorderRadius.circular(16)),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(left: 16, right: 4, top: 4),
+ child: Row(children: [
+ Expanded(child: Text('响应内容', style: theme.textTheme.labelLarge)),
+ IconButton(
+ tooltip: '复制响应内容',
+ onPressed: () async {
+ try {
+ await Clipboard.setData(ClipboardData(text: raw));
+ if (mounted) {
+ KazumiDialog.showToast(
+ context: context, message: '已复制响应内容');
+ }
+ } catch (_) {
+ if (mounted) {
+ KazumiDialog.showToast(
+ context: context, message: '复制失败,请重试');
+ }
+ }
+ },
+ icon: const Icon(Icons.copy_rounded, size: 18)),
+ ]),
+ ),
+ SizedBox(
+ height: 220,
+ child: Scrollbar(
+ controller: controller,
+ child: SingleChildScrollView(
+ controller: controller,
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
+ child: SelectableText(raw,
+ style: theme.textTheme.bodySmall
+ ?.copyWith(fontFamily: 'monospace')),
+ ),
+ ),
+ ),
+ ],
),
);
}
+ Widget _buildSearchContent(ThemeData theme) {
+ if (isTesting && !_hasSearchRaw) return _buildLoading(theme);
+ if (!_hasSearchRaw) return _buildEmpty('输入关键词后,点击「开始测试」。', theme);
+ return _codePanel(
+ _formattedRaw(searchRaw, isJson: plugin.searchMode == RuleMode.api),
+ theme,
+ controller: searchRawScrollController);
+ }
+
String _getParseSubtitle() {
- if (isTesting && _shownFragmentIndex == null) return '解析中...';
- if (!_hasSearchRaw) return '未执行解析';
+ if (isTesting && !_hasSearchRaw) return '等待搜索响应';
+ if (!_hasSearchRaw) return _hasRun ? '等待有效响应' : '等待开始';
if (!_hasSearchData) return '未解析到结果';
final skipped =
searchDiagnostics.isEmpty ? '' : ',跳过 ${searchDiagnostics.length} 条';
@@ -369,7 +444,7 @@ class _PluginTestPageState extends State<PluginTestPage> {
}
Widget _buildParseContent(ThemeData theme) {
- if (isTesting && _shownFragmentIndex == null) return _buildLoading(theme);
+ if (isTesting && !_hasSearchRaw) return _buildLoading(theme);
if (!_hasSearchRaw) return _buildEmpty('请先完成搜索请求测试', theme);
if (!_hasSearchData) return _buildEmpty('未解析到搜索结果', theme, isError: true);
@@ -394,20 +469,20 @@ class _PluginTestPageState extends State<PluginTestPage> {
padding: const EdgeInsets.all(12.0),
decoration: BoxDecoration(
color: theme.colorScheme.errorContainer,
- border: Border.all(color: theme.getCoreColor(CoreColorType.error)),
- borderRadius: BorderRadius.circular(8),
+ borderRadius: BorderRadius.circular(20),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Icon(Icons.warning_amber_outlined,
- color: theme.getCoreColor(CoreColorType.error), size: 20),
+ color: theme.colorScheme.error, size: 20),
const SizedBox(width: 8.0),
- Text('部分节点被跳过(${diagnostics.length})',
- style: theme.textTheme.bodyMedium?.copyWith(
- color: theme.colorScheme.onErrorContainer,
- fontWeight: FontWeight.w500)),
+ Expanded(
+ child: Text('部分节点被跳过(${diagnostics.length})',
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: theme.colorScheme.onErrorContainer,
+ fontWeight: FontWeight.w500))),
]),
_h8,
...diagnostics.map(
@@ -430,7 +505,9 @@ class _PluginTestPageState extends State<PluginTestPage> {
return Column(children: [
Card(
margin: const EdgeInsets.only(bottom: 8.0),
- elevation: 1,
+ elevation: 0,
+ color: theme.colorScheme.surfaceContainerHighest,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child:
@@ -450,45 +527,31 @@ class _PluginTestPageState extends State<PluginTestPage> {
icon: Icon(
isShowingFragment ? Icons.keyboard_arrow_up : Icons.code,
size: 18,
- color: theme.getCoreColor(CoreColorType.success),
+ color: theme.colorScheme.primary,
),
tooltip: isShowingFragment ? '隐藏匹配片段' : '查看匹配片段',
),
]),
_h8,
Text('链接:${item.src}',
- style: theme.textTheme.bodySmall?.copyWith(
- color: theme.getCoreColor(CoreColorType.waiting))),
+ style: theme.textTheme.bodySmall
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),
]),
),
),
if (isShowingFragment)
- Container(
- margin: const EdgeInsets.only(bottom: 8.0),
- padding: const EdgeInsets.all(8.0),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(8),
- border:
- Border.all(color: theme.getCoreColor(CoreColorType.waiting)),
- color: theme.colorScheme.surface,
- ),
- height: 250,
- child: SingleChildScrollView(
- controller: fragmentScrollController,
- physics: const ClampingScrollPhysics(),
- child: SelectableText(
- fragment,
- style:
- theme.textTheme.bodySmall?.copyWith(fontFamily: 'monospace'),
- ),
- ),
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child:
+ _codePanel(fragment, theme, controller: fragmentScrollController),
),
]);
}
String _getChapterSubtitle() {
- if (isTesting) return '获取中...';
- if (!_hasSearchData) return '无有效搜索结果';
+ if (!_hasRun) return '等待开始';
+ if (isTesting) return _hasSearchData ? '正在获取播放线路…' : '等待搜索结果';
+ if (!_hasSearchData) return '等待有效搜索结果';
if (!_needChapterParse) return '无需解析章节';
if (chapters == null) return '未获取章节数据';
final skipped =
@@ -507,26 +570,12 @@ class _PluginTestPageState extends State<PluginTestPage> {
children: [
_buildDiagnosticsWidget(chapterDiagnostics, theme),
if (chapterRaw.isNotEmpty)
- Container(
- margin: const EdgeInsets.only(bottom: 8),
- padding: const EdgeInsets.all(8),
- constraints: const BoxConstraints(maxHeight: 220),
- width: double.infinity,
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(8),
- border:
- Border.all(color: theme.getCoreColor(CoreColorType.waiting)),
- ),
- child: SingleChildScrollView(
- child: SelectableText(
- _formattedRaw(
- chapterRaw,
- isJson: plugin.chapterMode == RuleMode.api,
- ),
- style: theme.textTheme.bodySmall
- ?.copyWith(fontFamily: 'monospace'),
- ),
- ),
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: _codePanel(
+ _formattedRaw(chapterRaw,
+ isJson: plugin.chapterMode == RuleMode.api),
+ theme),
),
Container(
padding: const EdgeInsets.all(8.0),
@@ -552,7 +601,9 @@ class _PluginTestPageState extends State<PluginTestPage> {
Widget _buildChapterCard(Road road, int i, ThemeData theme) => Card(
margin: const EdgeInsets.only(bottom: 8.0),
- elevation: 1,
+ elevation: 0,
+ color: theme.colorScheme.surfaceContainerHighest,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
@@ -566,8 +617,8 @@ class _PluginTestPageState extends State<PluginTestPage> {
),
_h8,
Text('章节数量:${road.data.length}',
- style: theme.textTheme.bodySmall?.copyWith(
- color: theme.getCoreColor(CoreColorType.waiting))),
+ style: theme.textTheme.bodySmall
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),
_h8,
SizedBox(
width: double.infinity,
diff --git a/lib/pages/plugin_editor/plugin_view_page.dart b/lib/pages/plugin_editor/plugin_view_page.dart
index 24ce25fc..4abc42fc 100644
--- a/lib/pages/plugin_editor/plugin_view_page.dart
+++ b/lib/pages/plugin_editor/plugin_view_page.dart
@@ -9,20 +9,18 @@ import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/bean/card/rule_card.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
-import 'package:kazumi/plugins/plugins.dart';
-import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';
+import 'package:kazumi/bean/widget/loading_indicator.dart';
import 'package:kazumi/pages/plugin_editor/plugin_update_actions.dart';
+import 'package:kazumi/pages/plugin_editor/rule_dialogs.dart';
+import 'package:kazumi/pages/plugin_editor/rule_management_widgets.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/plugin_import_parser.dart';
-import 'package:kazumi/utils/encoding.dart';
class PluginViewPage extends StatefulWidget {
- const PluginViewPage({
- super.key,
- required this.controller,
- });
-
+ const PluginViewPage({super.key, required this.controller});
final PluginsController controller;
@override
@@ -30,583 +28,468 @@ class PluginViewPage extends StatefulWidget {
}
class _PluginViewPageState extends State<PluginViewPage> {
- PluginsController get pluginsController => widget.controller;
-
- // 是否处于多选模式
- bool isMultiSelectMode = false;
+ PluginsController get _controller => widget.controller;
+ final _search = TextEditingController();
+ final Set<String> _selected = {};
+ final Set<String> _updatingNames = {};
+ bool _selecting = false;
+ bool _updatesOnly = false;
+ bool _updating = false;
+ bool _deleting = false;
+ bool _catalogFailed = false;
- // 已选中的规则名称集合
- final Set<String> selectedNames = {};
+ @override
+ void initState() {
+ super.initState();
+ unawaited(_loadUpdateStatus());
+ }
- Future<void> _handleUpdate() async {
- await updateAllPluginsWithFeedback(
- pluginsController,
- ensureCatalog: true,
- );
- if (mounted) {
- setState(() {});
- }
+ @override
+ void dispose() {
+ _search.dispose();
+ super.dispose();
}
- Future<void> _handleReorder(int oldIndex, int newIndex) async {
+ Future<void> _loadUpdateStatus() async {
try {
- await pluginsController.onReorder(oldIndex, newIndex);
+ await _controller.ensurePluginCatalog();
+ if (mounted) setState(() => _catalogFailed = false);
} catch (_) {
- KazumiDialog.showToast(message: '保存规则顺序失败');
+ if (mounted) setState(() => _catalogFailed = true);
}
}
- void _handleAdd() {
- KazumiDialog.show(builder: (context) {
- return AlertDialog(
- content: SingleChildScrollView(
- // 使用可滚动的SingleChildScrollView包装Column
- child: Column(
- mainAxisSize: MainAxisSize.min, // 设置为MainAxisSize.min以减小高度
- children: [
- ListTile(
- title: const Text('新建规则'),
- onTap: () {
- KazumiDialog.dismiss();
- context.pushNamed('/settings/plugin/editor',
- arguments: Plugin.fromTemplate());
- },
- ),
- const SizedBox(height: 10),
- ListTile(
- title: const Text('从规则仓库导入'),
- onTap: () {
- KazumiDialog.dismiss();
- context.pushNamed('/settings/plugin/shop',
- arguments: Plugin.fromTemplate());
- },
- ),
- const SizedBox(height: 10),
- ListTile(
- title: const Text('从剪贴板导入'),
- onTap: () async {
- KazumiDialog.dismiss();
- final clipboard =
- await Clipboard.getData(Clipboard.kTextPlain);
- if (!mounted) return;
- _showInputDialog(initialValue: clipboard?.text ?? '');
- },
- ),
- const SizedBox(height: 10),
- ListTile(
- title: const Text('从文件导入'),
- onTap: () {
- KazumiDialog.dismiss();
- _importFromFile();
- },
- ),
- ],
- ),
- ),
- );
- });
+ Future<void> _updateAll() async {
+ if (_updating) return;
+ setState(() => _updating = true);
+ await updateAllPluginsWithFeedback(_controller, ensureCatalog: true);
+ if (mounted) {
+ setState(() {
+ _updating = false;
+ _catalogFailed = !_controller.isPluginCatalogFresh;
+ });
+ }
}
- void _showInputDialog({String initialValue = ''}) {
- var pluginText = initialValue;
- KazumiDialog.show(
- builder: (context) {
- return AlertDialog(
- title: const Text('从剪贴板导入规则'),
- content: SizedBox(
- width: 520,
- child: TextFormField(
- initialValue: initialValue,
- onChanged: (value) => pluginText = value,
- minLines: 4,
- maxLines: 10,
- decoration: const InputDecoration(
- hintText: '可粘贴多条 kazumi:// 链接或 JSON 数组',
- border: OutlineInputBorder(),
- ),
- ),
- ),
- actions: [
- TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(color: Theme.of(context).colorScheme.outline),
- ),
- ),
- TextButton(
- onPressed: () => _importFromText(
- pluginText,
- dismissDialog: true,
- ),
- child: const Text('导入'),
- ),
- ],
- );
- },
- );
+ Future<void> _add() async {
+ final source = await showRuleAddDialog(context);
+ if (!mounted || source == null) return;
+ switch (source) {
+ case RuleAddSource.catalog:
+ context.pushNamed('/settings/plugin/shop');
+ case RuleAddSource.create:
+ context.pushNamed('/settings/plugin/editor',
+ arguments: Plugin.fromTemplate());
+ case RuleAddSource.clipboard:
+ String? initialValue;
+ try {
+ initialValue = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
+ } catch (_) {
+ initialValue = null;
+ }
+ if (mounted) {
+ await showRuleImportDialog(context, _controller,
+ initialValue: initialValue ?? '');
+ }
+ case RuleAddSource.file:
+ await _importFromFile();
+ }
}
Future<void> _importFromFile() async {
try {
final result = await FilePicker.platform.pickFiles(
- type: FileType.custom,
- allowedExtensions: const ['json'],
- withData: true,
- );
+ type: FileType.custom,
+ allowedExtensions: const ['json'],
+ withData: true);
if (result == null) return;
final file = result.files.single;
final bytes = file.bytes ??
(file.path == null ? null : await File(file.path!).readAsBytes());
- if (bytes == null) {
- throw const FileSystemException('无法读取所选文件');
+ if (bytes == null) throw const FileSystemException('无法读取所选文件');
+ final parsed = PluginImportParser.parse(utf8.decode(bytes));
+ if (parsed.plugins.isEmpty) {
+ KazumiDialog.showToast(
+ message: parsed.failures.isEmpty
+ ? '文件中没有可导入的规则'
+ : parsed.failures.first);
+ return;
}
- await _importFromText(utf8.decode(bytes));
+ await _controller.updatePlugins(parsed.plugins);
+ KazumiDialog.showToast(
+ message: '已导入 ${parsed.plugins.length} 条规则,'
+ '跳过重复 ${parsed.duplicateCount} 条,失败 ${parsed.failureCount} 条');
} catch (error, stackTrace) {
- KazumiLogger().e(
- 'Plugin: failed to import rules from file',
- error: error,
- stackTrace: stackTrace,
- );
- KazumiDialog.showToast(message: '读取规则文件失败:$error');
+ KazumiLogger().e('Plugin: failed to import rules from file',
+ error: error, stackTrace: stackTrace);
+ KazumiDialog.showToast(message: '导入规则文件失败:$error');
}
}
- Future<void> _importFromText(
- String text, {
- bool dismissDialog = false,
- }) async {
- final result = PluginImportParser.parse(text);
- if (result.plugins.isEmpty) {
- if (dismissDialog) KazumiDialog.dismiss();
- KazumiDialog.showToast(
- message: result.failures.isEmpty ? '没有可导入的规则' : result.failures.first,
- );
+ void _leaveSelection() => setState(() {
+ _selecting = false;
+ _selected.clear();
+ });
+
+ void _toggleSelection(String name) => setState(() {
+ if (!_selected.add(name)) _selected.remove(name);
+ });
+
+ Future<void> _delete(Set<String> names) async {
+ if (_deleting || names.isEmpty) return;
+ setState(() => _deleting = true);
+ final confirmed = await confirmRuleDeletion(context, names);
+ if (!mounted) return;
+ if (!confirmed) {
+ setState(() => _deleting = false);
return;
}
-
- if (dismissDialog) KazumiDialog.dismiss();
try {
- await pluginsController.updatePlugins(result.plugins);
- KazumiDialog.showToast(
- message: '导入完成:成功 ${result.plugins.length} 条,'
- '跳过重复 ${result.duplicateCount} 条,失败 ${result.failureCount} 条',
- );
- } catch (error, stackTrace) {
- KazumiLogger().e(
- 'Plugin: failed to persist imported rules',
- error: error,
- stackTrace: stackTrace,
- );
- KazumiDialog.showToast(message: '保存导入规则失败:$error');
+ await _controller.removePlugins(names);
+ if (mounted) _leaveSelection();
+ KazumiDialog.showToast(message: '已删除 ${names.length} 条规则');
+ } catch (_) {
+ KazumiDialog.showToast(message: '删除规则失败,请重试');
+ } finally {
+ if (mounted) setState(() => _deleting = false);
}
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
+ Future<void> _reorder(int oldIndex, int newIndex) async {
+ try {
+ await _controller.onReorder(oldIndex, newIndex);
+ } catch (_) {
+ KazumiDialog.showToast(message: '保存规则顺序失败');
}
}
- @override
- void initState() {
- super.initState();
- unawaited(_loadPluginUpdateStatus());
- }
-
- Future<void> _loadPluginUpdateStatus() async {
+ Future<void> _updateOne(Plugin plugin) async {
+ if (_updating || !_updatingNames.add(plugin.name)) return;
+ setState(() {});
try {
- await pluginsController.ensurePluginCatalog();
- if (mounted) {
- setState(() {});
+ await _controller.ensurePluginCatalog();
+ final state = _controller.pluginUpdateStatus(plugin);
+ if (state == PluginUpdateAvailability.updatable) {
+ await updatePluginWithFeedback(_controller, plugin.name,
+ installing: false);
+ } else {
+ KazumiDialog.showToast(
+ message: state == PluginUpdateAvailability.notInCatalog
+ ? '规则仓库中没有当前规则'
+ : '规则已是最新');
}
} catch (_) {
KazumiDialog.showToast(message: '检查规则更新失败');
+ } finally {
+ if (mounted) setState(() => _updatingNames.remove(plugin.name));
}
}
@override
- Widget build(BuildContext context) {
- return PopScope(
- canPop: !isMultiSelectMode,
- onPopInvokedWithResult: (bool didPop, Object? result) {
- if (didPop) {
- return;
- }
- if (isMultiSelectMode) {
- setState(() {
- isMultiSelectMode = false;
- selectedNames.clear();
- });
- return;
- }
- onBackPressed(context);
- },
- child: SettingsDetailScaffold(
- title: isMultiSelectMode
- ? Text('已选择 ${selectedNames.length} 项')
- : const Text('规则管理'),
- leading: isMultiSelectMode
- ? IconButton(
- icon: const Icon(Icons.close),
- onPressed: () {
- setState(() {
- isMultiSelectMode = false;
- selectedNames.clear();
- });
- },
+ Widget build(BuildContext context) => PopScope(
+ canPop: !_selecting,
+ onPopInvokedWithResult: (didPop, _) {
+ if (!didPop && _selecting) _leaveSelection();
+ },
+ child: SettingsDetailScaffold(
+ title: Text(_selecting ? '已选择 ${_selected.length} 条' : '规则管理'),
+ leading: _selecting
+ ? IconButton(
+ tooltip: '退出多选',
+ onPressed: _leaveSelection,
+ icon: const Icon(Icons.close_rounded))
+ : null,
+ actions: [
+ if (_selecting)
+ IconButton(
+ tooltip: '删除所选规则',
+ onPressed: _selected.isEmpty || _deleting
+ ? null
+ : () => _delete(Set.of(_selected)),
+ icon: const Icon(Icons.delete_outline_rounded),
)
- : null,
- actions: [
- if (isMultiSelectMode) ...[
- IconButton(
- onPressed: selectedNames.isEmpty
- ? null
- : () {
- KazumiDialog.show(
- builder: (context) => AlertDialog(
- title: const Text('删除规则'),
- content:
- Text('确定要删除选中的 ${selectedNames.length} 条规则吗?'),
+ else
+ IconButton(
+ tooltip: '批量选择',
+ onPressed: () => setState(() => _selecting = true),
+ icon: const Icon(Icons.checklist_rounded),
+ ),
+ const SizedBox(width: 8),
+ ],
+ body: SafeArea(
+ top: false,
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1000),
+ child: Observer(builder: (context) {
+ final colors = Theme.of(context).colorScheme;
+ final all = _controller.pluginList.toList();
+ final updates = all
+ .where((p) =>
+ _controller.pluginUpdateStatus(p) ==
+ PluginUpdateAvailability.updatable)
+ .length;
+ final query = _search.text.trim().toLowerCase();
+ final visible = all
+ .where((p) =>
+ (p.name.toLowerCase().contains(query) ||
+ p.baseUrl.toLowerCase().contains(query)) &&
+ (!_updatesOnly ||
+ _controller.pluginUpdateStatus(p) ==
+ PluginUpdateAvailability.updatable))
+ .toList();
+ final canReorder =
+ query.isEmpty && !_updatesOnly && !_selecting;
+ return ReorderableListView.builder(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
+ buildDefaultDragHandles: false,
+ proxyDecorator: (child, index, animation) => Material(
+ elevation: 0, color: Colors.transparent, child: child),
+ onReorderItem: (oldIndex, newIndex) =>
+ unawaited(_reorder(oldIndex, newIndex)),
+ header: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ RulePageIntro(
+ title: '我的规则',
+ description: '管理你的番剧来源。拖动调整搜索顺序,点按规则进行编辑。',
+ icon: Icons.extension_rounded,
actions: [
- TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(
- color:
- Theme.of(context).colorScheme.outline),
- ),
- ),
- TextButton(
- onPressed: () async {
- try {
- await pluginsController
- .removePlugins(selectedNames);
- } catch (_) {
- KazumiDialog.showToast(message: '删除规则失败');
- return;
- }
- if (!mounted) return;
- setState(() {
- isMultiSelectMode = false;
- selectedNames.clear();
- });
- KazumiDialog.dismiss();
- },
- child: const Text('删除'),
- ),
+ FilledButton.icon(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(120, 48)),
+ onPressed: _add,
+ icon: const Icon(Icons.add_rounded),
+ label: const Text('添加规则')),
+ FilledButton.tonalIcon(
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(120, 48)),
+ onPressed: () =>
+ context.pushNamed('/settings/plugin/shop'),
+ icon: const Icon(Icons.travel_explore_rounded),
+ label: const Text('规则仓库')),
],
),
- );
- },
- icon: const Icon(Icons.delete),
- ),
- ] else ...[
- IconButton(
- onPressed: () {
- _handleUpdate();
- },
- tooltip: '更新全部',
- icon: const Icon(Icons.update),
- ),
- IconButton(
- onPressed: () {
- _handleAdd();
- },
- tooltip: '添加规则',
- icon: const Icon(Icons.add),
- )
- ],
- ],
- body: Observer(builder: (context) {
- return pluginsController.pluginList.isEmpty
- ? const Center(
- child: Text('啊咧(⊙.⊙) 没有可用规则的说'),
- )
- : Builder(builder: (context) {
- final colorScheme = Theme.of(context).colorScheme;
- return ReorderableListView.builder(
- buildDefaultDragHandles: false,
- padding: const EdgeInsets.symmetric(horizontal: 8),
- proxyDecorator: (child, index, animation) {
- return Material(
- elevation: 0,
- color: Colors.transparent,
- child: child,
- );
- },
- onReorderItem: (int oldIndex, int newIndex) {
- unawaited(_handleReorder(oldIndex, newIndex));
- },
- itemCount: pluginsController.pluginList.length,
- itemBuilder: (context, index) {
- var plugin = pluginsController.pluginList[index];
- bool canUpdate =
- pluginsController.pluginUpdateStatus(plugin) ==
- PluginUpdateAvailability.updatable;
- return RuleCard(
- key: ObjectKey(plugin),
- title: plugin.name,
- selected: selectedNames.contains(plugin.name),
- trailing: pluginCardTrailing(index),
- onLongPress: () {
- if (!isMultiSelectMode) {
- setState(() {
- isMultiSelectMode = true;
- selectedNames.add(plugin.name);
- });
- }
- },
- onTap: () {
- if (isMultiSelectMode) {
- setState(() {
- if (selectedNames.contains(plugin.name)) {
- selectedNames.remove(plugin.name);
- if (selectedNames.isEmpty) {
- isMultiSelectMode = false;
- }
- } else {
- selectedNames.add(plugin.name);
- }
- });
- }
- },
- tags: [
- RuleTag(
+ const SizedBox(height: 20),
+ TextField(
+ controller: _search,
+ onChanged: (_) => setState(() {}),
+ decoration: ruleInputDecoration(context,
+ hint: '搜索名称或站点',
+ prefix: const Icon(Icons.search_rounded),
+ suffix: query.isEmpty
+ ? null
+ : IconButton(
+ tooltip: '清除搜索',
+ onPressed: () => setState(_search.clear),
+ icon: const Icon(Icons.close_rounded))),
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ runSpacing: 4,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ FilterChip(
+ label: Text('全部 ${all.length}'),
+ selected: !_updatesOnly,
+ onSelected: (_) =>
+ setState(() => _updatesOnly = false)),
+ FilterChip(
+ label: Text('可更新 $updates'),
+ selected: _updatesOnly,
+ onSelected: (value) =>
+ setState(() => _updatesOnly = value)),
+ TextButton.icon(
+ onPressed:
+ _updating || _updatingNames.isNotEmpty
+ ? null
+ : _updateAll,
+ icon: _updating
+ ? const LoadingIndicator(size: 20)
+ : const Icon(Icons.sync_rounded, size: 20),
+ label: Text(_updating ? '正在更新' : '更新全部')),
+ if (_selecting)
+ TextButton(
+ onPressed: () => setState(() {
+ if (visible.every((p) =>
+ _selected.contains(p.name))) {
+ _selected.removeAll(
+ visible.map((p) => p.name));
+ } else {
+ _selected.addAll(
+ visible.map((p) => p.name));
+ }
+ }),
+ child: Text(visible.isNotEmpty &&
+ visible.every(
+ (p) => _selected.contains(p.name))
+ ? '取消全选'
+ : '全选当前列表')),
+ ],
+ ),
+ if (_catalogFailed)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Text('暂时无法检查更新,已安装的规则仍可使用。',
+ style: Theme.of(context)
+ .textTheme
+ .bodySmall
+ ?.copyWith(
+ color: colors.onSurfaceVariant))),
+ const SizedBox(height: 8),
+ ],
+ ),
+ footer: visible.isEmpty
+ ? RuleEmptyState(
+ title: all.isEmpty ? '从第一条规则开始' : '没有符合条件的规则',
+ description: all.isEmpty
+ ? '前往规则仓库,添加一个喜欢的番剧来源。'
+ : _updatesOnly && query.isEmpty
+ ? '当前没有可更新的规则。'
+ : '试试其他名称,或清除筛选。',
+ action: all.isEmpty
+ ? FilledButton.tonalIcon(
+ onPressed: () => context
+ .pushNamed('/settings/plugin/shop'),
+ icon: const Icon(
+ Icons.travel_explore_rounded),
+ label: const Text('浏览规则仓库'))
+ : TextButton(
+ onPressed: () => setState(() {
+ _search.clear();
+ _updatesOnly = false;
+ }),
+ child: const Text('显示全部规则')),
+ )
+ : null,
+ itemCount: visible.length,
+ itemBuilder: (context, index) {
+ final plugin = visible[index];
+ final actualIndex = all.indexOf(plugin);
+ final updatable =
+ _controller.pluginUpdateStatus(plugin) ==
+ PluginUpdateAvailability.updatable;
+ return RuleCard(
+ key: ValueKey(plugin.name),
+ title: plugin.name,
+ subtitle: Uri.tryParse(plugin.baseUrl)?.host ??
+ plugin.baseUrl,
+ selected: _selected.contains(plugin.name),
+ onTap: () {
+ if (_selecting) {
+ _toggleSelection(plugin.name);
+ } else {
+ context.pushNamed('/settings/plugin/editor',
+ arguments: plugin);
+ }
+ },
+ onLongPress: () => setState(() {
+ _selecting = true;
+ _selected.add(plugin.name);
+ }),
+ tags: [
+ RuleTag(
label: plugin.version,
- background: colorScheme.secondaryContainer,
- foreground: colorScheme.onSecondaryContainer,
- ),
- if (canUpdate)
- RuleTag(
+ background: colors.surfaceContainerHighest,
+ foreground: colors.onSurfaceVariant),
+ if (updatable)
+ RuleTag(
label: '可更新',
- background: colorScheme.errorContainer,
- foreground: colorScheme.onErrorContainer,
- ),
- if (pluginsController.validityTracker
- .isSearchValid(plugin.name))
- RuleTag(
- label: '搜索有效',
- background: colorScheme.tertiaryContainer,
- foreground: colorScheme.onTertiaryContainer,
+ background: colors.secondaryContainer,
+ foreground: colors.onSecondaryContainer),
+ if (_controller.validityTracker
+ .isSearchValid(plugin.name))
+ RuleTag(
+ label: '搜索通过',
+ background: colors.tertiaryContainer,
+ foreground: colors.onTertiaryContainer),
+ ],
+ trailing:
+ Row(mainAxisSize: MainAxisSize.min, children: [
+ if (_selecting)
+ Checkbox(
+ value: _selected.contains(plugin.name),
+ semanticLabel: '选择 ${plugin.name}',
+ onChanged: (_) => _toggleSelection(plugin.name))
+ else if (_updatingNames.contains(plugin.name))
+ const Padding(
+ padding: EdgeInsets.all(12),
+ child: LoadingIndicator(size: 24))
+ else
+ _menu(plugin, actualIndex),
+ if (canReorder)
+ Tooltip(
+ message: '拖动排序',
+ child: ReorderableDragStartListener(
+ index: index,
+ child: const SizedBox.square(
+ dimension: 48,
+ child: Icon(Icons.drag_indicator_rounded)),
),
- ],
- );
- });
- });
- }),
- ),
- );
- }
-
- Widget pluginCardTrailing(int index) {
- final plugin = pluginsController.pluginList[index];
- return Row(mainAxisSize: MainAxisSize.min, children: [
- isMultiSelectMode
- ? Checkbox(
- value: selectedNames.contains(plugin.name),
- onChanged: (bool? value) {
- setState(() {
- if (value == true) {
- selectedNames.add(plugin.name);
- } else {
- selectedNames.remove(plugin.name);
- if (selectedNames.isEmpty) {
- isMultiSelectMode = false;
- }
- }
- });
- },
- )
- : popupMenuButton(index),
- ReorderableDragStartListener(
- index: index,
- child: const Icon(Icons.drag_handle), // 单独的拖拽按钮
- )
- ]);
- }
-
- Widget popupMenuButton(int index) {
- final plugin = pluginsController.pluginList[index];
- return MenuAnchor(
- consumeOutsideTap: true,
- builder:
- (BuildContext context, MenuController controller, Widget? child) {
- return IconButton(
- onPressed: () {
- if (controller.isOpen) {
- controller.close();
- } else {
- controller.open();
- }
- },
- icon: const Icon(Icons.more_vert),
- );
- },
- menuChildren: [
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () async {
- try {
- await pluginsController.ensurePluginCatalog();
- if (mounted) {
- setState(() {});
- }
- } catch (_) {
- KazumiDialog.showToast(message: '检查规则更新失败');
- return;
- }
- final state = pluginsController.pluginUpdateStatus(plugin);
- switch (state) {
- case PluginUpdateAvailability.unknown:
- KazumiDialog.showToast(message: '尚未获取规则更新状态');
- case PluginUpdateAvailability.notInCatalog:
- KazumiDialog.showToast(message: '规则仓库中没有当前规则');
- case PluginUpdateAvailability.latest:
- KazumiDialog.showToast(message: '规则已是最新');
- case PluginUpdateAvailability.updatable:
- await updatePluginWithFeedback(
- pluginsController,
- plugin.name,
- installing: false,
- );
- }
- },
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(Icons.update_rounded),
- SizedBox(width: 8),
- Text('更新'),
- ],
- ),
- ),
- ),
- ),
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () {
- context.pushNamed('/settings/plugin/editor', arguments: plugin);
- },
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(Icons.edit),
- SizedBox(width: 8),
- Text('编辑'),
- ],
- ),
- ),
- ),
- ),
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () {
- context.pushNamed('/settings/plugin/test', arguments: plugin);
- },
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(Icons.bug_report_outlined),
- SizedBox(width: 8),
- Text('测试'),
- ],
- ),
- ),
- ),
- ),
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () {
- KazumiDialog.show(builder: (context) {
- return AlertDialog(
- title: const Text('规则链接'),
- content: SelectableText(
- jsonToKazumiBase64(json
- .encode(pluginsController.pluginList[index].toJson())),
- style: const TextStyle(fontWeight: FontWeight.bold),
- textAlign: TextAlign.center,
- ),
- actions: [
- TextButton(
- onPressed: () => KazumiDialog.dismiss(),
- child: Text(
- '取消',
- style: TextStyle(
- color: Theme.of(context).colorScheme.outline),
- ),
- ),
- TextButton(
- onPressed: () {
- Clipboard.setData(ClipboardData(
- text: jsonToKazumiBase64(
- json.encode(
- pluginsController.pluginList[index].toJson(),
- ),
- ),
- ));
- KazumiDialog.dismiss();
+ ),
+ ]),
+ );
},
- child: const Text('复制到剪贴板'),
- ),
- ],
- );
- });
- },
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(Icons.share),
- SizedBox(width: 8),
- Text('分享'),
- ],
+ );
+ }),
),
),
),
),
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () async {
- try {
- await pluginsController.removePlugin(plugin);
- } catch (_) {
- KazumiDialog.showToast(message: '删除规则失败');
- }
- },
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(Icons.delete),
- SizedBox(width: 8),
- Text('删除'),
- ],
- ),
- ),
- ),
+ );
+
+ Widget _menu(Plugin plugin, int index) => MenuAnchor(
+ consumeOutsideTap: true,
+ style: MenuStyle(
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(20))),
+ padding: const WidgetStatePropertyAll(EdgeInsets.all(8)),
),
- ],
- );
- }
+ builder: (context, controller, child) => IconButton(
+ tooltip: '${plugin.name} 的更多操作',
+ onPressed: () =>
+ controller.isOpen ? controller.close() : controller.open(),
+ icon: const Icon(Icons.more_horiz_rounded)),
+ menuChildren: [
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.edit_outlined),
+ onPressed: () => context.pushNamed('/settings/plugin/editor',
+ arguments: plugin),
+ child: const Text('编辑规则')),
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.bug_report_outlined),
+ onPressed: () =>
+ context.pushNamed('/settings/plugin/test', arguments: plugin),
+ child: const Text('测试规则')),
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.sync_rounded),
+ onPressed: _updating ? null : () => _updateOne(plugin),
+ child: const Text('检查更新')),
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.ios_share_rounded),
+ onPressed: () => showRuleShareDialog(context, plugin),
+ child: const Text('分享规则')),
+ const Divider(),
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.arrow_upward_rounded),
+ onPressed: index == 0 ? null : () => _reorder(index, index - 1),
+ child: const Text('上移')),
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.arrow_downward_rounded),
+ onPressed: index == _controller.pluginList.length - 1
+ ? null
+ : () => _reorder(index, index + 1),
+ child: const Text('下移')),
+ const Divider(),
+ MenuItemButton(
+ leadingIcon: Icon(Icons.delete_outline_rounded,
+ color: Theme.of(context).colorScheme.error),
+ onPressed: _deleting ? null : () => _delete({plugin.name}),
+ child: Text('删除规则',
+ style:
+ TextStyle(color: Theme.of(context).colorScheme.error))),
+ ],
+ );
}
diff --git a/lib/pages/plugin_editor/rule_dialogs.dart b/lib/pages/plugin_editor/rule_dialogs.dart
new file mode 100644
index 00000000..d4e20e7f
--- /dev/null
+++ b/lib/pages/plugin_editor/rule_dialogs.dart
@@ -0,0 +1,313 @@
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/bean/widget/loading_indicator.dart';
+import 'package:kazumi/pages/plugin_editor/rule_management_widgets.dart';
+import 'package:kazumi/plugins/plugins.dart';
+import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/services/plugin/plugin_import_parser.dart';
+import 'package:kazumi/utils/encoding.dart';
+
+enum RuleAddSource { catalog, clipboard, file, create }
+
+Future<RuleAddSource?> showRuleAddDialog(BuildContext context) =>
+ KazumiDialog.show<RuleAddSource>(
+ context: context,
+ builder: (context) {
+ final colors = Theme.of(context).colorScheme;
+ return _RuleDialog(
+ title: '添加规则',
+ icon: Icons.add_circle_outline_rounded,
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const Text('选择一种方式,添加新的番剧来源。'),
+ const SizedBox(height: 20),
+ for (final option in [
+ (
+ RuleAddSource.catalog,
+ Icons.travel_explore_rounded,
+ '浏览规则仓库',
+ '发现并安装社区规则'
+ ),
+ (
+ RuleAddSource.clipboard,
+ Icons.content_paste_rounded,
+ '从剪贴板导入',
+ '粘贴规则链接或 JSON'
+ ),
+ (
+ RuleAddSource.file,
+ Icons.file_open_outlined,
+ '从文件导入',
+ '读取本地 JSON 规则文件'
+ ),
+ (
+ RuleAddSource.create,
+ Icons.edit_note_rounded,
+ '新建规则',
+ '从模板开始编写'
+ ),
+ ])
+ Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Material(
+ color: option.$1 == RuleAddSource.catalog
+ ? colors.secondaryContainer
+ : colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(
+ option.$1 == RuleAddSource.catalog ? 20 : 12),
+ clipBehavior: Clip.antiAlias,
+ child: ListTile(
+ minVerticalPadding: 14,
+ leading: Icon(option.$2, color: colors.onSurfaceVariant),
+ title: Text(option.$3),
+ subtitle: Text(option.$4),
+ trailing:
+ const Icon(Icons.arrow_forward_rounded, size: 20),
+ onTap: () => Navigator.of(context).pop(option.$1),
+ ),
+ ),
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('取消')),
+ ],
+ );
+ },
+ );
+
+Future<bool> confirmRuleDeletion(
+ BuildContext context, Set<String> names) async =>
+ await KazumiDialog.show<bool>(
+ context: context,
+ builder: (context) => _RuleDialog(
+ title: names.length == 1 ? '删除这条规则?' : '删除 ${names.length} 条规则?',
+ icon: Icons.delete_outline_rounded,
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(names.take(5).join('、') + (names.length > 5 ? ' 等' : ''),
+ style: Theme.of(context).textTheme.titleMedium),
+ const SizedBox(height: 12),
+ const Text('删除后将不再使用这些来源搜索番剧。你可以稍后重新导入规则。'),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(false),
+ child: const Text('保留')),
+ FilledButton(
+ style: FilledButton.styleFrom(
+ backgroundColor: Theme.of(context).colorScheme.error,
+ foregroundColor: Theme.of(context).colorScheme.onError,
+ minimumSize: const Size(88, 48)),
+ onPressed: () => Navigator.of(context).pop(true),
+ child: const Text('删除'),
+ ),
+ ],
+ ),
+ ) ??
+ false;
+
+Future<void> showRuleShareDialog(BuildContext context, Plugin plugin) async {
+ final link = jsonToKazumiBase64(jsonEncode(plugin.toJson()));
+ await KazumiDialog.show<void>(
+ context: context,
+ builder: (context) => _RuleDialog(
+ title: '分享规则',
+ icon: Icons.ios_share_rounded,
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(plugin.name, style: Theme.of(context).textTheme.titleLarge),
+ const SizedBox(height: 8),
+ const Text('复制规则链接,对方可在「添加规则」中从剪贴板导入。'),
+ const SizedBox(height: 20),
+ Container(
+ padding: const EdgeInsets.all(16),
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(16)),
+ constraints: const BoxConstraints(maxHeight: 180),
+ child: SingleChildScrollView(
+ child: SelectableText(link,
+ style: Theme.of(context)
+ .textTheme
+ .bodySmall
+ ?.copyWith(fontFamily: 'monospace')),
+ ),
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('关闭')),
+ FilledButton.icon(
+ icon: const Icon(Icons.copy_rounded, size: 18),
+ label: const Text('复制链接'),
+ onPressed: () async {
+ try {
+ await Clipboard.setData(ClipboardData(text: link));
+ if (!context.mounted) return;
+ Navigator.of(context).pop();
+ KazumiDialog.showToast(message: '规则链接已复制');
+ } catch (_) {
+ if (context.mounted) {
+ KazumiDialog.showToast(context: context, message: '复制失败,请重试');
+ }
+ }
+ },
+ ),
+ ],
+ ),
+ );
+}
+
+Future<void> showRuleImportDialog(
+ BuildContext context,
+ PluginsController controller, {
+ String initialValue = '',
+}) =>
+ KazumiDialog.show<void>(
+ context: context,
+ clickMaskDismiss: false,
+ builder: (context) =>
+ _RuleImportDialog(controller: controller, initialValue: initialValue),
+ );
+
+class _RuleImportDialog extends StatefulWidget {
+ const _RuleImportDialog(
+ {required this.controller, required this.initialValue});
+ final PluginsController controller;
+ final String initialValue;
+
+ @override
+ State<_RuleImportDialog> createState() => _RuleImportDialogState();
+}
+
+class _RuleImportDialogState extends State<_RuleImportDialog> {
+ late final _text = TextEditingController(text: widget.initialValue);
+ bool _saving = false;
+ String? _error;
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ Future<void> _import() async {
+ if (_saving) return;
+ final result = PluginImportParser.parse(_text.text);
+ if (result.plugins.isEmpty) {
+ setState(() => _error = result.failures.isEmpty
+ ? '没有识别到规则,请粘贴规则链接或 JSON。'
+ : result.failures.first);
+ return;
+ }
+ setState(() {
+ _saving = true;
+ _error = null;
+ });
+ try {
+ await widget.controller.updatePlugins(result.plugins);
+ if (!mounted) return;
+ Navigator.of(context).pop();
+ KazumiDialog.showToast(
+ message: '已导入 ${result.plugins.length} 条规则'
+ ',跳过重复 ${result.duplicateCount} 条,失败 ${result.failureCount} 条');
+ } catch (_) {
+ if (mounted) {
+ setState(() {
+ _saving = false;
+ _error = '保存失败,内容已保留,请重试。';
+ });
+ }
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => PopScope(
+ canPop: !_saving,
+ child: _RuleDialog(
+ title: '导入规则',
+ icon: Icons.content_paste_go_rounded,
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const Text('支持多条 kazumi:// 链接、单条 JSON 或 JSON 数组。同名规则会被替换。'),
+ const SizedBox(height: 20),
+ TextField(
+ controller: _text,
+ enabled: !_saving,
+ minLines: 4,
+ maxLines: 8,
+ onChanged: (_) => setState(() => _error = null),
+ decoration: ruleInputDecoration(context,
+ label: '规则内容', hint: '在这里粘贴规则链接或 JSON')
+ .copyWith(
+ alignLabelWithHint: true,
+ errorText: _error,
+ errorMaxLines: 4),
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: _saving ? null : () => Navigator.of(context).pop(),
+ child: const Text('取消'),
+ ),
+ FilledButton.icon(
+ onPressed: _saving || _text.text.trim().isEmpty ? null : _import,
+ icon: _saving
+ ? const LoadingIndicator(size: 20)
+ : const Icon(Icons.download_rounded, size: 18),
+ label: Text(_saving ? '正在导入' : '导入规则'),
+ ),
+ ],
+ ),
+ );
+}
+
+class _RuleDialog extends StatelessWidget {
+ const _RuleDialog({
+ required this.title,
+ required this.icon,
+ required this.content,
+ required this.actions,
+ });
+
+ final String title;
+ final IconData icon;
+ final Widget content;
+ final List<Widget> actions;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return AlertDialog(
+ backgroundColor: colors.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
+ constraints: const BoxConstraints(maxWidth: 560),
+ insetPadding: const EdgeInsets.all(24),
+ scrollable: true,
+ icon: Icon(icon, color: colors.secondary, size: 32),
+ title: Text(title),
+ content: SizedBox(width: 480, child: content),
+ actionsPadding: const EdgeInsets.fromLTRB(24, 8, 24, 24),
+ actionsOverflowButtonSpacing: 8,
+ actions: actions,
+ );
+ }
+}
diff --git a/lib/pages/plugin_editor/rule_management_widgets.dart b/lib/pages/plugin_editor/rule_management_widgets.dart
new file mode 100644
index 00000000..535e59e3
--- /dev/null
+++ b/lib/pages/plugin_editor/rule_management_widgets.dart
@@ -0,0 +1,170 @@
+import 'package:flutter/material.dart';
+
+class RulePageIntro extends StatelessWidget {
+ const RulePageIntro({
+ super.key,
+ required this.title,
+ required this.description,
+ required this.icon,
+ this.actions = const [],
+ });
+
+ final String title;
+ final String description;
+ final IconData icon;
+ final List<Widget> actions;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ return Container(
+ width: double.infinity,
+ padding: const EdgeInsets.all(24),
+ decoration: BoxDecoration(
+ color: colors.primaryContainer,
+ borderRadius: BorderRadius.circular(32),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Expanded(
+ child: Text(title,
+ style: theme.textTheme.headlineMedium?.copyWith(
+ fontWeight: FontWeight.w700,
+ color: colors.onPrimaryContainer)),
+ ),
+ const SizedBox(width: 16),
+ Icon(icon, size: 32, color: colors.onPrimaryContainer),
+ ]),
+ const SizedBox(height: 8),
+ Text(description,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: colors.onPrimaryContainer)),
+ if (actions.isNotEmpty) ...[
+ const SizedBox(height: 20),
+ Wrap(spacing: 8, runSpacing: 8, children: actions),
+ ],
+ ],
+ ),
+ );
+ }
+}
+
+class RuleSection extends StatelessWidget {
+ const RuleSection({
+ super.key,
+ required this.title,
+ required this.child,
+ this.description,
+ this.icon,
+ });
+
+ final String title;
+ final String? description;
+ final IconData? icon;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ return Material(
+ color: theme.colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(28),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(20),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(children: [
+ if (icon != null) ...[
+ Icon(icon, color: theme.colorScheme.primary),
+ const SizedBox(width: 12),
+ ],
+ Expanded(
+ child: Text(title,
+ style: theme.textTheme.titleLarge
+ ?.copyWith(fontWeight: FontWeight.w600))),
+ ]),
+ if (description != null) ...[
+ const SizedBox(height: 6),
+ Text(description!,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),
+ ],
+ const SizedBox(height: 24),
+ child,
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class RuleEmptyState extends StatelessWidget {
+ const RuleEmptyState({
+ super.key,
+ required this.title,
+ required this.description,
+ this.icon = Icons.extension_outlined,
+ this.action,
+ });
+
+ final String title;
+ final String description;
+ final IconData icon;
+ final Widget? action;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ return Center(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
+ child: Column(mainAxisSize: MainAxisSize.min, children: [
+ Container(
+ padding: const EdgeInsets.all(20),
+ decoration: BoxDecoration(
+ color: theme.colorScheme.secondaryContainer,
+ borderRadius: BorderRadius.circular(24),
+ ),
+ child: Icon(icon,
+ size: 36, color: theme.colorScheme.onSecondaryContainer),
+ ),
+ const SizedBox(height: 20),
+ Text(title,
+ textAlign: TextAlign.center, style: theme.textTheme.titleLarge),
+ const SizedBox(height: 8),
+ Text(description,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),
+ if (action != null) ...[const SizedBox(height: 20), action!],
+ ]),
+ ),
+ );
+ }
+}
+
+InputDecoration ruleInputDecoration(BuildContext context,
+ {String? label, String? hint, Widget? prefix, Widget? suffix}) {
+ final colors = Theme.of(context).colorScheme;
+ return InputDecoration(
+ labelText: label,
+ hintText: hint,
+ prefixIcon: prefix,
+ suffixIcon: suffix,
+ filled: true,
+ fillColor: colors.surfaceContainerHighest,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(16),
+ borderSide: BorderSide(color: colors.primary, width: 2)),
+ );
+}