Skip to content

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

feat(search): redesign anime search

Predidit0aadad1e7ea8
diff --git a/lib/pages/search/search_controller.dart b/lib/pages/search/search_controller.dart
index e00789db..6c8c65d7 100644
--- a/lib/pages/search/search_controller.dart
+++ b/lib/pages/search/search_controller.dart
@@ -28,6 +28,7 @@ abstract class _SearchPageController with Store {
final ISearchHistoryRepository _searchHistoryRepository;
int _searchOffset = 0;
+ int _searchGeneration = 0;
bool hasMoreSearchResults = true;
@@ -67,44 +68,37 @@ abstract class _SearchPageController with Store {
@action
Future<void> searchBangumi(String input, {String type = 'add'}) async {
+ if (type == 'add' && (isLoading || !hasMoreSearchResults)) return;
+ final generation = type == 'add' ? _searchGeneration : ++_searchGeneration;
+ isLoading = true;
+ isTimeOut = false;
if (type != 'add') {
bangumiList.clear();
_searchOffset = 0;
hasMoreSearchResults = true;
- bool privateMode = _collectRepository.getPrivateMode();
- if (!privateMode) {
- // 检查是否已满,删除最旧的记录
+ if (!_collectRepository.getPrivateMode() && input.trim().isNotEmpty) {
if (_searchHistoryRepository.isHistoryFull(10)) {
await _searchHistoryRepository.deleteOldest();
}
- // 删除重复的历史记录
await _searchHistoryRepository.deleteDuplicates(input);
- // 保存新的搜索历史
await _searchHistoryRepository.saveHistory(input);
- // 重新加载历史记录
loadSearchHistories();
}
}
- isLoading = true;
- isTimeOut = false;
- SearchParser parser = SearchParser(input);
- final filterState = parser.toFilterState();
- String? idString = filterState.id.isEmpty ? null : filterState.id;
- if (idString != null) {
- final id = int.tryParse(idString);
- if (id != null) {
- final BangumiItem? item = await BangumiApi.getBangumiInfoByID(id);
- if (item != null) {
- bangumiList.add(item);
- }
- hasMoreSearchResults = false;
- isLoading = false;
- isTimeOut = bangumiList.isEmpty;
- return;
+ if (generation != _searchGeneration) return;
+ final filterState = SearchParser(input).toFilterState();
+ final id = int.tryParse(filterState.id);
+ if (id != null) {
+ final item = await BangumiApi.getBangumiInfoByID(id);
+ if (generation != _searchGeneration) return;
+ if (item != null) {
+ bangumiList.add(item);
}
+ hasMoreSearchResults = false;
+ isLoading = false;
+ isTimeOut = bangumiList.isEmpty;
+ return;
}
- var addedVisibleItems = false;
- var fetchedAnyPage = false;
var pagesFetched = 0;
do {
final page = await BangumiApi.bangumiSearch(filterState.keyword,
@@ -116,10 +110,11 @@ abstract class _SearchPageController with Store {
rankRange: filterState.rankRange,
scoreRange: filterState.scoreRange,
weekdays: filterState.weekdays);
+ // Discard stale responses before mutating the current search.
+ if (generation != _searchGeneration) return;
if (page == null) {
break;
}
- fetchedAnyPage = true;
pagesFetched++;
_searchOffset += page.rawCount;
hasMoreSearchResults = page.rawCount == _searchPageSize;
@@ -128,14 +123,12 @@ abstract class _SearchPageController with Store {
page.items.where((item) => existingIds.add(item.id)).toList();
if (newItems.isNotEmpty) {
bangumiList.addAll(newItems);
- addedVisibleItems = true;
+ break;
}
- } while (!addedVisibleItems &&
- hasMoreSearchResults &&
- pagesFetched < _maxPagesPerSearch);
+ } while (hasMoreSearchResults && pagesFetched < _maxPagesPerSearch);
isLoading = false;
isTimeOut =
- bangumiList.isEmpty && (!fetchedAnyPage || !hasMoreSearchResults);
+ bangumiList.isEmpty && (pagesFetched == 0 || !hasMoreSearchResults);
}
@action
diff --git a/lib/pages/search/search_filter_sheet.dart b/lib/pages/search/search_filter_sheet.dart
new file mode 100644
index 00000000..56d86716
--- /dev/null
+++ b/lib/pages/search/search_filter_sheet.dart
@@ -0,0 +1,452 @@
+part of 'search_page.dart';
+
+class _SearchFilterResult {
+ const _SearchFilterResult({
+ required this.filterState,
+ required this.notShowWatched,
+ required this.notShowAbandoned,
+ });
+
+ final SearchFilterState filterState;
+ final bool notShowWatched;
+ final bool notShowAbandoned;
+}
+
+class _SearchFilterSheet extends StatefulWidget {
+ const _SearchFilterSheet({
+ required this.initialState,
+ required this.initialNotShowWatched,
+ required this.initialNotShowAbandoned,
+ });
+
+ final SearchFilterState initialState;
+ final bool initialNotShowWatched;
+ final bool initialNotShowAbandoned;
+
+ @override
+ State<_SearchFilterSheet> createState() => _SearchFilterSheetState();
+}
+
+class _SearchFilterSheetState extends State<_SearchFilterSheet> {
+ late SearchFilterState _draft = widget.initialState;
+ late bool _notShowWatched = widget.initialNotShowWatched;
+ late bool _notShowAbandoned = widget.initialNotShowAbandoned;
+ final TextEditingController _tagController = TextEditingController();
+
+ @override
+ void dispose() {
+ _tagController.dispose();
+ super.dispose();
+ }
+
+ Map<String, String> get _seasonOptions {
+ final now = DateTime.now();
+ final values = <String, String>{};
+ for (int year = now.year; year >= now.year - 19; year--) {
+ for (int quarter = 4; quarter >= 1; quarter--) {
+ final date = DateTime(year, (quarter - 1) * 3 + 1, 1);
+ if (now.isAfter(date)) {
+ values['${year}Q$quarter'] =
+ '$year ${const ['冬季', '春季', '夏季', '秋季'][quarter - 1]}';
+ }
+ }
+ }
+ return {
+ if (_draft.season.isNotEmpty && !values.containsKey(_draft.season))
+ _draft.season: _draft.season,
+ ...values,
+ };
+ }
+
+ void _addTag(String value) {
+ final tag = value.trim();
+ if (tag.isEmpty || _draft.tags.contains(tag)) return;
+ setState(() {
+ _draft = _draft.copyWith(tags: [..._draft.tags, tag]);
+ _tagController.clear();
+ });
+ FocusScope.of(context).unfocus();
+ }
+
+ void _reset() {
+ setState(() {
+ _draft = SearchFilterState(id: _draft.id, keyword: _draft.keyword);
+ _notShowWatched = false;
+ _notShowAbandoned = false;
+ _tagController.clear();
+ });
+ }
+
+ Future<void> _pickCustomDateRange() async {
+ final now = DateTime.now();
+ final initialStart = _draft.dateRange?.start != null
+ ? DateTime.tryParse(_draft.dateRange!.start)
+ : null;
+ final initialEnd = _draft.dateRange?.end != null
+ ? DateTime.tryParse(_draft.dateRange!.end)
+ : null;
+ final result = await showDateRangePicker(
+ context: context,
+ firstDate: DateTime(1970),
+ lastDate: DateTime(now.year + 3, 12, 31),
+ initialDateRange: initialStart != null && initialEnd != null
+ ? DateTimeRange(start: initialStart, end: initialEnd)
+ : null,
+ );
+ if (!mounted || result == null) return;
+ setState(() {
+ _draft = _draft.copyWith(
+ season: '',
+ dateRange: SearchDateRange(
+ start: formatDateTime(result.start),
+ end: formatDateTime(result.end),
+ ),
+ );
+ });
+ }
+
+ Widget _buildScoreRangeSlider(SearchDoubleRange range) {
+ final values = _safeRangeValues(
+ range.min ?? 0,
+ range.max ?? 10,
+ 0,
+ 10,
+ );
+ return RangeSlider(
+ values: values,
+ min: 0,
+ max: 10,
+ divisions: 20,
+ labels: RangeLabels(
+ values.start.toStringAsFixed(1),
+ values.end.toStringAsFixed(1),
+ ),
+ onChanged: (value) {
+ setState(() {
+ _draft = _draft.copyWith(
+ scoreRange: SearchDoubleRange(
+ min: value.start,
+ max: value.end,
+ ),
+ );
+ });
+ },
+ );
+ }
+
+ Widget _buildRankRangeSlider(SearchIntRange range) {
+ final values = _safeRangeValues(
+ (range.min ?? 1).toDouble(),
+ (range.max ?? 10000).toDouble(),
+ 1,
+ 10000,
+ );
+ return RangeSlider(
+ values: values,
+ min: 1,
+ max: 10000,
+ divisions: 100,
+ labels: RangeLabels(
+ '${values.start.round()}',
+ '${values.end.round()}',
+ ),
+ onChanged: (value) {
+ setState(() {
+ _draft = _draft.copyWith(
+ rankRange: SearchIntRange(
+ min: value.start.round(),
+ max: value.end.round(),
+ ),
+ );
+ });
+ },
+ );
+ }
+
+ InputDecoration _fieldDecoration(String label) => InputDecoration(
+ labelText: label,
+ filled: true,
+ fillColor: Theme.of(context).colorScheme.surfaceContainerLow,
+ // Keep labels inside the fill to avoid ExpansionTile clipping.
+ border: UnderlineInputBorder(
+ borderRadius: BorderRadius.circular(16),
+ borderSide: BorderSide.none),
+ );
+
+ void _apply() => Navigator.pop(
+ context,
+ _SearchFilterResult(
+ filterState: _draft,
+ notShowWatched: _notShowWatched,
+ notShowAbandoned: _notShowAbandoned,
+ ));
+
+ @override
+ Widget build(BuildContext context) {
+ final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
+ final colors = Theme.of(context).colorScheme;
+ final dateSummary = _draft.season.isNotEmpty
+ ? _draft.season
+ : _draft.dateRange == null
+ ? '不限日期'
+ : '${_draft.dateRange!.start} 至 ${_draft.dateRange!.end}';
+ return Padding(
+ padding: EdgeInsets.only(bottom: keyboardInset),
+ child: LayoutBuilder(builder: (context, constraints) {
+ final shortWindow = keyboardInset > 0 && constraints.maxHeight < 280;
+ return Column(mainAxisSize: MainAxisSize.min, children: [
+ if (!shortWindow)
+ MaterialBottomSheetHeader(
+ title: '筛选番剧', onClose: () => Navigator.pop(context)),
+ Flexible(
+ child: ListView(
+ shrinkWrap: true,
+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
+ padding: const EdgeInsets.fromLTRB(24, 8, 24, 16),
+ children: [
+ if (_draft.isIdSearch)
+ ListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('当前按编号定位番剧'),
+ subtitle: const Text('清除编号后,可以组合其他条件查找。'),
+ trailing: TextButton(
+ onPressed: () =>
+ setState(() => _draft = _draft.copyWith(id: '')),
+ child: const Text('清除编号')),
+ ),
+ DropdownButtonFormField<String>(
+ key: ValueKey('sort-${_draft.sort}'),
+ initialValue: _draft.sort,
+ isExpanded: true,
+ decoration: _fieldDecoration('排序方式'),
+ items: [
+ for (final sort in _searchSortLabels.entries)
+ DropdownMenuItem(
+ value: sort.key, child: Text('按${sort.value}排序')),
+ ],
+ onChanged: (value) => setState(
+ () => _draft = _draft.copyWith(sort: value ?? 'heat')),
+ ),
+ const SizedBox(height: 16),
+ _SearchFilterGroup(
+ title: '题材标签',
+ summary: _draft.tags.isEmpty ? '不限题材' : _draft.tags.join('、'),
+ initiallyExpanded: _draft.tags.isNotEmpty,
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Wrap(spacing: 8, runSpacing: 4, children: [
+ for (final tag in {...defaultAnimeTags, ..._draft.tags})
+ FilterChip(
+ label: Text(tag),
+ selected: _draft.tags.contains(tag),
+ onSelected: (selected) =>
+ setState(() => _draft = _draft.copyWith(
+ tags: selected
+ ? [..._draft.tags, tag]
+ : _draft.tags
+ .where((item) => item != tag)
+ .toList(),
+ )),
+ ),
+ ])),
+ const SizedBox(height: 12),
+ TextField(
+ // Separate scroll offsets from the expansion's boolean state.
+ key: const PageStorageKey('custom-tag-input'),
+ controller: _tagController,
+ textInputAction: TextInputAction.done,
+ decoration: _fieldDecoration('自定义标签').copyWith(
+ suffixIcon: IconButton(
+ tooltip: '添加标签',
+ onPressed: () => _addTag(_tagController.text),
+ icon: const Icon(Icons.add_rounded))),
+ onSubmitted: _addTag,
+ ),
+ ],
+ ),
+ Divider(height: 1, color: colors.outlineVariant),
+ _SearchFilterGroup(
+ title: '放送时间',
+ summary:
+ '$dateSummary${_draft.weekdays.isNotEmpty ? ' · 已选 ${_draft.weekdays.length} 天' : ''}',
+ initiallyExpanded: _draft.season.isNotEmpty ||
+ _draft.dateRange != null ||
+ _draft.weekdays.isNotEmpty,
+ children: [
+ DropdownButtonFormField<String>(
+ key: ValueKey('season-${_draft.season}'),
+ initialValue: _draft.season,
+ isExpanded: true,
+ decoration: _fieldDecoration('放送季度'),
+ items: [
+ const DropdownMenuItem(value: '', child: Text('不限季度')),
+ for (final season in _seasonOptions.entries)
+ DropdownMenuItem(
+ value: season.key, child: Text(season.value)),
+ ],
+ onChanged: (value) => setState(() => _draft =
+ _draft.copyWith(season: value ?? '', dateRange: null)),
+ ),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Wrap(spacing: 8, children: [
+ TextButton.icon(
+ onPressed: _pickCustomDateRange,
+ icon: const Icon(Icons.date_range_outlined),
+ label: const Text('自定义日期')),
+ if (_draft.dateRange != null ||
+ _draft.season.isNotEmpty)
+ TextButton(
+ onPressed: () => setState(() => _draft =
+ _draft.copyWith(season: '', dateRange: null)),
+ child: const Text('清除日期')),
+ ])),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Wrap(spacing: 8, runSpacing: 4, children: [
+ for (var day = 1; day <= 7; day++)
+ FilterChip(
+ label: Text('周${'一二三四五六日'[day - 1]}'),
+ selected: _draft.weekdays.contains(day),
+ showCheckmark: false,
+ onSelected: (selected) {
+ final days = _draft.weekdays.toSet();
+ selected ? days.add(day) : days.remove(day);
+ setState(() => _draft = _draft.copyWith(
+ weekdays: days.toList()..sort()));
+ },
+ ),
+ ])),
+ ],
+ ),
+ Divider(height: 1, color: colors.outlineVariant),
+ _SearchFilterGroup(
+ title: '评分与排名',
+ summary: [
+ if (_draft.scoreRange?.isValid == true)
+ '评分 ${_draft.scoreRange!.toToken()}',
+ if (_draft.rankRange?.isValid == true)
+ '排名 ${_draft.rankRange!.toToken()}',
+ if (_draft.scoreRange == null && _draft.rankRange == null)
+ '不限',
+ ].join(' · '),
+ initiallyExpanded:
+ _draft.scoreRange != null || _draft.rankRange != null,
+ children: [
+ SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('限定评分'),
+ value: _draft.scoreRange?.isValid == true,
+ onChanged: (value) => setState(() => _draft =
+ _draft.copyWith(
+ scoreRange: value
+ ? const SearchDoubleRange(min: 7, max: 10)
+ : null)),
+ ),
+ if (_draft.scoreRange?.isValid == true) ...[
+ _buildScoreRangeSlider(_draft.scoreRange!),
+ Text('评分 ${_draft.scoreRange!.toToken()}'),
+ ],
+ SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('限定排名'),
+ value: _draft.rankRange?.isValid == true,
+ onChanged: (value) => setState(() => _draft =
+ _draft.copyWith(
+ rankRange: value
+ ? const SearchIntRange(min: 1, max: 5000)
+ : null)),
+ ),
+ if (_draft.rankRange?.isValid == true) ...[
+ _buildRankRangeSlider(_draft.rankRange!),
+ Text('排名 ${_draft.rankRange!.toToken()}'),
+ ],
+ ],
+ ),
+ Divider(height: 1, color: colors.outlineVariant),
+ _SearchFilterGroup(
+ title: '收藏状态',
+ summary: [
+ if (_notShowWatched) '隐藏已看',
+ if (_notShowAbandoned) '隐藏已弃',
+ if (!_notShowWatched && !_notShowAbandoned) '显示全部'
+ ].join(' · '),
+ initiallyExpanded: _notShowWatched || _notShowAbandoned,
+ children: [
+ SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('隐藏看过的番剧'),
+ value: _notShowWatched,
+ onChanged: (value) =>
+ setState(() => _notShowWatched = value)),
+ SwitchListTile(
+ contentPadding: EdgeInsets.zero,
+ title: const Text('隐藏抛弃的番剧'),
+ value: _notShowAbandoned,
+ onChanged: (value) =>
+ setState(() => _notShowAbandoned = value)),
+ ],
+ ),
+ ],
+ )),
+ if (!shortWindow)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 12, 24, 24),
+ child: Row(children: [
+ TextButton(onPressed: _reset, child: const Text('重置')),
+ const SizedBox(width: 16),
+ Expanded(
+ child: FilledButton(
+ onPressed: _apply,
+ style: FilledButton.styleFrom(
+ minimumSize: const Size(48, 56)),
+ child: const Text('查看结果'))),
+ ])),
+ ]);
+ }),
+ );
+ }
+}
+
+class _SearchFilterGroup extends StatelessWidget {
+ const _SearchFilterGroup(
+ {required this.title,
+ required this.summary,
+ required this.children,
+ this.initiallyExpanded = false});
+
+ final String title;
+ final String summary;
+ final List<Widget> children;
+ final bool initiallyExpanded;
+
+ @override
+ Widget build(BuildContext context) => ExpansionTile(
+ key: PageStorageKey(title),
+ title: Text(title),
+ subtitle: Text(summary),
+ initiallyExpanded: initiallyExpanded,
+ tilePadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
+ childrenPadding: const EdgeInsets.fromLTRB(4, 0, 4, 20),
+ shape: const Border(),
+ collapsedShape: const Border(),
+ children: children,
+ );
+}
+
+RangeValues _safeRangeValues(
+ double start,
+ double end,
+ double min,
+ double max,
+) {
+ final safeStart = start.clamp(min, max).toDouble();
+ final safeEnd = end.clamp(min, max).toDouble();
+ if (safeStart <= safeEnd) {
+ return RangeValues(safeStart, safeEnd);
+ }
+ return RangeValues(safeEnd, safeStart);
+}
diff --git a/lib/pages/search/search_page.dart b/lib/pages/search/search_page.dart
index 759d19bd..d694dffb 100644
--- a/lib/pages/search/search_page.dart
+++ b/lib/pages/search/search_page.dart
@@ -1,28 +1,25 @@
+import 'dart:math' as math;
+
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
-import 'package:kazumi/bean/card/bangumi_card.dart';
+import 'package:kazumi/bean/card/network_img_layer.dart';
import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';
import 'package:kazumi/bean/dialog/material_bottom_sheet.dart';
-import 'package:kazumi/bean/widget/connected_tabs.dart';
-import 'package:kazumi/bean/widget/content_section.dart';
-import 'package:kazumi/bean/widget/error_widget.dart';
import 'package:kazumi/bean/widget/loading_indicator.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/pages/search/search_controller.dart';
-import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/utils/constants.dart';
import 'package:kazumi/utils/date_time.dart';
import 'package:kazumi/utils/search_parser.dart';
+part 'search_filter_sheet.dart';
+part 'search_widgets.dart';
+
class SearchPage extends StatefulWidget {
- const SearchPage({
- super.key,
- required this.controller,
- this.inputTag = '',
- });
+ const SearchPage({super.key, required this.controller, this.inputTag = ''});
final SearchPageController controller;
final String inputTag;
@@ -32,938 +29,399 @@ class SearchPage extends StatefulWidget {
}
class _SearchPageState extends State<SearchPage> {
- final SearchController searchController = SearchController();
+ final _input = TextEditingController();
+ final _inputFocus = FocusNode();
+ final _scroll = ScrollController();
+ String? _submittedQuery;
+ bool _managingHistory = false;
- SearchPageController get searchPageController => widget.controller;
- final ScrollController scrollController = ScrollController();
-
- SearchFilterState filterState = const SearchFilterState();
- bool _syncingSearchText = false;
+ SearchPageController get _controller => widget.controller;
+ bool get _hasSearched => _submittedQuery != null;
@override
void initState() {
super.initState();
- scrollController.addListener(scrollListener);
- searchController.addListener(_syncFilterFromSearchText);
- searchPageController.loadSearchHistories();
- if (widget.inputTag != '') {
+ _scroll.addListener(_loadMoreOnScroll);
+ _controller.loadSearchHistories();
+ if (widget.inputTag.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted) {
- return;
- }
- final tagString = 'tag:${Uri.decodeComponent(widget.inputTag)}';
- _applyFilterState(SearchParser(tagString).toFilterState(),
- search: true);
+ if (!mounted) return;
+ _applyFilters(
+ SearchFilterState(tags: [Uri.decodeComponent(widget.inputTag)]));
});
}
}
@override
void dispose() {
- searchPageController.bangumiList.clear();
- searchController.removeListener(_syncFilterFromSearchText);
- searchController.dispose();
- scrollController.removeListener(scrollListener);
- scrollController.dispose();
+ _input.dispose();
+ _inputFocus.dispose();
+ _scroll.dispose();
super.dispose();
}
- void _syncFilterFromSearchText() {
- if (_syncingSearchText) return;
- final parsed = SearchParser(searchController.text).toFilterState();
- if (SearchParser.fromFilterState(parsed) !=
- SearchParser.fromFilterState(filterState)) {
- setState(() => filterState = parsed);
- }
- }
-
- void _setSearchText(String value) {
- _syncingSearchText = true;
- searchController.text = value;
- searchController.selection = TextSelection.collapsed(offset: value.length);
- _syncingSearchText = false;
- }
-
- Future<void> _applyFilterState(
- SearchFilterState state, {
- bool search = false,
- }) async {
- setState(() => filterState = state);
- _setSearchText(SearchParser.fromFilterState(state));
- if (search) {
- await searchPageController.searchBangumi(searchController.text,
- type: 'init');
- }
- }
-
- void scrollListener() {
- if (scrollController.position.pixels >=
- scrollController.position.maxScrollExtent - 200 &&
- !searchPageController.isLoading &&
- (searchController.text.trim().isNotEmpty ||
- filterState.hasAdvancedFilters) &&
- searchPageController.hasMoreSearchResults) {
- KazumiLogger().i('SearchController: search results is loading more');
- searchPageController.searchBangumi(searchController.text, type: 'add');
- }
- }
-
- Future<void> _showWorkbench() async {
- final result = await showAdaptiveBottomSheet<_SearchWorkbenchResult>(
- maxHeightFactor: 0.86,
- context: context,
- builder: (context) {
- return _SearchWorkbenchSheet(
- initialState: filterState,
- initialNotShowWatched: searchPageController.notShowWatchedBangumis,
- initialNotShowAbandoned:
- searchPageController.notShowAbandonedBangumis,
- );
- },
+ void _writeInput(String value) {
+ _input.value = TextEditingValue(
+ text: value,
+ selection: TextSelection.collapsed(offset: value.length),
);
-
- if (result == null) return;
- await searchPageController.setNotShowWatchedBangumis(result.notShowWatched);
- await searchPageController
- .setNotShowAbandonedBangumis(result.notShowAbandoned);
- await _applyFilterState(result.filterState, search: result.shouldSearch);
}
- SearchFilterState _removeTag(String tag) {
- return filterState.copyWith(
- tags: filterState.tags.where((item) => item != tag).toList(),
- );
+ Future<void> _submit(String value) async {
+ final filters = SearchParser(value).toFilterState();
+ final query = SearchParser.fromFilterState(filters);
+ _inputFocus.unfocus();
+ _writeInput(query);
+ setState(() => _submittedQuery = query);
+ final request = _controller.searchBangumi(query, type: 'init');
+ if (_scroll.hasClients) _scroll.jumpTo(0);
+ await request;
}
- List<Widget> buildFilterChips() {
- final chips = <Widget>[];
-
- for (final tag in filterState.tags) {
- chips.add(InputChip(
- label: Text('标签: $tag'),
- onDeleted: () => _applyFilterState(_removeTag(tag), search: true),
- ));
- }
- if (filterState.sort != 'heat') {
- chips.add(InputChip(
- label: Text('排序: ${_sortLabel(filterState.sort)}'),
- onDeleted: () => _applyFilterState(
- filterState.copyWith(sort: 'heat'),
- search: true,
- ),
- ));
- }
- if (filterState.season.isNotEmpty) {
- chips.add(InputChip(
- label: Text('季度: ${filterState.season}'),
- onDeleted: () => _applyFilterState(
- filterState.copyWith(season: '', dateRange: null),
- search: true,
- ),
- ));
- } else if (filterState.dateRange != null) {
- chips.add(InputChip(
- label: Text(
- '日期: ${filterState.dateRange!.start}..${filterState.dateRange!.end}'),
- onDeleted: () => _applyFilterState(
- filterState.copyWith(dateRange: null),
- search: true,
- ),
- ));
- }
- if (filterState.rankRange?.isValid == true) {
- chips.add(InputChip(
- label: Text('排名: ${filterState.rankRange!.toToken()}'),
- onDeleted: () => _applyFilterState(
- filterState.copyWith(rankRange: null),
- search: true,
- ),
- ));
- }
- if (filterState.scoreRange?.isValid == true) {
- chips.add(InputChip(
- label: Text('评分: ${filterState.scoreRange!.toToken()}'),
- onDeleted: () => _applyFilterState(
- filterState.copyWith(scoreRange: null),
- search: true,
- ),
- ));
- }
- if (filterState.weekdays.isNotEmpty) {
- chips.add(InputChip(
- label: Text('星期: ${filterState.weekdays.join(',')}'),
- onDeleted: () => _applyFilterState(
- filterState.copyWith(weekdays: []),
- search: true,
- ),
- ));
- }
- if (searchPageController.notShowWatchedBangumis) {
- chips.add(InputChip(
- label: const Text('隐藏已看'),
- onDeleted: () async {
- await searchPageController.setNotShowWatchedBangumis(false);
- },
- ));
- }
- if (searchPageController.notShowAbandonedBangumis) {
- chips.add(InputChip(
- label: const Text('隐藏已弃'),
- onDeleted: () async {
- await searchPageController.setNotShowAbandonedBangumis(false);
- },
- ));
- }
+ Future<void> _applyFilters(SearchFilterState filters) =>
+ _submit(SearchParser.fromFilterState(filters));
- return chips;
+ void _loadMoreOnScroll() {
+ if (!_scroll.hasClients || _scroll.position.extentAfter > 360) return;
+ _loadMore();
}
- Future<void> _submitSearch(String value) async {
- final parsed = SearchParser(value).toFilterState();
- setState(() => filterState = parsed);
- final normalizedValue = SearchParser.fromFilterState(parsed);
- _setSearchText(normalizedValue);
- await searchPageController.searchBangumi(normalizedValue, type: 'init');
- if (searchController.isOpen) {
- searchController.closeView(normalizedValue);
- }
+ void _loadMore() {
+ final query = _submittedQuery;
+ if (query != null) _controller.searchBangumi(query);
}
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: SysAppBar(
- backgroundColor: Colors.transparent,
- title: const Text("搜索"),
- ),
- floatingActionButton: FloatingActionButton.extended(
- onPressed: _showWorkbench,
- icon: const Icon(Icons.tune),
- label: const Text("筛选"),
- ),
- body: Column(
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
- child: FocusScope(
- descendantsAreFocusable: false,
- child: SearchAnchor.bar(
- searchController: searchController,
- barElevation: WidgetStateProperty<double>.fromMap(
- <WidgetStatesConstraint, double>{WidgetState.any: 0},
- ),
- viewElevation: 0,
- viewLeading: IconButton(
- onPressed: () {
- Navigator.of(context).pop();
- },
- icon: const Icon(Icons.arrow_back),
- ),
- barTrailing: [
- IconButton(
- tooltip: '以图搜番',
- onPressed: () async {
- final result = await context.pushNamed('/search/image');
- if (result is String && result.isNotEmpty) {
- await _applyFilterState(
- SearchParser(result).toFilterState(),
- search: true,
- );
- }
- },
- icon: const Icon(Icons.image_search_rounded),
- ),
- ],
- isFullScreen: MediaQuery.sizeOf(context).width <
- LayoutBreakpoint.compact['width']!,
- suggestionsBuilder: (context, controller) => [
- Observer(
- builder: (context) {
- if (controller.text.isNotEmpty) {
- return const SizedBox(
- height: 400,
- child: Center(
- child: Text("暂无搜索建议,按回车直接检索"),
- ),
- );
- } else {
- return Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- for (var history in searchPageController
- .searchHistories
- .take(10))
- ListTile(
- title: Text(history.keyword),
- onTap: () {
- controller.text = history.keyword;
- _submitSearch(controller.text);
- },
- trailing: IconButton(
- icon: const Icon(Icons.close),
- onPressed: () {
- searchPageController
- .deleteSearchHistory(history);
- },
- ),
- ),
- ],
- );
- }
- },
- ),
- ],
- onSubmitted: _submitSearch,
- ),
- ),
- ),
- Observer(
- builder: (_) {
- final chips = buildFilterChips();
- if (chips.isEmpty) return const SizedBox.shrink();
- return Padding(
- padding: const EdgeInsets.fromLTRB(12, 0, 12, 8),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Wrap(
- spacing: 8,
- runSpacing: 4,
- children: chips,
- ),
- ),
- );
- },
- ),
- Expanded(
- child: Observer(builder: (context) {
- if (searchPageController.isTimeOut) {
- return Center(
- child: SizedBox(
- height: 400,
- child: GeneralErrorWidget(
- errMsg: '什么都没有找到 (;´༎ຶД༎ຶ`)',
- actions: [
- GeneralErrorButton(
- onPressed: () {
- searchPageController.searchBangumi(
- searchController.text,
- type: 'init');
- },
- text: '点击重试',
- ),
- ],
- ),
- ),
- );
- }
-
- if (searchPageController.isLoading &&
- searchPageController.bangumiList.isEmpty) {
- return const Center(child: LoadingIndicator());
- }
- int crossCount = 3;
- if (MediaQuery.sizeOf(context).width >
- LayoutBreakpoint.compact['width']!) {
- crossCount = 5;
- }
- if (MediaQuery.sizeOf(context).width >
- LayoutBreakpoint.medium['width']!) {
- crossCount = 6;
- }
- List<BangumiItem> filteredList =
- searchPageController.bangumiList.toList();
-
- if (searchPageController.notShowWatchedBangumis) {
- final watchedBangumiIds =
- searchPageController.loadWatchedBangumiIds();
- filteredList = filteredList
- .where((item) => !watchedBangumiIds.contains(item.id))
- .toList();
- }
-
- if (searchPageController.notShowAbandonedBangumis) {
- final abandonedBangumiIds =
- searchPageController.loadAbandonedBangumiIds();
- filteredList = filteredList
- .where((item) => !abandonedBangumiIds.contains(item.id))
- .toList();
- }
-
- return GridView.builder(
- controller: scrollController,
- padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- mainAxisSpacing: StyleString.cardSpace - 2,
- crossAxisSpacing: StyleString.cardSpace,
- crossAxisCount: crossCount,
- mainAxisExtent:
- MediaQuery.of(context).size.width / crossCount / 0.65 +
- MediaQuery.textScalerOf(context).scale(32.0),
- ),
- itemCount: filteredList.isNotEmpty ? filteredList.length : 10,
- itemBuilder: (context, index) {
- return filteredList.isNotEmpty
- ? BangumiCardV(
- enableHero: false,
- bangumiItem: filteredList[index],
- )
- : Container();
- },
- );
- }),
- ),
- ],
+ Future<void> _showFilters() async {
+ _inputFocus.unfocus();
+ final result = await showAdaptiveBottomSheet<_SearchFilterResult>(
+ context: context,
+ maxHeightFactor: 0.9,
+ builder: (_) => _SearchFilterSheet(
+ initialState: SearchParser(_input.text).toFilterState(),
+ initialNotShowWatched: _controller.notShowWatchedBangumis,
+ initialNotShowAbandoned: _controller.notShowAbandonedBangumis,
),
);
+ if (!mounted || result == null) return;
+ await _controller.setNotShowWatchedBangumis(result.notShowWatched);
+ await _controller.setNotShowAbandonedBangumis(result.notShowAbandoned);
+ if (!mounted) return;
+ await _applyFilters(result.filterState);
}
-}
-class _SearchWorkbenchResult {
- const _SearchWorkbenchResult({
- required this.filterState,
- required this.notShowWatched,
- required this.notShowAbandoned,
- required this.shouldSearch,
- });
-
- final SearchFilterState filterState;
- final bool notShowWatched;
- final bool notShowAbandoned;
- final bool shouldSearch;
-}
-
-class _SearchWorkbenchSheet extends StatefulWidget {
- const _SearchWorkbenchSheet({
- required this.initialState,
- required this.initialNotShowWatched,
- required this.initialNotShowAbandoned,
- });
-
- final SearchFilterState initialState;
- final bool initialNotShowWatched;
- final bool initialNotShowAbandoned;
-
- @override
- State<_SearchWorkbenchSheet> createState() => _SearchWorkbenchSheetState();
-}
-
-class _SearchWorkbenchSheetState extends State<_SearchWorkbenchSheet> {
- late SearchFilterState draft = widget.initialState;
- late bool notShowWatched = widget.initialNotShowWatched;
- late bool notShowAbandoned = widget.initialNotShowAbandoned;
- final TextEditingController tagController = TextEditingController();
-
- @override
- void dispose() {
- tagController.dispose();
- super.dispose();
- }
-
- List<_SeasonOption> get seasonOptions {
- final now = DateTime.now();
- final values = <_SeasonOption>[];
- for (int year = now.year; year >= now.year - 19; year--) {
- for (int quarter = 4; quarter >= 1; quarter--) {
- final date = DateTime(year, (quarter - 1) * 3 + 1, 1);
- if (now.isAfter(date)) {
- values.add(_SeasonOption(
- value: '${year}Q$quarter',
- label: '$year ${_seasonLabel(quarter)}',
- ));
- }
- }
- }
- return values;
+ Future<void> _imageSearch() async {
+ _inputFocus.unfocus();
+ final result = await context.pushNamed('/search/image');
+ if (!mounted || result is! String || result.isEmpty) return;
+ await _submit(result);
}
- void addTag(String value) {
- final tag = value.trim();
- if (tag.isEmpty || draft.tags.contains(tag)) return;
+ void _clearSearch() {
+ _inputFocus.unfocus();
+ _writeInput('');
setState(() {
- draft = draft.copyWith(tags: [...draft.tags, tag]);
- tagController.clear();
+ _submittedQuery = null;
+ _managingHistory = false;
});
+ if (_scroll.hasClients) _scroll.jumpTo(0);
}
- SearchFilterState resetAdvancedFilters() {
- return draft.copyWith(
- tags: [],
- sort: 'heat',
- season: '',
- dateRange: null,
- rankRange: null,
- scoreRange: null,
- weekdays: [],
- );
- }
-
- Future<void> pickCustomDateRange() async {
- final now = DateTime.now();
- final initialStart = draft.dateRange?.start != null
- ? DateTime.tryParse(draft.dateRange!.start)
- : null;
- final initialEnd = draft.dateRange?.end != null
- ? DateTime.tryParse(draft.dateRange!.end)
- : null;
- final result = await showDateRangePicker(
- context: context,
- firstDate: DateTime(1970),
- lastDate: DateTime(now.year + 3, 12, 31),
- initialDateRange: initialStart != null && initialEnd != null
- ? DateTimeRange(start: initialStart, end: initialEnd)
- : null,
- );
- if (result == null) return;
- setState(() {
- draft = draft.copyWith(
- season: '',
- dateRange: SearchDateRange(
- start: formatDateTime(result.start),
- end: formatDateTime(result.end),
+ Widget _searchField() {
+ final colors = Theme.of(context).colorScheme;
+ return ValueListenableBuilder<TextEditingValue>(
+ valueListenable: _input,
+ builder: (context, value, child) => SearchBar(
+ controller: _input,
+ focusNode: _inputFocus,
+ hintText: '搜索番剧名称',
+ textInputAction: TextInputAction.search,
+ constraints: const BoxConstraints(minHeight: 64),
+ elevation: const WidgetStatePropertyAll(0),
+ backgroundColor: WidgetStatePropertyAll(colors.surfaceContainerHigh),
+ padding:
+ const WidgetStatePropertyAll(EdgeInsets.symmetric(horizontal: 8)),
+ leading: IconButton(
+ tooltip: '搜索',
+ onPressed: () => _submit(_input.text),
+ icon: const Icon(Icons.search_rounded),
),
- );
- });
- }
-
- Widget _buildScoreRangeSlider(SearchDoubleRange range) {
- final values = _safeRangeValues(
- range.min ?? 0,
- range.max ?? 10,
- 0,
- 10,
- );
- return RangeSlider(
- values: values,
- min: 0,
- max: 10,
- divisions: 20,
- labels: RangeLabels(
- values.start.toStringAsFixed(1),
- values.end.toStringAsFixed(1),
+ trailing: [
+ if (value.text.isNotEmpty || _hasSearched)
+ IconButton(
+ tooltip: '清空搜索',
+ onPressed: _clearSearch,
+ icon: const Icon(Icons.close_rounded)),
+ IconButton(
+ tooltip: '以图搜番',
+ onPressed: _imageSearch,
+ icon: const Icon(Icons.image_search_rounded),
+ ),
+ ],
+ onSubmitted: _submit,
),
- onChanged: (value) {
- setState(() {
- draft = draft.copyWith(
- scoreRange: SearchDoubleRange(
- min: value.start,
- max: value.end,
- ),
- );
- });
- },
);
}
- Widget _buildRankRangeSlider(SearchIntRange range) {
- final values = _safeRangeValues(
- (range.min ?? 1).toDouble(),
- (range.max ?? 10000).toDouble(),
- 1,
- 10000,
- );
- return RangeSlider(
- values: values,
- min: 1,
- max: 10000,
- divisions: 100,
- labels: RangeLabels(
- '${values.start.round()}',
- '${values.end.round()}',
- ),
- onChanged: (value) {
- setState(() {
- draft = draft.copyWith(
- rankRange: SearchIntRange(
- min: value.start.round(),
- max: value.end.round(),
- ),
- );
- });
- },
- );
- }
+ Widget _header() => Padding(
+ padding: EdgeInsets.only(top: _hasSearched ? 8 : 24, bottom: 16),
+ child: _searchField(),
+ );
- @override
- Widget build(BuildContext context) {
- final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
- return Padding(
- padding: EdgeInsets.only(bottom: keyboardInset),
- child: DefaultTabController(
- length: 2,
- child: LayoutBuilder(builder: (context, constraints) {
- final editingInShortWindow =
- keyboardInset > 0 && constraints.maxHeight < 280;
- return Column(
+ Widget _discovery() {
+ final theme = Theme.of(context);
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Material(
+ type: MaterialType.transparency,
+ child: ListTile(
+ shape:
+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
+ contentPadding:
+ const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
+ leading: const Icon(Icons.tune_rounded),
+ title: const Text('按条件查找'),
+ subtitle: const Text('题材、放送时间与评分'),
+ trailing: const Icon(Icons.chevron_right_rounded),
+ onTap: _showFilters,
+ )),
+ const SizedBox(height: 28),
+ Observer(builder: (_) {
+ final histories = _controller.searchHistories.toList();
+ if (histories.isEmpty) return const SizedBox.shrink();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- if (!editingInShortWindow)
- MaterialBottomSheetHeader(
- title: '筛选番剧',
- onClose: () => Navigator.pop(context),
- ),
- if (!editingInShortWindow)
- const ConnectedTabs(
- padding: materialBottomSheetTabsPadding,
- labels: ['常用', '进阶']),
- Expanded(
- child: TabBarView(children: [
- ListView(
- key: const PageStorageKey('search-basic-filters'),
- padding: materialBottomSheetContentPadding,
- children: [
- ContentSection(
- title: '排序',
- child: Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- for (final sort in [
- 'heat',
- 'rank',
- 'score',
- 'match'
- ])
- ChoiceChip(
- label: Text(_sortLabel(sort)),
- selected: draft.sort == sort,
- onSelected: (_) => setState(() {
- draft = draft.copyWith(sort: sort);
- }),
- ),
- ],
- ),
- ),
- const SizedBox(height: 24),
- ContentSection(
- title: '题材标签',
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- for (final tag in {
- ...defaultAnimeTags,
- ...draft.tags
- })
- FilterChip(
- label: Text(tag),
- selected: draft.tags.contains(tag),
- onSelected: (selected) => setState(() {
- draft = draft.copyWith(
- tags: selected
- ? [...draft.tags, tag]
- : draft.tags
- .where((item) => item != tag)
- .toList());
- }),
- ),
- ],
- ),
- const SizedBox(height: 12),
- TextField(
- controller: tagController,
- decoration: InputDecoration(
- hintText: '添加自定义标签',
- filled: true,
- fillColor:
- Theme.of(context).colorScheme.surface,
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(20),
- borderSide: BorderSide.none,
- ),
- suffixIcon: IconButton(
- tooltip: '添加标签',
- onPressed: () => addTag(tagController.text),
- icon: const Icon(Icons.add_rounded),
- ),
- ),
- onSubmitted: addTag,
- ),
- ],
- ),
- ),
- const SizedBox(height: 24),
- ContentSection(
- title: '收藏状态',
- child: Column(
- children: [
- _SearchSwitchTile(
- title: '隐藏看过的番剧',
- value: notShowWatched,
- onChanged: (value) {
- setState(() => notShowWatched = value);
- },
- ),
- _SearchSwitchTile(
- title: '隐藏抛弃的番剧',
- value: notShowAbandoned,
- onChanged: (value) {
- setState(() => notShowAbandoned = value);
- },
- ),
- ],
- ),
- ),
- ],
- ),
- ListView(
- key: const PageStorageKey('search-advanced-filters'),
- padding: materialBottomSheetContentPadding,
- children: [
- ContentSection(
- title: '放送日期',
- child: Column(
- children: [
- DropdownButtonFormField<String>(
- initialValue:
- draft.season.isEmpty ? null : draft.season,
- decoration: const InputDecoration(
- labelText: '季度',
- prefixIcon:
- Icon(Icons.event_available_outlined),
- ),
- items: [
- for (final season in seasonOptions)
- DropdownMenuItem(
- value: season.value,
- child: Text(season.label),
- ),
- ],
- onChanged: (value) {
- setState(() {
- draft = draft.copyWith(
- season: value ?? '',
- dateRange: null,
- );
- });
- },
- ),
- const SizedBox(height: 12),
- Align(
- alignment: Alignment.centerLeft,
- child: Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- OutlinedButton.icon(
- onPressed: pickCustomDateRange,
- icon: const Icon(Icons.date_range),
- label: Text(draft.dateRange == null
- ? '自定义日期'
- : '${draft.dateRange!.start}..${draft.dateRange!.end}'),
- ),
- if (draft.season.isNotEmpty ||
- draft.dateRange != null)
- TextButton.icon(
- onPressed: () {
- setState(() {
- draft = draft.copyWith(
- season: '',
- dateRange: null,
- );
- });
- },
- icon: const Icon(Icons.clear),
- label: const Text('不限日期'),
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- const SizedBox(height: 24),
- ContentSection(
- title: '放送星期',
- child: Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- for (int weekday = 1; weekday <= 7; weekday++)
- FilterChip(
- label: Text('周${[
- '一',
- '二',
- '三',
- '四',
- '五',
- '六',
- '日'
- ][weekday - 1]}'),
- selected: draft.weekdays.contains(weekday),
- showCheckmark: false,
- onSelected: (selected) {
- final weekdays = draft.weekdays.toSet();
- if (selected) {
- weekdays.add(weekday);
- } else {
- weekdays.remove(weekday);
- }
- final next = weekdays.toList()..sort();
- setState(() {
- draft = draft.copyWith(weekdays: next);
- });
- },
- ),
- ],
- ),
- ),
- const SizedBox(height: 24),
- ContentSection(
- title: '评分与排名',
- child: Column(
- children: [
- _SearchSwitchTile(
- title: '限定评分',
- value: draft.scoreRange?.isValid == true,
- onChanged: (value) {
- setState(() {
- draft = draft.copyWith(
- scoreRange: value
- ? const SearchDoubleRange(
- min: 7.0,
- max: 10.0,
- )
- : null,
- );
- });
- },
- ),
- if (draft.scoreRange?.isValid == true)
- _buildScoreRangeSlider(draft.scoreRange!),
- _SearchSwitchTile(
- title: '限定排名',
- value: draft.rankRange?.isValid == true,
- onChanged: (value) {
- setState(() {
- draft = draft.copyWith(
- rankRange: value
- ? const SearchIntRange(
- min: 1, max: 5000)
- : null,
- );
- });
- },
- ),
- if (draft.rankRange?.isValid == true)
- _buildRankRangeSlider(draft.rankRange!),
- ],
- ),
- ),
- ],
- ),
- ]),
- ),
- if (!editingInShortWindow)
- Padding(
- padding: const EdgeInsets.fromLTRB(24, 12, 24, 24),
+ Padding(
+ padding: const EdgeInsets.only(left: 16, right: 4),
child: Row(children: [
+ Expanded(
+ child: Text('最近搜索',
+ style: theme.textTheme.titleSmall?.copyWith(
+ color: theme.colorScheme.onSurfaceVariant))),
+ if (_managingHistory)
+ TextButton(
+ onPressed: () async {
+ await _controller.clearSearchHistory();
+ if (mounted) {
+ setState(() => _managingHistory = false);
+ }
+ },
+ child: const Text('清空')),
TextButton(
- onPressed: () => setState(() {
- draft = resetAdvancedFilters();
- notShowWatched = false;
- notShowAbandoned = false;
- tagController.clear();
- }),
- child: const Text('重置'),
- ),
- const Spacer(),
- FilledButton(
- onPressed: () => Navigator.pop(
- context,
- _SearchWorkbenchResult(
- filterState: draft,
- notShowWatched: notShowWatched,
- notShowAbandoned: notShowAbandoned,
- shouldSearch: true,
- )),
- child: const Text('查看结果'),
- ),
- ]),
- ),
- ],
- );
- }),
- ),
- );
+ onPressed: () => setState(
+ () => _managingHistory = !_managingHistory),
+ child: Text(_managingHistory ? '完成' : '管理')),
+ ])),
+ for (final history in histories.take(10))
+ Material(
+ type: MaterialType.transparency,
+ child: ListTile(
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 16, vertical: 4),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(16)),
+ leading: Icon(Icons.history_rounded,
+ color: theme.colorScheme.onSurfaceVariant, size: 22),
+ title: Text(_readableQuery(history.keyword),
+ maxLines: 2, overflow: TextOverflow.ellipsis),
+ trailing: _managingHistory
+ ? IconButton(
+ tooltip: '删除这条搜索记录',
+ onPressed: () =>
+ _controller.deleteSearchHistory(history),
+ icon: const Icon(Icons.close_rounded, size: 20))
+ : Icon(Icons.north_west_rounded,
+ size: 18,
+ color: theme.colorScheme.onSurfaceVariant),
+ onTap: () => _submit(history.keyword),
+ )),
+ ]);
+ }),
+ ]);
}
-}
-class _SearchSwitchTile extends StatelessWidget {
- const _SearchSwitchTile({
- required this.title,
- required this.value,
- required this.onChanged,
- });
-
- final String title;
- final bool value;
- final ValueChanged<bool> onChanged;
+ List<Widget> _resultSlivers(double width) {
+ final allItems = _controller.bangumiList.toList();
+ final watched = _controller.notShowWatchedBangumis
+ ? _controller.loadWatchedBangumiIds()
+ : <int>{};
+ final abandoned = _controller.notShowAbandonedBangumis
+ ? _controller.loadAbandonedBangumiIds()
+ : <int>{};
+ final items = allItems
+ .where((item) =>
+ !watched.contains(item.id) && !abandoned.contains(item.id))
+ .toList();
+ final busy = _controller.isLoading;
+ final failed = _controller.isTimeOut;
+ final submitted = SearchParser(_submittedQuery!).toFilterState();
+ final summary = _filterSummary(submitted);
+ final textScale = MediaQuery.textScalerOf(context);
+ final columns = math.max(2, (width / 180).floor());
+ final cardWidth = (width - (columns - 1) * 12) / columns;
+
+ return [
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: 20),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Expanded(
+ child: Text('搜索结果',
+ style: Theme.of(context)
+ .textTheme
+ .titleMedium
+ ?.copyWith(fontWeight: FontWeight.w600))),
+ if (!submitted.isIdSearch)
+ _SearchSortMenu(
+ value: submitted.sort,
+ onChanged: (sort) =>
+ _applyFilters(submitted.copyWith(sort: sort))),
+ IconButton(
+ tooltip: '筛选番剧',
+ onPressed: _showFilters,
+ icon: Badge(
+ backgroundColor: Theme.of(context).colorScheme.primary,
+ isLabelVisible: submitted.hasAdvancedFilters ||
+ _controller.notShowWatchedBangumis ||
+ _controller.notShowAbandonedBangumis,
+ smallSize: 6,
+ child: const Icon(Icons.tune_rounded)),
+ ),
+ ]),
+ Text(
+ busy
+ ? '正在搜索…'
+ : '${items.length} 部番剧${items.length < allItems.length ? ' · 隐藏 ${allItems.length - items.length} 部' : ''}',
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant)),
+ if (summary.isNotEmpty) ...[
+ const SizedBox(height: 6),
+ Text(summary,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant)),
+ ],
+ ]),
+ )),
+ if (busy && allItems.isEmpty)
+ const SliverToBoxAdapter(
+ child: _SearchStatus(
+ icon: Icons.search_rounded,
+ title: '正在搜索番剧',
+ message: '请稍候',
+ loading: true))
+ else if (items.isEmpty)
+ SliverToBoxAdapter(
+ child: _SearchStatus(
+ icon: allItems.isEmpty
+ ? Icons.travel_explore_rounded
+ : Icons.filter_alt_off_rounded,
+ title: allItems.isEmpty ? '没有找到番剧' : '这些番剧被筛选隐藏了',
+ message: allItems.isEmpty
+ ? (failed
+ ? '没有找到结果,试试其他名称、放宽筛选,或重新搜索。'
+ : '暂时没有匹配的番剧,可以继续加载或调整筛选。')
+ : '可以显示已看和已弃作品,或继续加载更多番剧。',
+ actions: [
+ FilledButton.tonalIcon(
+ onPressed: allItems.isEmpty
+ ? () => _submit(_submittedQuery!)
+ : () async {
+ await _controller.setNotShowWatchedBangumis(false);
+ await _controller.setNotShowAbandonedBangumis(false);
+ },
+ icon: Icon(allItems.isEmpty
+ ? Icons.refresh_rounded
+ : Icons.visibility_outlined),
+ label: Text(allItems.isEmpty ? '重新搜索' : '显示全部')),
+ TextButton(onPressed: _showFilters, child: const Text('调整筛选')),
+ ],
+ ))
+ else
+ SliverGrid.builder(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ crossAxisCount: columns,
+ crossAxisSpacing: 12,
+ mainAxisSpacing: 20,
+ mainAxisExtent: cardWidth / 0.7 +
+ textScale.scale(40) +
+ textScale.scale(18) +
+ 20),
+ itemCount: items.length,
+ itemBuilder: (_, index) => _SearchResultCard(item: items[index]),
+ ),
+ if (allItems.isNotEmpty || !failed)
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 24),
+ child: Center(
+ child: busy
+ ? (allItems.isEmpty
+ ? const SizedBox.shrink()
+ : const LoadingIndicator(size: 32))
+ : _controller.hasMoreSearchResults
+ ? TextButton.icon(
+ onPressed: _loadMore,
+ icon: const Icon(Icons.expand_more_rounded),
+ label: const Text('加载更多'))
+ : Text('已经看到全部结果',
+ style: Theme.of(context)
+ .textTheme
+ .bodySmall
+ ?.copyWith(
+ color: Theme.of(context)
+ .colorScheme
+ .onSurfaceVariant)),
+ ))),
+ ];
+ }
@override
Widget build(BuildContext context) {
- return Material(
- type: MaterialType.transparency,
- child: SwitchListTile(
- contentPadding: EdgeInsets.zero,
- visualDensity: VisualDensity.compact,
- title: Text(title),
- value: value,
- onChanged: onChanged,
- ),
+ return Scaffold(
+ appBar: const SysAppBar(
+ backgroundColor: Colors.transparent, title: Text('番剧搜索')),
+ body: SafeArea(
+ top: false,
+ child: LayoutBuilder(builder: (context, constraints) {
+ final horizontal = constraints.maxWidth >= 700 ? 32.0 : 20.0;
+ final width = math.min(_hasSearched ? 1120.0 : 760.0,
+ constraints.maxWidth - horizontal * 2);
+ final inset = (constraints.maxWidth - width) / 2;
+ final pinSearch = _hasSearched &&
+ constraints.maxHeight >= 420 &&
+ MediaQuery.textScalerOf(context).scale(16) <= 24;
+ Widget scrollView(List<Widget> slivers) => CustomScrollView(
+ controller: _scroll,
+ keyboardDismissBehavior:
+ ScrollViewKeyboardDismissBehavior.onDrag,
+ slivers: [
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(inset, 0, inset, 24),
+ sliver: SliverMainAxisGroup(slivers: slivers),
+ )
+ ],
+ );
+ return Column(children: [
+ if (pinSearch)
+ Padding(
+ padding: EdgeInsets.symmetric(horizontal: inset),
+ child: _header()),
+ Expanded(
+ child: _hasSearched
+ ? Observer(
+ builder: (_) => scrollView([
+ if (!pinSearch)
+ SliverToBoxAdapter(child: _header()),
+ ..._resultSlivers(width),
+ ]))
+ : scrollView([
+ SliverToBoxAdapter(child: _header()),
+ SliverToBoxAdapter(child: _discovery()),
+ ])),
+ ]);
+ })),
);
}
}
-
-class _SeasonOption {
- const _SeasonOption({
- required this.value,
- required this.label,
- });
-
- final String value;
- final String label;
-}
-
-RangeValues _safeRangeValues(
- double start,
- double end,
- double min,
- double max,
-) {
- final safeStart = start.clamp(min, max).toDouble();
- final safeEnd = end.clamp(min, max).toDouble();
- if (safeStart <= safeEnd) {
- return RangeValues(safeStart, safeEnd);
- }
- return RangeValues(safeEnd, safeStart);
-}
-
-String _sortLabel(String sort) {
- switch (sort) {
- case 'rank':
- return '排名';
- case 'score':
- return '评分';
- case 'match':
- return '匹配';
- default:
- return '热度';
- }
-}
-
-String _seasonLabel(int quarter) {
- switch (quarter) {
- case 1:
- return '冬季';
- case 2:
- return '春季';
- case 3:
- return '夏季';
- case 4:
- return '秋季';
- default:
- return '';
- }
-}
diff --git a/lib/pages/search/search_widgets.dart b/lib/pages/search/search_widgets.dart
new file mode 100644
index 00000000..69064b60
--- /dev/null
+++ b/lib/pages/search/search_widgets.dart
@@ -0,0 +1,180 @@
+part of 'search_page.dart';
+
+const _searchSortLabels = {
+ 'heat': '热度',
+ 'rank': '排名',
+ 'score': '评分',
+ 'match': '匹配',
+};
+
+String _sortLabel(String sort) => _searchSortLabels[sort] ?? '热度';
+
+String _filterSummary(SearchFilterState state) => [
+ ...state.tags,
+ if (state.season.isNotEmpty) state.season,
+ if (state.season.isEmpty && state.dateRange != null)
+ '${state.dateRange!.start} 至 ${state.dateRange!.end}',
+ if (state.scoreRange?.isValid == true)
+ '评分 ${state.scoreRange!.toToken()}',
+ if (state.rankRange?.isValid == true) '排名 ${state.rankRange!.toToken()}',
+ if (state.weekdays.isNotEmpty)
+ '周${state.weekdays.map((day) => '一二三四五六日'[day - 1]).join('、')}',
+ ].join(' · ');
+
+String _readableQuery(String query) {
+ final state = SearchParser(query).toFilterState();
+ final summary = _filterSummary(state);
+ return [
+ if (state.keyword.isNotEmpty) state.keyword,
+ if (state.id.isNotEmpty) '条目 ${state.id}',
+ if (summary.isNotEmpty) summary,
+ if (state.sort != 'heat') '${_sortLabel(state.sort)}排序',
+ ].join(' · ');
+}
+
+class _SearchSortMenu extends StatelessWidget {
+ const _SearchSortMenu({required this.value, required this.onChanged});
+
+ final String value;
+ final ValueChanged<String> onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ return PopupMenuButton<String>(
+ tooltip: '排序方式',
+ initialValue: value,
+ onSelected: onChanged,
+ itemBuilder: (_) => [
+ for (final sort in _searchSortLabels.entries)
+ CheckedPopupMenuItem(
+ value: sort.key,
+ checked: sort.key == value,
+ child: Text('按${sort.value}排序')),
+ ],
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Text(_sortLabel(value),
+ style: theme.textTheme.labelLarge
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant)),
+ const SizedBox(width: 4),
+ Icon(Icons.keyboard_arrow_down_rounded,
+ size: 20, color: theme.colorScheme.onSurfaceVariant),
+ ]),
+ ),
+ );
+ }
+}
+
+class _SearchResultCard extends StatelessWidget {
+ const _SearchResultCard({required this.item});
+
+ final BangumiItem item;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final title = item.nameCn.isNotEmpty ? item.nameCn : item.name;
+ final year = item.airDate.length >= 4 ? item.airDate.substring(0, 4) : '';
+ return Material(
+ type: MaterialType.transparency,
+ clipBehavior: Clip.antiAlias,
+ borderRadius: BorderRadius.circular(16),
+ child: InkWell(
+ onTap: () => context.pushNamed('/info/', arguments: item),
+ child:
+ Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ ClipRRect(
+ borderRadius: BorderRadius.circular(16),
+ child: AspectRatio(
+ aspectRatio: 0.7,
+ child: LayoutBuilder(
+ builder: (_, constraints) => NetworkImgLayer(
+ src: item.images['large'] ??
+ item.images['common'] ??
+ '',
+ width: constraints.maxWidth,
+ height: constraints.maxHeight,
+ )),
+ )),
+ const SizedBox(height: 10),
+ SizedBox(
+ height: MediaQuery.textScalerOf(context).scale(40),
+ child: Text(
+ title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.titleSmall
+ ?.copyWith(fontWeight: FontWeight.w600, height: 1.4),
+ )),
+ const SizedBox(height: 4),
+ Row(children: [
+ if (item.ratingScore > 0) ...[
+ Icon(Icons.star_rounded,
+ size: 14, color: theme.colorScheme.primary),
+ const SizedBox(width: 3),
+ Text(item.ratingScore.toStringAsFixed(1),
+ style: theme.textTheme.labelMedium),
+ const SizedBox(width: 10),
+ ],
+ Expanded(
+ child: Text(year,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.labelMedium?.copyWith(
+ color: theme.colorScheme.onSurfaceVariant))),
+ ]),
+ ])),
+ );
+ }
+}
+
+class _SearchStatus extends StatelessWidget {
+ const _SearchStatus(
+ {required this.icon,
+ required this.title,
+ required this.message,
+ this.loading = false,
+ this.actions = const []});
+
+ final IconData icon;
+ final String title;
+ final String message;
+ final bool loading;
+ final List<Widget> actions;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: 48, horizontal: 16),
+ child: Column(children: [
+ if (loading)
+ const LoadingIndicator(size: 40)
+ else
+ Icon(icon, size: 40, color: theme.colorScheme.onSurfaceVariant),
+ const SizedBox(height: 20),
+ Semantics(
+ liveRegion: true,
+ child: Text(title,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.titleMedium)),
+ const SizedBox(height: 8),
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360),
+ child: Text(message,
+ textAlign: TextAlign.center,
+ style: theme.textTheme.bodyMedium
+ ?.copyWith(color: theme.colorScheme.onSurfaceVariant))),
+ if (actions.isNotEmpty) ...[
+ const SizedBox(height: 20),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ alignment: WrapAlignment.center,
+ children: actions),
+ ],
+ ]));
+ }
+}
diff --git a/lib/utils/search_parser.dart b/lib/utils/search_parser.dart
index 72bc5430..7f08b688 100644
--- a/lib/utils/search_parser.dart
+++ b/lib/utils/search_parser.dart
@@ -247,19 +247,6 @@ class SearchParser {
.trim();
}
- bool hasSortSyntax() {
- return _sortRegExp.hasMatch(query);
- }
-
- String removeSort() {
- return query.replaceAll(_sortRegExp, '').trim();
- }
-
- String updateSort(String sortValue) {
- final state = toFilterState().copyWith(sort: sortValue);
- return fromFilterState(state);
- }
-
SearchFilterState toFilterState() {
return SearchFilterState(
id: parseId() ?? '',
diff --git a/test/search_parser_test.dart b/test/search_parser_test.dart
index a2357268..9765872f 100644
--- a/test/search_parser_test.dart
+++ b/test/search_parser_test.dart
@@ -78,11 +78,5 @@ void main() {
'孤独摇滚 tag:音乐 tag:漫画改 sort:score season:2022Q4 rank:1..1000 score:8..10 weekday:1,6',
);
});
-
- test('updates existing sort syntax', () {
- final parser = SearchParser('tag:日本 sort:heat');
-
- expect(parser.updateSort('rank'), 'tag:日本 sort:rank');
- });
});
}