Initial commit
This commit is contained in:
@@ -0,0 +1,486 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/contracts/script_widget.dart';
|
||||
import '../../core/domain/usecases/script_widget/script_widget_service.dart';
|
||||
import '../../providers/di_providers.dart';
|
||||
import '../../shared/constants/layout_constants.dart';
|
||||
import '../../shared/theme/app_theme.dart';
|
||||
import '../../shared/utils/user_error_formatter.dart';
|
||||
import '../../shared/widgets/app_card.dart';
|
||||
import '../../shared/widgets/app_error_state.dart';
|
||||
import '../../shared/widgets/app_loading_ring.dart';
|
||||
import '../../shared/widgets/app_sliver_header.dart';
|
||||
import '../../shared/widgets/empty_state.dart';
|
||||
import '../../shared/widgets/page_background.dart';
|
||||
import '../../shared/widgets/script_video_card.dart';
|
||||
import '../../shared/widgets/section_header.dart';
|
||||
|
||||
|
||||
const double _kInfiniteScrollThreshold = 200;
|
||||
|
||||
class ModuleAllPage extends ConsumerStatefulWidget {
|
||||
final String widgetId;
|
||||
final String moduleKey;
|
||||
|
||||
|
||||
final Map<String, String> initialParams;
|
||||
|
||||
const ModuleAllPage({
|
||||
super.key,
|
||||
required this.widgetId,
|
||||
required this.moduleKey,
|
||||
this.initialParams = const <String, String>{},
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<ModuleAllPage> createState() => _ModuleAllPageState();
|
||||
}
|
||||
|
||||
class _ModuleAllPageState extends ConsumerState<ModuleAllPage> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
|
||||
ScriptWidgetModule? _module;
|
||||
Map<String, Object?> _parameters = <String, Object?>{};
|
||||
|
||||
|
||||
final List<ScriptWidgetContentSection> _sections =
|
||||
<ScriptWidgetContentSection>[];
|
||||
|
||||
String? _initializedWidgetId;
|
||||
String? _initializationError;
|
||||
|
||||
|
||||
bool _isFirstLoad = true;
|
||||
bool _isLoadingMore = false;
|
||||
bool _hasMore = true;
|
||||
String? _loadError;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scrollController.addListener(_onScroll);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.removeListener(_onScroll);
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onScroll() {
|
||||
if (!_scrollController.hasClients) return;
|
||||
final remaining =
|
||||
_scrollController.position.maxScrollExtent -
|
||||
_scrollController.position.pixels;
|
||||
if (remaining <= _kInfiniteScrollThreshold) {
|
||||
unawaited(_fetchNextPage());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _initialize(InstalledScriptWidget installedWidget) async {
|
||||
if (_initializedWidgetId == installedWidget.manifest.id) return;
|
||||
_initializedWidgetId = installedWidget.manifest.id;
|
||||
|
||||
final module = installedWidget.manifest.modules
|
||||
.where((candidate) => _moduleKey(candidate) == widget.moduleKey)
|
||||
.firstOrNull;
|
||||
if (module == null) {
|
||||
setState(() {
|
||||
_initializationError = '未找到模块功能:${widget.moduleKey}';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final resolvedParameters = buildScriptWidgetParameterDefaults(module.params);
|
||||
for (final entry in widget.initialParams.entries) {
|
||||
if (resolvedParameters.containsKey(entry.key)) {
|
||||
resolvedParameters[entry.key] = entry.value;
|
||||
}
|
||||
}
|
||||
setState(() {
|
||||
_module = module;
|
||||
_parameters = resolvedParameters;
|
||||
_initializationError = null;
|
||||
});
|
||||
await _fetchNextPage();
|
||||
}
|
||||
|
||||
String _moduleKey(ScriptWidgetModule module) {
|
||||
return module.id.isEmpty ? module.functionName : module.id;
|
||||
}
|
||||
|
||||
ScriptWidgetParam? get _pagingParameter {
|
||||
return _module?.params
|
||||
.where(
|
||||
(parameter) => parameter.type == 'page' || parameter.type == 'offset',
|
||||
)
|
||||
.firstOrNull;
|
||||
}
|
||||
|
||||
|
||||
bool get _supportsPagination => _pagingParameter != null;
|
||||
|
||||
Future<void> _fetchNextPage() async {
|
||||
if (_isLoadingMore || !_hasMore) return;
|
||||
final module = _module;
|
||||
if (module == null) return;
|
||||
|
||||
setState(() {
|
||||
_isLoadingMore = true;
|
||||
_loadError = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final service = await ref.read(scriptWidgetServiceProvider.future);
|
||||
final freshSections = await service.loadModuleSections(
|
||||
widget.widgetId,
|
||||
module,
|
||||
_parameters,
|
||||
);
|
||||
if (!mounted) return;
|
||||
|
||||
final contentItemCount = freshSections.fold<int>(
|
||||
0,
|
||||
(count, section) =>
|
||||
count +
|
||||
section.items
|
||||
.where((item) => item.type.toLowerCase() != 'text')
|
||||
.length,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_mergeSections(freshSections);
|
||||
if (!_supportsPagination || contentItemCount == 0) {
|
||||
_hasMore = false;
|
||||
} else {
|
||||
_advancePagingCursor();
|
||||
}
|
||||
_isFirstLoad = false;
|
||||
_isLoadingMore = false;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loadError = formatUserError(error);
|
||||
_isFirstLoad = false;
|
||||
_isLoadingMore = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void _mergeSections(List<ScriptWidgetContentSection> freshSections) {
|
||||
for (final freshSection in freshSections) {
|
||||
final existingIndex = _sections.indexWhere(
|
||||
(existing) => existing.title == freshSection.title,
|
||||
);
|
||||
if (existingIndex == -1) {
|
||||
_sections.add(freshSection);
|
||||
continue;
|
||||
}
|
||||
final merged = <ScriptVideoItem>[
|
||||
..._sections[existingIndex].items,
|
||||
...freshSection.items,
|
||||
];
|
||||
_sections[existingIndex] = ScriptWidgetContentSection(
|
||||
title: freshSection.title,
|
||||
items: merged,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void _advancePagingCursor() {
|
||||
final module = _module;
|
||||
final pagingParameter = _pagingParameter;
|
||||
if (module == null || pagingParameter == null) return;
|
||||
|
||||
final minimumValue = pagingParameter.type == 'page' ? 1 : 0;
|
||||
final currentValue =
|
||||
int.tryParse(_parameters[pagingParameter.name]?.toString() ?? '') ??
|
||||
minimumValue;
|
||||
final countParameter = module.params
|
||||
.where((parameter) => parameter.type == 'count')
|
||||
.firstOrNull;
|
||||
final pageStep = pagingParameter.type == 'offset'
|
||||
? int.tryParse(_parameters[countParameter?.name]?.toString() ?? '') ??
|
||||
20
|
||||
: 1;
|
||||
_parameters[pagingParameter.name] = currentValue + pageStep;
|
||||
}
|
||||
|
||||
Future<void> _refresh() async {
|
||||
setState(() {
|
||||
_sections.clear();
|
||||
_isFirstLoad = true;
|
||||
_isLoadingMore = false;
|
||||
_hasMore = true;
|
||||
_loadError = null;
|
||||
final module = _module;
|
||||
if (module != null) {
|
||||
_parameters = buildScriptWidgetParameterDefaults(module.params);
|
||||
for (final entry in widget.initialParams.entries) {
|
||||
if (_parameters.containsKey(entry.key)) {
|
||||
_parameters[entry.key] = entry.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
await _fetchNextPage();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final installedWidget = ref.watch(
|
||||
installedScriptWidgetProvider(widget.widgetId),
|
||||
);
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
extendBodyBehindAppBar: true,
|
||||
body: Stack(
|
||||
children: [
|
||||
const Positioned.fill(child: PageBackground()),
|
||||
installedWidget.when(
|
||||
loading: () => const Center(child: AppLoadingRing()),
|
||||
error: (error, _) => Center(
|
||||
child: AppErrorState(
|
||||
message: formatUserError(error),
|
||||
onRetry: () => ref.invalidate(
|
||||
installedScriptWidgetProvider(widget.widgetId),
|
||||
),
|
||||
),
|
||||
),
|
||||
data: (widgetData) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) unawaited(_initialize(widgetData));
|
||||
});
|
||||
return _buildContent(widgetData);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(InstalledScriptWidget installedWidget) {
|
||||
final moduleTitle = _module?.title.trim();
|
||||
final title = moduleTitle == null || moduleTitle.isEmpty
|
||||
? installedWidget.manifest.title
|
||||
: moduleTitle;
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: CustomScrollView(
|
||||
controller: _scrollController,
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
slivers: [
|
||||
AppSliverHeader(title: title),
|
||||
..._buildBodySlivers(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _buildBodySlivers() {
|
||||
if (_initializationError case final initializationError?) {
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: AppErrorState(message: initializationError),
|
||||
),
|
||||
];
|
||||
}
|
||||
if (_module == null || (_isFirstLoad && _isLoadingMore)) {
|
||||
return const [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: Center(child: AppLoadingRing()),
|
||||
),
|
||||
];
|
||||
}
|
||||
final firstLoadError = _isFirstLoad ? _loadError : null;
|
||||
if (firstLoadError != null) {
|
||||
return [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: AppErrorState(
|
||||
message: firstLoadError,
|
||||
onRetry: _fetchNextPage,
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
if (_sections.every((section) => section.items.isEmpty)) {
|
||||
return const [
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: EmptyState(
|
||||
compact: true,
|
||||
icon: Icons.video_library_outlined,
|
||||
title: '没有可显示的内容',
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 14, 20, 0),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate.fixed([
|
||||
for (final section in _sections) ...[
|
||||
_ModuleGridSection(
|
||||
section: section,
|
||||
widgetId: widget.widgetId,
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
],
|
||||
]),
|
||||
),
|
||||
),
|
||||
SliverToBoxAdapter(child: _buildFooter()),
|
||||
];
|
||||
}
|
||||
|
||||
Widget _buildFooter() {
|
||||
if (_isLoadingMore) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 24),
|
||||
child: Center(child: AppLoadingRing()),
|
||||
);
|
||||
}
|
||||
if (_loadError case final loadError?) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
|
||||
child: AppErrorState(
|
||||
compact: true,
|
||||
message: loadError,
|
||||
onRetry: _fetchNextPage,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!_hasMore) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'没有更多了',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox(height: 40);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModuleGridSection extends StatelessWidget {
|
||||
final ScriptWidgetContentSection section;
|
||||
final String widgetId;
|
||||
|
||||
const _ModuleGridSection({required this.section, required this.widgetId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final statusItems = section.items
|
||||
.where((item) => item.type.toLowerCase() == 'text')
|
||||
.toList(growable: false);
|
||||
final contentItems = section.items
|
||||
.where((item) => item.type.toLowerCase() != 'text')
|
||||
.toList(growable: false);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SectionHeader(label: section.title, count: contentItems.length),
|
||||
for (final statusItem in statusItems) ...[
|
||||
_ModuleStatusCard(item: statusItem),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
if (contentItems.isNotEmpty)
|
||||
GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: contentItems.length,
|
||||
gridDelegate: mediaGridDelegate,
|
||||
itemBuilder: (context, index) {
|
||||
final item = contentItems[index];
|
||||
return ScriptVideoCard(
|
||||
item: item,
|
||||
width: double.infinity,
|
||||
onTap: () => context.push(
|
||||
'/modules/${Uri.encodeComponent(widgetId)}/detail',
|
||||
extra: item,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModuleStatusCard extends StatelessWidget {
|
||||
final ScriptVideoItem item;
|
||||
|
||||
const _ModuleStatusCard({required this.item});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final normalizedId = item.id.toLowerCase();
|
||||
final indicatesError =
|
||||
normalizedId.startsWith('err') ||
|
||||
item.title.contains('失败') ||
|
||||
item.title.contains('错误') ||
|
||||
item.title.contains('拦截');
|
||||
final foregroundColor = indicatesError
|
||||
? Theme.of(context).colorScheme.error
|
||||
: context.appTokens.mutedForeground;
|
||||
|
||||
return AppCard(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
indicatesError
|
||||
? Icons.error_outline_rounded
|
||||
: Icons.info_outline_rounded,
|
||||
color: foregroundColor,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.title.isEmpty ? '模块提示' : item.title,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
color: foregroundColor,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
if (item.description.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
item.description,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,961 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:forui/forui.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/contracts/script_widget.dart';
|
||||
import '../../core/domain/usecases/script_widget/script_widget_service.dart';
|
||||
import '../../providers/di_providers.dart';
|
||||
import '../../shared/constants/layout_constants.dart';
|
||||
import '../../shared/theme/app_theme.dart';
|
||||
import '../../shared/utils/user_error_formatter.dart';
|
||||
import '../../shared/widgets/app_card.dart';
|
||||
import '../../shared/widgets/app_error_state.dart';
|
||||
import '../../shared/widgets/app_loading_ring.dart';
|
||||
import '../../shared/widgets/app_sliver_header.dart';
|
||||
import '../../shared/widgets/empty_state.dart';
|
||||
import '../../shared/widgets/error_media_row.dart';
|
||||
import '../../shared/widgets/hover_scrollable_row.dart';
|
||||
import '../../shared/widgets/media_poster_card.dart';
|
||||
import '../../shared/widgets/media_row_metrics.dart';
|
||||
import '../../shared/widgets/page_background.dart';
|
||||
import '../../shared/widgets/script_video_card.dart';
|
||||
import '../../shared/widgets/section_header.dart';
|
||||
import '../../shared/widgets/skeleton_media_row.dart';
|
||||
import 'script_widget_parameter_form.dart';
|
||||
|
||||
class ModuleBrowsePage extends ConsumerStatefulWidget {
|
||||
final String widgetId;
|
||||
|
||||
const ModuleBrowsePage({super.key, required this.widgetId});
|
||||
|
||||
@override
|
||||
ConsumerState<ModuleBrowsePage> createState() => _ModuleBrowsePageState();
|
||||
}
|
||||
|
||||
class _ModuleBrowsePageState extends ConsumerState<ModuleBrowsePage> {
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
final Map<String, Map<String, Object?>> _moduleParameters =
|
||||
<String, Map<String, Object?>>{};
|
||||
|
||||
InstalledScriptWidget? _installedWidget;
|
||||
List<ScriptWidgetContentSection> _searchSections =
|
||||
const <ScriptWidgetContentSection>[];
|
||||
bool _searchMode = false;
|
||||
bool _filtersExpanded = false;
|
||||
bool _loadingSearch = false;
|
||||
String? _searchError;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
List<ScriptWidgetModule> _contentModules(ScriptWidgetManifest manifest) {
|
||||
return manifest.modules
|
||||
.where(
|
||||
(module) =>
|
||||
module.type != 'danmu' &&
|
||||
module.type != 'stream' &&
|
||||
module.id != 'loadResource',
|
||||
)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
Map<String, Object?> _parametersFor(ScriptWidgetModule module) {
|
||||
return _moduleParameters.putIfAbsent(
|
||||
_moduleKey(module),
|
||||
() => buildScriptWidgetParameterDefaults(module.params),
|
||||
);
|
||||
}
|
||||
|
||||
List<ScriptWidgetParam> _searchParameters(ScriptWidgetModule? searchModule) {
|
||||
if (searchModule == null) return const <ScriptWidgetParam>[];
|
||||
return searchModule.params
|
||||
.where((parameter) {
|
||||
final normalizedName = parameter.name.toLowerCase();
|
||||
final isKeywordParameter = const <String>{
|
||||
'keyword',
|
||||
'query',
|
||||
'search',
|
||||
'title',
|
||||
}.contains(normalizedName);
|
||||
final isInternalParameter = const <String>{
|
||||
'constant',
|
||||
'page',
|
||||
'offset',
|
||||
}.contains(parameter.type);
|
||||
return !isKeywordParameter && !isInternalParameter;
|
||||
})
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
Future<void> _search() async {
|
||||
final searchModule = _installedWidget?.manifest.search;
|
||||
if (searchModule == null) return;
|
||||
final keyword = _searchController.text.trim();
|
||||
if (keyword.isEmpty) return;
|
||||
|
||||
final searchParameters = <String, Object?>{
|
||||
...buildScriptWidgetParameterDefaults(searchModule.params),
|
||||
..._parametersFor(searchModule),
|
||||
};
|
||||
final keywordParameter = searchModule.params
|
||||
.where(
|
||||
(parameter) => const <String>{
|
||||
'keyword',
|
||||
'query',
|
||||
'search',
|
||||
'title',
|
||||
}.contains(parameter.name.toLowerCase()),
|
||||
)
|
||||
.firstOrNull;
|
||||
searchParameters[keywordParameter?.name ?? 'keyword'] = keyword;
|
||||
|
||||
setState(() {
|
||||
_loadingSearch = true;
|
||||
_searchError = null;
|
||||
});
|
||||
try {
|
||||
final service = await ref.read(scriptWidgetServiceProvider.future);
|
||||
final items = await service.search(widget.widgetId, searchParameters);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_searchSections = <ScriptWidgetContentSection>[
|
||||
ScriptWidgetContentSection(title: '搜索结果', items: items),
|
||||
];
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_searchError = formatUserError(error);
|
||||
_searchSections = const <ScriptWidgetContentSection>[];
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _loadingSearch = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ScriptWidgetParam? get _searchPagingParameter {
|
||||
final searchModule = _installedWidget?.manifest.search;
|
||||
return searchModule?.params
|
||||
.where(
|
||||
(parameter) => parameter.type == 'page' || parameter.type == 'offset',
|
||||
)
|
||||
.firstOrNull;
|
||||
}
|
||||
|
||||
Future<void> _changeSearchPage(int direction) async {
|
||||
final searchModule = _installedWidget?.manifest.search;
|
||||
final pagingParameter = _searchPagingParameter;
|
||||
if (searchModule == null || pagingParameter == null) return;
|
||||
|
||||
final parameters = _parametersFor(searchModule);
|
||||
final minimumValue = pagingParameter.type == 'page' ? 1 : 0;
|
||||
final currentValue =
|
||||
int.tryParse(parameters[pagingParameter.name]?.toString() ?? '') ??
|
||||
minimumValue;
|
||||
final countParameter = searchModule.params
|
||||
.where((parameter) => parameter.type == 'count')
|
||||
.firstOrNull;
|
||||
final pageStep = pagingParameter.type == 'offset'
|
||||
? int.tryParse(parameters[countParameter?.name]?.toString() ?? '') ?? 20
|
||||
: 1;
|
||||
parameters[pagingParameter.name] = (currentValue + direction * pageStep)
|
||||
.clamp(minimumValue, 1 << 31);
|
||||
await _search();
|
||||
}
|
||||
|
||||
bool get _canGoBackSearchPage {
|
||||
final searchModule = _installedWidget?.manifest.search;
|
||||
final pagingParameter = _searchPagingParameter;
|
||||
if (searchModule == null || pagingParameter == null) return false;
|
||||
final minimumValue = pagingParameter.type == 'page' ? 1 : 0;
|
||||
final currentValue =
|
||||
int.tryParse(
|
||||
_parametersFor(searchModule)[pagingParameter.name]?.toString() ?? '',
|
||||
) ??
|
||||
minimumValue;
|
||||
return currentValue > minimumValue;
|
||||
}
|
||||
|
||||
String get _currentSearchPageLabel {
|
||||
final searchModule = _installedWidget?.manifest.search;
|
||||
final pagingParameter = _searchPagingParameter;
|
||||
if (searchModule == null || pagingParameter == null) return '第 1 页';
|
||||
final parameters = _parametersFor(searchModule);
|
||||
final minimumValue = pagingParameter.type == 'page' ? 1 : 0;
|
||||
final currentValue =
|
||||
int.tryParse(parameters[pagingParameter.name]?.toString() ?? '') ??
|
||||
minimumValue;
|
||||
if (pagingParameter.type == 'page') return '第 $currentValue 页';
|
||||
|
||||
final countParameter = searchModule.params
|
||||
.where((parameter) => parameter.type == 'count')
|
||||
.firstOrNull;
|
||||
final pageSize =
|
||||
int.tryParse(parameters[countParameter?.name]?.toString() ?? '') ?? 20;
|
||||
return '第 ${(currentValue ~/ pageSize) + 1} 页';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final installedWidget = ref.watch(
|
||||
installedScriptWidgetProvider(widget.widgetId),
|
||||
);
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
extendBodyBehindAppBar: true,
|
||||
body: Stack(
|
||||
children: [
|
||||
const Positioned.fill(child: PageBackground()),
|
||||
installedWidget.when(
|
||||
loading: () => const Center(child: AppLoadingRing()),
|
||||
error: (error, _) => Center(
|
||||
child: AppErrorState(
|
||||
message: formatUserError(error),
|
||||
onRetry: () => ref.invalidate(
|
||||
installedScriptWidgetProvider(widget.widgetId),
|
||||
),
|
||||
),
|
||||
),
|
||||
data: (widgetData) {
|
||||
_installedWidget = widgetData;
|
||||
return _buildContent(widgetData);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(InstalledScriptWidget installedWidget) {
|
||||
final manifest = installedWidget.manifest;
|
||||
final contentModules = _contentModules(manifest);
|
||||
final searchParameters = _searchParameters(manifest.search);
|
||||
return CustomScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
slivers: [
|
||||
AppSliverHeader(
|
||||
title: manifest.title,
|
||||
bottom: _searchMode
|
||||
? PreferredSize(
|
||||
preferredSize: const Size.fromHeight(60),
|
||||
child: _SearchControlBar(
|
||||
searchController: _searchController,
|
||||
searchHint: manifest.search?.description,
|
||||
filtersExpanded: _filtersExpanded,
|
||||
hasFilters: searchParameters.isNotEmpty,
|
||||
onSearch: _search,
|
||||
onToggleFilters: () {
|
||||
setState(() => _filtersExpanded = !_filtersExpanded);
|
||||
},
|
||||
),
|
||||
)
|
||||
: null,
|
||||
actions: [
|
||||
if (manifest.search != null)
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_searchMode = !_searchMode;
|
||||
_filtersExpanded = false;
|
||||
});
|
||||
},
|
||||
tooltip: _searchMode ? '关闭搜索' : '搜索',
|
||||
icon: Icon(
|
||||
_searchMode ? Icons.close_rounded : Icons.search_rounded,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (manifest.description.trim().isNotEmpty)
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 14, 20, 6),
|
||||
sliver: SliverToBoxAdapter(
|
||||
child: _ModuleIdentityCard(installedWidget: installedWidget),
|
||||
),
|
||||
),
|
||||
if (_searchMode)
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 56),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate.fixed([
|
||||
_buildSearchFilterPanel(manifest),
|
||||
if (_filtersExpanded && searchParameters.isNotEmpty)
|
||||
const SizedBox(height: 18),
|
||||
_buildSearchResults(),
|
||||
]),
|
||||
),
|
||||
)
|
||||
else if (contentModules.isEmpty)
|
||||
const SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: EmptyState(
|
||||
icon: Icons.video_library_outlined,
|
||||
title: '没有内容功能',
|
||||
message: '该模块没有可浏览的内容功能。',
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverList(
|
||||
delegate: SliverChildListDelegate.fixed([
|
||||
for (final module in contentModules)
|
||||
_ModulePreviewSection(
|
||||
widgetId: widget.widgetId,
|
||||
module: module,
|
||||
),
|
||||
const SizedBox(height: 56),
|
||||
]),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSearchFilterPanel(ScriptWidgetManifest manifest) {
|
||||
final searchModule = manifest.search;
|
||||
final parameters = _searchParameters(searchModule);
|
||||
return AnimatedSize(
|
||||
duration: const Duration(milliseconds: 180),
|
||||
curve: Curves.easeOutCubic,
|
||||
child: !_filtersExpanded || searchModule == null || parameters.isEmpty
|
||||
? const SizedBox.shrink()
|
||||
: AppCard(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (searchModule.description.trim().isNotEmpty) ...[
|
||||
Text(
|
||||
searchModule.description,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
],
|
||||
ScriptWidgetParameterForm(
|
||||
parameters: parameters,
|
||||
initialValues: _parametersFor(searchModule),
|
||||
onChanged: (values) {
|
||||
_parametersFor(searchModule).addAll(values);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FButton(
|
||||
onPress: _search,
|
||||
child: const Text('应用并搜索'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSearchResults() {
|
||||
if (_loadingSearch) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 64),
|
||||
child: Center(child: AppLoadingRing()),
|
||||
);
|
||||
}
|
||||
if (_searchError case final searchError?) {
|
||||
return AppErrorState(
|
||||
compact: true,
|
||||
message: searchError,
|
||||
onRetry: _search,
|
||||
);
|
||||
}
|
||||
if (_searchSections.every((section) => section.items.isEmpty)) {
|
||||
return const EmptyState(
|
||||
compact: true,
|
||||
icon: Icons.search_rounded,
|
||||
title: '输入关键词开始搜索',
|
||||
message: '搜索结果会显示在这里。',
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (final section in _searchSections) ...[
|
||||
_ModuleSearchSection(section: section, widgetId: widget.widgetId),
|
||||
const SizedBox(height: 28),
|
||||
],
|
||||
if (_searchPagingParameter != null)
|
||||
_PaginationBar(
|
||||
canGoBack: _canGoBackSearchPage,
|
||||
pageLabel: _currentSearchPageLabel,
|
||||
onPrevious: () => unawaited(_changeSearchPage(-1)),
|
||||
onNext: () => unawaited(_changeSearchPage(1)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _moduleKey(ScriptWidgetModule module) {
|
||||
return module.id.isEmpty ? module.functionName : module.id;
|
||||
}
|
||||
|
||||
class _ModulePreviewSection extends ConsumerWidget {
|
||||
final String widgetId;
|
||||
final ScriptWidgetModule module;
|
||||
|
||||
const _ModulePreviewSection({required this.widgetId, required this.module});
|
||||
|
||||
|
||||
ScriptWidgetParam? get _primaryEnumerationParam {
|
||||
return module.params
|
||||
.where(
|
||||
(parameter) =>
|
||||
parameter.type == 'enumeration' &&
|
||||
parameter.enumOptions.length >= 2,
|
||||
)
|
||||
.firstOrNull;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final previewKey = (widgetId: widgetId, moduleKey: _moduleKey(module));
|
||||
final sections = ref.watch(scriptWidgetModulePreviewProvider(previewKey));
|
||||
final enumerationParam = _primaryEnumerationParam;
|
||||
final categoryRow = enumerationParam == null
|
||||
? const SizedBox.shrink()
|
||||
: _ModuleCategoryRow(
|
||||
widgetId: widgetId,
|
||||
moduleKey: _moduleKey(module),
|
||||
moduleTitle: module.title,
|
||||
parameter: enumerationParam,
|
||||
);
|
||||
return sections.when(
|
||||
loading: () => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [categoryRow, SkeletonMediaRow(title: module.title)],
|
||||
),
|
||||
error: (error, _) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
categoryRow,
|
||||
ErrorMediaRow(
|
||||
title: module.title,
|
||||
message: formatUserError(error),
|
||||
onRetry: () =>
|
||||
ref.invalidate(scriptWidgetModulePreviewProvider(previewKey)),
|
||||
),
|
||||
],
|
||||
),
|
||||
data: (loadedSections) {
|
||||
final visibleSections = loadedSections
|
||||
.where((section) => section.items.isNotEmpty)
|
||||
.toList(growable: false);
|
||||
if (visibleSections.isEmpty && enumerationParam == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
categoryRow,
|
||||
for (final section in visibleSections)
|
||||
_ModulePreviewRow(
|
||||
widgetId: widgetId,
|
||||
moduleKey: _moduleKey(module),
|
||||
section: section,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class _ModuleCategoryRow extends StatelessWidget {
|
||||
final String widgetId;
|
||||
final String moduleKey;
|
||||
final String moduleTitle;
|
||||
final ScriptWidgetParam parameter;
|
||||
|
||||
const _ModuleCategoryRow({
|
||||
required this.widgetId,
|
||||
required this.moduleKey,
|
||||
required this.moduleTitle,
|
||||
required this.parameter,
|
||||
});
|
||||
|
||||
static const double _cardHeight = 74;
|
||||
static const double _cardWidth = 168;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final options = parameter.enumOptions;
|
||||
final headerLabel = parameter.title.trim().isEmpty
|
||||
? '$moduleTitle · 类型'
|
||||
: '$moduleTitle · ${parameter.title.trim()}';
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 12, 24, 4),
|
||||
child: SectionHeader(label: headerLabel, count: options.length),
|
||||
),
|
||||
SizedBox(
|
||||
height: _cardHeight,
|
||||
child: HoverScrollableRow(
|
||||
builder: (_, scrollController) => ListView.separated(
|
||||
controller: scrollController,
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
itemCount: options.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(width: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final option = options[index];
|
||||
return _CategoryCard(
|
||||
label: option.title.isEmpty ? option.value : option.title,
|
||||
width: _cardWidth,
|
||||
onTap: () => _openCategory(context, option),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
void _openCategory(BuildContext context, ScriptWidgetOption option) {
|
||||
final targetUri = Uri(
|
||||
path:
|
||||
'/modules/${Uri.encodeComponent(widgetId)}/module/'
|
||||
'${Uri.encodeComponent(moduleKey)}',
|
||||
queryParameters: <String, String>{parameter.name: option.value},
|
||||
);
|
||||
context.push(targetUri.toString());
|
||||
}
|
||||
}
|
||||
|
||||
class _CategoryCard extends StatefulWidget {
|
||||
final String label;
|
||||
final double width;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _CategoryCard({
|
||||
required this.label,
|
||||
required this.width,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_CategoryCard> createState() => _CategoryCardState();
|
||||
}
|
||||
|
||||
class _CategoryCardState extends State<_CategoryCard> {
|
||||
bool _isHovered = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final tokens = context.appTokens;
|
||||
return SizedBox(
|
||||
width: widget.width,
|
||||
child: AppCard(
|
||||
filled: true,
|
||||
enableHover: false,
|
||||
radius: tokens.radiusCard,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
onTap: widget.onTap,
|
||||
onHoverChanged: (isHovered) {
|
||||
if (_isHovered == isHovered) return;
|
||||
setState(() => _isHovered = isHovered);
|
||||
},
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.style_outlined,
|
||||
size: 20,
|
||||
color: theme.colorScheme.primary.withValues(
|
||||
alpha: _isHovered ? 0.9 : 0.65,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.label,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModulePreviewRow extends StatelessWidget {
|
||||
final String widgetId;
|
||||
final String moduleKey;
|
||||
final ScriptWidgetContentSection section;
|
||||
|
||||
const _ModulePreviewRow({
|
||||
required this.widgetId,
|
||||
required this.moduleKey,
|
||||
required this.section,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final statusItems = section.items
|
||||
.where((item) => item.type.toLowerCase() == 'text')
|
||||
.toList(growable: false);
|
||||
final contentItems = section.items
|
||||
.where((item) => item.type.toLowerCase() != 'text')
|
||||
.take(20)
|
||||
.toList(growable: false);
|
||||
final compact = MediaRowMetrics.isCompact(context);
|
||||
final cardWidth = MediaRowMetrics.cardWidth(
|
||||
MediaCardVariant.poster,
|
||||
compact: compact,
|
||||
);
|
||||
final rowHeight = MediaRowMetrics.rowHeight(
|
||||
MediaCardVariant.poster,
|
||||
compact: compact,
|
||||
);
|
||||
final allRoute =
|
||||
'/modules/${Uri.encodeComponent(widgetId)}/module/'
|
||||
'${Uri.encodeComponent(moduleKey)}';
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (contentItems.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 12, 24, 4),
|
||||
child: SectionHeader(
|
||||
label: section.title,
|
||||
count: contentItems.length,
|
||||
trailing: TextButton(
|
||||
onPressed: () => context.push(allRoute),
|
||||
child: const Text('查看全部'),
|
||||
),
|
||||
),
|
||||
),
|
||||
for (final statusItem in statusItems)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 4, 24, 12),
|
||||
child: _ModuleStatusCard(item: statusItem),
|
||||
),
|
||||
if (contentItems.isNotEmpty)
|
||||
SizedBox(
|
||||
height: rowHeight,
|
||||
child: HoverScrollableRow(
|
||||
builder: (_, scrollController) => ListView.separated(
|
||||
controller: scrollController,
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
itemCount: contentItems.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(width: 14),
|
||||
itemBuilder: (context, index) {
|
||||
final item = contentItems[index];
|
||||
return ScriptVideoCard(
|
||||
item: item,
|
||||
width: cardWidth,
|
||||
onTap: () => context.push(
|
||||
'/modules/${Uri.encodeComponent(widgetId)}/detail',
|
||||
extra: item,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModuleSearchSection extends StatelessWidget {
|
||||
final ScriptWidgetContentSection section;
|
||||
final String widgetId;
|
||||
|
||||
const _ModuleSearchSection({required this.section, required this.widgetId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final statusItems = section.items
|
||||
.where((item) => item.type.toLowerCase() == 'text')
|
||||
.toList(growable: false);
|
||||
final contentItems = section.items
|
||||
.where((item) => item.type.toLowerCase() != 'text')
|
||||
.toList(growable: false);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SectionHeader(label: section.title, count: contentItems.length),
|
||||
for (final statusItem in statusItems) ...[
|
||||
_ModuleStatusCard(item: statusItem),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
if (contentItems.isNotEmpty)
|
||||
GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: contentItems.length,
|
||||
gridDelegate: mediaGridDelegate,
|
||||
itemBuilder: (context, index) {
|
||||
final item = contentItems[index];
|
||||
return ScriptVideoCard(
|
||||
item: item,
|
||||
width: double.infinity,
|
||||
onTap: () => context.push(
|
||||
'/modules/${Uri.encodeComponent(widgetId)}/detail',
|
||||
extra: item,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModuleIdentityCard extends StatelessWidget {
|
||||
final InstalledScriptWidget installedWidget;
|
||||
|
||||
const _ModuleIdentityCard({required this.installedWidget});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final manifest = installedWidget.manifest;
|
||||
return AppCard(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.extension_rounded,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
manifest.description,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
[
|
||||
if (manifest.author.isNotEmpty) manifest.author,
|
||||
'v${manifest.version}',
|
||||
].join(' · '),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModuleStatusCard extends StatelessWidget {
|
||||
final ScriptVideoItem item;
|
||||
|
||||
const _ModuleStatusCard({required this.item});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final normalizedId = item.id.toLowerCase();
|
||||
final indicatesError =
|
||||
normalizedId.startsWith('err') ||
|
||||
item.title.contains('失败') ||
|
||||
item.title.contains('错误') ||
|
||||
item.title.contains('拦截');
|
||||
final foregroundColor = indicatesError
|
||||
? Theme.of(context).colorScheme.error
|
||||
: context.appTokens.mutedForeground;
|
||||
return AppCard(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
indicatesError
|
||||
? Icons.error_outline_rounded
|
||||
: Icons.info_outline_rounded,
|
||||
color: foregroundColor,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.title.isEmpty ? '模块提示' : item.title,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
color: foregroundColor,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
if (item.description.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
item.description,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SearchControlBar extends StatelessWidget {
|
||||
final TextEditingController searchController;
|
||||
final String? searchHint;
|
||||
final bool filtersExpanded;
|
||||
final bool hasFilters;
|
||||
final VoidCallback onSearch;
|
||||
final VoidCallback onToggleFilters;
|
||||
|
||||
const _SearchControlBar({
|
||||
required this.searchController,
|
||||
required this.searchHint,
|
||||
required this.filtersExpanded,
|
||||
required this.hasFilters,
|
||||
required this.onSearch,
|
||||
required this.onToggleFilters,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final tokens = context.appTokens;
|
||||
return SizedBox(
|
||||
height: 60,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 6, 12, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: searchController,
|
||||
autofocus: true,
|
||||
textInputAction: TextInputAction.search,
|
||||
decoration: InputDecoration(
|
||||
hintText: searchHint?.trim().isNotEmpty == true
|
||||
? searchHint
|
||||
: '输入关键词',
|
||||
prefixIcon: const Icon(Icons.search_rounded, size: 19),
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.onSurface.withValues(
|
||||
alpha: 0.05,
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 10,
|
||||
),
|
||||
isDense: true,
|
||||
),
|
||||
onSubmitted: (_) => onSearch(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
onPressed: onSearch,
|
||||
icon: const Icon(Icons.arrow_forward_rounded),
|
||||
tooltip: '搜索',
|
||||
),
|
||||
if (hasFilters)
|
||||
IconButton(
|
||||
onPressed: onToggleFilters,
|
||||
icon: Icon(
|
||||
Icons.tune_rounded,
|
||||
color: filtersExpanded
|
||||
? theme.colorScheme.primary
|
||||
: tokens.mutedForeground,
|
||||
),
|
||||
tooltip: filtersExpanded ? '收起筛选' : '展开筛选',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PaginationBar extends StatelessWidget {
|
||||
final bool canGoBack;
|
||||
final String pageLabel;
|
||||
final VoidCallback onPrevious;
|
||||
final VoidCallback onNext;
|
||||
|
||||
const _PaginationBar({
|
||||
required this.canGoBack,
|
||||
required this.pageLabel,
|
||||
required this.onPrevious,
|
||||
required this.onNext,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
FButton(
|
||||
variant: FButtonVariant.outline,
|
||||
onPress: canGoBack ? onPrevious : null,
|
||||
child: const Text('上一页'),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14),
|
||||
child: Text(
|
||||
pageLabel,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
),
|
||||
FButton(onPress: onNext, child: const Text('下一页')),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,518 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:forui/forui.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../core/contracts/script_widget.dart';
|
||||
import '../../providers/di_providers.dart';
|
||||
import '../../shared/theme/app_theme.dart';
|
||||
import '../../shared/utils/user_error_formatter.dart';
|
||||
import '../../shared/widgets/app_dialog.dart';
|
||||
import '../../shared/widgets/app_error_state.dart';
|
||||
import '../../shared/widgets/app_inline_alert.dart';
|
||||
import '../../shared/widgets/app_loading_ring.dart';
|
||||
import '../../shared/widgets/app_snack_bar.dart';
|
||||
import '../../shared/widgets/empty_state.dart';
|
||||
import '../../shared/widgets/hover_scrollable_row.dart';
|
||||
import '../../shared/widgets/script_video_card.dart';
|
||||
import '../detail/widgets/detail_hero_panel.dart';
|
||||
import '../detail/widgets/detail_immersive_scaffold.dart';
|
||||
import '../detail/widgets/detail_nav_bar.dart';
|
||||
import '../player/player_launcher.dart';
|
||||
|
||||
const _moduleDetailChromeColor = Color(0xFF08090C);
|
||||
|
||||
class ModuleDetailPage extends ConsumerStatefulWidget {
|
||||
final String widgetId;
|
||||
final ScriptVideoItem seedItem;
|
||||
|
||||
const ModuleDetailPage({
|
||||
super.key,
|
||||
required this.widgetId,
|
||||
required this.seedItem,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<ModuleDetailPage> createState() => _ModuleDetailPageState();
|
||||
}
|
||||
|
||||
class _ModuleDetailPageState extends ConsumerState<ModuleDetailPage> {
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final ValueNotifier<double> _scrollProgress = ValueNotifier<double>(0);
|
||||
|
||||
late ScriptVideoItem _item;
|
||||
bool _loadingDetail = false;
|
||||
bool _loadingResource = false;
|
||||
String? _detailError;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_item = widget.seedItem;
|
||||
_scrollController.addListener(_updateScrollProgress);
|
||||
unawaited(_loadDetail());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.removeListener(_updateScrollProgress);
|
||||
_scrollController.dispose();
|
||||
_scrollProgress.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _updateScrollProgress() {
|
||||
_scrollProgress.value = (_scrollController.offset / 180).clamp(0, 1);
|
||||
}
|
||||
|
||||
Future<void> _loadDetail() async {
|
||||
final link = widget.seedItem.link.trim();
|
||||
if (link.isEmpty) return;
|
||||
setState(() {
|
||||
_loadingDetail = true;
|
||||
_detailError = null;
|
||||
});
|
||||
try {
|
||||
final service = await ref.read(scriptWidgetServiceProvider.future);
|
||||
final loadedItem = await service.loadDetail(widget.widgetId, link);
|
||||
if (!mounted || loadedItem == null) return;
|
||||
setState(() {
|
||||
_item = _mergeSeedWithDetail(widget.seedItem, loadedItem);
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_detailError = formatUserError(error);
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_loadingDetail = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _playItem(ScriptVideoItem playableItem) async {
|
||||
if (_loadingResource) return;
|
||||
setState(() {
|
||||
_loadingResource = true;
|
||||
});
|
||||
try {
|
||||
final resources = await _resolveResources(playableItem);
|
||||
if (!mounted) return;
|
||||
if (resources.isEmpty) {
|
||||
showAppToast(context, '模块没有返回可播放地址', tone: AppAlertTone.error);
|
||||
return;
|
||||
}
|
||||
|
||||
final selectedResource = resources.length == 1
|
||||
? resources.first
|
||||
: await showAppRawDialog<ScriptVideoResource>(
|
||||
context,
|
||||
builder: (_) => _ResourcePickerDialog(resources: resources),
|
||||
);
|
||||
if (selectedResource == null || !mounted) return;
|
||||
await _launchResource(playableItem, selectedResource);
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
showAppToast(context, formatUserError(error), tone: AppAlertTone.error);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_loadingResource = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<ScriptVideoResource>> _resolveResources(
|
||||
ScriptVideoItem playableItem,
|
||||
) async {
|
||||
final service = await ref.read(scriptWidgetServiceProvider.future);
|
||||
final itemJson = playableItem.toJson();
|
||||
final resources = await service
|
||||
.loadResources(widget.widgetId, <String, Object?>{
|
||||
...itemJson,
|
||||
'item': itemJson,
|
||||
'link': playableItem.link,
|
||||
'url': playableItem.videoUrl,
|
||||
'videoUrl': playableItem.videoUrl,
|
||||
});
|
||||
if (resources.isNotEmpty) return resources;
|
||||
final videoUrl = playableItem.videoUrl.trim();
|
||||
if (videoUrl.isEmpty) return const <ScriptVideoResource>[];
|
||||
return <ScriptVideoResource>[
|
||||
ScriptVideoResource(
|
||||
name: playableItem.title,
|
||||
url: videoUrl,
|
||||
playerType: playableItem.playerType,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
Future<void> _launchResource(
|
||||
ScriptVideoItem playableItem,
|
||||
ScriptVideoResource resource,
|
||||
) async {
|
||||
final playerType = resource.playerType.trim().toLowerCase();
|
||||
final shouldUseInternalPlayer =
|
||||
playerType.isEmpty || playerType == 'app' || playerType == 'internal';
|
||||
if (!shouldUseInternalPlayer) {
|
||||
final launched = await launchUrl(
|
||||
Uri.parse(resource.url),
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
if (!launched && mounted) {
|
||||
showAppToast(context, '无法打开外部播放器', tone: AppAlertTone.error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final itemIdentity = base64Url
|
||||
.encode(
|
||||
utf8.encode(
|
||||
'${widget.widgetId}:${playableItem.id}:${playableItem.link}',
|
||||
),
|
||||
)
|
||||
.replaceAll('=', '');
|
||||
await PlayerLauncher.launch(
|
||||
context: context,
|
||||
itemId: 'script-$itemIdentity',
|
||||
directStream: DirectStreamLaunchData(
|
||||
url: resource.url,
|
||||
headers: resource.customHeaders,
|
||||
title: playableItem.title.isEmpty ? _item.title : playableItem.title,
|
||||
durationSeconds: playableItem.duration,
|
||||
seriesName: playableItem == _item ? null : _item.title,
|
||||
episode: playableItem.episode,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final backdropUrl = _firstNonEmpty(<String>[
|
||||
_item.backdropPath,
|
||||
..._item.backdropPaths,
|
||||
_item.detailPoster,
|
||||
_item.posterPath,
|
||||
_item.coverUrl,
|
||||
]);
|
||||
final posterUrl = _firstNonEmpty(<String>[
|
||||
_item.detailPoster,
|
||||
_item.posterPath,
|
||||
_item.coverUrl,
|
||||
]);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: _moduleDetailChromeColor,
|
||||
body: Stack(
|
||||
children: [
|
||||
DetailImmersiveScaffold(
|
||||
scrollController: _scrollController,
|
||||
scrollProgress: _scrollProgress,
|
||||
backdropUrl: backdropUrl,
|
||||
fallbackUrls: _item.backdropPaths,
|
||||
compact: MediaQuery.sizeOf(context).width < 700,
|
||||
horizontalPadding: MediaQuery.sizeOf(context).width < 700 ? 18 : 32,
|
||||
child: _buildDetailContent(posterUrl),
|
||||
),
|
||||
DetailNavBar(
|
||||
scrollProgress: _scrollProgress,
|
||||
title: _item.title,
|
||||
onBack: () => context.pop(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailContent(String? posterUrl) {
|
||||
final metaParts = <String>[
|
||||
if (_item.releaseDate.isNotEmpty) _item.releaseDate,
|
||||
if (_item.mediaType.isNotEmpty) _item.mediaType,
|
||||
if (_item.durationText.isNotEmpty) _item.durationText,
|
||||
];
|
||||
final genres = _item.genreItems
|
||||
.map((genre) => genre.title)
|
||||
.where((title) => title.trim().isNotEmpty)
|
||||
.toList();
|
||||
if (_item.genreTitle.trim().isNotEmpty) genres.add(_item.genreTitle);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
DetailHeroPanel(
|
||||
title: _item.title.isEmpty ? _item.id : _item.title,
|
||||
posterUrl: posterUrl,
|
||||
rating: _item.rating,
|
||||
metaParts: metaParts,
|
||||
genres: genres,
|
||||
overview: _item.description,
|
||||
actions: _buildPlayActions(),
|
||||
),
|
||||
if (_loadingDetail)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 28),
|
||||
child: Center(child: AppLoadingRing(size: 28)),
|
||||
),
|
||||
if (_detailError != null) ...[
|
||||
const SizedBox(height: 24),
|
||||
AppErrorState(
|
||||
compact: true,
|
||||
message: _detailError!,
|
||||
onRetry: _loadDetail,
|
||||
),
|
||||
],
|
||||
if (_item.episodeItems.isNotEmpty || _item.childItems.isNotEmpty) ...[
|
||||
const SizedBox(height: 36),
|
||||
_EpisodeSection(
|
||||
items: _item.episodeItems.isNotEmpty
|
||||
? _item.episodeItems
|
||||
: _item.childItems,
|
||||
onPlay: _playItem,
|
||||
),
|
||||
],
|
||||
if (_item.relatedItems.isNotEmpty) ...[
|
||||
const SizedBox(height: 36),
|
||||
_RelatedSection(widgetId: widget.widgetId, items: _item.relatedItems),
|
||||
],
|
||||
if (!_loadingDetail &&
|
||||
_item.episodeItems.isEmpty &&
|
||||
_item.childItems.isEmpty &&
|
||||
_item.relatedItems.isEmpty &&
|
||||
_item.description.trim().isEmpty) ...[
|
||||
const SizedBox(height: 32),
|
||||
const EmptyState(
|
||||
compact: true,
|
||||
icon: Icons.info_outline_rounded,
|
||||
title: '暂无更多详情',
|
||||
message: '仍可尝试解析并播放该条目。',
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPlayActions() {
|
||||
return FButton(
|
||||
onPress: _loadingResource ? null : () => _playItem(_item),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (_loadingResource)
|
||||
const AppLoadingRing(size: 17)
|
||||
else
|
||||
const Icon(Icons.play_arrow_rounded, size: 20),
|
||||
const SizedBox(width: 7),
|
||||
Text(_loadingResource ? '正在解析' : '播放'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ResourcePickerDialog extends StatelessWidget {
|
||||
final List<ScriptVideoResource> resources;
|
||||
|
||||
const _ResourcePickerDialog({required this.resources});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('选择播放线路', style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'模块返回了 ${resources.length} 条可播放线路。',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 420),
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
itemCount: resources.length,
|
||||
separatorBuilder: (_, _) => const Divider(height: 1),
|
||||
itemBuilder: (context, index) {
|
||||
final resource = resources[index];
|
||||
return FItemGroup(
|
||||
children: [
|
||||
FItem(
|
||||
prefix: Container(
|
||||
width: 30,
|
||||
height: 30,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'${index + 1}',
|
||||
style: Theme.of(context).textTheme.labelMedium
|
||||
?.copyWith(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
resource.name.isEmpty
|
||||
? '线路 ${index + 1}'
|
||||
: resource.name,
|
||||
),
|
||||
subtitle: Text(
|
||||
resource.description.trim().isEmpty
|
||||
? resource.playerType == 'app'
|
||||
? '应用内播放'
|
||||
: '外部播放'
|
||||
: resource.description,
|
||||
),
|
||||
suffix: const Icon(Icons.chevron_right_rounded),
|
||||
onPress: () => Navigator.of(context).pop(resource),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: FButton(
|
||||
variant: FButtonVariant.outline,
|
||||
onPress: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _EpisodeSection extends StatelessWidget {
|
||||
final List<ScriptVideoItem> items;
|
||||
final ValueChanged<ScriptVideoItem> onPlay;
|
||||
|
||||
const _EpisodeSection({required this.items, required this.onPlay});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'选集',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: [
|
||||
for (var index = 0; index < items.length; index++)
|
||||
FButton(
|
||||
variant: FButtonVariant.outline,
|
||||
onPress: () => onPlay(items[index]),
|
||||
child: Text(
|
||||
items[index].title.isNotEmpty
|
||||
? items[index].title
|
||||
: '第 ${items[index].episode ?? index + 1} 集',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RelatedSection extends StatelessWidget {
|
||||
final String widgetId;
|
||||
final List<ScriptVideoItem> items;
|
||||
|
||||
const _RelatedSection({required this.widgetId, required this.items});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'相关推荐',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
height: 250,
|
||||
child: HoverScrollableRow(
|
||||
builder: (context, scrollController) => ListView.separated(
|
||||
controller: scrollController,
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: items.length,
|
||||
separatorBuilder: (_, _) => const SizedBox(width: 14),
|
||||
itemBuilder: (context, index) {
|
||||
final item = items[index];
|
||||
return ScriptVideoCard(
|
||||
item: item,
|
||||
width: 138,
|
||||
textColor: Colors.white,
|
||||
onTap: () => context.push(
|
||||
'/modules/${Uri.encodeComponent(widgetId)}/detail',
|
||||
extra: item,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ScriptVideoItem _mergeSeedWithDetail(
|
||||
ScriptVideoItem seed,
|
||||
ScriptVideoItem detail,
|
||||
) {
|
||||
return detail.copyWith(
|
||||
id: detail.id.isEmpty ? seed.id : detail.id,
|
||||
title: detail.title.isEmpty ? seed.title : detail.title,
|
||||
coverUrl: detail.coverUrl.isEmpty ? seed.coverUrl : detail.coverUrl,
|
||||
posterPath: detail.posterPath.isEmpty ? seed.posterPath : detail.posterPath,
|
||||
detailPoster: detail.detailPoster.isEmpty
|
||||
? seed.detailPoster
|
||||
: detail.detailPoster,
|
||||
backdropPath: detail.backdropPath.isEmpty
|
||||
? seed.backdropPath
|
||||
: detail.backdropPath,
|
||||
link: detail.link.isEmpty ? seed.link : detail.link,
|
||||
videoUrl: detail.videoUrl.isEmpty ? seed.videoUrl : detail.videoUrl,
|
||||
);
|
||||
}
|
||||
|
||||
String? _firstNonEmpty(List<String> values) {
|
||||
for (final value in values) {
|
||||
if (value.trim().isNotEmpty) return value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:forui/forui.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/contracts/script_widget.dart';
|
||||
import '../../providers/di_providers.dart';
|
||||
import '../../shared/theme/app_theme.dart';
|
||||
import '../../shared/utils/user_error_formatter.dart';
|
||||
import '../../shared/widgets/adaptive_modal.dart';
|
||||
import '../../shared/widgets/app_card.dart';
|
||||
import '../../shared/widgets/app_dialog.dart';
|
||||
import '../../shared/widgets/app_error_state.dart';
|
||||
import '../../shared/widgets/app_inline_alert.dart';
|
||||
import '../../shared/widgets/app_loading_ring.dart';
|
||||
import '../../shared/widgets/app_snack_bar.dart';
|
||||
import '../../shared/widgets/auto_dismiss_menu.dart';
|
||||
import '../../shared/widgets/empty_state.dart';
|
||||
import '../../shared/widgets/pill_tab_bar.dart';
|
||||
import 'script_widget_parameter_form.dart';
|
||||
|
||||
|
||||
Future<void> showModuleCenterSheet(BuildContext context) {
|
||||
return showAdaptiveModal<void>(
|
||||
context: context,
|
||||
maxWidth: 720,
|
||||
compactHeightFactor: 0.92,
|
||||
useRootNavigator: true,
|
||||
builder: (sheetContext) => const _ModuleCenterSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
class _ModuleCenterSheet extends StatelessWidget {
|
||||
const _ModuleCenterSheet();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Material(
|
||||
color: theme.colorScheme.surface,
|
||||
child: const ModuleCenterContent(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SheetHeader extends StatelessWidget {
|
||||
final String title;
|
||||
final List<Widget> actions;
|
||||
final bool showCloseButton;
|
||||
|
||||
const _SheetHeader({
|
||||
required this.title,
|
||||
required this.actions,
|
||||
this.showCloseButton = true,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 8, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
title,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
...actions,
|
||||
if (showCloseButton)
|
||||
IconButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.close_rounded),
|
||||
tooltip: '关闭',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class ModuleCenterContent extends ConsumerStatefulWidget {
|
||||
final bool embedded;
|
||||
|
||||
const ModuleCenterContent({super.key, this.embedded = false});
|
||||
|
||||
@override
|
||||
ConsumerState<ModuleCenterContent> createState() =>
|
||||
_ModuleCenterContentState();
|
||||
}
|
||||
|
||||
class _ModuleCenterContentState extends ConsumerState<ModuleCenterContent> {
|
||||
int _selectedSectionIndex = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final installedWidgets = ref.watch(installedScriptWidgetsProvider);
|
||||
final subscriptions = ref.watch(scriptWidgetSubscriptionsProvider);
|
||||
final embedded = widget.embedded;
|
||||
|
||||
final headerActions = <Widget>[
|
||||
IconButton(
|
||||
onPressed: () => _addFromFile(context),
|
||||
icon: const Icon(Icons.file_open_outlined),
|
||||
tooltip: '从本地文件导入',
|
||||
),
|
||||
FButton(
|
||||
onPress: () => _addFromUrl(context),
|
||||
child: const Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.add_link_rounded, size: 17),
|
||||
SizedBox(width: 6),
|
||||
Text('添加 URL'),
|
||||
],
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
|
||||
final headerHorizontalPadding = embedded
|
||||
? const EdgeInsets.fromLTRB(4, 0, 4, 4)
|
||||
: EdgeInsets.zero;
|
||||
final tabPadding = embedded
|
||||
? const EdgeInsets.fromLTRB(4, 8, 4, 4)
|
||||
: const EdgeInsets.fromLTRB(20, 14, 20, 4);
|
||||
final sectionPadding = embedded
|
||||
? const EdgeInsets.fromLTRB(4, 12, 4, 24)
|
||||
: const EdgeInsets.fromLTRB(20, 12, 20, 48);
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: _refresh,
|
||||
child: CustomScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
slivers: [
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: headerHorizontalPadding,
|
||||
child: _SheetHeader(
|
||||
title: embedded ? '' : '模块中心',
|
||||
actions: headerActions,
|
||||
showCloseButton: !embedded,
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: tabPadding,
|
||||
child: PillTabBar(
|
||||
tabs: const <String>['已安装', '模块订阅'],
|
||||
selectedIndex: _selectedSectionIndex,
|
||||
onSelect: (selectedIndex) {
|
||||
setState(() => _selectedSectionIndex = selectedIndex);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverPadding(
|
||||
padding: sectionPadding,
|
||||
sliver: SliverToBoxAdapter(
|
||||
child: _selectedSectionIndex == 0
|
||||
? installedWidgets.when(
|
||||
data: (widgets) => _InstalledWidgetsSection(
|
||||
widgets: widgets,
|
||||
onChanged: () => ref.invalidate(
|
||||
installedScriptWidgetsProvider,
|
||||
),
|
||||
),
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.all(32),
|
||||
child: Center(child: AppLoadingRing()),
|
||||
),
|
||||
error: (error, _) => AppErrorState(
|
||||
compact: true,
|
||||
message: formatUserError(error),
|
||||
onRetry: () => ref.invalidate(
|
||||
installedScriptWidgetsProvider,
|
||||
),
|
||||
),
|
||||
)
|
||||
: subscriptions.when(
|
||||
data: (items) => _SubscriptionsSection(
|
||||
subscriptions: items,
|
||||
onChanged: () {
|
||||
ref.invalidate(scriptWidgetSubscriptionsProvider);
|
||||
ref.invalidate(installedScriptWidgetsProvider);
|
||||
},
|
||||
),
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Center(child: AppLoadingRing(size: 30)),
|
||||
),
|
||||
error: (error, _) => AppErrorState(
|
||||
compact: true,
|
||||
message: formatUserError(error),
|
||||
onRetry: () => ref.invalidate(
|
||||
scriptWidgetSubscriptionsProvider,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _refresh() async {
|
||||
ref.invalidate(installedScriptWidgetsProvider);
|
||||
ref.invalidate(scriptWidgetSubscriptionsProvider);
|
||||
await Future.wait([
|
||||
ref.read(installedScriptWidgetsProvider.future),
|
||||
ref.read(scriptWidgetSubscriptionsProvider.future),
|
||||
]);
|
||||
}
|
||||
|
||||
Future<void> _addFromUrl(BuildContext context) async {
|
||||
final url = await showModuleUrlImportSheet(context);
|
||||
if (url == null || url.trim().isEmpty || !context.mounted) return;
|
||||
try {
|
||||
final service = await ref.read(scriptWidgetServiceProvider.future);
|
||||
if (url.toLowerCase().split('?').first.endsWith('.fwd')) {
|
||||
await service.importSubscription(url.trim());
|
||||
ref.invalidate(scriptWidgetSubscriptionsProvider);
|
||||
if (context.mounted) showAppToast(context, '模块订阅已添加');
|
||||
} else {
|
||||
final installed = await service.installFromUrl(url.trim());
|
||||
ref.invalidate(installedScriptWidgetsProvider);
|
||||
if (context.mounted) {
|
||||
showAppToast(context, '已安装 ${installed.manifest.title}');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (context.mounted) {
|
||||
showAppToast(context, formatUserError(error), tone: AppAlertTone.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _addFromFile(BuildContext context) async {
|
||||
const acceptedFiles = XTypeGroup(
|
||||
label: 'ForwardWidgets',
|
||||
extensions: <String>['js', 'fwd'],
|
||||
);
|
||||
final selectedFile = await openFile(
|
||||
acceptedTypeGroups: const <XTypeGroup>[acceptedFiles],
|
||||
);
|
||||
if (selectedFile == null || !context.mounted) return;
|
||||
try {
|
||||
final source = await selectedFile.readAsString();
|
||||
if (!context.mounted) return;
|
||||
final service = await ref.read(scriptWidgetServiceProvider.future);
|
||||
if (selectedFile.name.toLowerCase().endsWith('.fwd')) {
|
||||
await service.importSubscriptionSource(
|
||||
source,
|
||||
sourceId: 'local:${selectedFile.name}',
|
||||
);
|
||||
ref.invalidate(scriptWidgetSubscriptionsProvider);
|
||||
if (context.mounted) showAppToast(context, '本地模块订阅已添加');
|
||||
return;
|
||||
}
|
||||
final installed = await service.installFromSource(source);
|
||||
ref.invalidate(installedScriptWidgetsProvider);
|
||||
if (context.mounted) {
|
||||
showAppToast(context, '已安装 ${installed.manifest.title}');
|
||||
}
|
||||
} catch (error) {
|
||||
if (context.mounted) {
|
||||
showAppToast(context, formatUserError(error), tone: AppAlertTone.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _InstalledWidgetsSection extends ConsumerWidget {
|
||||
final List<InstalledScriptWidget> widgets;
|
||||
final VoidCallback onChanged;
|
||||
|
||||
const _InstalledWidgetsSection({
|
||||
required this.widgets,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (widgets.isEmpty) {
|
||||
return const EmptyState(
|
||||
compact: true,
|
||||
icon: Icons.widgets_outlined,
|
||||
title: '尚未安装模块',
|
||||
message: '可导入 ForwardWidgets 的 JS 地址、.fwd 订阅或本地脚本。',
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: [
|
||||
for (var index = 0; index < widgets.length; index++) ...[
|
||||
_InstalledWidgetTile(
|
||||
installedWidget: widgets[index],
|
||||
onOpen: () {
|
||||
final widgetId = widgets[index].manifest.id;
|
||||
|
||||
|
||||
Navigator.of(context).pop();
|
||||
context.go('/modules/${Uri.encodeComponent(widgetId)}');
|
||||
},
|
||||
onToggle: (enabled) async {
|
||||
final service = await ref.read(
|
||||
scriptWidgetServiceProvider.future,
|
||||
);
|
||||
await service.setWidgetEnabled(
|
||||
widgets[index].manifest.id,
|
||||
enabled,
|
||||
);
|
||||
onChanged();
|
||||
},
|
||||
onConfigure: widgets[index].manifest.globalParams.isEmpty
|
||||
? null
|
||||
: () async {
|
||||
final values = await showAppRawDialog<Map<String, Object?>>(
|
||||
context,
|
||||
builder: (_) => _GlobalParametersDialog(
|
||||
parameters: widgets[index].manifest.globalParams,
|
||||
initialValues: widgets[index].globalParams,
|
||||
),
|
||||
);
|
||||
if (values == null || !context.mounted) return;
|
||||
final service = await ref.read(
|
||||
scriptWidgetServiceProvider.future,
|
||||
);
|
||||
await service.updateGlobalParams(
|
||||
widgets[index].manifest.id,
|
||||
values,
|
||||
);
|
||||
ref.invalidate(
|
||||
installedScriptWidgetProvider(widgets[index].manifest.id),
|
||||
);
|
||||
onChanged();
|
||||
if (context.mounted) {
|
||||
showAppToast(context, '模块参数已保存');
|
||||
}
|
||||
},
|
||||
onRefresh: widgets[index].sourceUrl.isEmpty
|
||||
? null
|
||||
: () async {
|
||||
try {
|
||||
final service = await ref.read(
|
||||
scriptWidgetServiceProvider.future,
|
||||
);
|
||||
await service.refreshWidget(widgets[index].manifest.id);
|
||||
onChanged();
|
||||
if (context.mounted) {
|
||||
showAppToast(context, '模块已更新');
|
||||
}
|
||||
} catch (error) {
|
||||
if (context.mounted) {
|
||||
showAppToast(
|
||||
context,
|
||||
formatUserError(error),
|
||||
tone: AppAlertTone.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
onDelete: () async {
|
||||
final confirmed = await showAppConfirmDialog(
|
||||
context,
|
||||
title: '删除模块',
|
||||
body: Text('确定删除“${widgets[index].manifest.title}”吗?'),
|
||||
confirmLabel: '删除',
|
||||
destructive: true,
|
||||
);
|
||||
if (!confirmed) return;
|
||||
final service = await ref.read(
|
||||
scriptWidgetServiceProvider.future,
|
||||
);
|
||||
await service.deleteWidget(widgets[index].manifest.id);
|
||||
onChanged();
|
||||
},
|
||||
),
|
||||
if (index < widgets.length - 1) const SizedBox(height: 10),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InstalledWidgetTile extends StatelessWidget {
|
||||
final InstalledScriptWidget installedWidget;
|
||||
final VoidCallback onOpen;
|
||||
final ValueChanged<bool> onToggle;
|
||||
final VoidCallback? onConfigure;
|
||||
final VoidCallback? onRefresh;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
const _InstalledWidgetTile({
|
||||
required this.installedWidget,
|
||||
required this.onOpen,
|
||||
required this.onToggle,
|
||||
required this.onConfigure,
|
||||
required this.onRefresh,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final manifest = installedWidget.manifest;
|
||||
final theme = Theme.of(context);
|
||||
final tokens = context.appTokens;
|
||||
final menuItems = <FItem>[
|
||||
if (onConfigure != null)
|
||||
FItem(
|
||||
prefix: const Icon(Icons.settings_outlined, size: 17),
|
||||
title: const Text('配置全局参数'),
|
||||
onPress: onConfigure,
|
||||
),
|
||||
if (onRefresh != null)
|
||||
FItem(
|
||||
prefix: const Icon(Icons.refresh_rounded, size: 17),
|
||||
title: const Text('检查更新'),
|
||||
onPress: onRefresh,
|
||||
),
|
||||
FItem(
|
||||
prefix: Icon(
|
||||
Icons.delete_outline_rounded,
|
||||
size: 17,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
title: Text('删除模块', style: TextStyle(color: theme.colorScheme.error)),
|
||||
onPress: onDelete,
|
||||
),
|
||||
];
|
||||
|
||||
return Opacity(
|
||||
opacity: installedWidget.enabled ? 1 : 0.62,
|
||||
child: AppCard(
|
||||
onTap: installedWidget.enabled ? onOpen : null,
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 42,
|
||||
height: 42,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(tokens.radiusCard),
|
||||
),
|
||||
child: Text(
|
||||
manifest.title.isEmpty ? '?' : manifest.title[0],
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
manifest.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
[
|
||||
if (manifest.author.isNotEmpty) manifest.author,
|
||||
'v${manifest.version}',
|
||||
'${manifest.modules.length} 个功能',
|
||||
].join(' · '),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: tokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FSwitch(value: installedWidget.enabled, onChange: onToggle),
|
||||
const SizedBox(width: 6),
|
||||
FPopoverMenu(
|
||||
menuBuilder: autoDismissMenuBuilder,
|
||||
menuAnchor: Alignment.topRight,
|
||||
childAnchor: Alignment.bottomRight,
|
||||
menu: [FItemGroup(children: menuItems)],
|
||||
builder: (context, controller, child) =>
|
||||
GestureDetector(onTap: controller.toggle, child: child),
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: Icon(Icons.more_vert_rounded, size: 19),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SubscriptionsSection extends ConsumerWidget {
|
||||
final List<ScriptWidgetSubscription> subscriptions;
|
||||
final VoidCallback onChanged;
|
||||
|
||||
const _SubscriptionsSection({
|
||||
required this.subscriptions,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (subscriptions.isEmpty) {
|
||||
return const EmptyState(
|
||||
compact: true,
|
||||
icon: Icons.inventory_2_outlined,
|
||||
title: '尚未添加订阅',
|
||||
message: '添加 .fwd URL 后,可从仓库中安装和更新模块。',
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
for (final subscription in subscriptions)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: AppCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: ExpansionTile(
|
||||
shape: const Border(),
|
||||
collapsedShape: const Border(),
|
||||
title: Text(subscription.catalog.title),
|
||||
subtitle: Text(
|
||||
'${subscription.catalog.widgets.length} 个模块 · ${subscription.url}',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
tooltip: '刷新订阅',
|
||||
onPressed: subscription.url.startsWith('http')
|
||||
? () async {
|
||||
try {
|
||||
final service = await ref.read(
|
||||
scriptWidgetServiceProvider.future,
|
||||
);
|
||||
await service.importSubscription(subscription.url);
|
||||
onChanged();
|
||||
} catch (error) {
|
||||
if (context.mounted) {
|
||||
showAppToast(
|
||||
context,
|
||||
formatUserError(error),
|
||||
tone: AppAlertTone.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
: null,
|
||||
),
|
||||
children: [
|
||||
for (final entry in subscription.catalog.widgets)
|
||||
_CatalogEntryRow(
|
||||
entry: entry,
|
||||
onInstall: () async {
|
||||
try {
|
||||
final service = await ref.read(
|
||||
scriptWidgetServiceProvider.future,
|
||||
);
|
||||
await service.installFromUrl(entry.url);
|
||||
onChanged();
|
||||
if (context.mounted) {
|
||||
showAppToast(context, '已安装 ${entry.title}');
|
||||
}
|
||||
} catch (error) {
|
||||
if (context.mounted) {
|
||||
showAppToast(
|
||||
context,
|
||||
formatUserError(error),
|
||||
tone: AppAlertTone.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CatalogEntryRow extends StatelessWidget {
|
||||
final ScriptWidgetCatalogEntry entry;
|
||||
final VoidCallback onInstall;
|
||||
|
||||
const _CatalogEntryRow({required this.entry, required this.onInstall});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 10, 16, 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
entry.title,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
entry.description.isNotEmpty
|
||||
? entry.description
|
||||
: '${entry.author} · v${entry.version}',
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: context.appTokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
FButton(
|
||||
variant: FButtonVariant.outline,
|
||||
onPress: onInstall,
|
||||
child: const Text('安装'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _GlobalParametersDialog extends StatefulWidget {
|
||||
final List<ScriptWidgetParam> parameters;
|
||||
final Map<String, Object?> initialValues;
|
||||
|
||||
const _GlobalParametersDialog({
|
||||
required this.parameters,
|
||||
required this.initialValues,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_GlobalParametersDialog> createState() =>
|
||||
_GlobalParametersDialogState();
|
||||
}
|
||||
|
||||
class _GlobalParametersDialogState extends State<_GlobalParametersDialog> {
|
||||
late Map<String, Object?> _values;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_values = <String, Object?>{
|
||||
...buildScriptWidgetParameterDefaults(widget.parameters),
|
||||
...widget.initialValues,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('全局参数', style: Theme.of(context).textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
const Text('这些值会自动合并到该模块的每次调用中。'),
|
||||
const SizedBox(height: 18),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 440),
|
||||
child: SingleChildScrollView(
|
||||
child: ScriptWidgetParameterForm(
|
||||
parameters: widget.parameters,
|
||||
initialValues: _values,
|
||||
onChanged: (values) {
|
||||
_values = Map<String, Object?>.from(values);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
FButton(
|
||||
variant: FButtonVariant.outline,
|
||||
onPress: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FButton(
|
||||
onPress: () => Navigator.of(context).pop(_values),
|
||||
child: const Text('保存'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> showModuleUrlImportSheet(BuildContext context) {
|
||||
return showAdaptiveModal<String>(
|
||||
context: context,
|
||||
maxWidth: 520,
|
||||
useRootNavigator: true,
|
||||
compactMaxHeightFactor: 0.6,
|
||||
builder: (sheetContext) => const _UrlImportSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
class _UrlImportSheet extends StatefulWidget {
|
||||
const _UrlImportSheet();
|
||||
|
||||
@override
|
||||
State<_UrlImportSheet> createState() => _UrlImportSheetState();
|
||||
}
|
||||
|
||||
class _UrlImportSheetState extends State<_UrlImportSheet> {
|
||||
final TextEditingController _urlController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_urlController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final tokens = context.appTokens;
|
||||
final inputBorder = OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(
|
||||
color: tokens.mutedForeground.withValues(alpha: 0.28),
|
||||
),
|
||||
);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('添加模块', style: theme.textTheme.titleLarge),
|
||||
const SizedBox(height: 8),
|
||||
const Text('支持单个 .js 脚本地址或 ForwardWidgets .fwd 订阅地址。'),
|
||||
const SizedBox(height: 18),
|
||||
TextField(
|
||||
controller: _urlController,
|
||||
autofocus: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'HTTP(S) URL',
|
||||
hintText: 'https://example.com/widgets.fwd',
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.surface.withValues(alpha: 0.42),
|
||||
border: inputBorder,
|
||||
enabledBorder: inputBorder,
|
||||
focusedBorder: inputBorder.copyWith(
|
||||
borderSide: BorderSide(color: theme.colorScheme.primary),
|
||||
),
|
||||
isDense: true,
|
||||
),
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
FButton(
|
||||
variant: FButtonVariant.outline,
|
||||
onPress: () => Navigator.of(context).pop(),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FButton(onPress: _submit, child: const Text('继续')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
final url = _urlController.text.trim();
|
||||
if (url.isEmpty) return;
|
||||
Navigator.of(context).pop(url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/contracts/script_widget.dart';
|
||||
import '../../shared/theme/app_theme.dart';
|
||||
import '../../shared/widgets/setting_select.dart';
|
||||
|
||||
class ScriptWidgetParameterForm extends StatefulWidget {
|
||||
final List<ScriptWidgetParam> parameters;
|
||||
final Map<String, Object?> initialValues;
|
||||
final ValueChanged<Map<String, Object?>> onChanged;
|
||||
final bool hidePagingParameters;
|
||||
|
||||
const ScriptWidgetParameterForm({
|
||||
super.key,
|
||||
required this.parameters,
|
||||
required this.initialValues,
|
||||
required this.onChanged,
|
||||
this.hidePagingParameters = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<ScriptWidgetParameterForm> createState() =>
|
||||
_ScriptWidgetParameterFormState();
|
||||
}
|
||||
|
||||
class _ScriptWidgetParameterFormState extends State<ScriptWidgetParameterForm> {
|
||||
final Map<String, TextEditingController> _textControllers =
|
||||
<String, TextEditingController>{};
|
||||
late Map<String, Object?> _values;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_values = _buildInitialValues();
|
||||
_synchronizeTextControllers();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ScriptWidgetParameterForm oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.parameters != widget.parameters ||
|
||||
oldWidget.initialValues != widget.initialValues) {
|
||||
_values = _buildInitialValues();
|
||||
_synchronizeTextControllers();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final controller in _textControllers.values) {
|
||||
controller.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Map<String, Object?> _buildInitialValues() {
|
||||
final defaultValues = buildScriptWidgetParameterDefaults(widget.parameters);
|
||||
return <String, Object?>{
|
||||
for (final parameter in widget.parameters)
|
||||
parameter.name:
|
||||
widget.initialValues[parameter.name] ??
|
||||
defaultValues[parameter.name],
|
||||
};
|
||||
}
|
||||
|
||||
void _synchronizeTextControllers() {
|
||||
final activeNames = widget.parameters
|
||||
.where((parameter) => !_usesOptionSelector(parameter))
|
||||
.map((parameter) => parameter.name)
|
||||
.toSet();
|
||||
final staleNames = _textControllers.keys
|
||||
.where((name) => !activeNames.contains(name))
|
||||
.toList(growable: false);
|
||||
for (final name in staleNames) {
|
||||
_textControllers.remove(name)?.dispose();
|
||||
}
|
||||
for (final parameter in widget.parameters) {
|
||||
if (_usesOptionSelector(parameter)) continue;
|
||||
final value = _values[parameter.name]?.toString() ?? '';
|
||||
final controller = _textControllers.putIfAbsent(
|
||||
parameter.name,
|
||||
TextEditingController.new,
|
||||
);
|
||||
if (controller.text != value) {
|
||||
controller.value = TextEditingValue(
|
||||
text: value,
|
||||
selection: TextSelection.collapsed(offset: value.length),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _usesOptionSelector(ScriptWidgetParam parameter) {
|
||||
return parameter.type == 'enumeration' ||
|
||||
parameter.enumOptions.isNotEmpty ||
|
||||
parameter.placeholders.isNotEmpty;
|
||||
}
|
||||
|
||||
bool _isVisible(ScriptWidgetParam parameter) {
|
||||
if (parameter.type == 'constant') return false;
|
||||
if (widget.hidePagingParameters &&
|
||||
const <String>{'page', 'offset'}.contains(parameter.type)) {
|
||||
return false;
|
||||
}
|
||||
final condition = parameter.belongTo;
|
||||
if (condition == null || condition.paramName.isEmpty) return true;
|
||||
final parentValue = _values[condition.paramName]?.toString() ?? '';
|
||||
return condition.value.contains(parentValue);
|
||||
}
|
||||
|
||||
void _updateValue(String name, Object? value) {
|
||||
setState(() {
|
||||
_values[name] = value;
|
||||
});
|
||||
widget.onChanged(Map<String, Object?>.unmodifiable(_values));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final visibleParameters = widget.parameters
|
||||
.where(_isVisible)
|
||||
.toList(growable: false);
|
||||
if (visibleParameters.isEmpty) return const SizedBox.shrink();
|
||||
|
||||
return Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
for (final parameter in visibleParameters)
|
||||
SizedBox(
|
||||
width: _fieldWidth(parameter),
|
||||
child: _buildField(parameter),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
double _fieldWidth(ScriptWidgetParam parameter) {
|
||||
if (const <String>{'count', 'page', 'offset'}.contains(parameter.type)) {
|
||||
return 132;
|
||||
}
|
||||
return 240;
|
||||
}
|
||||
|
||||
Widget _buildField(ScriptWidgetParam parameter) {
|
||||
final options = parameter.enumOptions.isNotEmpty
|
||||
? parameter.enumOptions
|
||||
: parameter.placeholders;
|
||||
if (_usesOptionSelector(parameter)) {
|
||||
final selectedValue = _values[parameter.name]?.toString() ?? '';
|
||||
final optionValues = options.map((option) => option.value).toSet();
|
||||
final effectiveValue = optionValues.contains(selectedValue)
|
||||
? selectedValue
|
||||
: null;
|
||||
final labelsByValue = <String, String>{
|
||||
for (final option in options)
|
||||
option.value: option.title.isEmpty ? option.value : option.title,
|
||||
};
|
||||
final theme = Theme.of(context);
|
||||
final tokens = context.appTokens;
|
||||
final helper = _helperFor(parameter);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
_labelFor(parameter),
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
SettingSelect<String>(
|
||||
value: effectiveValue,
|
||||
options: options
|
||||
.map((option) => option.value)
|
||||
.toList(growable: false),
|
||||
labelOf: (value) => labelsByValue[value] ?? value,
|
||||
onChanged: (value) => _updateValue(parameter.name, value ?? ''),
|
||||
),
|
||||
if (helper != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
helper,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: tokens.mutedForeground,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final isNumeric = const <String>{
|
||||
'count',
|
||||
'page',
|
||||
'offset',
|
||||
}.contains(parameter.type);
|
||||
final theme = Theme.of(context);
|
||||
final tokens = context.appTokens;
|
||||
final inputBorder = OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(
|
||||
color: tokens.mutedForeground.withValues(alpha: 0.28),
|
||||
),
|
||||
);
|
||||
return TextField(
|
||||
controller: _textControllers[parameter.name],
|
||||
keyboardType: isNumeric ? TextInputType.number : TextInputType.text,
|
||||
decoration: InputDecoration(
|
||||
labelText: _labelFor(parameter),
|
||||
helperText: _helperFor(parameter),
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.surface.withValues(alpha: 0.42),
|
||||
border: inputBorder,
|
||||
enabledBorder: inputBorder,
|
||||
focusedBorder: inputBorder.copyWith(
|
||||
borderSide: BorderSide(color: theme.colorScheme.primary),
|
||||
),
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: (value) {
|
||||
final parsedValue = isNumeric ? int.tryParse(value) ?? value : value;
|
||||
_updateValue(parameter.name, parsedValue);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
String _labelFor(ScriptWidgetParam parameter) {
|
||||
return parameter.title.isEmpty ? parameter.name : parameter.title;
|
||||
}
|
||||
|
||||
String? _helperFor(ScriptWidgetParam parameter) {
|
||||
final description = parameter.description.trim();
|
||||
return description.isEmpty ? null : description;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user