Author SHA1 Message Date
Zhou Weidong 67e178c89d chore(merge): 将 develop 同步到 release/v1.0.0 2026-10-23 13:07:33 +08:00
86 changed files with 1246 additions and 3600 deletions

No files matched your search

-4
View File
@@ -11,7 +11,6 @@
331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
8C4E1A022F9A4B1000C636F3 /* WirelessDataPrompt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */; };
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; };
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
@@ -50,7 +49,6 @@
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WirelessDataPrompt.swift; sourceTree = "<group>"; };
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
@@ -124,7 +122,6 @@
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */,
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
);
@@ -285,7 +282,6 @@
buildActionMask = 2147483647;
files = (
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
8C4E1A022F9A4B1000C636F3 /* WirelessDataPrompt.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
);
-29
View File
@@ -37,7 +37,6 @@ final class RunnerFlutterViewController: FlutterViewController {
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
private let wirelessDataPrompt = WirelessDataPrompt()
private let thumbnailQueue = DispatchQueue(
label: "com.stormg.lumadrama.thumbnail",
qos: .userInitiated
@@ -51,18 +50,8 @@ final class RunnerFlutterViewController: FlutterViewController {
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
override func applicationDidBecomeActive(_ application: UIApplication) {
super.applicationDidBecomeActive(application)
requestWirelessDataPrompt()
}
func requestWirelessDataPrompt() {
wirelessDataPrompt.requestSystemPrompt()
}
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
registerWirelessDataChannel(engineBridge)
let channel = FlutterMethodChannel(
name: "com.stormg.lumadrama/share",
binaryMessenger: engineBridge.applicationRegistrar.messenger()
@@ -143,22 +132,4 @@ final class RunnerFlutterViewController: FlutterViewController {
}
}
}
private func registerWirelessDataChannel(_ engineBridge: FlutterImplicitEngineBridge) {
let channel = FlutterMethodChannel(
name: WirelessDataPrompt.channelName,
binaryMessenger: engineBridge.applicationRegistrar.messenger()
)
channel.setMethodCallHandler { [weak self] call, result in
guard call.method == WirelessDataPrompt.awaitDecisionMethod else {
result(FlutterMethodNotImplemented)
return
}
guard let self else {
result(nil)
return
}
self.wirelessDataPrompt.awaitDecision(result)
}
}
}
+1 -6
View File
@@ -1,11 +1,6 @@
// Author: fruit.com.cn
import Flutter
import UIKit
class SceneDelegate: FlutterSceneDelegate {
override func sceneDidBecomeActive(_ scene: UIScene) {
super.sceneDidBecomeActive(scene)
(UIApplication.shared.delegate as? AppDelegate)?.requestWirelessDataPrompt()
}
}
-68
View File
@@ -1,68 +0,0 @@
// Author: fruit.com.cn
import CoreTelephony
import Flutter
import Foundation
/// 监听系统无线数据选择,并用 URLSession 唤起系统选择框。
final class WirelessDataPrompt {
static let channelName = "com.stormg.lumadrama/wireless-data"
static let awaitDecisionMethod = "awaitDecision"
/// 系统选择框由 URLSession 触发,Dart 的 Socket 请求不会弹出。
private static let promptURL = URL(string: "https://captive.apple.com/hotspot-detect.html")
private let cellularData = CTCellularData()
private let lock = NSLock()
private var pending: [FlutterResult] = []
private var decided = false
private var didRequestPrompt = false
init() {
cellularData.cellularDataRestrictionDidUpdateNotifier = { [weak self] state in
DispatchQueue.main.async {
self?.completeIfDecided(state)
}
}
}
/// 应用进入前台后请求一次,促使系统弹出无线数据选择。
func requestSystemPrompt() {
guard !didRequestPrompt, let promptURL = Self.promptURL else {
return
}
didRequestPrompt = true
_ = cellularData.restrictedState
URLSession.shared.dataTask(with: promptURL) { _, _, _ in }.resume()
}
/// 未允许前先挂起;用户允许无线数据后再放行。
func awaitDecision(_ result: @escaping FlutterResult) {
lock.lock()
if decided {
lock.unlock()
DispatchQueue.main.async {
result(nil)
}
return
}
pending.append(result)
lock.unlock()
}
private func completeIfDecided(_ state: CTCellularDataRestrictedState) {
if state != .notRestricted {
return
}
lock.lock()
if decided {
lock.unlock()
return
}
decided = true
let waiters = pending
pending.removeAll()
lock.unlock()
waiters.forEach { $0(nil) }
}
}
+5 -36
View File
@@ -30,7 +30,6 @@ import 'core/data/repositories/favorite_repository.dart';
import 'core/data/repositories/interaction_repository.dart';
import 'core/data/repositories/notice_repository.dart';
import 'core/data/repositories/playback_repository.dart';
import 'core/data/repositories/playlist_repository.dart';
import 'core/data/repositories/search_repository.dart';
import 'core/data/repositories/store_repository.dart';
import 'core/data/repositories/watch_history_repository.dart';
@@ -42,7 +41,6 @@ import 'core/data/services/download_controller.dart';
import 'core/data/services/favorite_controller.dart';
import 'core/data/services/interaction_controller.dart';
import 'core/data/services/locale_controller.dart';
import 'core/data/services/playlist_controller.dart';
import 'core/data/services/event_tracker.dart';
import 'core/data/services/playback_position_cache.dart';
import 'core/data/services/playback_session.dart';
@@ -85,7 +83,6 @@ class LumaDramaApp extends StatefulWidget {
this.commerceRepository,
this.storeRepository,
this.searchRepository,
this.playlistRepository,
this.haptics = const FlutterHaptics(),
});
@@ -106,7 +103,6 @@ class LumaDramaApp extends StatefulWidget {
final CommerceRepository? commerceRepository;
final StoreRepository? storeRepository;
final SearchRepository? searchRepository;
final PlaylistRepository? playlistRepository;
final Haptics haptics;
@override
@@ -130,10 +126,8 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
_sessionStore,
);
late final CatalogApi _catalogApi = CatalogApi(_apiClient);
late final CatalogRepository _catalogRepository =
widget.catalogRepository ?? HttpCatalogRepository(_catalogApi);
widget.catalogRepository ?? HttpCatalogRepository(CatalogApi(_apiClient));
late final CategoryRepository _categoryRepository =
widget.categoryRepository ??
@@ -183,13 +177,6 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
late final SearchRepository _searchRepository =
widget.searchRepository ?? HttpSearchRepository(CatalogApi(_apiClient));
/// 测试注入了目录仓库时不打剧单接口,剧单页继续用本地分区。
late final PlaylistRepository? _playlistRepository =
widget.playlistRepository ??
(widget.catalogRepository == null
? HttpPlaylistRepository(CatalogApi(_apiClient))
: null);
late final StoreRepository _storeRepository =
widget.storeRepository ?? HttpStoreRepository(CommerceApi(_apiClient));
@@ -252,26 +239,14 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
super.dispose();
}
CategoryController _createCategories() {
final controller = CategoryController(_categoryRepository);
if (widget.catalogRepository == null) {
controller.dramaPageLoader = CategoryApi(_apiClient).dramas;
}
controller.load();
return controller;
}
@override
Widget build(BuildContext context) {
final playlists = _playlistRepository;
return MultiProvider(
providers: [
Provider(create: (_) => PlaybackCoordinator()),
Provider<EventTracker>(create: (_) => EventTracker(_apiClient)),
Provider<PlayerFactory>(create: (_) => widget.playerFactory),
Provider<CatalogRepository>.value(value: _catalogRepository),
if (widget.catalogRepository == null)
Provider<CatalogApi>.value(value: _catalogApi),
Provider<PlaybackRepository>.value(value: _playback),
Provider<PlaybackPositionCache>.value(value: _playbackPositionCache),
Provider<WatchHistoryRepository>.value(value: _watchHistory),
@@ -285,17 +260,11 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
Provider<SearchRepository>.value(value: _searchRepository),
Provider<Haptics>.value(value: widget.haptics),
ChangeNotifierProvider(
create: (_) {
final catalog = CatalogController(_catalogRepository);
if (widget.catalogRepository != null) catalog.load();
return catalog;
},
create: (_) => CatalogController(_catalogRepository)..load(),
),
ChangeNotifierProvider(
create: (_) => CategoryController(_categoryRepository)..load(),
),
ChangeNotifierProvider(create: (_) => _createCategories()),
if (playlists != null)
ChangeNotifierProvider(
create: (_) => PlaylistController(playlists),
),
ChangeNotifierProvider.value(value: _favoriteController),
ChangeNotifierProvider.value(value: _downloadController),
ChangeNotifierProvider.value(value: _walletController),
+5 -18
View File
@@ -1,30 +1,17 @@
// Author: fruit.com.cn
import 'locale_text.dart';
/// 服务端内容分类。id 按契约保持字符串,避免雪花 ID 精度丢失。
class ContentCategory {
const ContentCategory({
required this.id,
required this.name,
this.locales = const {},
});
const ContentCategory({required this.id, required this.name});
final String id;
/// 中文名称,与 locales 里的 zh 相同。
final String name;
final Map<String, String> locales;
/// 解析 `GET /app/categories` 的单项。
factory ContentCategory.fromJson(Map<String, dynamic> json) {
final locales = localeMap(json['locales']);
final name = json['name'] as String? ?? locales['zh'] ?? '';
return ContentCategory(id: (json['id'] ?? '').toString(), name: name, locales: locales);
}
/// 按界面语言取名称。缺对应语言时回落到中文。
String localizedName(String languageCode) {
return localizedText(languageCode, name, locales);
return ContentCategory(
id: (json['id'] ?? '').toString(),
name: json['name'] as String? ?? '',
);
}
}
+9 -150
View File
@@ -1,9 +1,6 @@
// Author: fruit.com.cn
import 'dart:ui';
import 'json_numbers.dart';
import 'locale_text.dart';
/// 短剧与剧集,字段与后端 `/app/**` 的下发结构对应。
///
@@ -79,14 +76,7 @@ class Drama {
required this.synopsis,
required this.posterUrl,
this.episodes = const [],
this.titleLocales = const {},
this.synopsisLocales = const {},
this.tag = '',
this.tagLocales = const {},
this.tagColor = '',
this.category = '',
this.categoryLocales = const {},
this.types = const [],
this.genre = '',
this.totalEpisodes = 0,
this.freeEpisodes = 0,
@@ -104,16 +94,9 @@ class Drama {
final String id;
final String title;
final String synopsis;
final Map<String, String> titleLocales;
final Map<String, String> synopsisLocales;
final String tag;
final Map<String, String> tagLocales;
final String tagColor;
final String posterUrl;
final List<Episode> episodes;
final String category;
final Map<String, String> categoryLocales;
final List<Map<String, String>> types;
final String genre;
final int totalEpisodes;
final int freeEpisodes;
@@ -144,26 +127,19 @@ class Drama {
/// 列表卡片:带一集可播预览(首页直接起播),完整剧集进详情再取。
factory Drama.fromCardJson(Map<String, dynamic> json) {
final preview = json['preview'];
final text = _DramaText.fromJson(json);
return Drama(
id: (json['id'] ?? '').toString(),
title: text.title,
synopsis: text.synopsis,
titleLocales: text.titleLocales,
synopsisLocales: text.synopsisLocales,
tag: text.tag,
tagLocales: text.tagLocales,
tagColor: json['tagColor'] as String? ?? '',
title: json['title'] as String? ?? '',
synopsis: json['synopsis'] as String? ?? '',
posterUrl: json['cover'] as String? ?? '',
episodes: preview is Map<String, dynamic>
? [Episode.fromJson(preview)]
: const [],
category: text.category,
categoryLocales: text.categoryLocales,
types: text.types,
genre: text.genre,
category: json['category'] as String? ?? '',
genre: json['genre'] as String? ?? '',
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
isHot: json['isHot'] == true,
// viewCount 后端是 Long,按字符串下发(见 json_numbers.dart)
viewCount: jsonToInt(json['viewCount']),
likeCount: _optionalInt(json['likeCount']),
favoriteCount: _optionalInt(json['favoriteCount']),
@@ -176,21 +152,13 @@ class Drama {
/// 详情:带剧集列表。
factory Drama.fromDetailJson(Map<String, dynamic> json) {
final text = _DramaText.fromJson(json);
return Drama(
id: (json['id'] ?? '').toString(),
title: text.title,
synopsis: text.synopsis,
titleLocales: text.titleLocales,
synopsisLocales: text.synopsisLocales,
tag: text.tag,
tagLocales: text.tagLocales,
tagColor: json['tagColor'] as String? ?? '',
title: json['title'] as String? ?? '',
synopsis: json['synopsis'] as String? ?? '',
posterUrl: json['cover'] as String? ?? '',
category: text.category,
categoryLocales: text.categoryLocales,
types: text.types,
genre: text.genre,
category: json['category'] as String? ?? '',
genre: json['genre'] as String? ?? '',
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
freeEpisodes: (json['freeEpisodes'] as num?)?.toInt() ?? 0,
isHot: json['isHot'] == true,
@@ -208,37 +176,6 @@ class Drama {
.toList(),
);
}
String localizedTitle(String languageCode) {
return localizedText(languageCode, title, titleLocales);
}
String localizedSynopsis(String languageCode) {
return localizedText(languageCode, synopsis, synopsisLocales);
}
String localizedTag(String languageCode) {
return localizedText(languageCode, tag, tagLocales);
}
/// 标签角标背景色。接口没给合法色值时用 fallback。
Color tagRibbonColor(Color fallback) {
final parsed = _colorFromHex(tagColor);
return parsed ?? fallback;
}
/// 按当前语言取类型名称。接口没带语言表时返回空,调用方继续用中文 genre。
List<String> localizedTypeLabels(String languageCode) {
final labels = <String>[];
for (final item in types) {
final label = localizedText(languageCode, item['zh'] ?? '', item);
if (label.isNotEmpty && !labels.contains(label)) labels.add(label);
}
if (labels.isNotEmpty) return labels;
final primary = localizedText(languageCode, '', categoryLocales);
if (primary.isNotEmpty) return [primary];
return const [];
}
}
int? _optionalInt(dynamic value) => value == null ? null : jsonToInt(value);
@@ -247,81 +184,3 @@ String? _optionalString(dynamic value) {
final text = value is String ? value.trim() : '';
return text.isEmpty ? null : text;
}
Color? _colorFromHex(String raw) {
final text = raw.trim();
if (text.length != 7 || !text.startsWith('#')) return null;
final value = int.tryParse(text.substring(1), radix: 16);
if (value == null) return null;
return Color(0xFF000000 | value);
}
List<Map<String, String>> _typeLocales(Object? raw) {
if (raw is! List) return const [];
return raw.whereType<Map>().map(localeMap).toList(growable: false);
}
/// 从语言表还原中文展示字段。列表接口不再单独下发 title / synopsis / tag。
class _DramaText {
const _DramaText({
required this.title,
required this.synopsis,
required this.titleLocales,
required this.synopsisLocales,
required this.tag,
required this.tagLocales,
required this.category,
required this.categoryLocales,
required this.types,
required this.genre,
});
final String title;
final String synopsis;
final Map<String, String> titleLocales;
final Map<String, String> synopsisLocales;
final String tag;
final Map<String, String> tagLocales;
final String category;
final Map<String, String> categoryLocales;
final List<Map<String, String>> types;
final String genre;
factory _DramaText.fromJson(Map<String, dynamic> json) {
final titleLocales = localeMap(json['titleLocales']);
final synopsisLocales = localeMap(json['synopsisLocales']);
final tagLocales = localeMap(json['tagLocales']);
final categoryLocales = localeMap(json['categoryLocales']);
final types = _typeLocales(json['types']);
final category = _firstText(categoryLocales, json['category'], types);
return _DramaText(
title: _firstText(titleLocales, json['title']),
synopsis: _firstText(synopsisLocales, json['synopsis'] ?? json['description']),
titleLocales: titleLocales,
synopsisLocales: synopsisLocales,
tag: _firstText(tagLocales, json['tag']),
tagLocales: tagLocales,
category: category,
categoryLocales: categoryLocales,
types: types,
genre: _genreText(types, json['genre']),
);
}
}
String _firstText(Map<String, String> locales, Object? fallback, [List<Map<String, String>>? types]) {
final chinese = locales['zh'] ?? '';
if (chinese.isNotEmpty) return chinese;
if (types != null && types.isNotEmpty) {
final label = types.first['zh'] ?? '';
if (label.isNotEmpty) return label;
}
return fallback is String ? fallback : '';
}
String _genreText(List<Map<String, String>> types, Object? fallback) {
final names = types.map((item) => item['zh'] ?? '').where((value) => value.isNotEmpty);
final joined = names.join(' / ');
if (joined.isNotEmpty) return joined;
return fallback is String ? fallback : '';
}
+1 -10
View File
@@ -48,7 +48,7 @@ class FeedSection {
factory FeedSection.fromJson(Map<String, dynamic> json) {
return FeedSection(
code: json['code'] as String? ?? '',
title: _sectionTitle(json),
title: json['title'] as String? ?? '',
dramas: (json['dramas'] as List? ?? const [])
.whereType<Map<String, dynamic>>()
.map(Drama.fromCardJson)
@@ -84,12 +84,3 @@ class FeedBanner {
);
}
}
String _sectionTitle(Map<String, dynamic> json) {
final locales = json['titleLocales'];
if (locales is Map) {
final chinese = locales['zh']?.toString() ?? '';
if (chinese.isNotEmpty) return chinese;
}
return json['title'] as String? ?? '';
}
-16
View File
@@ -1,16 +0,0 @@
// Author: fruit.com.cn
/// 把接口里的语言表解析成字符串映射。
Map<String, String> localeMap(Object? raw) {
if (raw is! Map) return const {};
return raw.map((key, value) => MapEntry('$key', value?.toString() ?? ''));
}
/// 按当前语言取文案。没有对应语言时用中文,中文也没有时用 fallback。
String localizedText(String languageCode, String fallback, Map<String, String> locales) {
final selected = locales[languageCode] ?? '';
if (selected.isNotEmpty) return selected;
final chinese = locales['zh'] ?? '';
if (chinese.isNotEmpty) return chinese;
return fallback;
}
-68
View File
@@ -1,68 +0,0 @@
// Author: fruit.com.cn
import 'drama.dart';
import 'locale_text.dart';
/// C 端剧单:`GET /app/playlists` 与 `GET /app/playlists/{id}` 的同一结构。
class PlaylistDetail {
const PlaylistDetail({
required this.id,
required this.name,
required this.description,
this.locales = const {},
this.descriptionLocales = const {},
required this.dramaCount,
required this.dramas,
this.pageIndex = 1,
this.pageSize = 0,
});
final String id;
/// 中文名称,与 locales 里的 zh 相同。
final String name;
final Map<String, String> locales;
/// 中文描述,与 descriptionLocales 里的 zh 相同。
final String description;
final Map<String, String> descriptionLocales;
final int dramaCount;
final int pageIndex;
final int pageSize;
final List<Drama> dramas;
factory PlaylistDetail.fromJson(Map<String, dynamic> json) {
final dramas = _dramasOf(json['list']);
final locales = localeMap(json['locales']);
final descriptions = localeMap(json['descriptionLocales']);
return PlaylistDetail(
id: (json['id'] ?? '').toString(),
name: json['name'] as String? ?? locales['zh'] ?? '',
locales: locales,
description: json['description'] as String? ?? descriptions['zh'] ?? '',
descriptionLocales: descriptions,
dramaCount: (json['dramaCount'] as num?)?.toInt() ?? dramas.length,
pageIndex: (json['pageIndex'] as num?)?.toInt() ?? 1,
pageSize: (json['pageSize'] as num?)?.toInt() ?? dramas.length,
dramas: dramas,
);
}
/// 按界面语言取名称。缺对应语言时回落到中文。
String localizedName(String languageCode) {
return localizedText(languageCode, name, locales);
}
/// 按界面语言取描述。缺对应语言时回落到中文。
String localizedDescription(String languageCode) {
return localizedText(languageCode, description, descriptionLocales);
}
}
List<Drama> _dramasOf(Object? rows) {
if (rows is! List) return const [];
return rows
.whereType<Map>()
.map((item) => Drama.fromCardJson(Map<String, dynamic>.from(item)))
.toList(growable: false);
}
-10
View File
@@ -1,7 +1,6 @@
// Author: fruit.com.cn
import 'json_numbers.dart';
import 'locale_text.dart';
/// 服务端续看记录:`GET /app/watch/progress?dramaId=` 与 `/app/watch/recent` 的下发结构。
///
@@ -14,7 +13,6 @@ class WatchProgress {
required this.position,
required this.duration,
this.dramaTitle,
this.titleLocales = const {},
this.dramaCover,
this.episodeNumber,
this.totalEpisodes,
@@ -27,7 +25,6 @@ class WatchProgress {
final String dramaId;
final String episodeId;
final String? dramaTitle;
final Map<String, String> titleLocales;
final String? dramaCover;
final int? episodeNumber;
final int? totalEpisodes;
@@ -48,17 +45,11 @@ class WatchProgress {
return (position.inMilliseconds / duration.inMilliseconds).clamp(0.0, 1.0);
}
/// 按当前语言取剧名。没有对应语言时回退中文,再回退 dramaTitle。
String localizedTitle(String languageCode) {
return localizedText(languageCode, dramaTitle ?? '', titleLocales);
}
factory WatchProgress.fromJson(Map<String, dynamic> json) {
return WatchProgress(
dramaId: (json['dramaId'] ?? '').toString(),
episodeId: (json['episodeId'] ?? '').toString(),
dramaTitle: json['dramaTitle']?.toString(),
titleLocales: localeMap(json['titleLocales']),
dramaCover: json['dramaCover']?.toString(),
episodeNumber: json['episodeNumber'] == null
? null
@@ -81,7 +72,6 @@ class WatchProgress {
'dramaId': dramaId,
'episodeId': episodeId,
if (dramaTitle != null) 'dramaTitle': dramaTitle,
if (titleLocales.isNotEmpty) 'titleLocales': titleLocales,
if (dramaCover != null) 'dramaCover': dramaCover,
if (episodeNumber != null) 'episodeNumber': episodeNumber,
if (totalEpisodes != null) 'totalEpisodes': totalEpisodes,
+3 -7
View File
@@ -31,13 +31,9 @@ class WatchRecord {
}
/// 服务端分页标题优先,详情标题作为回退。
String get displayTitle => localizedDisplayTitle('zh');
/// 按当前语言取标题。分页语言表优先,详情语言表作为回退。
String localizedDisplayTitle(String languageCode) {
final pageTitle = progress.localizedTitle(languageCode).trim();
if (pageTitle.isNotEmpty) return pageTitle;
return drama?.localizedTitle(languageCode).trim() ?? '';
String get displayTitle {
final pageTitle = progress.dramaTitle?.trim() ?? '';
return pageTitle.isNotEmpty ? pageTitle : drama?.title.trim() ?? '';
}
/// 服务端分页封面优先,详情封面作为回退。
-86
View File
@@ -1,9 +1,6 @@
import '../models/content_category.dart';
import '../models/drama.dart';
import '../models/feed_page.dart';
import '../models/home_feed.dart';
import '../models/page_result.dart';
import '../models/playlist_detail.dart';
import '../models/search_result.dart';
import 'api_client.dart';
@@ -61,95 +58,12 @@ class CatalogApi {
return SearchResult.fromJson(_asMap(data));
}
static const int playlistPageSize = 10;
static const int playlistDramaPageSize = 20;
/// 已启用剧单,分页返回,每条带已上线短剧卡片。
Future<PageResult<PlaylistDetail>> playlists({
int pageIndex = 1,
int pageSize = playlistPageSize,
}) async {
final data = await _client.get(
'/app/playlists',
query: {
'pageIndex': '$pageIndex',
'pageSize': '$pageSize',
},
);
return PageResult.parse(data, PlaylistDetail.fromJson);
}
/// 单个剧单详情。短剧按 pageIndex、pageSize 翻页。
Future<PlaylistDetail> playlist(
String id, {
int pageIndex = 1,
int pageSize = playlistDramaPageSize,
}) async {
return PlaylistDetail.fromJson(
_asMap(
await _client.get(
'/app/playlists/$id',
query: {
'pageIndex': '$pageIndex',
'pageSize': '$pageSize',
},
),
),
);
}
/// 已启用首页分类,名称在 locales。
Future<List<ContentCategory>> classifications() async {
return _categories(await _client.get('/app/categories'));
}
/// 已启用类型,名称在 locales。
Future<List<ContentCategory>> dramaCategories() async {
return _categories(await _client.get('/app/drama-categories'));
}
/// 已启用标签,名称在 locales。
Future<List<ContentCategory>> tags() async {
return _categories(await _client.get('/app/tags'));
}
static const int libraryPageSize = 20;
/// 全部短剧。同一组 id 多选为或,组与组之间为且。
Future<PageResult<Drama>> libraryDramas({
List<String> categoryIds = const [],
List<String> classificationIds = const [],
List<String> tagIds = const [],
int pageIndex = 1,
int pageSize = libraryPageSize,
}) async {
final data = await _client.post(
'/app/dramas/page',
body: {
'pageIndex': pageIndex,
'pageSize': pageSize,
'categoryIds': categoryIds,
'classificationIds': classificationIds,
'tagIds': tagIds,
},
);
return PageResult.parse(data, Drama.fromCardJson);
}
Future<Drama> dramaDetail(String dramaId) async {
return Drama.fromDetailJson(
_asMap(await _client.get('/app/dramas/$dramaId')),
);
}
List<ContentCategory> _categories(Object? data) {
if (data is! List) return const [];
return [
for (final item in data)
if (item is Map<String, dynamic>) ContentCategory.fromJson(item),
];
}
Map<String, dynamic> _asMap(Object? data) {
if (data is Map<String, dynamic>) return data;
throw const ApiException(-1, '返回数据格式异常');
-20
View File
@@ -1,16 +1,12 @@
// Author: fruit.com.cn
import '../models/content_category.dart';
import '../models/drama.dart';
import '../models/page_result.dart';
import 'api_client.dart';
/// 内容分类接口,对应契约 `GET /app/categories`。
class CategoryApi {
const CategoryApi(this._client);
static const int dramaPageSize = 20;
final ApiClient _client;
/// 拉取已启用分类,id 全程按字符串解析。
@@ -22,20 +18,4 @@ class CategoryApi {
if (item is Map<String, dynamic>) ContentCategory.fromJson(item),
];
}
/// 分类下已上线短剧,pageIndex 从 1 开始。
Future<PageResult<Drama>> dramas(
String categoryId, {
int pageIndex = 1,
int pageSize = dramaPageSize,
}) async {
final data = await _client.get(
'/app/categories/$categoryId/dramas',
query: {
'pageIndex': '$pageIndex',
'pageSize': '$pageSize',
},
);
return PageResult.parse(data, Drama.fromCardJson);
}
}
@@ -1,38 +0,0 @@
// Author: fruit.com.cn
import '../models/page_result.dart';
import '../models/playlist_detail.dart';
import '../remote/catalog_api.dart';
/// 剧单来源:列表分页拉取,详情用于打开单条时刷新。
abstract interface class PlaylistRepository {
Future<PageResult<PlaylistDetail>> fetchPlaylists({
int pageIndex = 1,
int pageSize = CatalogApi.playlistPageSize,
});
Future<PlaylistDetail> fetchPlaylist(
String id, {
int pageIndex = 1,
int pageSize = CatalogApi.playlistDramaPageSize,
});
}
class HttpPlaylistRepository implements PlaylistRepository {
HttpPlaylistRepository(this._api);
final CatalogApi _api;
@override
Future<PageResult<PlaylistDetail>> fetchPlaylists({
int pageIndex = 1,
int pageSize = CatalogApi.playlistPageSize,
}) => _api.playlists(pageIndex: pageIndex, pageSize: pageSize);
@override
Future<PlaylistDetail> fetchPlaylist(
String id, {
int pageIndex = 1,
int pageSize = CatalogApi.playlistDramaPageSize,
}) => _api.playlist(id, pageIndex: pageIndex, pageSize: pageSize);
}
@@ -1,173 +0,0 @@
// Author: fruit.com.cn
// 全部短剧筛选与分页:拉取分类、类型、标签,并按页加载短剧。
import '../models/content_category.dart';
import '../models/drama.dart';
import '../models/page_result.dart';
import '../remote/catalog_api.dart';
/// 全部短剧筛选与分页所需的远端能力。
abstract interface class AllDramasRemote {
/// 已启用分类。
Future<List<ContentCategory>> classifications();
/// 已启用类型。
Future<List<ContentCategory>> categories();
/// 已启用标签。
Future<List<ContentCategory>> tags();
/// 按当前筛选取一页短剧。
Future<PageResult<Drama>> dramas({
required List<String> categoryIds,
required List<String> classificationIds,
required List<String> tagIds,
required int pageIndex,
});
}
/// 用现有目录接口实现全部短剧远端能力。
class CatalogAllDramasRemote implements AllDramasRemote {
/// 绑定目录接口。
const CatalogAllDramasRemote(this._api);
final CatalogApi _api;
@override
Future<List<ContentCategory>> classifications() => _api.classifications();
@override
Future<List<ContentCategory>> categories() => _api.dramaCategories();
@override
Future<List<ContentCategory>> tags() => _api.tags();
@override
Future<PageResult<Drama>> dramas({
required List<String> categoryIds,
required List<String> classificationIds,
required List<String> tagIds,
required int pageIndex,
}) {
return _api.libraryDramas(
categoryIds: categoryIds,
classificationIds: classificationIds,
tagIds: tagIds,
pageIndex: pageIndex,
);
}
}
/// 全部短剧:筛选项来自类型、分类、标签,列表按页加载。
class AllDramasController {
AllDramasController({
AllDramasRemote? api,
this.classifications = const [],
this.categories = const [],
this.tags = const [],
this.dramas = const [],
}) : _api = api;
final AllDramasRemote? _api;
List<ContentCategory> classifications;
List<ContentCategory> categories;
List<ContentCategory> tags;
final Set<String> selectedClassifications = {};
final Set<String> selectedCategories = {};
final Set<String> selectedTags = {};
List<Drama> dramas;
bool loading = false;
bool loadingMore = false;
bool hasMore = false;
String? error;
int _page = 1;
int _total = 0;
bool get usesRemote => _api != null;
/// 预览用:筛选项和列表都已在本地,不请求接口。
factory AllDramasController.preview({
List<ContentCategory> classifications = const [],
List<ContentCategory> categories = const [],
List<ContentCategory> tags = const [],
List<Drama> dramas = const [],
}) {
return AllDramasController(
classifications: classifications,
categories: categories,
tags: tags,
dramas: dramas,
);
}
/// 从第一页重新拉取筛选项和短剧。没有接口时直接返回。
Future<void> refresh() async {
if (_api == null) return;
loading = true;
error = null;
_page = 1;
try {
final filters = await Future.wait([
_api.classifications(),
_api.categories(),
_api.tags(),
]);
classifications = filters[0];
categories = filters[1];
tags = filters[2];
final page = await _loadPage(1);
dramas = page;
hasMore = dramas.length < _total;
} catch (caught) {
error = '$caught';
} finally {
loading = false;
}
}
/// 追加下一页。没有更多、正在加载或没有接口时直接返回。
Future<void> loadMore() async {
if (_api == null || loading || loadingMore || !hasMore) return;
loadingMore = true;
error = null;
try {
final next = await _loadPage(_page + 1);
_page += 1;
dramas = [...dramas, ...next];
hasMore = dramas.length < _total;
} catch (caught) {
error = '$caught';
} finally {
loadingMore = false;
}
}
/// 切换一个分类。传入空字符串表示清空这一组。
void toggleClassification(String id) =>
_toggle(selectedClassifications, id);
/// 切换一个类型。传入空字符串表示清空这一组。
void toggleCategory(String id) => _toggle(selectedCategories, id);
/// 切换一个标签。传入空字符串表示清空这一组。
void toggleTag(String id) => _toggle(selectedTags, id);
void _toggle(Set<String> selected, String id) {
if (id.isEmpty) {
selected.clear();
return;
}
if (!selected.add(id)) selected.remove(id);
}
Future<List<Drama>> _loadPage(int pageIndex) async {
final page = await _api!.dramas(
categoryIds: selectedCategories.toList(growable: false),
classificationIds: selectedClassifications.toList(growable: false),
tagIds: selectedTags.toList(growable: false),
pageIndex: pageIndex,
);
_total = page.total;
return page.list;
}
}
@@ -6,8 +6,6 @@ import '../../config/app_config.dart';
import '../models/content_category.dart';
import '../models/drama.dart';
import '../models/home_feed.dart';
import '../models/page_result.dart';
import '../remote/category_api.dart';
import '../repositories/category_repository.dart';
/// 剧场页数据:服务端分类清单与发现 feed。
@@ -16,80 +14,13 @@ class CategoryController extends ChangeNotifier {
final CategoryRepository _repository;
/// 生产环境注入。未注入时首页分类继续用本地筛选。
Future<PageResult<Drama>> Function(
String categoryId, {
int pageIndex,
int pageSize,
})? dramaPageLoader;
List<ContentCategory> categories = const [];
final Map<String, CategoryDramaSlot> _slots = {};
HomeFeed feed = const HomeFeed();
bool loading = false;
String? error;
String? debugError;
bool _disposed = false;
/// 某个分类自己的短剧分页,不和别的分类共用。
CategoryDramaSlot slotOf(String categoryId) {
return _slots.putIfAbsent(categoryId, CategoryDramaSlot.new);
}
/// 打开分类并加载第一页短剧。
Future<void> openCategory(String categoryId) async {
final loader = dramaPageLoader;
if (loader == null) return;
final slot = slotOf(categoryId);
slot.loading = true;
slot.loadingMore = false;
_notify();
try {
final page = await loader(
categoryId,
pageIndex: 1,
pageSize: CategoryApi.dramaPageSize,
);
slot.dramas = page.list;
slot.total = page.total;
slot.pageIndex = 1;
} catch (exception) {
if (kDebugMode) debugPrint('[category] $exception');
} finally {
slot.loading = false;
_notify();
}
}
/// 上拉加载这个分类的下一页。
Future<void> loadMore(String categoryId) async {
final loader = dramaPageLoader;
final slot = _slots[categoryId];
if (loader == null || slot == null) return;
if (slot.loading || slot.loadingMore || !slot.hasMore) return;
slot.loadingMore = true;
_notify();
try {
final page = await loader(
categoryId,
pageIndex: slot.pageIndex + 1,
pageSize: CategoryApi.dramaPageSize,
);
if (page.list.isEmpty) {
slot.total = slot.dramas.length;
} else {
slot.dramas = [...slot.dramas, ...page.list];
slot.total = page.total;
slot.pageIndex += 1;
}
} catch (exception) {
if (kDebugMode) debugPrint('[category] more $exception');
} finally {
slot.loadingMore = false;
_notify();
}
}
/// 分类九宫格点击后读取该分类的剧目;缺失分区返回空列表。
List<Drama> dramasOf(String categoryId) {
final code = 'category-$categoryId';
@@ -99,23 +30,19 @@ class CategoryController extends ChangeNotifier {
return const [];
}
/// 首页只拉分类,再拉第一个分类的短剧。发现页聚合留到没有短剧分页时再取。
/// 加载分类与发现 feed;失败保留可重试错误态。
Future<void> load() async {
loading = true;
error = null;
debugError = null;
_notify();
try {
if (dramaPageLoader != null) {
categories = await _repository.fetchCategories();
} else {
final results = await Future.wait<Object>([
_repository.fetchCategories(),
_repository.fetchDiscoverFeed(),
]);
categories = results[0] as List<ContentCategory>;
feed = results[1] as HomeFeed;
}
final results = await Future.wait<Object>([
_repository.fetchCategories(),
_repository.fetchDiscoverFeed(),
]);
categories = results[0] as List<ContentCategory>;
feed = results[1] as HomeFeed;
} catch (exception) {
error = 'categoriesError';
debugError = exception.toString();
@@ -126,9 +53,6 @@ class CategoryController extends ChangeNotifier {
loading = false;
_notify();
}
if (error == null && dramaPageLoader != null && categories.isNotEmpty) {
await openCategory(categories.first.id);
}
}
void _notify() {
@@ -141,14 +65,3 @@ class CategoryController extends ChangeNotifier {
super.dispose();
}
}
/// 单个分类的短剧分页状态。
class CategoryDramaSlot {
List<Drama> dramas = const [];
int total = 0;
int pageIndex = 0;
bool loading = false;
bool loadingMore = false;
bool get hasMore => dramas.length < total;
}
@@ -1,177 +0,0 @@
// Author: fruit.com.cn
part of 'playback_session.dart';
/// 当前集加上一集、下一集,切集时最多三个解码器。
const int maxLivePlayers = 3;
/// 另一条播放路由必须等当前路由释放完全部原生播放器。
class PlaybackCoordinator {
PlaybackSession? _owner;
Future<void> _handoff = Future<void>.value();
Future<bool> _acquire(PlaybackSession session, bool Function() valid) {
final result = _handoff.then((_) async {
if (!valid()) return false;
if (_owner != session) {
final previous = _owner;
await previous?._releasePlayers();
if (previous != null && previous.livePlayerCount != 0) return false;
_owner = null;
if (!valid()) return false;
_owner = session;
}
return true;
});
_handoff = result.then<void>((_) {});
return result;
}
void _forget(PlaybackSession session) {
if (_owner == session && session.livePlayerCount == 0) _owner = null;
}
}
_PlayerSlot? _usableWarm(
PlaybackSession session,
_PlayerSlot? slot,
int index,
) {
if (slot == null || slot.index != index || slot.failure != null) return null;
if (session.isLocked) return null;
return slot;
}
/// 滑走的一集若仍是相邻集,就留着最后一帧,其余槽位释放。
Future<void> _parkNeighbors(
PlaybackSession session,
_PlayerSlot? old,
_PlayerSlot? warmNext,
_PlayerSlot? warmPrevious,
) async {
await _placeNeighbor(session, old);
await _placeNeighbor(session, warmNext);
await _placeNeighbor(session, warmPrevious);
}
Future<void> _placeNeighbor(PlaybackSession session, _PlayerSlot? slot) async {
if (slot == null || slot == session._active || slot.retiring) return;
if (session._next == null && slot.index == session._nextIndex) {
session._next = slot;
return;
}
if (session._previous == null && slot.index == session._previousIndex) {
session._previous = slot;
return;
}
await session._retire(slot);
}
/// 当前集已经出画后,静默准备上一集和下一集。
void _warmNeighbors(PlaybackSession session) {
final request = session._generation;
session._preloadTask = () async {
await Future.wait([
_warmOne(session, request, session._nextIndex, next: true),
_warmOne(session, request, session._previousIndex, next: false),
]);
}();
}
Future<void> _warmOne(
PlaybackSession session,
int request,
int? index, {
required bool next,
}) async {
final candidate = await _allocateNeighbor(
session,
request,
index,
next: next,
);
if (candidate == null) return;
await candidate.ready;
if (session._closed || !_stillHeld(session, candidate, next: next)) return;
if (candidate.failure == null) {
session._notify();
return;
}
await session._enqueue(() async {
if (!_stillHeld(session, candidate, next: next)) return;
_clearNeighbor(session, next: next);
await session._retire(candidate);
});
}
Future<_PlayerSlot?> _allocateNeighbor(
PlaybackSession session,
int request,
int? index, {
required bool next,
}) async {
_PlayerSlot? created;
await session._enqueue(() async {
if (session._closed || request != session._generation) return;
final allowed = _neighborAllowed(session, index);
final current = next ? session._next : session._previous;
if (!allowed || current?.index != index) {
_clearNeighbor(session, next: next);
await session._retire(current);
}
if (!_canAllocate(session, request, allowed: allowed, next: next)) {
return;
}
try {
created = session._create(index!);
} on StateError catch (error) {
if (kDebugMode) debugPrint('相邻集预热跳过: $error');
return;
}
if (next) {
session._next = created;
} else {
session._previous = created;
}
});
return created;
}
bool _neighborAllowed(PlaybackSession session, int? index) {
return index != null &&
index >= 0 &&
index < session.episodes.length &&
index != session._currentIndex &&
session.canPlay(session.episodes[index]);
}
bool _canAllocate(
PlaybackSession session,
int request, {
required bool allowed,
required bool next,
}) {
final held = next ? session._next : session._previous;
return session._visible &&
!session._overlayOpen &&
request == session._generation &&
session._active?.prepared == true &&
allowed &&
held == null;
}
bool _stillHeld(
PlaybackSession session,
_PlayerSlot slot, {
required bool next,
}) {
return (next ? session._next : session._previous) == slot;
}
void _clearNeighbor(PlaybackSession session, {required bool next}) {
if (next) {
session._next = null;
return;
}
session._previous = null;
}
+102 -60
View File
@@ -7,8 +7,6 @@ import '../models/drama.dart';
import '../models/player_port.dart';
import 'video_player_port.dart';
part 'playback_neighbors.dart';
/// 新纹理第一帧常是黑的,旧画面只盖住这一小段。
const Duration _qualityHandoffHold = Duration(milliseconds: 200);
@@ -16,7 +14,37 @@ typedef PlayerFactory = PlayerPort Function(Episode episode);
typedef PlayerPreparation =
Future<void> Function(Episode episode, PlayerPort player);
/// Owns current plus previous/next frames; allocation stays serialized.
/// Shared by routes: the previous session releases all native players before
/// another session allocates. The app therefore has at most two, not two per page.
class PlaybackCoordinator {
PlaybackSession? _owner;
Future<void> _handoff = Future<void>.value();
Future<bool> _acquire(PlaybackSession session, bool Function() valid) {
final result = _handoff.then((_) async {
if (!valid()) return false;
if (_owner != session) {
final previous = _owner;
await previous?._releasePlayers();
// A failed native disposal cannot be treated as a free decoder slot.
if (previous != null && previous.livePlayerCount != 0) return false;
_owner = null;
if (!valid()) return false;
_owner = session;
}
return true;
});
_handoff = result.then<void>((_) {});
return result;
}
void _forget(PlaybackSession session) {
if (_owner == session && session.livePlayerCount == 0) _owner = null;
}
}
/// Owns current + one prepared successor. All allocation, playback and disposal
/// operations are serialized; initialization can run while current plays.
class PlaybackSession extends ChangeNotifier {
PlaybackSession({
required this.episodes,
@@ -42,14 +70,12 @@ class PlaybackSession extends ChangeNotifier {
final Set<_PlayerSlot> _live = {};
_PlayerSlot? _active;
_PlayerSlot? _next;
_PlayerSlot? _previous;
_PlayerSlot? _handoff;
Future<void> _operations = Future<void>.value();
Future<void> _preloadTask = Future<void>.value();
int _generation = 0;
int _currentIndex = 0;
int? _nextIndex;
int? _previousIndex;
bool _selected = false;
bool _loading = false;
bool _closed = false;
@@ -94,7 +120,7 @@ class PlaybackSession extends ChangeNotifier {
/// during a swipe without starting audio or registering history listeners.
PlayerPort? preparedPlayerAt(int index) {
if (_closed) return null;
for (final slot in [_active, _next, _previous]) {
for (final slot in [_active, _next]) {
if (slot == null ||
slot.retiring ||
slot.index != index ||
@@ -116,36 +142,24 @@ class PlaybackSession extends ChangeNotifier {
}
/// 队列重排后把当前仍在播放的 slot 映射到新索引,不重新创建播放器。
void remapCurrentIndex(int index, {int? preloadIndex, int? previousIndex}) {
void remapCurrentIndex(int index, {int? preloadIndex}) {
if (_closed || index < 0 || index >= episodes.length) return;
final activeSlot = _active;
if (activeSlot == null || activeSlot.index != _currentIndex) {
_currentIndex = index;
_rememberNeighbors(preloadIndex, previousIndex);
_nextIndex = preloadIndex;
_notify();
return;
}
_generation++;
activeSlot.index = index;
_currentIndex = index;
_rememberNeighbors(preloadIndex, previousIndex);
final staleNext = _next;
final stalePrevious = _previous;
_next = null;
_previous = null;
_notify();
unawaited(
_enqueue(() async {
await _retire(staleNext);
await _retire(stalePrevious);
}),
);
if (_visible && !_overlayOpen) _warmNeighbors(this);
}
void _rememberNeighbors(int? preloadIndex, int? previousIndex) {
_nextIndex = preloadIndex;
_previousIndex = previousIndex;
final staleNext = _next;
_next = null;
_notify();
unawaited(_enqueue(() async => _retire(staleNext)));
if (_visible && !_overlayOpen) _schedulePreload();
}
Future<void> _enqueue(Future<void> Function() operation) {
@@ -162,9 +176,7 @@ class PlaybackSession extends ChangeNotifier {
}
_PlayerSlot _create(int index) {
if (_live.length >= maxLivePlayers) {
throw StateError('Playback resource limit reached');
}
if (_live.length >= 2) throw StateError('Playback resource limit reached');
final slot = _PlayerSlot(index, factory(episodes[index]));
_live.add(slot);
slot.ready = () async {
@@ -186,14 +198,9 @@ class PlaybackSession extends ChangeNotifier {
Future<void> _retire(_PlayerSlot? slot) async {
if (slot == null || !_live.contains(slot)) return;
slot.retiring = true;
final cleared =
_active == slot ||
_next == slot ||
_previous == slot ||
_handoff == slot;
final cleared = _active == slot || _next == slot || _handoff == slot;
if (_active == slot) _active = null;
if (_next == slot) _next = null;
if (_previous == slot) _previous = null;
if (_handoff == slot) _handoff = null;
if (cleared) _notify();
await waitForFrame?.call();
@@ -208,11 +215,7 @@ class PlaybackSession extends ChangeNotifier {
/// preloadIndex comes from the visible queue, so filtered categories and series
/// use exactly the same mechanism without warming an unrelated episode.
Future<void> select(
int index, {
int? preloadIndex,
int? previousIndex,
}) async {
Future<void> select(int index, {int? preloadIndex}) async {
if (_closed || index < 0 || index >= episodes.length) return;
// 切到另一集时,上一集按下的暂停不跟着走:滑过去就应该自动播放。
// 重复选中同一集(例如页面重新可见)不在这里恢复,尊重用户按下的暂停。
@@ -222,7 +225,7 @@ class PlaybackSession extends ChangeNotifier {
final request = ++_generation;
_selected = true;
_currentIndex = index;
_rememberNeighbors(preloadIndex, previousIndex);
_nextIndex = preloadIndex;
_error = null;
if (!_visible) {
_loading = false;
@@ -257,22 +260,19 @@ class PlaybackSession extends ChangeNotifier {
return;
}
if (old != null) await old.player.pause();
final warmNext = _next;
final warmPrevious = _previous;
final warm = _next;
_active = null;
_next = null;
_previous = null;
final warm =
_usableWarm(this, warmNext, index) ??
_usableWarm(this, warmPrevious, index);
if (warm != null) {
final hit = warm?.index == index && warm?.failure == null && !isLocked;
if (hit) {
target = _active = warm;
_loading = !warm.prepared;
_loading = !warm!.prepared;
_notify();
// Start a ready successor before awaiting slow disposal of the old one.
if (warm.prepared) await _start(warm, request);
}
await _parkNeighbors(this, old, warmNext, warmPrevious);
await _retire(old);
if (!hit) await _retire(warm);
if (_closed || request != _generation || isLocked) return;
if (target == null) {
target = _active = _create(index);
@@ -285,7 +285,7 @@ class PlaybackSession extends ChangeNotifier {
await slot.ready;
if (_closed || request != _generation || _active != slot) return;
await _enqueue(() => _start(slot, request));
if (!_closed && request == _generation) _warmNeighbors(this);
if (!_closed && request == _generation) _schedulePreload();
}
/// 后台准备新片源,成功后再替换当前播放器。失败时原播放器保持不动。
@@ -316,7 +316,7 @@ class PlaybackSession extends ChangeNotifier {
if (previous != null && _handoff == previous && _active == slot) {
await _enqueue(() => _retire(previous));
}
if (!_closed && request == _generation) _warmNeighbors(this);
if (!_closed && request == _generation) _schedulePreload();
return _active == slot && slot.failure == null;
}
@@ -422,6 +422,54 @@ class PlaybackSession extends ChangeNotifier {
slot.playing = shouldPlay;
}
void _schedulePreload() {
final request = _generation;
final index = _nextIndex;
_preloadTask = () async {
_PlayerSlot? candidate;
await _enqueue(() async {
if (_closed || request != _generation) return;
final allowed =
index != null &&
index >= 0 &&
index < episodes.length &&
index != _currentIndex &&
canPlay(episodes[index]);
if (!allowed || _next?.index != index) {
final stale = _next;
_next = null;
await _retire(stale);
}
if (!_visible ||
_overlayOpen ||
request != _generation ||
_active?.prepared != true ||
!allowed) {
return;
}
try {
candidate = _next ??= _create(index);
} catch (_) {
// Optional allocation failure must not interrupt the playing item.
}
});
final slot = candidate;
if (slot == null) return;
await slot.ready;
if (_closed || _next != slot) return;
if (slot.failure != null) {
// Optional work fails silently. A later explicit selection retries.
await _enqueue(() async {
if (_next != slot) return;
_next = null;
await _retire(slot);
});
} else {
_notify();
}
}();
}
void setAppResumed(bool value) {
_appResumed = value;
_syncPlayback();
@@ -446,24 +494,18 @@ class PlaybackSession extends ChangeNotifier {
void _syncPlayback() {
if (_closed) return;
if (_visible && _selected && active == null) {
unawaited(
select(
_currentIndex,
preloadIndex: _nextIndex,
previousIndex: _previousIndex,
),
);
unawaited(select(_currentIndex, preloadIndex: _nextIndex));
return;
}
final slot = _active;
if (slot != null) unawaited(_enqueue(() => _applyPlayback(slot)));
if (_visible && !_overlayOpen && !_loading) _warmNeighbors(this);
if (_visible && !_overlayOpen && !_loading) _schedulePreload();
}
Future<void> _releasePlayers() {
_generation++;
return _enqueue(() async {
_active = _next = _previous = _handoff = null;
_active = _next = _handoff = null;
_loading = false;
_notify();
for (final slot in _live.toList()) {
@@ -1,107 +0,0 @@
// Author: fruit.com.cn
import 'package:flutter/foundation.dart';
import '../models/playlist_detail.dart';
import '../remote/catalog_api.dart';
import '../repositories/playlist_repository.dart';
/// 推荐页剧单:已启用剧单及其短剧卡片。
class PlaylistController extends ChangeNotifier {
PlaylistController(this._repository);
final PlaylistRepository _repository;
static const int pageSize = CatalogApi.playlistPageSize;
List<PlaylistDetail> items = const [];
bool loading = false;
bool loadingMore = false;
bool loaded = false;
bool hasMore = false;
String? error;
int _pageIndex = 1;
bool _disposed = false;
/// 从第一页重新拉取。失败保留错误态,成功后替换本地缓存。
Future<void> load() async {
loading = true;
error = null;
_notify();
try {
final page = await _repository.fetchPlaylists(pageSize: pageSize);
items = page.list;
_pageIndex = 1;
hasMore = items.length < page.total;
loaded = true;
} catch (exception) {
error = 'playlistsError';
if (kDebugMode) debugPrint('[playlist] $exception');
} finally {
loading = false;
_notify();
}
}
/// 滚到底时追加下一页。没有更多或正在请求时直接返回。
Future<void> loadMore() async {
if (loading || loadingMore || !hasMore) return;
loadingMore = true;
_notify();
try {
final page = await _repository.fetchPlaylists(
pageIndex: _pageIndex + 1,
pageSize: pageSize,
);
if (page.list.isEmpty) {
hasMore = false;
} else {
items = [...items, ...page.list];
_pageIndex += 1;
hasMore = items.length < page.total;
}
} catch (exception) {
if (kDebugMode) debugPrint('[playlist] more $exception');
} finally {
loadingMore = false;
_notify();
}
}
/// 打开某一剧单时再取一次详情;失败则回落到列表里已有的那条。
Future<PlaylistDetail> detail(
String id, {
int pageIndex = 1,
int pageSize = CatalogApi.playlistDramaPageSize,
}) async {
try {
return await _repository.fetchPlaylist(
id,
pageIndex: pageIndex,
pageSize: pageSize,
);
} catch (exception) {
if (kDebugMode) debugPrint('[playlist] detail $id $exception');
return items.firstWhere(
(item) => item.id == id,
orElse: () => PlaylistDetail(
id: id,
name: '',
description: '',
dramaCount: 0,
dramas: const [],
),
);
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
+2 -2
View File
@@ -8,7 +8,7 @@ String localizedDramaTitle(AppLocalizations l10n, Drama drama) =>
'the-signal-demo' => l10n.dramaSignalTitle,
'city-lights-demo' => l10n.dramaCityTitle,
'vengeance-demo' => l10n.dramaVengeanceTitle,
_ => drama.localizedTitle(l10n.localeName.split(RegExp(r'[_-]')).first),
_ => drama.title,
};
String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
@@ -16,7 +16,7 @@ String localizedDramaSynopsis(AppLocalizations l10n, Drama drama) =>
'the-signal-demo' => l10n.dramaSignalSynopsis,
'city-lights-demo' => l10n.dramaCitySynopsis,
'vengeance-demo' => l10n.dramaVengeanceSynopsis,
_ => drama.localizedSynopsis(l10n.localeName.split(RegExp(r'[_-]')).first),
_ => drama.synopsis,
};
String localizedEpisodeTitle(AppLocalizations l10n, int number) =>
@@ -1,62 +0,0 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// iOS 首次启动等待系统无线数据选择,再发首个接口请求。
abstract final class WirelessDataPrompt {
const WirelessDataPrompt._();
/// 系统选择超过此时长仍未回调时继续启动。
static const Duration decisionTimeout = Duration(seconds: 15);
/// 与 iOS `WirelessDataPrompt.channelName` 保持一致。
static const String channelName = 'com.stormg.lumadrama/wireless-data';
static const String _awaitDecisionMethod = 'awaitDecision';
static const MethodChannel _channel = MethodChannel(channelName);
static Future<void>? _pending;
/// 非 iOS 立即返回。iOS 只等待一次,失败或超时后放行。
static Future<void> awaitDecision({
required bool enabled,
Future<void> Function()? ask,
Duration? timeout,
}) {
if (!enabled) return Future<void>.value();
return _pending ??= _askOnce(ask, timeout ?? decisionTimeout);
}
/// 测试隔离用,清掉已完成的等待。
@visibleForTesting
static void resetForTest() {
_pending = null;
}
static Future<void> _askOnce(
Future<void> Function()? ask,
Duration timeout,
) async {
try {
await (ask ?? _invokeChannel).call().timeout(timeout);
} on TimeoutException {
_log('decision timed out');
} catch (error) {
_log('decision skipped: $error');
}
}
static Future<void> _invokeChannel() {
return _channel.invokeMethod<void>(_awaitDecisionMethod);
}
static void _log(String message) {
if (kDebugMode) {
debugPrint('[wireless-data] $message');
}
}
}
-3
View File
@@ -112,9 +112,6 @@ abstract final class AppColors {
static const textPrimary = Color(0xFFFFFFFF);
static const textSecondary = Color(0xFFB0B0B0);
static const textTertiary = Color(0xFF8E8E93);
/// 列表底部「没有更多了」这类弱提示。
static const textHint = Color(0xFF5C5C60);
static const textTabInactive = Color(0xFFB0B0B0);
static const textFilterIcon = Color(0xFF7A7A7E);
static const searchResultMeta = Color(0xFF9E9E9E);
+47 -128
View File
@@ -1,20 +1,11 @@
// Author: fruit.com.cn
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
const Duration _shimmerPeriod = Duration(milliseconds: 1400);
const double _shimmerTravel = 2.4;
const double _shimmerStart = -1.2;
const double _subtitleWidthFactor = 0.62;
const Color _shimmerHighlight = Color(0x38FFFFFF);
/// 首页短剧网格的占位。行数至少铺满可视高度,并带一道扫光。
class DramaGridSkeleton extends StatefulWidget {
class DramaGridSkeleton extends StatelessWidget {
const DramaGridSkeleton({
super.key,
required this.columns,
@@ -32,133 +23,61 @@ class DramaGridSkeleton extends StatefulWidget {
final int itemCount;
final ScrollPhysics physics;
@override
State<DramaGridSkeleton> createState() => _DramaGridSkeletonState();
}
class _DramaGridSkeletonState extends State<DramaGridSkeleton>
with SingleTickerProviderStateMixin {
late final AnimationController _shimmer = AnimationController(
vsync: this,
duration: _shimmerPeriod,
)..repeat();
@override
void dispose() {
_shimmer.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final grid = _grid(constraints.maxWidth, constraints.maxHeight);
return AnimatedBuilder(
animation: _shimmer,
builder: (context, child) => ShaderMask(
blendMode: BlendMode.srcATop,
shaderCallback: (bounds) => _shader(bounds),
child: child,
final itemWidth =
(constraints.maxWidth -
horizontalPadding * 2 -
crossAxisSpacing * (columns - 1)) /
columns;
final itemExtent =
itemWidth / AppDimens.cardCoverAspectRatio +
AppDimens.skeletonBodyExtent;
return GridView.builder(
physics: physics,
padding: EdgeInsets.fromLTRB(
horizontalPadding,
AppDimens.spaceMd,
horizontalPadding,
AppDimens.spaceXl,
),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: crossAxisSpacing,
mainAxisSpacing: mainAxisSpacing,
mainAxisExtent: itemExtent,
),
itemCount: itemCount,
itemBuilder: (context, index) => Column(
key: Key('drama-grid-skeleton-$index'),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AspectRatio(
aspectRatio: AppDimens.cardCoverAspectRatio,
child: Container(
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
borderRadius: BorderRadius.circular(
AppDimens.homeCardRadius,
),
),
),
),
const SizedBox(height: AppDimens.cardCoverTitleGap),
const _SkeletonBar(),
const SizedBox(height: AppDimens.skeletonTitleBarGap),
const FractionallySizedBox(
widthFactor: 0.62,
child: _SkeletonBar(),
),
],
),
child: grid,
);
},
);
}
Widget _grid(double width, double height) {
final itemWidth = _itemWidth(width);
final itemExtent = _itemExtent(itemWidth);
return GridView.builder(
physics: widget.physics,
padding: EdgeInsets.fromLTRB(
widget.horizontalPadding,
AppDimens.spaceMd,
widget.horizontalPadding,
AppDimens.spaceXl,
),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: widget.columns,
crossAxisSpacing: widget.crossAxisSpacing,
mainAxisSpacing: widget.mainAxisSpacing,
mainAxisExtent: itemExtent,
),
itemCount: _fillCount(height, itemExtent),
itemBuilder: (context, index) => _SkeletonCard(index: index),
);
}
double _itemWidth(double width) {
final gaps = widget.crossAxisSpacing * (widget.columns - 1);
return (width - widget.horizontalPadding * 2 - gaps) / widget.columns;
}
double _itemExtent(double itemWidth) {
return itemWidth / AppDimens.cardCoverAspectRatio +
AppDimens.skeletonBodyExtent;
}
int _fillCount(double height, double extent) {
if (!height.isFinite || extent <= 0) return widget.itemCount;
final rowHeight = extent + widget.mainAxisSpacing;
final rows = (height / rowHeight).ceil() + 1;
return math.max(widget.itemCount, rows * widget.columns);
}
Shader _shader(Rect bounds) {
final shift = _shimmerStart + _shimmerTravel * _shimmer.value;
return LinearGradient(
begin: Alignment(shift, -0.3),
end: Alignment(shift + 1, 0.3),
colors: const [
AppColors.skeletonSurface,
_shimmerHighlight,
AppColors.skeletonSurface,
],
).createShader(bounds);
}
}
class _SkeletonCard extends StatelessWidget {
const _SkeletonCard({required this.index});
final int index;
@override
Widget build(BuildContext context) {
return Column(
key: Key('drama-grid-skeleton-$index'),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AspectRatio(
aspectRatio: AppDimens.cardCoverAspectRatio,
child: const _SkeletonBlock(),
),
const SizedBox(height: AppDimens.cardCoverTitleGap),
const _SkeletonBar(),
const SizedBox(height: AppDimens.skeletonTitleBarGap),
const FractionallySizedBox(
widthFactor: _subtitleWidthFactor,
child: _SkeletonBar(),
),
],
);
}
}
class _SkeletonBlock extends StatelessWidget {
const _SkeletonBlock();
@override
Widget build(BuildContext context) {
return DecoratedBox(
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
),
);
}
}
class _SkeletonBar extends StatelessWidget {
+1 -20
View File
@@ -8,27 +8,19 @@ import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
import '../../l10n/app_localizations.dart';
/// 网络分页列表底部:加载中、失败重试、没有下一页。
/// 网络分页列表底部状态:仅保留加载圈与错误重试。
class PagedListFooter extends StatelessWidget {
const PagedListFooter({
super.key,
required this.loading,
required this.onRetry,
this.errorMessage,
this.hasMore = true,
this.hasItems = false,
});
final bool loading;
final String? errorMessage;
final Future<void> Function() onRetry;
/// 还有下一页时不显示结束文案。
final bool hasMore;
/// 列表为空时不显示「没有更多了」。
final bool hasItems;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
@@ -66,17 +58,6 @@ class PagedListFooter extends StatelessWidget {
),
);
}
if (hasItems && !hasMore) {
return Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
);
}
return const SizedBox.shrink();
}
}
-17
View File
@@ -2,7 +2,6 @@
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
@@ -72,14 +71,10 @@ class PagedLoadFooter extends StatelessWidget {
super.key,
required this.loading,
required this.loadMoreKey,
this.hasMore = true,
this.hasItems = false,
});
final bool loading;
final Key loadMoreKey;
final bool hasMore;
final bool hasItems;
@override
Widget build(BuildContext context) {
@@ -98,18 +93,6 @@ class PagedLoadFooter extends StatelessWidget {
),
);
}
if (hasItems && !hasMore) {
final l10n = AppLocalizations.of(context)!;
return Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
);
}
return const SizedBox.shrink();
}
}
-1
View File
@@ -219,7 +219,6 @@
"postComment": "Post",
"commentPostSuccess": "Comment posted",
"loadMore": "Load more",
"noMoreItems": "No more",
"commentsLoadFailed": "Comments could not be loaded.",
"commentPostFailed": "Could not post your comment.",
"delete": "Delete",
-1
View File
@@ -193,7 +193,6 @@
"postComment": "Kirim",
"commentPostSuccess": "Komentar terkirim",
"loadMore": "Muat lebih banyak",
"noMoreItems": "Tidak ada lagi",
"commentsLoadFailed": "Komentar tidak dapat dimuat.",
"commentPostFailed": "Komentar tidak dapat dikirim.",
"delete": "Hapus",
-6
View File
@@ -994,12 +994,6 @@ abstract class AppLocalizations {
/// **'Load more'**
String get loadMore;
/// No description provided for @noMoreItems.
///
/// In en, this message translates to:
/// **'No more'**
String get noMoreItems;
/// No description provided for @commentsLoadFailed.
///
/// In en, this message translates to:
-3
View File
@@ -486,9 +486,6 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get loadMore => 'Load more';
@override
String get noMoreItems => 'No more';
@override
String get commentsLoadFailed => 'Comments could not be loaded.';
-3
View File
@@ -487,9 +487,6 @@ class AppLocalizationsId extends AppLocalizations {
@override
String get loadMore => 'Muat lebih banyak';
@override
String get noMoreItems => 'Tidak ada lagi';
@override
String get commentsLoadFailed => 'Komentar tidak dapat dimuat.';
-3
View File
@@ -481,9 +481,6 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get loadMore => '加载更多';
@override
String get noMoreItems => '没有更多了';
@override
String get commentsLoadFailed => '评论加载失败,请重试。';
-1
View File
@@ -193,7 +193,6 @@
"postComment": "发布",
"commentPostSuccess": "发表成功",
"loadMore": "加载更多",
"noMoreItems": "没有更多了",
"commentsLoadFailed": "评论加载失败,请重试。",
"commentPostFailed": "评论发布失败,请重试。",
"delete": "删除",
+1 -5
View File
@@ -2,21 +2,17 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'app.dart';
import 'core/config/app_config.dart';
import 'core/config/server_endpoint.dart';
import 'core/platform/wireless_data_prompt.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await ServerEndpoint.load();
AppConfig.ready = WirelessDataPrompt.awaitDecision(
enabled: !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS,
).then((_) => AppConfig.probeAndApplyBaseUrl());
AppConfig.ready = AppConfig.probeAndApplyBaseUrl();
runApp(const LumaDramaApp());
unawaited(
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
@@ -119,10 +119,7 @@ class _AccountDeactivatePageState extends State<AccountDeactivatePage> {
controller: _reason,
maxLength: AccountDeactivateLogic.maxReasonLength,
maxLines: 4,
textAlignVertical: TextAlignVertical.top,
decoration: InputDecoration(
alignLabelWithHint: true,
floatingLabelBehavior: FloatingLabelBehavior.auto,
labelText: l10n.accountDeactivateReason,
hintText: l10n.accountDeactivateReasonHint,
),
+2 -2
View File
@@ -181,7 +181,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
).showSnackBar(SnackBar(content: Text(l10n.authCodeSent)));
_codeFocus.requestFocus();
} on ApiException catch (error) {
failureMessage = error.message;
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
@@ -229,7 +229,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
}
if (mounted) Navigator.of(context).pop(true);
} on ApiException catch (error) {
failureMessage = error.message;
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
+180 -17
View File
@@ -23,18 +23,30 @@ import '../../core/widgets/catalog_debug_info.dart';
import '../../core/widgets/catalog_endpoint_editor.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../filter/filter_page.dart';
import '../new_releases/new_releases_page.dart';
import '../player/open_player.dart';
import '../ranking/ranking_page.dart';
import '../reserve/reserve_page.dart';
import 'discover_binding.dart';
import 'discover_logic.dart';
import 'discover_types.dart';
import 'widgets/discover_category_tab.dart';
import 'widgets/discover_header.dart';
import 'widgets/discover_search_results.dart';
import 'widgets/discover_toolbar.dart';
import 'widgets/drama_grid.dart';
const Color _filterIconColor = AppColors.blueSoft;
const Color _newIconColor = AppColors.blueSoft;
const double _toolbarHeight = 36;
const double _toolbarGap = 10;
const double _toolbarRadius = 10;
const double _categoryTabHeight = 44;
const double _categoryTabGap = 20;
const double _categorySelectedFontSize = 16;
const double _categoryFontSize = 15;
const double _categoryUnderlineWidth = 20;
const double _categoryUnderlineHeight = 3;
const double _categoryUnderlineStrokeWidth = 2;
const double _stickyHeaderHeight = 44;
const Duration _stickyHeaderTransition = Duration(milliseconds: 160);
const Duration _categoryScrollDuration = Duration(milliseconds: 200);
@@ -283,7 +295,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
List<Widget> _theaterBlocks(AppLocalizations l10n) {
final dramas = theater.dramas;
return [
_toolbar(),
_toolbar(l10n),
if (dramas.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 40),
@@ -306,16 +318,6 @@ class _DiscoverPageState extends State<DiscoverPage> {
child: CircularProgressIndicator(strokeWidth: 2),
),
),
)
else if (dramas.isNotEmpty && !theater.hasMore)
Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
),
];
}
@@ -333,7 +335,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
DiscoverCategoryTab(
_categoryTab(
key: const Key('theater-category-all'),
anchorKey: _anchorFor('all'),
id: 'all',
label: l10n.all,
@@ -342,7 +345,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
),
for (final category in categories.categories) ...[
const SizedBox(width: _categoryTabGap),
DiscoverCategoryTab(
_categoryTab(
key: Key('theater-category-${category.id}'),
anchorKey: _anchorFor(category.id),
id: category.id,
label: category.name,
@@ -356,6 +360,52 @@ class _DiscoverPageState extends State<DiscoverPage> {
);
}
Widget _categoryTab({
required Key key,
required GlobalKey anchorKey,
required String id,
required String label,
required bool selected,
required VoidCallback onTap,
}) {
return KeyedSubtree(
key: anchorKey,
child: GestureDetector(
key: key,
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
label,
maxLines: 1,
style: TextStyle(
color: selected ? AppColors.onSurface : AppColors.muted,
fontSize: selected
? _categorySelectedFontSize
: _categoryFontSize,
fontWeight: selected ? FontWeight.w800 : FontWeight.w500,
),
),
const SizedBox(height: 4),
CustomPaint(
key: Key('theater-category-underline-$id'),
size: const Size(
_categoryUnderlineWidth,
_categoryUnderlineHeight,
),
painter: CategoryUnderlinePainter(
color: selected ? AppColors.blue : AppColors.transparent,
),
),
],
),
),
);
}
GlobalKey _anchorFor(String id) {
return _categoryAnchors.putIfAbsent(id, GlobalKey.new);
}
@@ -394,8 +444,97 @@ class _DiscoverPageState extends State<DiscoverPage> {
return true;
}
Widget _toolbar() {
return DiscoverToolbar(onOpen: (page) => _openPage(context, page));
Widget _toolbar(AppLocalizations l10n) {
return Padding(
padding: const EdgeInsets.fromLTRB(14, 2, 14, 12),
child: Row(
children: [
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-filter'),
icon: Icons.tune_rounded,
color: _filterIconColor,
label: l10n.filter,
onTap: () => _openPage(context, const FilterPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-ranking'),
icon: Icons.local_fire_department_rounded,
color: AppColors.blue,
label: l10n.rankingTab,
onTap: () => _openPage(context, const RankingPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-new'),
icon: Icons.play_circle_fill_rounded,
color: _newIconColor,
label: l10n.newDramas,
onTap: () => _openPage(context, const NewReleasesPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _toolButton(
key: const Key('theater-toolbar-reserve'),
icon: Icons.calendar_month_rounded,
color: AppColors.blue,
label: l10n.reserve,
onTap: () => _openPage(context, const ReservePage()),
),
),
],
),
);
}
Widget _toolButton({
required Key key,
required IconData icon,
required Color color,
required String label,
required VoidCallback onTap,
}) {
return Material(
color: AppColors.card,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: InkWell(
key: key,
onTap: onTap,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: Container(
height: _toolbarHeight,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(_toolbarRadius),
border: Border.all(color: AppColors.border),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 4),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.onSurface,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
);
}
void _openPage(BuildContext context, Widget page) {
@@ -462,3 +601,27 @@ class _DiscoverPageState extends State<DiscoverPage> {
AppRootTab.mine => DiscoverPageAction.mine,
};
}
/// 分类 tab 的弧形选中线。
class CategoryUnderlinePainter extends CustomPainter {
const CategoryUnderlinePainter({required this.color});
final Color color;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = _categoryUnderlineStrokeWidth
..strokeCap = StrokeCap.round;
final path = Path()
..moveTo(1, 1)
..quadraticBezierTo(size.width / 2, size.height + 1, size.width - 1, 1);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CategoryUnderlinePainter oldDelegate) =>
color != oldDelegate.color;
}
@@ -1,89 +0,0 @@
// Author: fruit.com.cn
// 剧场顶部分类标签和选中下划线。
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
const double _selectedFontSize = 16;
const double _fontSize = 15;
const double _underlineWidth = 20;
const double _underlineHeight = 3;
const double _underlineStrokeWidth = 2;
/// 一个可横向滚动的分类标签。
class DiscoverCategoryTab extends StatelessWidget {
const DiscoverCategoryTab({
super.key,
required this.id,
required this.anchorKey,
required this.label,
required this.selected,
required this.onTap,
});
final String id;
final GlobalKey anchorKey;
final String label;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return KeyedSubtree(
key: anchorKey,
child: GestureDetector(
key: Key('theater-category-$id'),
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
label,
maxLines: 1,
style: TextStyle(
color: selected ? AppColors.onSurface : AppColors.muted,
fontSize: selected ? _selectedFontSize : _fontSize,
fontWeight: selected ? FontWeight.w800 : FontWeight.w500,
),
),
const SizedBox(height: 4),
CustomPaint(
key: Key('theater-category-underline-$id'),
size: const Size(_underlineWidth, _underlineHeight),
painter: CategoryUnderlinePainter(
color: selected ? AppColors.blue : AppColors.transparent,
),
),
],
),
),
);
}
}
/// 分类 tab 的弧形选中线。
class CategoryUnderlinePainter extends CustomPainter {
const CategoryUnderlinePainter({required this.color});
final Color color;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = _underlineStrokeWidth
..strokeCap = StrokeCap.round;
final path = Path()
..moveTo(1, 1)
..quadraticBezierTo(size.width / 2, size.height + 1, size.width - 1, 1);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CategoryUnderlinePainter oldDelegate) =>
color != oldDelegate.color;
}
@@ -1,119 +0,0 @@
// Author: fruit.com.cn
// 剧场页筛选、排行、新剧、预约四个入口。
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import '../../filter/filter_page.dart';
import '../../new_releases/new_releases_page.dart';
import '../../ranking/ranking_page.dart';
import '../../reserve/reserve_page.dart';
const double _toolbarHeight = 36;
const double _toolbarGap = 10;
const double _toolbarRadius = 10;
const Color _filterIconColor = AppColors.blueSoft;
const Color _newIconColor = AppColors.blueSoft;
/// 剧场工具条。点按后由调用方打开对应页面。
class DiscoverToolbar extends StatelessWidget {
const DiscoverToolbar({super.key, required this.onOpen});
final void Function(Widget page) onOpen;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.fromLTRB(14, 2, 14, 12),
child: Row(
children: [
Expanded(
child: _button(
key: const Key('theater-toolbar-filter'),
icon: Icons.tune_rounded,
color: _filterIconColor,
label: l10n.filter,
onTap: () => onOpen(const FilterPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _button(
key: const Key('theater-toolbar-ranking'),
icon: Icons.local_fire_department_rounded,
color: AppColors.blue,
label: l10n.rankingTab,
onTap: () => onOpen(const RankingPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _button(
key: const Key('theater-toolbar-new'),
icon: Icons.play_circle_fill_rounded,
color: _newIconColor,
label: l10n.newDramas,
onTap: () => onOpen(const NewReleasesPage()),
),
),
const SizedBox(width: _toolbarGap),
Expanded(
child: _button(
key: const Key('theater-toolbar-reserve'),
icon: Icons.calendar_month_rounded,
color: AppColors.blue,
label: l10n.reserve,
onTap: () => onOpen(const ReservePage()),
),
),
],
),
);
}
Widget _button({
required Key key,
required IconData icon,
required Color color,
required String label,
required VoidCallback onTap,
}) {
return Material(
color: AppColors.card,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: InkWell(
key: key,
onTap: onTap,
borderRadius: BorderRadius.circular(_toolbarRadius),
child: Container(
height: _toolbarHeight,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(_toolbarRadius),
border: Border.all(color: AppColors.border),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 16, color: color),
const SizedBox(width: 4),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.onSurface,
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
);
}
}
+7 -9
View File
@@ -96,9 +96,9 @@ class DramaGridCard extends StatelessWidget {
children: [
_cover(),
const SizedBox(height: _titleGap),
_title(context),
_title(),
const SizedBox(height: _tagsGap),
_tags(context),
_tags(),
],
),
);
@@ -151,9 +151,9 @@ class DramaGridCard extends StatelessWidget {
);
}
Widget _title(BuildContext context) {
Widget _title() {
return Text(
drama.localizedTitle(Localizations.localeOf(context).languageCode),
drama.title,
key: Key('home-drama-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -166,8 +166,8 @@ class DramaGridCard extends StatelessWidget {
);
}
Widget _tags(BuildContext context) {
final tags = _tagValues(context);
Widget _tags() {
final tags = _tagValues();
if (tags.isEmpty) return const SizedBox.shrink();
return Wrap(
spacing: 6,
@@ -193,9 +193,7 @@ class DramaGridCard extends StatelessWidget {
);
}
List<String> _tagValues(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
List<String> _tagValues() {
final result = <String>[];
for (final value in [drama.genre, drama.category]) {
for (final part in value.split(_tagSplitter)) {
@@ -16,7 +16,7 @@ class SearchResultCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final tags = _tags(context);
final tags = _tags();
return Material(
key: Key('search-result-card-${drama.id}'),
color: AppColors.transparent,
@@ -60,7 +60,7 @@ class SearchResultCard extends StatelessWidget {
),
const SizedBox(height: AppDimens.searchResultTitleGap),
Text(
drama.localizedTitle(Localizations.localeOf(context).languageCode),
drama.title,
key: Key('search-result-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -92,9 +92,7 @@ class SearchResultCard extends StatelessWidget {
);
}
List<String> _tags(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
List<String> _tags() {
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(RegExp(r'[,/、·]')))
+8 -13
View File
@@ -163,8 +163,8 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
synopsis: localizedDramaSynopsis(l10n, drama),
),
),
if (_tagValues(context, drama).isNotEmpty)
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(context, drama))),
if (_tagValues(drama).isNotEmpty)
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(drama))),
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
const SliverToBoxAdapter(child: SizedBox(height: 24)),
],
@@ -442,18 +442,13 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
return record.fraction;
}
List<String> _tagValues(BuildContext context, Drama drama) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
List<String> _tagValues(Drama drama) {
final result = <String>[];
if (localized.isNotEmpty) {
result.addAll(localized.take(_maxTags));
} else {
for (final source in [drama.category, drama.genre]) {
for (final part in source.split(_tagSplitter)) {
final value = part.trim();
if (value.isNotEmpty && !result.contains(value)) result.add(value);
if (result.length == _maxTags) return result;
}
for (final source in [drama.category, drama.genre]) {
for (final part in source.split(_tagSplitter)) {
final value = part.trim();
if (value.isNotEmpty && !result.contains(value)) result.add(value);
if (result.length == _maxTags) return result;
}
}
final language = drama.language.trim();
+4 -9
View File
@@ -176,8 +176,6 @@ class _FavoritesBody extends StatelessWidget {
],
PagedListFooter(
loading: favorites.loadingMore,
hasMore: favorites.hasMore,
hasItems: favorites.cards.isNotEmpty,
errorMessage: favorites.loadMoreError == null
? null
: errorText(l10n, favorites.loadMoreError, l10n.favoritesError),
@@ -267,9 +265,8 @@ class _FavoriteCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final languageCode = Localizations.localeOf(context).languageCode;
final tags = _tags(languageCode);
final synopsis = drama.localizedSynopsis(languageCode).trim();
final tags = _tags();
final synopsis = drama.synopsis.trim();
return Container(
key: ValueKey('favorite-card-${drama.id}'),
decoration: BoxDecoration(
@@ -312,7 +309,7 @@ class _FavoriteCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
drama.localizedTitle(languageCode),
drama.title,
key: ValueKey('favorite-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -447,9 +444,7 @@ class _FavoriteCard extends StatelessWidget {
);
}
List<String> _tags(String languageCode) {
final localized = drama.localizedTypeLabels(languageCode);
if (localized.isNotEmpty) return localized.take(_maxTags).toList();
List<String> _tags() {
final values = <String>[];
for (final source in [drama.genre, drama.category]) {
for (final part in source.split(_tagSplitter)) {
@@ -97,7 +97,7 @@ class FollowingFavoritesGrid extends StatelessWidget {
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
return FollowingGridCard(
dramaId: drama.id,
title: drama.localizedTitle(Localizations.localeOf(context).languageCode),
title: drama.title,
posterUrl: drama.posterUrl,
viewCount: drama.viewCount,
editing: isEditing,
+5 -12
View File
@@ -402,11 +402,7 @@ class _HistoryList extends StatelessWidget {
return FollowingHistoryCard(
dramaId: record.dramaId,
title: _historyTitle(
l10n,
record,
Localizations.localeOf(context).languageCode,
),
title: _historyTitle(l10n, record),
posterUrl: record.displayCover,
viewCount:
record.progress.viewCount ??
@@ -437,13 +433,10 @@ class _HistoryList extends StatelessWidget {
}
}
String _historyTitle(
AppLocalizations l10n,
WatchRecord record,
String languageCode,
) {
final title = record.localizedDisplayTitle(languageCode);
return title.isEmpty ? l10n.episodeLabel(record.episodeNumber) : title;
String _historyTitle(AppLocalizations l10n, WatchRecord record) {
return record.displayTitle.isEmpty
? l10n.episodeLabel(record.episodeNumber)
: record.displayTitle;
}
String _historySubtitle(AppLocalizations l10n, WatchRecord record) {
@@ -130,8 +130,6 @@ class FollowingPagedGrid extends StatelessWidget {
SliverToBoxAdapter(
child: PagedListFooter(
loading: loadingMore,
hasMore: hasMore,
hasItems: hasItems,
errorMessage: loadMoreError,
onRetry: onLoadMore,
),
-10
View File
@@ -7,7 +7,6 @@ import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../core/config/app_config.dart';
import '../../core/data/remote/catalog_api.dart';
import '../../core/data/services/home_feed_controller.dart';
import '../../core/data/services/catalog_controller.dart';
import '../../core/data/services/category_controller.dart';
@@ -210,7 +209,6 @@ class _HomeTabsState extends State<_HomeTabs> {
Widget _recommend(BuildContext context) {
return RecommendPage(
feedController: widget.feedController,
catalogApi: _catalogApi(context),
active: logic.tab == 1,
videoOnly: logic.videoImmersive,
onImmersiveChanged: logic.onImmersiveChanged,
@@ -218,14 +216,6 @@ class _HomeTabsState extends State<_HomeTabs> {
);
}
CatalogApi? _catalogApi(BuildContext context) {
try {
return context.read<CatalogApi>();
} on ProviderNotFoundException {
return null;
}
}
void _openSearch(BuildContext context) {
Navigator.of(
context,
@@ -1,178 +0,0 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/services/category_controller.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/drama_grid_skeleton.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../l10n/app_localizations.dart';
import 'home_feed_card.dart';
const double _loadMoreThreshold = 240;
/// 首页分类下的短剧:按分类分页,滑到底加载下一页。
class HomeCategoryDramas extends StatefulWidget {
const HomeCategoryDramas({
super.key,
required this.onOpenDrama,
this.lockedCategoryId,
});
final ValueChanged<Drama> onOpenDrama;
final String? lockedCategoryId;
@override
State<HomeCategoryDramas> createState() => _HomeCategoryDramasState();
}
class _HomeCategoryDramasState extends State<HomeCategoryDramas> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => _ensureOpened());
}
@override
void didUpdateWidget(HomeCategoryDramas oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.lockedCategoryId != widget.lockedCategoryId) {
_ensureOpened();
}
}
void _ensureOpened() {
if (!mounted) return;
final controller = context.read<CategoryController>();
final locked = widget.lockedCategoryId;
if (locked == null || locked.isEmpty) return;
final slot = controller.slotOf(locked);
if (slot.loading || slot.pageIndex > 0) return;
unawaited(controller.openCategory(locked));
}
bool _onScroll(ScrollNotification notification) {
final categoryId = widget.lockedCategoryId;
if (categoryId == null || categoryId.isEmpty) return false;
if (notification.depth != 0) return false;
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification &&
notification is! OverscrollNotification) {
return false;
}
unawaited(context.read<CategoryController>().loadMore(categoryId));
return false;
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final controller = context.watch<CategoryController>();
final categoryId = widget.lockedCategoryId ?? '';
final slot = categoryId.isEmpty ? null : controller.slotOf(categoryId);
final dramas = slot?.dramas ?? const <Drama>[];
return Column(
children: [
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
onRefresh: () async {
if (categoryId.isNotEmpty) {
await controller.openCategory(categoryId);
}
},
child: _body(context, l10n, controller, categoryId, dramas),
),
),
),
],
);
}
Widget _body(
BuildContext context,
AppLocalizations l10n,
CategoryController controller,
String categoryId,
List<Drama> dramas,
) {
final slot = categoryId.isEmpty ? null : controller.slotOf(categoryId);
if (slot != null && slot.loading && dramas.isEmpty) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
columns: 3,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
if (dramas.isEmpty) {
return EmptyState(
key: const Key('home-grid-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
);
}
return LayoutBuilder(
builder: (context, constraints) {
final itemWidth =
(constraints.maxWidth -
AppDimens.feedPageHorizontal * 2 -
AppDimens.homeGridGap * 2) /
3;
final itemExtent =
itemWidth / AppDimens.cardCoverAspectRatio +
AppDimens.homeCardBodyExtent;
return CustomScrollView(
key: const Key('home-grid-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
SliverPadding(
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.feedPageHorizontal,
),
sliver: SliverGrid(
key: const Key('home-grid-cards'),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => widget.onOpenDrama(dramas[index]),
),
childCount: dramas.length,
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
child: PagedListFooter(
loading: slot != null && slot.loadingMore,
hasMore: slot?.hasMore ?? false,
hasItems: dramas.isNotEmpty,
errorMessage: null,
onRetry: () => context.read<CategoryController>().loadMore(
categoryId,
),
),
),
),
],
);
},
);
}
}
+6 -9
View File
@@ -99,9 +99,9 @@ class HomeDramaCard extends StatelessWidget {
children: [
_cover(),
const SizedBox(height: _coverTitleGap),
_title(context),
_title(),
const SizedBox(height: _lineGap),
_genre(context),
_genre(),
const SizedBox(height: _lineGap),
_metadata(),
],
@@ -211,9 +211,9 @@ class HomeDramaCard extends StatelessWidget {
);
}
Widget _title(BuildContext context) {
Widget _title() {
return Text(
drama.localizedTitle(Localizations.localeOf(context).languageCode),
drama.title,
key: Key('home-drama-title-${drama.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -225,11 +225,8 @@ class HomeDramaCard extends StatelessWidget {
);
}
Widget _genre(BuildContext context) {
final labels = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
final genre = labels.isEmpty
? (drama.genre.isEmpty ? drama.category : drama.genre)
: labels.join(' / ');
Widget _genre() {
final genre = drama.genre.isEmpty ? drama.category : drama.genre;
return Text(
genre.isEmpty ? l10n.videoPending : genre,
key: Key('home-drama-genre-${drama.id}'),
+46 -14
View File
@@ -8,21 +8,28 @@ import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/cover_play_count.dart';
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
import 'home_drama_classification.dart';
final RegExp _tagSplitter = RegExp(r'[,/、·]');
enum HomeDramaBadge { hot, newRelease, anime }
class HomeFeedCard extends StatelessWidget {
const HomeFeedCard({
super.key,
required this.drama,
required this.onTap,
this.now,
});
final Drama drama;
final VoidCallback onTap;
final DateTime? now;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return Material(
key: Key('home-feed-card-${drama.id}'),
color: AppColors.transparent,
@@ -33,7 +40,7 @@ class HomeFeedCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
_cover(context),
_cover(l10n),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
@@ -44,7 +51,7 @@ class HomeFeedCard extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
drama.localizedTitle(Localizations.localeOf(context).languageCode),
drama.title,
key: Key('home-feed-title-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -57,7 +64,7 @@ class HomeFeedCard extends StatelessWidget {
),
),
const SizedBox(height: AppDimens.cardTitleTagGap),
_tags(context),
_tags(),
],
),
),
@@ -68,8 +75,8 @@ class HomeFeedCard extends StatelessWidget {
);
}
Widget _cover(BuildContext context) {
final label = drama.localizedTag(Localizations.localeOf(context).languageCode);
Widget _cover(AppLocalizations l10n) {
final badge = _badge();
return ClipRRect(
key: Key('home-feed-cover-clip-${drama.id}'),
borderRadius: BorderRadius.circular(AppDimens.cardCoverRadius),
@@ -85,14 +92,14 @@ class HomeFeedCard extends StatelessWidget {
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
if (label.isNotEmpty)
if (badge != null)
Positioned(
top: 0,
right: 0,
child: DramaCoverBadgeRibbon(
label: label,
color: drama.tagRibbonColor(AppColors.badgeHot),
keyPrefix: '${drama.id}-tag',
label: _badgeLabel(l10n, badge),
color: _badgeColor(badge),
keyPrefix: '${drama.id}-${badge.name}',
),
),
const Positioned(
@@ -115,8 +122,35 @@ class HomeFeedCard extends StatelessWidget {
);
}
Widget _tags(BuildContext context) {
final tags = _cardTags(context);
HomeDramaBadge? _badge() {
if (drama.dramaType.toUpperCase() == 'ANIME') {
return HomeDramaBadge.anime;
}
if (isNewDrama(drama, now: now)) return HomeDramaBadge.newRelease;
if (isHotDrama(drama)) {
return HomeDramaBadge.hot;
}
return null;
}
String _badgeLabel(AppLocalizations l10n, HomeDramaBadge badge) {
return switch (badge) {
HomeDramaBadge.hot => l10n.homeBadgeHot,
HomeDramaBadge.newRelease => l10n.homeBadgeNew,
HomeDramaBadge.anime => l10n.homeBadgeAnime,
};
}
Color _badgeColor(HomeDramaBadge badge) {
return switch (badge) {
HomeDramaBadge.hot => AppColors.badgeHot,
HomeDramaBadge.newRelease => AppColors.badgeNew,
HomeDramaBadge.anime => AppColors.badgeAnime,
};
}
Widget _tags() {
final tags = _cardTags();
if (tags.isEmpty) return const SizedBox.shrink();
return Text(
tags.join(' | '),
@@ -132,9 +166,7 @@ class HomeFeedCard extends StatelessWidget {
);
}
List<String> _cardTags(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
List<String> _cardTags() {
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(_tagSplitter))
+116 -89
View File
@@ -14,16 +14,20 @@ import '../../../core/data/services/home_feed_controller.dart';
import '../../../core/data/services/wallet_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_theme.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/drama_grid_skeleton.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../l10n/app_localizations.dart';
import 'home_category_dramas.dart';
import '../../ranking/ranking_page.dart';
import 'home_drama_classification.dart';
import 'home_feed_card.dart';
import 'home_grid_header.dart';
const double _loadMoreThreshold = 240;
const List<String> _costumeAliases = ['古装', 'costume', 'period'];
const List<String> _communityAliases = ['社群', 'community', 'komunitas'];
class HomeFeedGrid extends StatefulWidget {
const HomeFeedGrid({
@@ -42,15 +46,21 @@ class HomeFeedGrid extends StatefulWidget {
}
class _HomeFeedGridState extends State<HomeFeedGrid> {
int _sectionIndex = 0;
HomePrimaryTab _selectedPrimary = HomePrimaryTab.featured;
final PageController _pageController = PageController();
final Map<HomePrimaryTab, ScrollController> _scrollControllers = {
for (final tab in HomePrimaryTab.values) tab: ScrollController(),
};
final Map<HomePrimaryTab, String?> _selectedTags = {
for (final tab in HomePrimaryTab.values) tab: null,
};
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _pageController.hasClients) {
_pageController.jumpToPage(_sectionIndex);
_pageController.jumpToPage(_selectedPrimary.index);
}
});
}
@@ -58,6 +68,9 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
@override
void dispose() {
_pageController.dispose();
for (final controller in _scrollControllers.values) {
controller.dispose();
}
super.dispose();
}
@@ -68,16 +81,17 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
final catalog = context.watch<CatalogController>();
final auth = context.watch<AuthController>();
final wallet = context.watch<WalletController>();
final shortcuts = _categoryShortcuts(
categories,
Localizations.localeOf(context).languageCode,
);
final shortcuts = _categoryShortcuts(categories, l10n);
final walletBadge = auth.isSignedIn && wallet.snapshot != null
? wallet.balance
: null;
final ranking = _selectedPrimary == HomePrimaryTab.ranking;
return DecoratedBox(
key: const Key('home-grid'),
decoration: const BoxDecoration(color: AppColors.appBackground),
decoration: BoxDecoration(
color: ranking ? null : AppColors.appBackground,
gradient: ranking ? AppTheme.pageGradient : null,
),
child: SafeArea(
bottom: false,
child: Column(
@@ -86,8 +100,8 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
HomeGridHeader(
callbacks: widget.callbacks,
categories: shortcuts,
selectedIndex: _sectionIndex,
onSectionSelected: _selectSection,
selectedPrimary: _selectedPrimary,
onPrimarySelected: _selectPrimary,
walletBadge: walletBadge,
),
Expanded(
@@ -96,29 +110,22 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
builder: (context, _) => PageView.builder(
key: const Key('home-primary-page-view'),
controller: _pageController,
itemCount: shortcuts.isEmpty ? 1 : shortcuts.length,
onPageChanged: (index) =>
setState(() => _sectionIndex = index),
itemBuilder: (context, index) {
if (shortcuts.isEmpty) {
return _categoryPlaceholder(
l10n,
context.watch<CategoryController>(),
);
}
final category = shortcuts[index];
return _KeepAlivePage(
key: PageStorageKey(
'home-primary-page-${category.categoryId}',
),
child: _tabGrid(
context,
l10n,
category: category,
catalog: catalog,
),
);
},
itemCount: HomePrimaryTab.values.length,
onPageChanged: (index) => setState(
() => _selectedPrimary = HomePrimaryTab.values[index],
),
itemBuilder: (context, index) => _KeepAlivePage(
key: PageStorageKey(
'home-primary-page-${HomePrimaryTab.values[index].name}',
),
child: _tabGrid(
context,
l10n,
tab: HomePrimaryTab.values[index],
catalog: catalog,
shortcuts: shortcuts,
),
),
),
),
),
@@ -128,54 +135,28 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
);
}
void _selectSection(int index) {
if (index == _sectionIndex) return;
void _selectPrimary(HomePrimaryTab tab) {
if (tab == _selectedPrimary) return;
if (!_pageController.hasClients) {
setState(() => _sectionIndex = index);
setState(() => _selectedPrimary = tab);
return;
}
unawaited(
_pageController.animateToPage(
index,
tab.index,
duration: AppDimens.homePrimaryTabAnimationDuration,
curve: Curves.easeOut,
),
);
}
Widget _categoryPlaceholder(
AppLocalizations l10n,
CategoryController controller,
) {
if (controller.loading) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
columns: 3,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
return EmptyState(
key: const Key('home-grid-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
);
}
Widget _tabGrid(
BuildContext context,
AppLocalizations l10n, {
required HomeGridCategoryShortcut category,
required HomePrimaryTab tab,
required CatalogController catalog,
required List<HomeGridCategoryShortcut> shortcuts,
}) {
final controller = context.read<CategoryController>();
if (controller.dramaPageLoader != null && category.categoryId.isNotEmpty) {
return HomeCategoryDramas(
lockedCategoryId: category.categoryId,
onOpenDrama: widget.onOpenDrama,
);
}
if (catalog.error != null && widget.feedController.dramas.isEmpty) {
return _catalogErrorState(l10n, catalog);
}
@@ -189,7 +170,11 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
final dramas = _dramasFor(category);
if (tab == HomePrimaryTab.ranking) {
return const RankingPage(embedded: true);
}
final tag = _selectedTags[tab];
final dramas = _dramasFor(tab, tag, shortcuts);
if (widget.feedController.loadingFirstPage && dramas.isEmpty) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
@@ -216,7 +201,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
onRefresh: _refresh,
child: CustomScrollView(
key: const Key('home-grid-scroll'),
controller: null,
controller: _scrollControllers[tab],
physics: AppPullToRefresh.physics,
slivers: [
if (dramas.isEmpty)
@@ -252,8 +237,6 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
child: PagedListFooter(
loading: widget.feedController.loadingMore,
hasMore: widget.feedController.hasMore,
hasItems: true,
errorMessage: widget.feedController.lastError == null
? null
: l10n.catalogError,
@@ -306,31 +289,75 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
List<HomeGridCategoryShortcut> _categoryShortcuts(
List<ContentCategory> categories,
String languageCode,
AppLocalizations l10n,
) {
final costume = _findCategory(categories, _costumeAliases);
final community = _findCategory(categories, _communityAliases);
return [
for (final category in categories)
HomeGridCategoryShortcut(
label: category.localizedName(languageCode),
categoryName: category.name,
categoryId: category.id,
tab: HomePrimaryTab.categories,
),
HomeGridCategoryShortcut(
label: l10n.homeSectionCostume,
categoryName: costume?.name ?? '',
tab: HomePrimaryTab.costume,
),
HomeGridCategoryShortcut(
label: l10n.homeSectionCommunity,
categoryName: community?.name ?? '',
tab: HomePrimaryTab.community,
),
];
}
List<Drama> _dramasFor(HomeGridCategoryShortcut category) {
final dramas = widget.feedController.dramas;
final categoryName = category.categoryName.toLowerCase();
if (categoryName.isEmpty) return dramas;
final matched = dramas
.where(
(drama) =>
drama.category.toLowerCase().contains(categoryName) ||
drama.genre.toLowerCase().contains(categoryName),
)
.toList(growable: false);
return matched.isEmpty ? dramas : matched;
ContentCategory? _findCategory(
List<ContentCategory> categories,
List<String> aliases,
) {
for (final category in categories) {
final name = category.name.toLowerCase();
if (aliases.any(name.contains)) return category;
}
return null;
}
List<Drama> _dramasFor(
HomePrimaryTab tab,
String? tag,
List<HomeGridCategoryShortcut> shortcuts,
) {
Iterable<Drama> source = widget.feedController.dramas;
if (tab == HomePrimaryTab.costume || tab == HomePrimaryTab.community) {
final categoryName = shortcuts
.firstWhere((shortcut) => shortcut.tab == tab)
.categoryName
.toLowerCase();
if (categoryName.isEmpty) return const [];
source = source.where(
(drama) =>
drama.category.toLowerCase().contains(categoryName) ||
drama.genre.toLowerCase().contains(categoryName),
);
}
if (tag != null) {
source = source.where((drama) => matchesHomeTag(drama, tag));
}
final dramas = source.toList(growable: false);
switch (tab) {
case HomePrimaryTab.newReleases:
return [...dramas]..sort((a, b) {
final left = publishedAtForDrama(a);
final right = publishedAtForDrama(b);
if (left == null && right == null) return b.id.compareTo(a.id);
if (left == null) return 1;
if (right == null) return -1;
return right.compareTo(left);
});
case HomePrimaryTab.ranking:
return [...dramas]..sort((a, b) => b.viewCount.compareTo(a.viewCount));
case HomePrimaryTab.featured:
case HomePrimaryTab.categories:
case HomePrimaryTab.costume:
case HomePrimaryTab.community:
return dramas;
}
}
Widget _emptyState(AppLocalizations l10n) {
+47 -84
View File
@@ -20,13 +20,11 @@ class HomeGridCategoryShortcut {
const HomeGridCategoryShortcut({
required this.label,
required this.categoryName,
required this.categoryId,
required this.tab,
});
final String label;
final String categoryName;
final String categoryId;
final HomePrimaryTab tab;
}
@@ -49,15 +47,15 @@ class HomeGridHeader extends StatelessWidget {
super.key,
required this.callbacks,
required this.categories,
required this.selectedIndex,
required this.onSectionSelected,
required this.selectedPrimary,
required this.onPrimarySelected,
this.walletBadge,
});
final HomeGridCallbacks callbacks;
final List<HomeGridCategoryShortcut> categories;
final int selectedIndex;
final ValueChanged<int> onSectionSelected;
final HomePrimaryTab selectedPrimary;
final ValueChanged<HomePrimaryTab> onPrimarySelected;
final int? walletBadge;
@override
@@ -69,7 +67,7 @@ class HomeGridHeader extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.start,
children: [
_searchRow(l10n),
_primaryRow(),
_primaryRow(l10n),
const SizedBox(height: AppDimens.homeSecondaryGridGap),
],
);
@@ -227,73 +225,7 @@ class HomeGridHeader extends StatelessWidget {
);
}
Widget _primaryRow() {
return _CategoryBar(
categories: categories,
selectedIndex: selectedIndex,
onSectionSelected: onSectionSelected,
);
}
}
class _CategoryBar extends StatefulWidget {
const _CategoryBar({
required this.categories,
required this.selectedIndex,
required this.onSectionSelected,
});
final List<HomeGridCategoryShortcut> categories;
final int selectedIndex;
final ValueChanged<int> onSectionSelected;
@override
State<_CategoryBar> createState() => _CategoryBarState();
}
class _CategoryBarState extends State<_CategoryBar> {
final List<GlobalKey> _itemKeys = [];
@override
void initState() {
super.initState();
_syncKeys();
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
}
@override
void didUpdateWidget(_CategoryBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.categories.length != widget.categories.length) {
_syncKeys();
}
if (oldWidget.selectedIndex != widget.selectedIndex ||
oldWidget.categories.length != widget.categories.length) {
WidgetsBinding.instance.addPostFrameCallback((_) => _revealSelected());
}
}
void _syncKeys() {
_itemKeys
..clear()
..addAll(List.generate(widget.categories.length, (_) => GlobalKey()));
}
void _revealSelected() {
final index = widget.selectedIndex;
if (!mounted || index < 0 || index >= _itemKeys.length) return;
final target = _itemKeys[index].currentContext;
if (target == null) return;
Scrollable.ensureVisible(
target,
alignment: 0.5,
duration: AppDimens.homePrimaryTabAnimationDuration,
curve: Curves.easeOut,
);
}
@override
Widget build(BuildContext context) {
Widget _primaryRow(AppLocalizations l10n) {
return SingleChildScrollView(
key: const Key('home-primary-sections'),
scrollDirection: Axis.horizontal,
@@ -302,29 +234,60 @@ class _CategoryBarState extends State<_CategoryBar> {
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
for (var index = 0; index < widget.categories.length; index++)
_item(index),
_primaryItem(
key: const Key('home-section-featured'),
label: l10n.homeSectionFeatured,
tab: HomePrimaryTab.featured,
),
_primaryItem(
key: const Key('home-section-new'),
label: l10n.homeSectionNew,
tab: HomePrimaryTab.newReleases,
),
_primaryItem(
key: const Key('home-section-categories'),
label: l10n.homeSectionCategories,
tab: HomePrimaryTab.categories,
),
_primaryItem(
key: const Key('home-section-ranking'),
label: l10n.homeSectionRanking,
tab: HomePrimaryTab.ranking,
),
for (final category in categories)
_primaryItem(
key: Key(
category.categoryName.isEmpty
? 'home-section-${category.tab.name}'
: 'home-section-category-${category.categoryName}',
),
label: category.label,
tab: category.tab,
),
],
),
);
}
Widget _item(int index) {
final category = widget.categories[index];
final selected = widget.selectedIndex == index;
Widget _primaryItem({
required Key key,
required String label,
required HomePrimaryTab tab,
}) {
final selected = selectedPrimary == tab;
return InkWell(
key: _itemKeys[index],
onTap: () => widget.onSectionSelected(index),
key: key,
onTap: () => onPrimarySelected(tab),
child: Padding(
key: Key('home-section-category-${category.categoryName}'),
padding: const EdgeInsets.only(right: AppDimens.homePrimaryCategoryGap),
child: SizedBox(
height: AppDimens.homePrimaryRowHeight,
child: Align(
alignment: Alignment.bottomLeft,
child: AnimatedDefaultTextStyle(
key: Key('home-primary-label-${category.categoryId}'),
key: Key('home-primary-label-${tab.name}'),
duration: AppDimens.homePrimaryTabAnimationDuration,
curve: Curves.easeOut,
style: TextStyle(
@@ -337,7 +300,7 @@ class _CategoryBarState extends State<_CategoryBar> {
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
letterSpacing: 0,
),
child: Text(category.label, textAlign: TextAlign.left),
child: Text(label, textAlign: TextAlign.left),
),
),
),
@@ -82,11 +82,7 @@ class MineContinueWatching extends StatelessWidget {
const SizedBox(width: AppDimens.spaceMd),
itemBuilder: (_, index) {
final record = visible[index];
return _card(
l10n,
record,
Localizations.localeOf(context).languageCode,
);
return _card(l10n, record);
},
),
),
@@ -94,8 +90,8 @@ class MineContinueWatching extends StatelessWidget {
);
}
Widget _card(AppLocalizations l10n, WatchProgress record, String languageCode) {
final title = record.localizedTitle(languageCode).trim();
Widget _card(AppLocalizations l10n, WatchProgress record) {
final title = record.dramaTitle?.trim() ?? '';
final episode = record.episodeNumber;
final hasProgress = record.duration > Duration.zero;
return SizedBox(
@@ -192,8 +192,6 @@ class _NewReleasesPageState extends State<NewReleasesPage> {
),
PagedLoadFooter(
loading: pager.loading,
hasMore: pager.hasMore,
hasItems: visible.isNotEmpty,
loadMoreKey: const Key(
'new-releases-load-more',
),
-11
View File
@@ -171,17 +171,6 @@ class _NoticesPageState extends State<NoticesPage> {
label: Text(l10n.retry),
);
}
if (_controller.notices.isNotEmpty && !_controller.hasMore) {
return Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
);
}
return const SizedBox.shrink();
}
+2 -20
View File
@@ -299,7 +299,6 @@ class PlayerLogic extends ChangeNotifier {
session.remapCurrentIndex(
keepIndex,
preloadIndex: nextVisibleIndex(keepIndex),
previousIndex: previousVisibleIndex(keepIndex),
);
_jumpToFeedPage(keepIndex);
_notifyAfterFrameIfNeeded();
@@ -531,7 +530,6 @@ class PlayerLogic extends ChangeNotifier {
if (done.isCompleted) return;
if (value.hasError || !value.isBuffering) done.complete();
}
controller.addListener(onChange);
try {
await done.future.timeout(const Duration(seconds: 4));
@@ -568,7 +566,7 @@ class PlayerLogic extends ChangeNotifier {
}
final ready = await ensureTicket(index, forceRefresh: true);
if (ready) {
await _selectVisible(index);
await session.select(index, preloadIndex: nextVisibleIndex(index));
}
return ready;
} finally {
@@ -970,16 +968,7 @@ class PlayerLogic extends ChangeNotifier {
return;
}
if (!ready && ticketError != null) return;
await _selectVisible(index);
}
/// 按可见队列选择一集,并预热上一集与下一集。
Future<void> _selectVisible(int index) {
return session.select(
index,
preloadIndex: nextVisibleIndex(index),
previousIndex: previousVisibleIndex(index),
);
await session.select(index, preloadIndex: nextVisibleIndex(index));
}
int? nextVisibleIndex(int index) {
@@ -989,13 +978,6 @@ class PlayerLogic extends ChangeNotifier {
: null;
}
/// 可见队列里当前集的上一集;已经是第一集时为空。
int? previousVisibleIndex(int index) {
final position = visibleIndices.indexOf(index);
if (position <= 0) return null;
return visibleIndices[position - 1];
}
bool get hasNextEpisode => nextVisibleIndex(session.currentIndex) != null;
Future<void> playNextEpisode() async {
+2 -8
View File
@@ -41,7 +41,6 @@ import 'widgets/player_overlay.dart';
import 'widgets/player_overlay_models.dart';
import 'widgets/player_speed_sheet.dart';
import 'widgets/player_unlock_sheet.dart';
import 'widgets/player_opening_frame.dart';
import 'widgets/player_video_surface.dart';
import '../../core/data/repositories/watch_history_repository.dart';
import '../../core/data/repositories/playback_repository.dart';
@@ -553,9 +552,7 @@ class _PlayerPageState extends State<PlayerPage>
final ready = videoReady || port != null;
final theater = logic.pip || logic.pipPreparing;
final locked = logic.session.isLocked || episode.locked;
if (selected &&
videoPort != null &&
videoPort.controller.value.isInitialized) {
if (selected && videoPort != null && videoPort.controller.value.isInitialized) {
unawaited(
_spriteAxisService.prepareAt(
episode.thumbnailsUrl,
@@ -577,7 +574,6 @@ class _PlayerPageState extends State<PlayerPage>
handoff: handoffPort?.controller,
videoUrl: videoPort?.controller.dataSource ?? episode.videoUrl,
theater: theater,
openingFrame: playerOpeningFrame(episode.thumbnailsUrl),
),
if (selected &&
!theater &&
@@ -730,9 +726,7 @@ class _PlayerPageState extends State<PlayerPage>
},
onEpisodes: () => logic.showEpisodes(context),
onMore: _openCurrentMore,
onScrubStart: videoReady
? () => logic.beginScrub(videoPort!)
: null,
onScrubStart: videoReady ? () => logic.beginScrub(videoPort!) : null,
onScrubEnd: _finishFeedScrub,
onScrubVisibilityChanged: _setScrubbing,
cancelScrubRequest: widget.scrubCancelRequest,
@@ -1,119 +0,0 @@
// Author: fruit.com.cn
// 评论楼中楼:展开回复、继续加载,没有下一页时给出结束提示。
import 'package:flutter/material.dart';
import '../../../core/data/models/comment.dart';
import '../../../core/data/services/comment_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import 'comment_tile.dart';
const double _replyIndent = 52;
/// 一条评论及其回复。
class CommentThread extends StatelessWidget {
const CommentThread({
super.key,
required this.comment,
required this.controller,
required this.handlers,
});
final DramaComment comment;
final CommentController controller;
final CommentInteractionHandlers handlers;
@override
Widget build(BuildContext context) {
final replies = controller.repliesFor(comment.id);
final expanded = controller.repliesExpanded(comment.id);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CommentTile(comment: comment, handlers: handlers),
if (comment.replyCount > 0 || replies.isNotEmpty) _toggle(context, expanded),
if (expanded) _replies(context, replies),
],
);
}
Widget _toggle(BuildContext context, bool expanded) {
final l10n = AppLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.only(left: _replyIndent, bottom: 4),
child: TextButton(
key: Key('comment-replies-${comment.id}'),
onPressed: () => _toggleReplies(context),
style: TextButton.styleFrom(
foregroundColor: AppColors.muted,
padding: EdgeInsets.zero,
minimumSize: const Size(0, 24),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(width: 16, height: 1, color: AppColors.border),
const SizedBox(width: 8),
Text(
expanded ? l10n.hideReplies : l10n.viewReplies(comment.replyCount),
style: const TextStyle(
color: AppColors.muted,
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
const SizedBox(width: 4),
Icon(
expanded
? Icons.keyboard_arrow_up_rounded
: Icons.keyboard_arrow_down_rounded,
size: 14,
color: AppColors.muted,
),
],
),
),
);
}
Widget _replies(BuildContext context, List<DramaComment> replies) {
final l10n = AppLocalizations.of(context)!;
return Padding(
padding: const EdgeInsets.only(left: _replyIndent),
child: Column(
children: [
if (controller.repliesLoading(comment.id))
const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: CircularProgressIndicator(),
),
for (final reply in replies)
CommentTile(comment: reply, handlers: handlers, isReply: true),
if (controller.repliesHasMore(comment.id))
TextButton(
onPressed: () => controller.loadMoreReplies(comment.id),
child: Text(l10n.loadMore),
)
else if (replies.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
l10n.noMoreItems,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
),
],
),
);
}
Future<void> _toggleReplies(BuildContext context) async {
if (controller.repliesExpanded(comment.id)) {
controller.hideReplies(comment.id);
return;
}
await controller.loadReplies(comment.id);
}
}
@@ -19,7 +19,6 @@ import '../../../core/widgets/auth_gate.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../l10n/app_localizations.dart';
import 'comment_composer_sheet.dart';
import 'comment_thread.dart';
import 'comment_tile.dart';
const double _composerRadius = 22;
@@ -27,6 +26,7 @@ const double _composerHeight = 44;
const double _sendButtonSize = 38;
const double _sheetRadius = 20;
const double _headerHeight = 44;
const double _replyIndent = 52;
const double _composerTopGap = 8;
/// 服务端评论底部弹窗:匿名列表、游标翻页、回复与登录发布。
@@ -315,7 +315,7 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
itemCount: _controller.comments.length + 1,
itemBuilder: (context, index) {
if (index == _controller.comments.length) return _footer(l10n);
return CommentThread(
return _CommentThread(
comment: _controller.comments[index],
controller: _controller,
handlers: CommentInteractionHandlers(onReply: _beginReply),
@@ -338,17 +338,6 @@ class _DramaCommentsSheetState extends State<DramaCommentsSheet> {
child: Text(l10n.loadMore),
);
}
if (_controller.comments.isNotEmpty) {
return Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
);
}
return const SizedBox(height: 8);
}
@@ -446,3 +435,100 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
);
}
}
class _CommentThread extends StatelessWidget {
const _CommentThread({
required this.comment,
required this.controller,
required this.handlers,
});
final DramaComment comment;
final CommentController controller;
final CommentInteractionHandlers handlers;
@override
Widget build(BuildContext context) {
final replies = controller.repliesFor(comment.id);
final expanded = controller.repliesExpanded(comment.id);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CommentTile(comment: comment, handlers: handlers),
if (comment.replyCount > 0 || replies.isNotEmpty)
Padding(
padding: const EdgeInsets.only(left: _replyIndent, bottom: 4),
child: TextButton(
key: Key('comment-replies-${comment.id}'),
onPressed: () => _toggleReplies(context),
style: TextButton.styleFrom(
foregroundColor: AppColors.muted,
padding: EdgeInsets.zero,
minimumSize: const Size(0, 24),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(width: 16, height: 1, color: AppColors.border),
const SizedBox(width: 8),
Text(
expanded
? AppLocalizations.of(context)!.hideReplies
: AppLocalizations.of(
context,
)!.viewReplies(comment.replyCount),
style: const TextStyle(
color: AppColors.muted,
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
const SizedBox(width: 4),
Icon(
expanded
? Icons.keyboard_arrow_up_rounded
: Icons.keyboard_arrow_down_rounded,
size: 14,
color: AppColors.muted,
),
],
),
),
),
if (expanded)
Padding(
padding: const EdgeInsets.only(left: _replyIndent),
child: Column(
children: [
if (controller.repliesLoading(comment.id))
const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: CircularProgressIndicator(),
),
for (final reply in replies)
CommentTile(
comment: reply,
handlers: handlers,
isReply: true,
),
if (controller.repliesHasMore(comment.id))
TextButton(
onPressed: () => controller.loadMoreReplies(comment.id),
child: Text(AppLocalizations.of(context)!.loadMore),
),
],
),
),
],
);
}
Future<void> _toggleReplies(BuildContext context) async {
if (controller.repliesExpanded(comment.id)) {
controller.hideReplies(comment.id);
return;
}
await controller.loadReplies(comment.id);
}
}
@@ -49,7 +49,7 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
final l10n = AppLocalizations.of(context)!;
final dramaTitle = localizedDramaTitle(l10n, widget.drama);
final synopsis = localizedDramaSynopsis(l10n, widget.drama).trim();
final genres = _genreValues(Localizations.localeOf(context).languageCode);
final genres = _genreValues();
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -285,9 +285,7 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
);
}
List<String> _genreValues(String languageCode) {
final localized = widget.drama.localizedTypeLabels(languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
List<String> _genreValues() {
final result = <String>[];
for (final value in [widget.drama.genre, widget.drama.category]) {
for (final part in value.split(_tagSplitter)) {
@@ -1,167 +0,0 @@
// Author: fruit.com.cn
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../../../core/config/app_config.dart';
import '../../../core/data/services/sprite_thumbnail_asset_loader.dart';
import '../../../core/data/services/sprite_thumbnail_axis.dart';
import 'scrub_preview_card.dart';
/// 无雪碧图地址时不垫帧,交还给纯黑底。
Widget? playerOpeningFrame(String? thumbnailsUrl) {
final url = thumbnailsUrl?.trim() ?? '';
if (url.isEmpty) return null;
return PlayerOpeningFrame(thumbnailsUrl: url);
}
/// 解码出视频画面前,用本集雪碧图第一帧垫底。
class PlayerOpeningFrame extends StatefulWidget {
const PlayerOpeningFrame({
super.key,
required this.thumbnailsUrl,
this.loader,
this.cache,
});
final String thumbnailsUrl;
final SpriteThumbnailAssetLoader? loader;
final OpeningFrameCache? cache;
@override
State<PlayerOpeningFrame> createState() => _PlayerOpeningFrameState();
}
class _PlayerOpeningFrameState extends State<PlayerOpeningFrame> {
SpriteThumbnailFrame? _frame;
int _serial = 0;
@override
void initState() {
super.initState();
unawaited(_load());
}
@override
void didUpdateWidget(covariant PlayerOpeningFrame oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.thumbnailsUrl != widget.thumbnailsUrl) {
_frame = null;
unawaited(_load());
}
}
Future<void> _load() async {
final serial = ++_serial;
final frame = await (widget.cache ?? OpeningFrameCache.shared).load(
widget.thumbnailsUrl,
loader: widget.loader,
);
if (!mounted || serial != _serial) return;
setState(() => _frame = frame);
}
@override
Widget build(BuildContext context) {
final frame = _frame;
if (frame == null) return const SizedBox.expand();
return SpriteCropPreview(
key: const Key('player-opening-sprite'),
image: frame.image,
sourceRect: frame.sourceRect,
);
}
}
/// 相邻页共用的雪碧图首帧缓存,避免每页重复拉 VTT。
class OpeningFrameCache {
OpeningFrameCache({this.capacity = 6});
static final OpeningFrameCache shared = OpeningFrameCache();
final int capacity;
final Map<String, SpriteThumbnailFrame> _frames = {};
final Map<String, Future<SpriteThumbnailFrame?>> _loads = {};
/// 取 [thumbnailsUrl] 对应的第一帧;失败返回 null。
Future<SpriteThumbnailFrame?> load(
String? thumbnailsUrl, {
SpriteThumbnailAssetLoader? loader,
}) {
final url = _normalize(thumbnailsUrl);
if (url == null) return Future<SpriteThumbnailFrame?>.value();
final cached = _frames[url];
if (cached != null) return Future.value(cached);
return _loads.putIfAbsent(url, () => _fetch(url, loader));
}
Future<SpriteThumbnailFrame?> _fetch(
String url,
SpriteThumbnailAssetLoader? loader,
) async {
try {
final asset = loader ?? DioSpriteThumbnailAssetLoader();
final text = await asset.loadVtt(Uri.parse(url));
if (text == null || text.isEmpty) return null;
final axis = parseSpriteThumbnailVtt(text, vttUrl: url);
final cue = axis.cues.isEmpty ? null : axis.cues.first;
if (cue == null) return null;
final decoded = await asset.loadSprite(
axis.resolveSpriteUri(cue.spriteFile),
);
if (decoded == null) return null;
final frame = SpriteThumbnailFrame(
image: decoded.image,
sourceRect: _scaledRect(decoded, cue.sourceRect),
spriteUrl: axis.resolveSpriteUri(cue.spriteFile).toString(),
cue: cue,
);
_store(url, frame);
return frame;
} catch (_) {
return null;
} finally {
_loads.remove(url);
}
}
void _store(String url, SpriteThumbnailFrame frame) {
_frames.remove(url);
_frames[url] = frame;
while (_frames.length > capacity) {
final oldest = _frames.keys.first;
_frames.remove(oldest)?.image.dispose();
}
}
ui.Rect _scaledRect(SpriteThumbnailDecodedImage decoded, ui.Rect source) {
if (decoded.originalWidth <= 0 || decoded.originalHeight <= 0) {
return source;
}
final scaleX = decoded.image.width / decoded.originalWidth;
final scaleY = decoded.image.height / decoded.originalHeight;
return ui.Rect.fromLTWH(
source.left * scaleX,
source.top * scaleY,
source.width * scaleX,
source.height * scaleY,
);
}
String? _normalize(String? raw) {
final value = AppConfig.mediaUrl(raw?.trim() ?? '');
if (value.isEmpty) return null;
return value;
}
/// 测试收尾时清空缓存。
void clear() {
for (final frame in _frames.values) {
frame.image.dispose();
}
_frames.clear();
_loads.clear();
}
}
@@ -18,14 +18,10 @@ class PlayerVideoSurface extends StatefulWidget {
required this.videoUrl,
required this.theater,
this.handoff,
this.openingFrame,
});
final VideoPlayerController? controller;
final VideoPlayerController? handoff;
/// 解码出第一帧之前垫上的视频首帧,没有则为空。
final Widget? openingFrame;
final String videoUrl;
final bool theater;
@@ -64,11 +60,6 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
key: Key('player-fallback-background'),
color: AppColors.mediaBlack,
),
if (!reveal && widget.openingFrame != null)
KeyedSubtree(
key: const Key('player-opening-frame'),
child: widget.openingFrame!,
),
AnimatedOpacity(
key: const Key('player-video-opacity'),
opacity: reveal ? 1 : 0,
@@ -108,9 +99,10 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
}
bool _shouldReveal(VideoPlayerValue? value, bool covered) {
if (covered) return value?.isInitialized ?? false;
if (value == null || value.hasError || !value.isInitialized) return false;
return value.size.width > 0 && value.size.height > 0;
if (value.size.width <= 0) return false;
if (covered) return true;
return value.position > Duration.zero || value.isPlaying;
}
/// 只画会话仍持有的旧画面,控制器一旦被换掉就不再引用。
-2
View File
@@ -153,8 +153,6 @@ class _RankingPageState extends State<RankingPage> {
],
PagedLoadFooter(
loading: _pager!.loading,
hasMore: _pager!.hasMore,
hasItems: _pager!.visibleItems.isNotEmpty,
loadMoreKey: const Key('ranking-load-more'),
),
],
-80
View File
@@ -6,11 +6,8 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/data/models/drama.dart';
import '../../core/data/remote/catalog_api.dart';
import '../../core/data/models/playlist_detail.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/data/services/home_feed_controller.dart';
import '../../core/data/services/playlist_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
@@ -26,7 +23,6 @@ class RecommendPage extends StatefulWidget {
const RecommendPage({
super.key,
required this.feedController,
this.catalogApi,
required this.active,
required this.onSearch,
this.videoOnly = false,
@@ -34,7 +30,6 @@ class RecommendPage extends StatefulWidget {
});
final HomeFeedController feedController;
final CatalogApi? catalogApi;
final bool active;
final VoidCallback onSearch;
@@ -51,32 +46,6 @@ class _RecommendPageState extends State<RecommendPage> {
final PageController _pageController = PageController();
int _scrubCancelRequest = 0;
@override
void initState() {
super.initState();
if (widget.active) _scheduleRecommendData();
}
@override
void didUpdateWidget(RecommendPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.active && !oldWidget.active) _scheduleRecommendData();
}
void _scheduleRecommendData() {
final feed = widget.feedController;
if (!feed.loaded && !feed.loadingFirstPage) {
unawaited(feed.refreshCurrent());
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !widget.active) return;
final playlists = _readPlaylists();
if (playlists != null && !playlists.loaded && !playlists.loading) {
unawaited(playlists.load());
}
});
}
@override
void dispose() {
_pageController.dispose();
@@ -113,7 +82,6 @@ class _RecommendPageState extends State<RecommendPage> {
child: _withTopNavSpace(
AllDramasFilterGrid(
feedController: widget.feedController,
catalogApi: widget.catalogApi,
onOpenDrama: _openDrama,
),
),
@@ -200,22 +168,6 @@ class _RecommendPageState extends State<RecommendPage> {
);
}
PlaylistController? _watchPlaylists(BuildContext context) {
try {
return context.watch<PlaylistController>();
} on ProviderNotFoundException {
return null;
}
}
PlaylistController? _readPlaylists() {
try {
return context.read<PlaylistController>();
} on ProviderNotFoundException {
return null;
}
}
Widget _recommendPlaylists(CategoryController categories) {
return DecoratedBox(
key: const Key('recommend-playlist-surface'),
@@ -253,8 +205,6 @@ class _RecommendPageState extends State<RecommendPage> {
categories: categories,
onOpenDrama: _openDrama,
onMore: _handleMore,
playlists: _watchPlaylists(context),
onOpenPlaylist: _openPlaylist,
),
),
],
@@ -302,36 +252,6 @@ class _RecommendPageState extends State<RecommendPage> {
);
}
Future<void> _openPlaylist(PlaylistDetail playlist) async {
final controller = _readPlaylists();
const pageSize = CatalogApi.playlistDramaPageSize;
final fresh = controller == null
? playlist
: await controller.detail(playlist.id, pageSize: pageSize);
if (!mounted) return;
final shown = fresh.dramas.isEmpty && playlist.dramas.isNotEmpty
? playlist
: fresh;
await Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (_) => PlaylistDetailPage(
title: shown.name,
subtitle: shown.description,
source: shown,
dramas: shown.dramas,
dramaCount: shown.dramaCount,
loadPage: controller == null
? null
: (pageIndex) => controller.detail(
playlist.id,
pageIndex: pageIndex,
pageSize: pageSize,
),
),
),
);
}
void _handleMore(RecommendSectionKind section) {
final l10n = AppLocalizations.of(context)!;
final copy = _sectionCopy(l10n, section);
@@ -1,14 +1,10 @@
// Author: fruit.com.cn
// 全部短剧:分类、类型、标签多选,列表下拉刷新、上拉加载。
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../core/data/models/content_category.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/remote/catalog_api.dart';
import '../../../core/data/services/all_dramas_controller.dart';
import '../../../core/data/services/home_feed_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
@@ -16,24 +12,21 @@ import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
import '../../home/widgets/home_feed_card.dart';
const double _loadMoreThreshold = 240;
const int _gridColumns = 3;
const List<String> _modernTerms = ['现代', 'modern', 'moderno'];
const List<String> _reversalTerms = ['逆袭', 'comeback', 'balas'];
/// 推荐页「全部短剧」筛选和三列列表。
class AllDramasFilterGrid extends StatefulWidget {
const AllDramasFilterGrid({
super.key,
required this.feedController,
required this.onOpenDrama,
this.feedController,
this.catalogApi,
this.controller,
});
final HomeFeedController? feedController;
final CatalogApi? catalogApi;
final AllDramasController? controller;
final HomeFeedController feedController;
final ValueChanged<Drama> onOpenDrama;
@override
@@ -41,143 +34,102 @@ class AllDramasFilterGrid extends StatefulWidget {
}
class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
late final AllDramasController _library;
@override
void initState() {
super.initState();
_library = widget.controller ??
AllDramasController(
api: widget.catalogApi == null
? null
: CatalogAllDramasRemote(widget.catalogApi!),
);
if (_library.usesRemote) {
unawaited(_reload());
}
}
Future<void> _reload() async {
await _library.refresh();
if (mounted) setState(() {});
}
Future<void> _loadMore() async {
if (_library.usesRemote) {
await _library.loadMore();
if (mounted) setState(() {});
return;
}
await widget.feedController?.loadMore();
}
List<Drama> get _dramas =>
_library.usesRemote ? _library.dramas : widget.feedController?.dramas ?? _library.dramas;
String _region = 'all';
String _audio = 'all';
String? _genre;
bool _newest = false;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final dramas = _filtered();
return LayoutBuilder(
builder: (context, constraints) {
final itemWidth =
(constraints.maxWidth -
AppDimens.allDramasHorizontal * 2 -
AppDimens.allDramasGridGap * 2) /
3;
final itemExtent =
itemWidth / AppDimens.cardCoverAspectRatio +
AppDimens.homeCardBodyExtent;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_filters(l10n),
Expanded(child: _dramaList(l10n, _itemExtent(constraints.maxWidth))),
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
key: const Key('all-dramas-refresh'),
onRefresh: () async {
await widget.feedController.refreshCurrent();
},
child: CustomScrollView(
key: const Key('all-dramas-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
if (dramas.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: EmptyState(
key: const Key('all-dramas-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
),
)
else
SliverPadding(
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.allDramasHorizontal,
),
sliver: SliverGrid(
key: const Key('all-dramas-grid'),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: AppDimens.allDramasGridGap,
mainAxisSpacing:
AppDimens.allDramasGridRowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => widget.onOpenDrama(dramas[index]),
),
childCount: dramas.length,
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(
bottom: AppDimens.spaceXl,
),
child: PagedListFooter(
loading: widget.feedController.loadingMore,
errorMessage:
widget.feedController.lastError == null
? null
: l10n.catalogError,
onRetry: widget.feedController.loadMore,
),
),
),
],
),
),
),
),
],
);
},
);
}
double _itemExtent(double width) {
final itemWidth =
(width - AppDimens.allDramasHorizontal * 2 - AppDimens.allDramasGridGap * 2) /
_gridColumns;
return itemWidth / AppDimens.cardCoverAspectRatio + AppDimens.homeCardBodyExtent;
}
Widget _dramaList(AppLocalizations l10n, double itemExtent) {
final dramas = _dramas;
return NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
key: const Key('all-dramas-refresh'),
onRefresh: _refresh,
child: CustomScrollView(
key: const Key('all-dramas-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
if (dramas.isEmpty) _empty(l10n) else _grid(dramas, itemExtent),
_footer(l10n, dramas.isNotEmpty),
],
),
),
);
}
Future<void> _refresh() async {
if (_library.usesRemote) {
await _reload();
return;
}
await widget.feedController?.refreshCurrent();
}
Widget _empty(AppLocalizations l10n) {
return SliverFillRemaining(
hasScrollBody: false,
child: EmptyState(
key: const Key('all-dramas-empty'),
icon: Icons.movie_filter_outlined,
title: l10n.emptyContent,
),
);
}
Widget _grid(List<Drama> dramas, double itemExtent) {
return SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: AppDimens.allDramasHorizontal),
sliver: SliverGrid(
key: const Key('all-dramas-grid'),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: _gridColumns,
crossAxisSpacing: AppDimens.allDramasGridGap,
mainAxisSpacing: AppDimens.allDramasGridRowGap,
mainAxisExtent: itemExtent,
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: dramas[index],
onTap: () => widget.onOpenDrama(dramas[index]),
),
childCount: dramas.length,
),
),
);
}
Widget _footer(AppLocalizations l10n, bool hasItems) {
return SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
child: PagedListFooter(
loading: _library.usesRemote
? _library.loadingMore
: widget.feedController?.loadingMore ?? false,
hasMore: _library.usesRemote
? _library.hasMore
: widget.feedController?.hasMore ?? false,
hasItems: hasItems,
errorMessage: _library.error == null ? null : l10n.catalogError,
onRetry: _loadMore,
),
),
);
}
Widget _filters(AppLocalizations l10n) {
final languageCode = Localizations.localeOf(context).languageCode;
final genres = _availableGenres(l10n);
return Padding(
padding: const EdgeInsets.fromLTRB(
AppDimens.allDramasHorizontal,
@@ -188,75 +140,60 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
child: Column(
key: const Key('all-dramas-filters'),
children: [
_optionRow(
_FilterRow(
row: 0,
group: 'classification',
options: _library.classifications,
selected: _library.selectedClassifications,
onToggle: _library.toggleClassification,
),
languageCode,
l10n,
_selectableRow(
0,
[
(id: 'all', label: l10n.all),
(id: 'local', label: l10n.localFilter),
(id: 'asia', label: l10n.asiaFilter),
(id: 'western', label: l10n.westernFilter),
],
selected: _region,
onSelected: (value) => setState(() => _region = value),
),
_optionRow(
_FilterRow(
row: 1,
group: 'category',
options: _library.categories,
selected: _library.selectedCategories,
onToggle: _library.toggleCategory,
),
languageCode,
l10n,
),
_optionRow(
_FilterRow(
row: 2,
group: 'tag',
options: _library.tags,
selected: _library.selectedTags,
onToggle: _library.toggleTag,
),
languageCode,
l10n,
_selectableRow(
1,
[
(id: 'all', label: l10n.all),
(id: 'subtitles', label: l10n.subtitlesOnlyFilter),
(id: 'dubbed', label: l10n.dubbedFilter),
],
selected: _audio,
onSelected: (value) => setState(() => _audio = value),
),
_genreRow(2, genres, l10n),
_sortRow(l10n),
],
),
);
}
Widget _optionRow(_FilterRow spec, String languageCode, AppLocalizations l10n) {
Widget _selectableRow(
int row,
List<({String id, String label})> options, {
required String selected,
required ValueChanged<String> onSelected,
}) {
return _filterRow(
row: spec.row,
row: row,
child: _horizontalChipScroll(
scrollKey: Key('all-filter-scroll-${spec.row}'),
scrollKey: Key('all-filter-scroll-$row'),
chips: [
_chip(
key: Key('all-filter-${spec.group}-all'),
label: l10n.all,
selected: spec.selected.isEmpty,
onTap: () => _select(spec.onToggle, ''),
),
for (final option in spec.options) ...[
const SizedBox(width: AppDimens.filterItemGap),
for (var index = 0; index < options.length; index++) ...[
_chip(
key: Key('all-filter-${spec.group}-${option.id}'),
label: option.localizedName(languageCode),
selected: spec.selected.contains(option.id),
onTap: () => _select(spec.onToggle, option.id),
key: Key('all-filter-${options[index].id}'),
label: options[index].label,
selected: selected == options[index].id,
onTap: () => onSelected(options[index].id),
),
if (index < options.length - 1)
const SizedBox(width: AppDimens.filterItemGap),
],
],
),
);
}
void _select(void Function(String id) onToggle, String id) {
setState(() => onToggle(id));
if (_library.usesRemote) unawaited(_reload());
}
Widget _horizontalChipScroll({
required Key scrollKey,
required List<Widget> chips,
@@ -268,17 +205,43 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
physics: const BouncingScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: Row(children: chips),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: chips,
),
),
),
);
}
Widget _filterRow({required int row, required Widget child}) {
Widget _filterRow({
required int row,
required Widget child,
double height = AppDimens.filterChipHeight,
}) {
return Padding(
key: Key('all-filter-row-$row'),
padding: EdgeInsets.only(bottom: row < 2 ? AppDimens.filterRowGap : 0),
child: SizedBox(height: AppDimens.filterChipHeight, child: child),
padding: EdgeInsets.only(bottom: row < 3 ? AppDimens.filterRowGap : 0),
child: SizedBox(height: height, child: child),
);
}
Widget _genreRow(
int row,
List<({String id, String label})> options,
AppLocalizations l10n,
) {
return _selectableRow(
row,
[
(id: 'all', label: l10n.all),
for (final genre in options) (id: genre.id, label: genre.label),
],
selected: _genre ?? 'all',
onSelected: (value) =>
setState(() => _genre = value == 'all' ? null : value),
);
}
@@ -299,7 +262,9 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
),
alignment: Alignment.center,
decoration: BoxDecoration(
color: selected ? AppColors.filterChipSelected : AppColors.transparent,
color: selected
? AppColors.filterChipSelected
: AppColors.transparent,
borderRadius: BorderRadius.circular(AppDimens.filterChipRadius),
),
child: Text(
@@ -317,32 +282,84 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
);
}
Widget _sortRow(AppLocalizations l10n) {
return _filterRow(
row: 3,
child: _horizontalChipScroll(
scrollKey: const Key('all-filter-scroll-3'),
chips: [
_chip(
key: const Key('all-sort-hot'),
label: l10n.hot,
selected: !_newest,
onTap: () => setState(() => _newest = false),
),
const SizedBox(width: AppDimens.filterItemGap),
_chip(
key: const Key('all-sort-new'),
label: l10n.newest,
selected: _newest,
onTap: () => setState(() => _newest = true),
),
],
),
);
}
List<({String id, String label})> _availableGenres(AppLocalizations l10n) {
final definitions = [
(id: 'reversal', label: l10n.reversalFilter, terms: _reversalTerms),
(id: 'uplifting', label: l10n.homeTagUplifting, terms: <String>[]),
(id: 'modern', label: l10n.modernFilter, terms: _modernTerms),
(id: 'sweet', label: l10n.homeTagSweet, terms: <String>[]),
(id: 'angst', label: l10n.homeTagAngst, terms: <String>[]),
];
return definitions
.map((definition) => (id: definition.id, label: definition.label))
.toList(growable: false);
}
List<Drama> _filtered() {
if (_region != 'all' || _audio != 'all') return const [];
final dramas = widget.feedController.dramas
.where((drama) {
return _genre == null || _matchesGenre(drama, _genre!, const []);
})
.toList(growable: false);
if (_newest) {
return [...dramas]..sort((a, b) {
final left = publishedAtForDrama(a);
final right = publishedAtForDrama(b);
if (left == null && right == null) return b.id.compareTo(a.id);
if (left == null) return 1;
if (right == null) return -1;
return right.compareTo(left);
});
}
return [...dramas]..sort((a, b) => b.viewCount.compareTo(a.viewCount));
}
bool _matchesGenre(Drama drama, String id, List<String> terms) {
if (id == 'reversal' ||
id == 'uplifting' ||
id == 'sweet' ||
id == 'angst') {
return matchesHomeTag(drama, id == 'reversal' ? 'uplifting' : id);
}
final text = '${drama.genre} ${drama.category}'.toLowerCase();
return terms.any(text.contains);
}
bool _onScroll(ScrollNotification notification) {
if (notification.depth != 0) return false;
if (notification.metrics.pixels <= 0) return false;
final reachedBottom = notification.metrics.extentAfter <= _loadMoreThreshold;
final reachedBottom =
notification.metrics.extentAfter <= _loadMoreThreshold;
if (reachedBottom &&
(notification is ScrollUpdateNotification ||
notification is ScrollEndNotification ||
notification is OverscrollNotification)) {
unawaited(_loadMore());
unawaited(widget.feedController.loadMore());
}
return false;
}
}
class _FilterRow {
const _FilterRow({
required this.row,
required this.group,
required this.options,
required this.selected,
required this.onToggle,
});
final int row;
final String group;
final List<ContentCategory> options;
final Set<String> selected;
final void Function(String id) onToggle;
}
@@ -3,20 +3,15 @@
import 'package:flutter/material.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/models/playlist_detail.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/theme/app_theme.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/paged_list_footer.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_feed_card.dart';
import '../../player/open_player.dart';
const double _collageHeight = 188;
const int _collageCoverCount = 5;
const double _loadMoreThreshold = 200;
const double _pageHorizontal = 14;
const double _gridGap = 10;
const double _sprocketBand = 22;
@@ -24,88 +19,17 @@ const Color _filmBody = Color(0xFF161311);
const Color _filmHole = Color(0xFFE6D3BE);
/// 剧单「更多」:顶部拼图、与剧单一致的标题描述,以及两列卡片。
class PlaylistDetailPage extends StatefulWidget {
class PlaylistDetailPage extends StatelessWidget {
const PlaylistDetailPage({
super.key,
required this.title,
required this.subtitle,
required this.dramas,
this.dramaCount = 0,
this.source,
this.loadPage,
});
final String title;
final String subtitle;
final List<Drama> dramas;
final PlaylistDetail? source;
final int dramaCount;
final Future<PlaylistDetail> Function(int pageIndex)? loadPage;
@override
State<PlaylistDetailPage> createState() => _PlaylistDetailPageState();
}
class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
late List<Drama> _dramas = widget.dramas;
late int _dramaCount = widget.dramaCount;
int _pageIndex = 1;
bool _loadingMore = false;
bool _failed = false;
bool get _hasMore =>
widget.loadPage != null && _dramas.length < _dramaCount;
Future<void> _refresh() async {
final loadPage = widget.loadPage;
if (loadPage == null) return;
try {
final page = await loadPage(1);
if (!mounted) return;
setState(() {
_dramas = page.dramas;
_dramaCount = page.dramaCount;
_pageIndex = page.pageIndex == 0 ? 1 : page.pageIndex;
_failed = false;
});
} catch (_) {
if (!mounted) return;
setState(() => _failed = true);
}
}
Future<void> _loadMore() async {
final loadPage = widget.loadPage;
if (loadPage == null || _loadingMore || !_hasMore) return;
setState(() => _loadingMore = true);
final next = _pageIndex + 1;
try {
final page = await loadPage(next);
if (!mounted) return;
setState(() {
_dramas = [..._dramas, ...page.dramas];
_dramaCount = page.dramaCount;
_pageIndex = page.pageIndex == 0 ? next : page.pageIndex;
_failed = false;
});
} catch (_) {
if (!mounted) return;
setState(() => _failed = true);
} finally {
if (mounted) setState(() => _loadingMore = false);
}
}
bool _onScroll(ScrollNotification notification) {
if (!_hasMore || notification.depth != 0) return false;
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification) {
return false;
}
_loadMore();
return false;
}
@override
Widget build(BuildContext context) {
@@ -128,16 +52,7 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
icon: const Icon(Icons.chevron_left_rounded),
color: AppColors.textPrimary,
),
Expanded(
child: NotificationListener<ScrollNotification>(
onNotification: _onScroll,
child: AppPullToRefresh(
key: const Key('playlist-detail-refresh'),
onRefresh: _refresh,
child: _body(itemExtent),
),
),
),
Expanded(child: _body(itemExtent)),
],
),
),
@@ -148,7 +63,6 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
Widget _body(double itemExtent) {
return CustomScrollView(
key: const Key('playlist-detail-scroll'),
physics: AppPullToRefresh.physics,
slivers: [
SliverPadding(
padding: const EdgeInsets.fromLTRB(
@@ -157,7 +71,7 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
_pageHorizontal,
12,
),
sliver: SliverToBoxAdapter(child: _PlaylistCollage(dramas: _dramas)),
sliver: SliverToBoxAdapter(child: _PlaylistCollage(dramas: dramas)),
),
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: _pageHorizontal),
@@ -181,22 +95,10 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
),
delegate: SliverChildBuilderDelegate(
(context, index) => HomeFeedCard(
drama: _dramas[index],
onTap: () => playDramaFromCatalog(context, _dramas[index]),
drama: dramas[index],
onTap: () => playDramaFromCatalog(context, dramas[index]),
),
childCount: _dramas.length,
),
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 24),
child: PagedListFooter(
loading: _loadingMore,
hasMore: _hasMore,
hasItems: _dramas.isNotEmpty,
errorMessage: _failed ? AppLocalizations.of(context)!.catalogError : null,
onRetry: _loadingMore ? _loadMore : (_hasMore ? _loadMore : _refresh),
childCount: dramas.length,
),
),
),
@@ -204,26 +106,12 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
);
}
String _title(BuildContext context) {
final item = widget.source;
if (item == null) return widget.title;
return item.localizedName(Localizations.localeOf(context).languageCode);
}
String _subtitle(BuildContext context) {
final item = widget.source;
if (item == null) return widget.subtitle;
return item.localizedDescription(
Localizations.localeOf(context).languageCode,
);
}
Widget _heading() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_title(context),
title,
key: const Key('playlist-detail-title'),
style: const TextStyle(
color: AppColors.textPrimary,
@@ -233,7 +121,7 @@ class _PlaylistDetailPageState extends State<PlaylistDetailPage> {
),
const SizedBox(height: 2),
Text(
_subtitle(context),
subtitle,
key: const Key('playlist-detail-subtitle'),
style: const TextStyle(
color: AppColors.textSecondary,
@@ -8,6 +8,8 @@ import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/cover_play_count.dart';
import '../../../core/widgets/drama_cover_badge_ribbon.dart';
import '../../../core/widgets/remote_image.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
final RegExp _tagSplitter = RegExp(r'[,/、·]');
@@ -25,7 +27,7 @@ class RecommendSectionCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final tagLabel = drama.localizedTag(Localizations.localeOf(context).languageCode);
final l10n = AppLocalizations.of(context)!;
return SizedBox(
width: AppDimens.recommendCardWidth,
child: InkWell(
@@ -50,14 +52,14 @@ class RecommendSectionCard extends StatelessWidget {
showFallbackIcon: true,
fallbackColor: AppColors.contentSurface,
),
if (tagLabel.isNotEmpty)
if (isHotDrama(drama))
Positioned(
top: 0,
right: 0,
child: DramaCoverBadgeRibbon(
label: tagLabel,
color: drama.tagRibbonColor(AppColors.badgeHot),
keyPrefix: '$sectionKey-${drama.id}-tag',
label: l10n.homeBadgeHot,
color: AppColors.badgeHot,
keyPrefix: '$sectionKey-${drama.id}-hot',
),
),
const Positioned(
@@ -80,7 +82,7 @@ class RecommendSectionCard extends StatelessWidget {
),
const SizedBox(height: AppDimens.cardCoverTitleGap),
Text(
drama.localizedTitle(Localizations.localeOf(context).languageCode),
drama.title,
key: Key('recommend-title-$sectionKey-${drama.id}'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
@@ -92,15 +94,25 @@ class RecommendSectionCard extends StatelessWidget {
),
),
const SizedBox(height: AppDimens.cardTitleTagGap),
_tags(context),
_tags(),
],
),
),
);
}
Widget _tags(BuildContext context) {
final tags = _cardTags(context);
List<String> _cardTags() {
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(_tagSplitter))
.map((value) => value.trim())
.where((value) => value.isNotEmpty && seen.add(value))
.take(3)
.toList(growable: false);
}
Widget _tags() {
final tags = _cardTags();
if (tags.isEmpty) return const SizedBox.shrink();
return Text(
tags.join(' | '),
@@ -114,16 +126,4 @@ class RecommendSectionCard extends StatelessWidget {
),
);
}
List<String> _cardTags(BuildContext context) {
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
final seen = <String>{};
return [drama.genre, drama.category]
.expand((value) => value.split(_tagSplitter))
.map((value) => value.trim())
.where((value) => value.isNotEmpty && seen.add(value))
.take(3)
.toList(growable: false);
}
}
@@ -4,21 +4,17 @@ import 'package:flutter/material.dart';
import '../../../core/data/models/content_category.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/models/playlist_detail.dart';
import '../../../core/data/services/category_controller.dart';
import '../../../core/data/services/home_feed_controller.dart';
import '../../../core/data/services/playlist_controller.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
import '../../../core/widgets/app_pull_to_refresh.dart';
import '../../../core/widgets/empty_state.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
import 'recommend_section_card.dart';
const List<String> _costumeNames = ['古装', 'costume', 'kostum'];
const int _sectionPreviewCount = 10;
const double _loadMoreThreshold = 200;
enum RecommendSectionKind { hits, newReleases, costume }
@@ -29,51 +25,17 @@ class RecommendSectionsView extends StatelessWidget {
required this.categories,
required this.onOpenDrama,
required this.onMore,
this.playlists,
this.onOpenPlaylist,
});
final HomeFeedController feedController;
final CategoryController categories;
final ValueChanged<Drama> onOpenDrama;
final ValueChanged<RecommendSectionKind> onMore;
final PlaylistController? playlists;
final ValueChanged<PlaylistDetail>? onOpenPlaylist;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final source = feedController.dramas;
final remote = playlists;
return AppPullToRefresh(
key: const Key('recommend-sections-refresh'),
onRefresh: () async {
await Future.wait([
feedController.refreshCurrent(),
categories.load(),
if (remote != null) remote.load(),
]);
},
child: NotificationListener<ScrollNotification>(
onNotification: (notification) =>
remote == null ? false : _onPlaylistScroll(notification, remote),
child: ListView(
key: const Key('recommend-sections-scroll'),
physics: AppPullToRefresh.physics,
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
children: remote == null
? _localSections(context, l10n, source)
: _remoteSections(context, l10n, remote),
),
),
);
}
List<Widget> _localSections(
BuildContext context,
AppLocalizations l10n,
List<Drama> source,
) {
final hits = recommendSectionDramas(
kind: RecommendSectionKind.hits,
source: source,
@@ -82,7 +44,16 @@ class RecommendSectionsView extends StatelessWidget {
kind: RecommendSectionKind.newReleases,
source: source,
);
return [
return AppPullToRefresh(
key: const Key('recommend-sections-refresh'),
onRefresh: () async {
await Future.wait([feedController.refreshCurrent(), categories.load()]);
},
child: ListView(
key: const Key('recommend-sections-scroll'),
physics: AppPullToRefresh.physics,
padding: const EdgeInsets.only(bottom: AppDimens.spaceXl),
children: [
_section(
context,
l10n,
@@ -116,97 +87,9 @@ class RecommendSectionsView extends StatelessWidget {
).take(_sectionPreviewCount).toList(),
onMore: () => onMore(RecommendSectionKind.costume),
),
];
}
List<Widget> _remoteSections(
BuildContext context,
AppLocalizations l10n,
PlaylistController remote,
) {
if (!remote.loaded && remote.loading) {
return const [
SizedBox(
height: 240,
child: Center(
child: CircularProgressIndicator(
key: Key('recommend-playlists-loading'),
),
),
),
];
}
if (remote.items.isEmpty) {
return [
EmptyState(
key: const Key('recommend-playlists-empty'),
icon: Icons.video_library_outlined,
title: remote.error == null ? l10n.emptyContent : l10n.networkError,
actionLabel: l10n.retry,
onAction: remote.load,
),
];
}
final sections = <Widget>[];
for (final playlist in remote.items) {
if (sections.isNotEmpty) {
sections.add(const SizedBox(height: AppDimens.spaceXl));
}
sections.add(
_section(
context,
l10n,
key: playlist.id,
title: playlist.localizedName(
Localizations.localeOf(context).languageCode,
),
subtitle: playlist.localizedDescription(
Localizations.localeOf(context).languageCode,
),
dramas: playlist.dramas.take(_sectionPreviewCount).toList(),
onMore: () => onOpenPlaylist?.call(playlist),
),
);
}
if (remote.loadingMore) {
sections.add(
const Padding(
padding: EdgeInsets.symmetric(vertical: AppDimens.spaceMd),
child: Center(
child: CircularProgressIndicator(
key: Key('recommend-playlists-more'),
),
),
),
);
} else if (!remote.hasMore) {
sections.add(
Padding(
key: const Key('paged-list-no-more'),
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
l10n.noMoreItems,
textAlign: TextAlign.center,
style: const TextStyle(color: AppColors.textHint, fontSize: 12),
),
),
);
}
return sections;
}
bool _onPlaylistScroll(
ScrollNotification notification,
PlaylistController remote,
) {
if (notification.depth != 0) return false;
if (notification.metrics.extentAfter > _loadMoreThreshold) return false;
if (notification is! ScrollUpdateNotification &&
notification is! ScrollEndNotification) {
return false;
}
remote.loadMore();
return false;
],
),
);
}
Widget _section(
@@ -145,8 +145,6 @@ class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
],
PagedListFooter(
loading: controller.loadingMore,
hasMore: controller.hasMore,
hasItems: controller.records.isNotEmpty,
errorMessage: controller.loadMoreError == null
? null
: errorText(l10n, controller.loadMoreError, l10n.progressError),
@@ -52,10 +52,9 @@ class WatchRecordCard extends StatelessWidget {
final episodeLabel = episodeNumber > 0
? l10n.episodeLabel(record.episodeNumber)
: l10n.episodeUnavailable;
final titleText = record.localizedDisplayTitle(
Localizations.localeOf(context).languageCode,
);
final title = titleText.isEmpty ? episodeLabel : titleText;
final title = record.displayTitle.isEmpty
? episodeLabel
: record.displayTitle;
return _card(
onTap: onOpen,
child: Stack(
+1 -1
View File
@@ -63,7 +63,7 @@ void main() {
});
test('should_use_the_configured_local_address_for_device_default', () {
expect(AppConfig.devHostBaseUrl, 'http://192.168.31.243:8081');
expect(AppConfig.devHostBaseUrl, 'http://10.43.47.1:8081');
});
test('should_skip_probe_when_compiled_override_is_set', () async {
@@ -1,128 +0,0 @@
// Author: fruit.com.cn
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/data/models/content_category.dart';
import 'package:fruitshorts/core/data/models/drama.dart';
import 'package:fruitshorts/core/data/models/page_result.dart';
import 'package:fruitshorts/core/data/services/all_dramas_controller.dart';
void main() {
test('should_replace_first_page_when_refresh_succeeds', () async {
final remote = _ScriptedRemote(
pages: [
PageResult(total: 2, list: [_drama('a'), _drama('b')]),
],
);
final controller = AllDramasController(api: remote);
await controller.refresh();
expect(controller.dramas.map((item) => item.id), ['a', 'b']);
expect(controller.hasMore, isFalse);
expect(controller.error, isNull);
expect(remote.pagesRequested, [1]);
});
test('should_append_next_page_when_more_dramas_remain', () async {
final remote = _ScriptedRemote(
pages: [
PageResult(total: 3, list: [_drama('a'), _drama('b')]),
PageResult(total: 3, list: [_drama('c')]),
],
);
final controller = AllDramasController(api: remote);
await controller.refresh();
await controller.loadMore();
expect(controller.dramas.map((item) => item.id), ['a', 'b', 'c']);
expect(controller.hasMore, isFalse);
expect(remote.pagesRequested, [1, 2]);
});
test('should_keep_loaded_dramas_when_next_page_fails', () async {
final remote = _ScriptedRemote(
pages: [PageResult(total: 3, list: [_drama('a')])],
failOnPage: 2,
);
final controller = AllDramasController(api: remote);
await controller.refresh();
await controller.loadMore();
expect(controller.dramas.map((item) => item.id), ['a']);
expect(controller.error, isNotNull);
});
test('should_clear_selected_type_when_all_is_chosen', () {
final controller = AllDramasController.preview(
categories: const [ContentCategory(id: '2', name: '甜宠')],
);
controller.toggleCategory('2');
controller.toggleCategory('');
expect(controller.selectedCategories, isEmpty);
});
test('should_send_selected_ids_when_loading_a_page', () async {
final remote = _ScriptedRemote(
pages: [PageResult(total: 0, list: const [])],
);
final controller = AllDramasController(api: remote);
controller.toggleCategory('2');
controller.toggleClassification('3');
controller.toggleTag('4');
await controller.refresh();
expect(remote.lastCategoryIds, ['2']);
expect(remote.lastClassificationIds, ['3']);
expect(remote.lastTagIds, ['4']);
});
}
Drama _drama(String id) {
return Drama(id: id, title: id, synopsis: '', posterUrl: '');
}
class _ScriptedRemote implements AllDramasRemote {
_ScriptedRemote({required this.pages, this.failOnPage});
final List<PageResult<Drama>> pages;
final int? failOnPage;
final List<int> pagesRequested = [];
List<String> lastCategoryIds = const [];
List<String> lastClassificationIds = const [];
List<String> lastTagIds = const [];
@override
Future<List<ContentCategory>> classifications() async => const [
ContentCategory(id: '3', name: '精选'),
];
@override
Future<List<ContentCategory>> categories() async => const [
ContentCategory(id: '2', name: '甜宠'),
];
@override
Future<List<ContentCategory>> tags() async => const [
ContentCategory(id: '4', name: '热剧'),
];
@override
Future<PageResult<Drama>> dramas({
required List<String> categoryIds,
required List<String> classificationIds,
required List<String> tagIds,
required int pageIndex,
}) async {
lastCategoryIds = categoryIds;
lastClassificationIds = classificationIds;
lastTagIds = tagIds;
pagesRequested.add(pageIndex);
if (pageIndex == failOnPage) throw StateError('page failed');
return pages[pageIndex - 1];
}
}
-65
View File
@@ -1,65 +0,0 @@
// Author: fruit.com.cn
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/data/models/page_result.dart';
import 'package:fruitshorts/core/data/models/playlist_detail.dart';
import 'package:fruitshorts/core/data/repositories/playlist_repository.dart';
import 'package:fruitshorts/core/data/services/playlist_controller.dart';
void main() {
test('should_append_the_next_page_when_more_playlists_remain', () async {
final repository = _PagedPlaylists(total: 12);
final controller = PlaylistController(repository);
await controller.load();
expect(controller.items, hasLength(PlaylistController.pageSize));
expect(controller.hasMore, isTrue);
await controller.loadMore();
expect(controller.items, hasLength(12));
expect(controller.items.last.id, '11');
expect(controller.hasMore, isFalse);
controller.dispose();
});
}
class _PagedPlaylists implements PlaylistRepository {
_PagedPlaylists({required this.total});
final int total;
@override
Future<PageResult<PlaylistDetail>> fetchPlaylists({
int pageIndex = 1,
int pageSize = 10,
}) async {
final start = (pageIndex - 1) * pageSize;
if (start >= total) {
return PageResult(total: total);
}
final end = start + pageSize > total ? total : start + pageSize;
return PageResult(
total: total,
list: [
for (var index = start; index < end; index++)
PlaylistDetail(
id: '$index',
name: '剧单$index',
description: '',
dramaCount: 0,
dramas: const [],
),
],
);
}
@override
Future<PlaylistDetail> fetchPlaylist(
String id, {
int pageIndex = 1,
int pageSize = 20,
}) {
throw UnimplementedError();
}
}
-42
View File
@@ -1,42 +0,0 @@
// Author: fruit.com.cn
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/data/models/playlist_detail.dart';
void main() {
test('should_parse_playlist_cards_when_detail_json_arrives', () {
final playlist = PlaylistDetail.fromJson({
'id': '2112807182243336196',
'name': '本周必看',
'locales': {'zh': '本周必看', 'en': 'Weekly Hits', 'id': 'Hits Mingguan'},
'description': '编辑精选',
'descriptionLocales': {
'zh': '编辑精选',
'en': 'Editor picks',
'id': 'Pilihan editor',
},
'dramaCount': 1,
'list': [
{
'id': '5',
'title': '命运的相遇',
'cover': '/files/cover.jpg',
'synopsis': '一次意外',
'totalEpisodes': 12,
'viewCount': '20',
},
],
});
expect(playlist.id, '2112807182243336196');
expect(playlist.name, '本周必看');
expect(playlist.description, '编辑精选');
expect(playlist.localizedName('en'), 'Weekly Hits');
expect(playlist.localizedDescription('id'), 'Pilihan editor');
expect(playlist.localizedName('zh'), '本周必看');
expect(playlist.dramaCount, 1);
expect(playlist.dramas.single.title, '命运的相遇');
expect(playlist.dramas.single.posterUrl, '/files/cover.jpg');
expect(playlist.dramas.single.totalEpisodes, 12);
});
}
@@ -14,7 +14,6 @@ import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart
import 'package:fruitshorts/core/theme/app_colors.dart';
import 'package:fruitshorts/core/widgets/app_pull_to_refresh.dart';
import 'package:fruitshorts/pages/discover/discover_view.dart';
import 'package:fruitshorts/pages/discover/widgets/discover_category_tab.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
+24 -18
View File
@@ -21,8 +21,6 @@ void main() {
title: 'A very long home grid drama title that must wrap',
dramaType: 'ANIME',
viewCount: 444500,
tag: '漫剧',
tagLocales: const {'zh': '漫剧', 'en': 'Anime', 'id': 'Anime'},
),
onTap: () => taps++,
);
@@ -54,7 +52,7 @@ void main() {
BorderRadius.circular(AppDimens.cardCoverRadius),
);
final badge = find.byKey(
const Key('drama-cover-badge-ribbon-anime-card-tag'),
const Key('drama-cover-badge-ribbon-anime-card-anime'),
);
expect(badge, findsOneWidget);
expect(
@@ -122,7 +120,10 @@ void main() {
expect(taps, 1);
});
testWidgets('should_show_cover_badge_from_tag_locale', (tester) async {
testWidgets('should_choose_anime_new_and_hot_badges_from_real_data', (
tester,
) async {
final now = DateTime(2026, 10, 22, 12);
await tester.pumpWidget(
MaterialApp(
theme: AppTheme.dark(),
@@ -133,18 +134,18 @@ void main() {
body: Row(
children: [
for (final drama in [
_drama(id: 'anime', title: 'Anime', dramaType: 'ANIME'),
_drama(
id: 'tagged',
title: 'Tagged',
tag: '新剧',
tagLocales: const {'zh': '新剧', 'en': 'New', 'id': 'Baru'},
id: 'new',
title: 'New',
createdAt: now.subtract(const Duration(days: 2)),
),
_drama(id: 'plain', title: 'Plain'),
_drama(id: 'hot', title: 'Hot', isHot: true),
])
SizedBox(
width: 130,
height: 240,
child: HomeFeedCard(drama: drama, onTap: () {}),
child: HomeFeedCard(drama: drama, onTap: () {}, now: now),
),
],
),
@@ -153,10 +154,18 @@ void main() {
);
await tester.pumpAndSettle();
final badge = find.byKey(const Key('drama-cover-badge-ribbon-tagged-tag'));
expect(badge, findsOneWidget);
expect(find.text('New'), findsOneWidget);
expect(find.byKey(const Key('drama-cover-badge-ribbon-plain-tag')), findsNothing);
expect(
find.byKey(const Key('drama-cover-badge-ribbon-anime-anime')),
findsOneWidget,
);
expect(
find.byKey(const Key('drama-cover-badge-ribbon-new-newRelease')),
findsOneWidget,
);
expect(
find.byKey(const Key('drama-cover-badge-ribbon-hot-hot')),
findsOneWidget,
);
});
}
@@ -167,8 +176,6 @@ Drama _drama({
int viewCount = 0,
bool isHot = false,
DateTime? createdAt,
String tag = '',
Map<String, String> tagLocales = const {},
}) {
return Drama(
id: id,
@@ -181,8 +188,6 @@ Drama _drama({
isHot: isHot,
dramaType: dramaType,
createdAt: createdAt,
tag: tag,
tagLocales: tagLocales,
);
}
@@ -205,6 +210,7 @@ Future<void> _pumpCard(
child: HomeFeedCard(
drama: drama,
onTap: onTap,
now: DateTime(2026, 10, 22, 12),
),
),
),
+36 -14
View File
@@ -45,24 +45,24 @@ void main() {
await _pumpApp(tester, repository);
final sectionKeys = [
const Key('home-section-featured'),
const Key('home-section-new'),
const Key('home-section-categories'),
const Key('home-section-ranking'),
const Key('home-section-category-古装'),
const Key('home-section-category-社群'),
const Key('home-section-category-爽剧'),
const Key('home-section-category-甜宠'),
const Key('home-section-category-打脸虐渣'),
const Key('home-section-category-虐恋'),
];
final sectionCenters = sectionKeys
.map((key) => tester.getCenter(find.byKey(key)).dx)
.toList();
expect(sectionCenters, orderedEquals(sectionCenters.toList()..sort()));
expect(find.byKey(const Key('home-secondary-tags')), findsNothing);
expect(find.text('Featured'), findsNothing);
expect(find.text('New'), findsNothing);
expect(find.text('Categories'), findsNothing);
expect(find.text('Charts'), findsNothing);
expect(find.text('古装'), findsOneWidget);
expect(find.text('社群'), findsOneWidget);
expect(find.text('Featured'), findsOneWidget);
expect(find.text('New'), findsOneWidget);
expect(find.text('Categories'), findsOneWidget);
expect(find.text('Charts'), findsOneWidget);
expect(find.text('Costume'), findsOneWidget);
expect(find.text('Community'), findsOneWidget);
expect(find.byKey(const Key('mine-mini-player')), findsNothing);
expect(find.byType(FloatingActionButton), findsNothing);
});
@@ -94,9 +94,31 @@ void main() {
}
expect(find.byKey(const Key('home-grid')), findsOneWidget);
expect(find.byKey(const Key('home-section-featured')), findsNothing);
expect(firstDramaId(), 'page1-0');
await tester.tap(find.byKey(const Key('home-section-new')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('new-releases-page')), findsNothing);
expect(find.byKey(const Key('home-secondary-tags')), findsNothing);
expect(firstDramaId(), 'page1-9');
await tester.tap(find.byKey(const Key('home-section-ranking')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('ranking-page')), findsOneWidget);
expect(find.byKey(const Key('ranking-hero')), findsOneWidget);
expect(find.byKey(const Key('home-grid-cards')), findsNothing);
final home = tester.widget<DecoratedBox>(find.byKey(const Key('home-grid')));
expect(
(home.decoration as BoxDecoration).gradient,
AppTheme.pageGradient,
);
await tester.tap(find.byKey(const Key('home-section-categories')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('filter-page')), findsNothing);
expect(find.byKey(const Key('home-secondary-tags')), findsNothing);
expect(find.byKey(const Key('home-grid-cards')), findsOneWidget);
await tester.tap(find.byKey(const Key('home-section-category-古装')));
await tester.pumpAndSettle();
expect(firstDramaId(), 'page1-0');
@@ -127,9 +149,9 @@ void main() {
final before = tester.state<ScrollableState>(scrollable).position.pixels;
expect(before, greaterThan(0));
await tester.tap(find.byKey(const Key('home-section-category-社群')));
await tester.tap(find.byKey(const Key('home-section-new')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('home-section-category-古装')));
await tester.tap(find.byKey(const Key('home-section-featured')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('home-secondary-tags')), findsNothing);
@@ -158,7 +180,7 @@ void main() {
expect(find.byKey(const Key('home-secondary-tags')), findsNothing);
final selected = tester.widget<AnimatedDefaultTextStyle>(
find.byKey(const Key('home-primary-label-community')),
find.byKey(const Key('home-primary-label-newReleases')),
);
expect(selected.style.fontSize, AppDimens.homePrimaryTabSelectedFont);
expect(selected.style.fontWeight, FontWeight.w700);
+11 -8
View File
@@ -87,7 +87,10 @@ void main() {
expect(delegate.crossAxisCount, 3);
expect(delegate.crossAxisSpacing, AppDimens.homeGridGap);
expect(delegate.mainAxisSpacing, AppDimens.homeGridRowGap);
expect(find.byKey(const Key('home-section-featured')), findsNothing);
expect(find.byKey(const Key('home-section-featured')), findsOneWidget);
expect(find.byKey(const Key('home-section-new')), findsOneWidget);
expect(find.byKey(const Key('home-section-categories')), findsOneWidget);
expect(find.byKey(const Key('home-section-ranking')), findsOneWidget);
expect(find.byKey(const Key('home-section-category-古装')), findsOneWidget);
expect(find.byKey(const Key('home-section-category-社群')), findsOneWidget);
expect(find.byKey(const Key('home-secondary-tags')), findsNothing);
@@ -108,10 +111,10 @@ void main() {
expect(placeholder.style?.fontSize, AppDimens.searchPlaceholderFont);
expect(placeholder.style?.color, AppColors.textSecondary);
final selectedPrimary = tester.widget<AnimatedDefaultTextStyle>(
find.byKey(const Key('home-primary-label-costume')),
find.byKey(const Key('home-primary-label-featured')),
);
final unselectedPrimary = tester.widget<AnimatedDefaultTextStyle>(
find.byKey(const Key('home-primary-label-community')),
find.byKey(const Key('home-primary-label-newReleases')),
);
expect(
selectedPrimary.style.fontSize,
@@ -125,19 +128,19 @@ void main() {
expect(unselectedPrimary.style.color, AppColors.textTabInactive);
expect(
find.descendant(
of: find.byKey(const Key('home-section-category-古装')),
of: find.byKey(const Key('home-section-featured')),
matching: find.byType(Container),
),
findsNothing,
);
final primaryStart = tester.getTopLeft(find.text('古装'));
final primaryStart = tester.getTopLeft(find.text('Featured'));
final pageStart = tester.getTopLeft(searchBox);
expect(primaryStart.dx, pageStart.dx);
final primaryGap =
tester.getTopLeft(find.text('社群')).dx -
tester.getBottomRight(find.text('古装')).dx;
tester.getTopLeft(find.text('New')).dx -
tester.getBottomRight(find.text('Featured')).dx;
expect(primaryGap, closeTo(AppDimens.homePrimaryCategoryGap, 0.1));
expect(find.byKey(const Key('home-primary-page-view')), findsOneWidget);
expect(find.byType(PageView), findsNothing);
expect(tester.takeException(), isNull);
});
+1 -1
View File
@@ -108,7 +108,7 @@ void main() {
await tester.tap(find.byKey(const Key('recommend-tab-all')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('all-dramas-grid')), findsOneWidget);
for (var row = 0; row < 3; row++) {
for (var row = 0; row < 4; row++) {
expect(find.byKey(Key('all-filter-row-$row')), findsOneWidget);
}
_expectNoFloatingOverlays();
@@ -1,54 +0,0 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/platform/wireless_data_prompt.dart';
void main() {
setUp(WirelessDataPrompt.resetForTest);
tearDown(WirelessDataPrompt.resetForTest);
test('should_return_immediately_when_disabled', () async {
var calls = 0;
await WirelessDataPrompt.awaitDecision(
enabled: false,
ask: () async {
calls++;
},
);
expect(calls, 0);
});
test('should_ask_once_when_enabled', () async {
var calls = 0;
Future<void> ask() async {
calls++;
}
await WirelessDataPrompt.awaitDecision(enabled: true, ask: ask);
await WirelessDataPrompt.awaitDecision(enabled: true, ask: ask);
expect(calls, 1);
});
test('should_continue_when_decision_times_out', () async {
await WirelessDataPrompt.awaitDecision(
enabled: true,
ask: () => Completer<void>().future,
timeout: const Duration(milliseconds: 20),
);
});
test('should_continue_when_ask_fails', () async {
await WirelessDataPrompt.awaitDecision(
enabled: true,
ask: () async {
throw StateError('channel missing');
},
);
});
}
+4 -47
View File
@@ -91,63 +91,20 @@ void main() {
expect(session.preloadedIndex, 1);
final loadingStates = <bool>[];
session.addListener(() => loadingStates.add(session.loading));
await session.select(1, preloadIndex: 2, previousIndex: 0);
await session.select(1, preloadIndex: 2);
await session.preloadSettled;
expect(session.active, same(warm));
expect(warm.initializeCalls, 1);
expect(warm.playCalls, 1);
expect(loadingStates, isNot(contains(true)));
expect(activated, ['ep-0', 'ep-1']);
expect(session.preparedPlayerAt(0), isNotNull);
expect(session.preparedPlayerAt(2), isNotNull);
expect(factory.peakLive, lessThanOrEqualTo(3));
expect(factory.peakLive, 2);
expect(factory.peakPlaying, 1);
await session.close();
expect(factory.live, 0);
},
);
test('should_prepare_previous_neighbor_when_selected', () async {
final factory = _Factory();
final session = PlaybackSession(
episodes: episodes,
factory: factory.create,
canPlay: (_) => true,
);
await session.select(1, preloadIndex: 2, previousIndex: 0);
await session.preloadSettled;
expect(session.preparedPlayerAt(0), isNotNull);
expect(session.preparedPlayerAt(2), isNotNull);
expect(factory.players.map((player) => player.id).toSet(), {
'ep-0',
'ep-1',
'ep-2',
});
expect(factory.peakLive, 3);
await session.close();
});
test('should_warm_previous_without_waiting_for_slow_next', () async {
final nextGate = Completer<void>();
final factory = _Factory(gates: {'ep-2': nextGate});
final session = PlaybackSession(
episodes: episodes,
factory: factory.create,
canPlay: (_) => true,
);
await session.select(1, preloadIndex: 2, previousIndex: 0);
await _tick();
expect(session.preparedPlayerAt(0), isNotNull);
expect(session.preparedPlayerAt(2), isNull);
nextGate.complete();
await session.preloadSettled;
expect(session.preparedPlayerAt(2), isNotNull);
await session.close();
});
test('should_reuse_in_flight_preload_when_swiped_before_ready', () async {
final gate = Completer<void>();
final factory = _Factory(gates: {'ep-1': gate});
@@ -167,7 +124,7 @@ void main() {
await session.preloadSettled;
expect(session.active, same(warm));
expect(warm.initializeCalls, 1);
expect(factory.peakLive, lessThanOrEqualTo(3));
expect(factory.peakLive, lessThanOrEqualTo(2));
expect(factory.peakPlaying, 1);
await session.close();
});
@@ -192,7 +149,7 @@ void main() {
expect(session.preloadedIndex, 2);
expect(stale.playCalls, 0);
expect(stale.disposed, isTrue);
expect(factory.peakLive, lessThanOrEqualTo(3));
expect(factory.peakLive, lessThanOrEqualTo(2));
expect(factory.peakPlaying, 1);
await session.close();
});
+2 -3
View File
@@ -594,9 +594,8 @@ void main() {
await _drain(logic);
expect(logic.session.currentIndex, 2);
// 最后一集没有下一集,但仍会预热上一集。
expect(factory.created, hasLength(2));
expect(logic.session.preparedPlayerAt(1), isNotNull);
// The last episode has no successor to warm.
expect(factory.created, hasLength(1));
logic.dispose();
await _drain(logic);
@@ -1,95 +0,0 @@
// Author: fruit.com.cn
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/data/services/sprite_thumbnail_asset_loader.dart';
import 'package:fruitshorts/pages/player/widgets/player_opening_frame.dart';
const String _spriteVtt = '''
WEBVTT
00:00:00.000 --> 00:00:01.000
sprite_001.jpg#xywh=0,0,160,90
''';
void main() {
test('should_return_no_opening_frame_when_thumbnails_url_is_empty', () {
expect(playerOpeningFrame(null), isNull);
expect(playerOpeningFrame(' '), isNull);
});
testWidgets('should_load_and_reuse_first_sprite_frame', (tester) async {
final loader = _FakeSpriteLoader();
final cache = OpeningFrameCache();
addTearDown(cache.clear);
final first = await cache.load(
'https://cdn.test/thumbnails.vtt',
loader: loader,
);
final second = await cache.load(
'https://cdn.test/thumbnails.vtt',
loader: loader,
);
expect(first, isNotNull);
expect(second, same(first));
expect(loader.vttCalls, 1);
expect(loader.spriteCalls, ['sprite_001.jpg']);
});
testWidgets('should_render_decoded_opening_frame', (tester) async {
final loader = _FakeSpriteLoader();
final cache = OpeningFrameCache();
addTearDown(cache.clear);
await tester.pumpWidget(
MaterialApp(
home: PlayerOpeningFrame(
thumbnailsUrl: 'https://cdn.test/thumbnails.vtt',
loader: loader,
cache: cache,
),
),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('player-opening-sprite')), findsOneWidget);
});
}
class _FakeSpriteLoader implements SpriteThumbnailAssetLoader {
int vttCalls = 0;
final List<String> spriteCalls = [];
@override
Future<String?> loadVtt(Uri uri) async {
vttCalls++;
return _spriteVtt;
}
@override
Future<SpriteThumbnailDecodedImage?> loadSprite(Uri uri) async {
spriteCalls.add(uri.pathSegments.last);
return SpriteThumbnailDecodedImage(
image: await _createImage(320, 180),
originalWidth: 320,
originalHeight: 180,
);
}
}
Future<ui.Image> _createImage(int width, int height) async {
final recorder = ui.PictureRecorder();
final canvas = Canvas(recorder);
canvas.drawRect(
Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
Paint()..color = Colors.blue,
);
final picture = recorder.endRecording();
final image = await picture.toImage(width, height);
picture.dispose();
return image;
}
+9 -39
View File
@@ -13,48 +13,16 @@ void main() {
await _pumpSurface(tester);
expect(_fallbackColor(tester), Colors.black);
expect(find.byKey(const Key('player-opening-frame')), findsNothing);
expect(find.byKey(const Key('player-fallback-cover')), findsNothing);
expect(find.byKey(const Key('player-fallback-scrim')), findsNothing);
expect(_opacity(tester), 0);
});
testWidgets('should_show_opening_frame_before_decode_is_ready', (
tester,
) async {
await _pumpSurface(
tester,
openingFrame: const ColoredBox(
key: Key('fake-opening'),
color: Colors.red,
),
);
expect(find.byKey(const Key('player-opening-frame')), findsOneWidget);
expect(find.byKey(const Key('fake-opening')), findsOneWidget);
expect(_opacity(tester), 0);
});
testWidgets('should_reveal_paused_frame_when_initialized', (tester) async {
final controller = await _pumpSurface(tester);
controller.value = const VideoPlayerValue(
duration: Duration(minutes: 1),
size: Size(1280, 720),
position: Duration.zero,
isInitialized: true,
isPlaying: false,
);
await tester.pump();
expect(_opacity(tester), 1);
expect(find.byKey(const Key('player-opening-frame')), findsNothing);
expect(find.byKey(const Key('player-debug-video')), findsNothing);
});
testWidgets('should_fade_video_in_within_200ms_after_first_frame', (
tester,
) async {
final controller = await _pumpSurface(
tester,
openingFrame: const ColoredBox(color: Colors.red),
);
final controller = await _pumpSurface(tester);
expect(_opacity(tester), 0);
controller.value = const VideoPlayerValue(
@@ -67,7 +35,6 @@ void main() {
await tester.pump();
expect(_opacity(tester), 1);
expect(find.byKey(const Key('player-opening-frame')), findsNothing);
expect(
tester
.widget<AnimatedOpacity>(
@@ -82,6 +49,9 @@ void main() {
expect(halfway, lessThan(1));
await tester.pump(const Duration(milliseconds: 100));
expect(_fadeValue(tester), 1);
expect(_fallbackColor(tester), Colors.black);
expect(find.byKey(const Key('player-fallback-cover')), findsNothing);
expect(find.byKey(const Key('player-debug-video')), findsNothing);
});
testWidgets('should_show_video_error_above_retained_fallback', (
@@ -95,7 +65,9 @@ void main() {
expect(find.byKey(const Key('player-video-error')), findsOneWidget);
expect(find.text('No route to host'), findsOneWidget);
expect(_fallbackColor(tester), Colors.black);
expect(find.byKey(const Key('player-fallback-cover')), findsNothing);
expect(_opacity(tester), 0);
expect(find.byKey(const Key('player-debug-video')), findsNothing);
});
testWidgets('should_cover_new_video_only_while_handoff_is_held', (
@@ -147,7 +119,6 @@ void main() {
Future<VideoPlayerController> _pumpSurface(
WidgetTester tester, {
VideoPlayerValue? value,
Widget? openingFrame,
}) async {
final controller = VideoPlayerController.networkUrl(
Uri.parse('http://192.168.31.187:8081/files/video.mp4'),
@@ -161,7 +132,6 @@ Future<VideoPlayerController> _pumpSurface(
controller: controller,
videoUrl: controller.dataSource,
theater: false,
openingFrame: openingFrame,
),
),
),
@@ -2,8 +2,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:fruitshorts/core/data/models/content_category.dart';
import 'package:fruitshorts/core/data/services/all_dramas_controller.dart';
import 'package:fruitshorts/core/data/services/home_feed_controller.dart';
import 'package:fruitshorts/core/theme/app_dimens.dart';
import 'package:fruitshorts/l10n/app_localizations.dart';
import 'package:fruitshorts/pages/recommend/widgets/all_dramas_filter_grid.dart';
@@ -13,21 +12,9 @@ import '../support/fake_catalog.dart';
void main() {
testWidgets('all filter rows start at the same left edge', (tester) async {
final catalog = FakeCatalogRepository();
final controller = AllDramasController.preview(
classifications: const [
ContentCategory(id: 'local', name: 'Local'),
ContentCategory(id: 'asia', name: 'Asia'),
],
categories: const [
ContentCategory(id: 'subtitles', name: 'Subtitles'),
ContentCategory(id: 'dubbed', name: 'Dubbed'),
],
tags: const [
ContentCategory(id: 'reversal', name: 'Reversal'),
ContentCategory(id: 'uplifting', name: 'Uplifting'),
],
dramas: catalog.dramas,
);
final controller = HomeFeedController(catalog)
..seedRecommend(catalog.dramas);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
@@ -36,7 +23,7 @@ void main() {
localizationsDelegates: AppLocalizations.localizationsDelegates,
home: Scaffold(
body: AllDramasFilterGrid(
controller: controller,
feedController: controller,
onOpenDrama: (_) {},
),
),
@@ -46,9 +33,19 @@ void main() {
expect(AppDimens.allDramasHorizontal, 12);
final firstChips = [
find.byKey(const Key('all-filter-classification-all')),
find.byKey(const Key('all-filter-category-all')),
find.byKey(const Key('all-filter-tag-all')),
find.descendant(
of: find.byKey(const Key('all-filter-row-0')),
matching: find.byKey(const Key('all-filter-all')),
),
find.descendant(
of: find.byKey(const Key('all-filter-row-1')),
matching: find.byKey(const Key('all-filter-all')),
),
find.descendant(
of: find.byKey(const Key('all-filter-row-2')),
matching: find.byKey(const Key('all-filter-all')),
),
find.byKey(const Key('all-sort-hot')),
];
final starts = firstChips
.map((finder) => tester.getTopLeft(finder).dx)
@@ -60,9 +57,9 @@ void main() {
}
final rowZeroChips = [
find.byKey(const Key('all-filter-classification-all')),
find.byKey(const Key('all-filter-classification-local')),
find.byKey(const Key('all-filter-classification-asia')),
find.byKey(const Key('all-filter-all')).first,
find.byKey(const Key('all-filter-local')),
find.byKey(const Key('all-filter-asia')),
];
final rowZeroRects = rowZeroChips.map(tester.getRect).toList();
final rowZeroGaps = [
@@ -72,9 +69,12 @@ void main() {
expect(rowZeroGaps[0], closeTo(10, 0.5));
expect(rowZeroGaps[1], closeTo(rowZeroGaps[0], 0.5));
final rowOneAll = find.byKey(const Key('all-filter-category-all'));
final rowOneSubtitles = find.byKey(const Key('all-filter-category-subtitles'));
final rowOneDubbed = find.byKey(const Key('all-filter-category-dubbed'));
final rowOneAll = find.descendant(
of: find.byKey(const Key('all-filter-row-1')),
matching: find.byKey(const Key('all-filter-all')),
);
final rowOneSubtitles = find.byKey(const Key('all-filter-subtitles'));
final rowOneDubbed = find.byKey(const Key('all-filter-dubbed'));
final rowOneGap =
tester.getTopLeft(rowOneSubtitles).dx -
tester.getTopRight(rowOneAll).dx;
@@ -85,9 +85,12 @@ void main() {
closeTo(rowOneGap, 0.5),
);
final rowTwoAll = find.byKey(const Key('all-filter-tag-all'));
final rowTwoReversal = find.byKey(const Key('all-filter-tag-reversal'));
final rowTwoUplifting = find.byKey(const Key('all-filter-tag-uplifting'));
final rowTwoAll = find.descendant(
of: find.byKey(const Key('all-filter-row-2')),
matching: find.byKey(const Key('all-filter-all')),
);
final rowTwoReversal = find.byKey(const Key('all-filter-reversal'));
final rowTwoUplifting = find.byKey(const Key('all-filter-uplifting'));
final rowTwoGap =
tester.getTopLeft(rowTwoReversal).dx - tester.getTopRight(rowTwoAll).dx;
expect(rowTwoGap, closeTo(10, 0.5));
@@ -96,5 +99,11 @@ void main() {
tester.getTopRight(rowTwoReversal).dx,
closeTo(rowTwoGap, 0.5),
);
expect(
tester.getTopLeft(find.byKey(const Key('all-sort-new'))).dx -
tester.getTopRight(find.byKey(const Key('all-sort-hot'))).dx,
closeTo(10, 0.5),
);
});
}
+130 -29
View File
@@ -34,7 +34,7 @@ void main() {
expect(find.byKey(const Key('recommend-tab-recommend')), findsOneWidget);
expect(find.byKey(const Key('recommend-tab-playlist')), findsOneWidget);
expect(find.byKey(const Key('recommend-tab-all')), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player'), skipOffstage: false), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player')), findsOneWidget);
expect(find.byKey(const Key('recommend-top-gradient')), findsOneWidget);
final recommendText = tester.widget<Text>(
find.descendant(
@@ -81,12 +81,12 @@ void main() {
tester
.getRect(find.byKey(const Key('recommend-top-nav')))
.overlaps(
tester.getRect(find.byKey(const Key('recommend-feed-player'), skipOffstage: false)),
tester.getRect(find.byKey(const Key('recommend-feed-player'))),
),
isTrue,
);
final player = tester.widget<PlayerPage>(
find.byKey(const Key('recommend-feed-player'), skipOffstage: false),
find.byKey(const Key('recommend-feed-player')),
);
expect(player.homeMode, isTrue);
expect(player.embedded, isTrue);
@@ -227,9 +227,15 @@ void main() {
);
expect(viewIcon, findsOneWidget);
final badge = find.byKey(
const Key('drama-cover-badge-ribbon-hits-the-signal-demo-tag'),
const Key('drama-cover-badge-ribbon-hits-the-signal-demo-hot'),
);
expect(badge, findsNothing);
expect(badge, findsOneWidget);
final badgeText = tester.widget<Text>(
find.descendant(of: badge, matching: find.byType(Text)),
);
expect(badgeText.data, 'Hit');
expect(badgeText.style?.fontSize, AppDimens.cardBadgeFont);
expect(badgeText.style?.color, AppColors.textPrimary);
final tagsFinder = find.byKey(
const Key('recommend-tags-hits-the-signal-demo'),
);
@@ -303,7 +309,7 @@ void main() {
expect(delegate.crossAxisCount, 3);
expect(delegate.crossAxisSpacing, AppDimens.allDramasGridGap);
expect(delegate.mainAxisSpacing, AppDimens.allDramasGridRowGap);
for (var row = 0; row < 3; row++) {
for (var row = 0; row < 4; row++) {
expect(find.byKey(Key('all-filter-row-$row')), findsOneWidget);
final scroll = tester.widget<SingleChildScrollView>(
find.byKey(Key('all-filter-scroll-$row')),
@@ -312,7 +318,7 @@ void main() {
expect(scroll.physics, isA<BouncingScrollPhysics>());
}
final filterStarts = [
for (var row = 0; row < 3; row++)
for (var row = 0; row < 4; row++)
tester.getRect(find.byKey(Key('all-filter-row-$row'))).left,
];
expect(
@@ -320,7 +326,7 @@ void main() {
everyElement(closeTo(AppDimens.allDramasHorizontal, 0.1)),
);
final pageRect = tester.getRect(find.byKey(const Key('recommend-page')));
for (var row = 0; row < 3; row++) {
for (var row = 0; row < 4; row++) {
final rowRect = tester.getRect(find.byKey(Key('all-filter-row-$row')));
expect(
rowRect.left,
@@ -341,6 +347,10 @@ void main() {
of: find.byKey(const Key('all-filter-row-2')),
matching: find.byType(Text),
),
find.descendant(
of: find.byKey(const Key('all-filter-row-3')),
matching: find.byType(Text),
),
];
final firstTextX = firstTexts
.map((finder) => tester.getTopLeft(finder.first).dx)
@@ -355,14 +365,14 @@ void main() {
0.1,
),
);
for (var row = 0; row < 2; row++) {
for (var row = 0; row < 3; row++) {
expect(
tester.getSize(find.byKey(Key('all-filter-row-$row'))).height,
AppDimens.filterChipHeight + AppDimens.filterRowGap,
);
}
expect(
tester.getSize(find.byKey(const Key('all-filter-row-2'))).height,
tester.getSize(find.byKey(const Key('all-filter-row-3'))).height,
AppDimens.filterChipHeight,
);
expect(
@@ -396,31 +406,112 @@ void main() {
tester.getRect(find.byKey(const Key('all-dramas-filters'))).top,
closeTo(fixedFilterTop, 0.1),
);
expect(find.byKey(const Key('all-filter-classification-all')), findsOneWidget);
expect(find.byKey(const Key('all-filter-category-all')), findsOneWidget);
expect(find.byKey(const Key('all-filter-tag-all')), findsOneWidget);
expect(find.byKey(const Key('all-filter-local')), findsOneWidget);
expect(_textStyle(tester, 'Local').color, AppColors.filterChipTextInactive);
expect(find.byKey(const Key('all-filter-subtitles')), findsOneWidget);
for (final key in [
'all-filter-reversal',
'all-filter-uplifting',
'all-filter-modern',
'all-filter-sweet',
'all-filter-angst',
]) {
expect(find.byKey(Key(key)), findsOneWidget);
}
final rowZero = find.byKey(const Key('all-filter-row-0'));
final rowZeroAll = find.descendant(
of: rowZero,
matching: find.byKey(const Key('all-filter-all')),
);
final rowZeroLocal = find.descendant(
of: rowZero,
matching: find.byKey(const Key('all-filter-local')),
);
expect(
tester
.widget<Text>(
find.descendant(
of: find.byKey(const Key('all-filter-classification-all')),
matching: find.text('All'),
),
tester.getTopLeft(rowZeroAll).dx,
closeTo(pageRect.left + AppDimens.allDramasHorizontal, 0.1),
);
expect(
tester.getTopLeft(rowZeroLocal).dx - tester.getTopRight(rowZeroAll).dx,
AppDimens.filterItemGap,
);
final rowOne = find.byKey(const Key('all-filter-row-1'));
final rowTwo = find.byKey(const Key('all-filter-row-2'));
for (final row in [rowOne, rowTwo]) {
final all = find.descendant(
of: row,
matching: find.byKey(const Key('all-filter-all')),
);
final next = find.descendant(
of: row,
matching: row == rowOne
? find.byKey(const Key('all-filter-subtitles'))
: find.byKey(const Key('all-filter-reversal')),
);
expect(
tester.getTopLeft(next).dx - tester.getTopRight(all).dx,
AppDimens.filterItemGap,
);
}
expect(
tester.getTopLeft(find.byKey(const Key('all-sort-new'))).dx -
tester.getTopRight(find.byKey(const Key('all-sort-hot'))).dx,
AppDimens.filterItemGap,
);
await tester.tap(find.byKey(const Key('all-filter-local')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('all-dramas-empty')), findsOneWidget);
expect(_textStyle(tester, 'Local').fontWeight, FontWeight.w600);
expect(_textStyle(tester, 'Local').fontSize, AppDimens.filterChipFont);
expect(_textStyle(tester, 'Local').color, AppColors.filterChipTextSelected);
final selectedChip = tester.widget<Container>(
find
.descendant(
of: find.byKey(const Key('all-filter-local')),
matching: find.byType(Container),
)
.style
?.color,
AppColors.filterChipTextSelected,
.first,
);
expect(
(selectedChip.decoration! as BoxDecoration).color,
AppColors.filterChipSelected,
);
expect(
tester.getSize(find.byKey(const Key('all-filter-local'))).height,
AppDimens.filterChipHeight,
);
await tester.tap(find.byKey(const Key('all-filter-all')).first);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('all-sort-new')));
await tester.pump();
expect(_textStyle(tester, 'New').fontWeight, FontWeight.w600);
expect(_textStyle(tester, 'New').fontSize, AppDimens.filterChipFont);
expect(_textStyle(tester, 'New').color, AppColors.filterChipTextSelected);
expect(
tester.getSize(find.byKey(const Key('all-sort-new'))).height,
AppDimens.filterChipHeight,
);
final chipContainer = tester.widget<Container>(
find.descendant(
of: find.byKey(const Key('all-sort-new')),
matching: find.byType(Container),
),
);
expect(
(chipContainer.decoration! as BoxDecoration).borderRadius,
BorderRadius.circular(AppDimens.filterChipRadius),
);
expect(find.byKey(const Key('all-dramas-filter-page')), findsNothing);
await tester.tap(find.byKey(const Key('recommend-tab-playlist')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('recommend-section-hits')), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player'), skipOffstage: false), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player')), findsOneWidget);
expect(find.byType(AppBottomNav), findsOneWidget);
await tester.tap(find.byKey(const Key('recommend-tab-all')));
await tester.pumpAndSettle();
expect(_textStyle(tester, 'New').fontWeight, FontWeight.w700);
expect(find.byKey(const Key('all-dramas-grid')), findsOneWidget);
});
@@ -436,7 +527,7 @@ void main() {
await tester.drag(pages, const Offset(-320, 0));
await tester.pumpAndSettle();
expect(find.byKey(const Key('recommend-section-hits')), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player'), skipOffstage: false), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player')), findsOneWidget);
expect(
tester
.widget<Text>(
@@ -460,7 +551,7 @@ void main() {
await tester.drag(pages, const Offset(640, 0));
await tester.pumpAndSettle();
expect(find.byKey(const Key('recommend-feed-player'), skipOffstage: false), findsOneWidget);
expect(find.byKey(const Key('recommend-feed-player')), findsOneWidget);
expect(find.byKey(const Key('recommend-tab-recommend')), findsOneWidget);
});
@@ -494,7 +585,7 @@ void main() {
await _pumpRecommend(tester);
final gesture = await tester.startGesture(
tester.getCenter(find.byKey(const Key('recommend-feed-player'), skipOffstage: false)),
tester.getCenter(find.byKey(const Key('recommend-feed-player'))),
);
await gesture.moveBy(const Offset(0, 80));
await tester.pump();
@@ -502,7 +593,7 @@ void main() {
final feedScroll = tester.state<ScrollableState>(
find
.descendant(
of: find.byKey(const Key('recommend-feed-player'), skipOffstage: false),
of: find.byKey(const Key('recommend-feed-player')),
matching: find.byType(Scrollable),
)
.first,
@@ -530,8 +621,7 @@ void main() {
final player = tester.widget<PlayerPage>(find.byType(PlayerPage).last);
expect(player.homeMode, isFalse);
await tester.binding.handlePopRoute();
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('recommend-search')));
await tester.pumpAndSettle();
@@ -542,6 +632,17 @@ void main() {
});
}
TextStyle _textStyle(WidgetTester tester, String text) {
return tester
.widget<Text>(
find.descendant(
of: find.byKey(const Key('all-sort-new')),
matching: find.text(text),
),
)
.style!;
}
Future<void> _pumpRecommend(WidgetTester tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;