Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
222bacdeeb | ||
|
|
b83b5799e3 | ||
|
|
d4ae8f427f | ||
|
|
98d7debfb5 | ||
|
|
b5e9deb4bd | ||
|
|
47df002d8e | ||
|
|
4f1feeadbd | ||
|
|
8b50b5bd06 | ||
|
|
8481611372 | ||
|
|
b1e95b370c | ||
|
|
0ef0d46919 | ||
|
|
b4d38f8e10 | ||
|
|
c034627fdb | ||
|
|
ef29fc5f15 | ||
|
|
671e0ce143 | ||
|
|
0f1f64a09f | ||
|
|
a1c0af3f00 | ||
|
|
1d2ba93e48 | ||
|
|
be166f5856 | ||
|
|
8ed6cd9fd6 | ||
|
|
3dcfa02372 | ||
|
|
cd3d84cf9a | ||
|
|
2577797772 | ||
|
|
6ae9e8e043 | ||
|
|
8bb365db2a | ||
|
|
5c174b007c |
No files matched your search
@@ -11,6 +11,7 @@
|
||||
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 */; };
|
||||
@@ -49,6 +50,7 @@
|
||||
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>"; };
|
||||
@@ -122,6 +124,7 @@
|
||||
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
|
||||
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
|
||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
|
||||
8C4E1A012F9A4B1000C636F3 /* WirelessDataPrompt.swift */,
|
||||
7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */,
|
||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
|
||||
);
|
||||
@@ -282,6 +285,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
|
||||
8C4E1A022F9A4B1000C636F3 /* WirelessDataPrompt.swift in Sources */,
|
||||
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
|
||||
7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */,
|
||||
);
|
||||
|
||||
@@ -37,6 +37,7 @@ 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
|
||||
@@ -50,8 +51,18 @@ 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()
|
||||
@@ -132,4 +143,22 @@ 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 +1,11 @@
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// 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) }
|
||||
}
|
||||
}
|
||||
+36
-5
@@ -30,6 +30,7 @@ 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';
|
||||
@@ -41,6 +42,7 @@ 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';
|
||||
@@ -83,6 +85,7 @@ class LumaDramaApp extends StatefulWidget {
|
||||
this.commerceRepository,
|
||||
this.storeRepository,
|
||||
this.searchRepository,
|
||||
this.playlistRepository,
|
||||
this.haptics = const FlutterHaptics(),
|
||||
});
|
||||
|
||||
@@ -103,6 +106,7 @@ class LumaDramaApp extends StatefulWidget {
|
||||
final CommerceRepository? commerceRepository;
|
||||
final StoreRepository? storeRepository;
|
||||
final SearchRepository? searchRepository;
|
||||
final PlaylistRepository? playlistRepository;
|
||||
final Haptics haptics;
|
||||
|
||||
@override
|
||||
@@ -126,8 +130,10 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
_sessionStore,
|
||||
);
|
||||
|
||||
late final CatalogApi _catalogApi = CatalogApi(_apiClient);
|
||||
|
||||
late final CatalogRepository _catalogRepository =
|
||||
widget.catalogRepository ?? HttpCatalogRepository(CatalogApi(_apiClient));
|
||||
widget.catalogRepository ?? HttpCatalogRepository(_catalogApi);
|
||||
|
||||
late final CategoryRepository _categoryRepository =
|
||||
widget.categoryRepository ??
|
||||
@@ -177,6 +183,13 @@ 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));
|
||||
|
||||
@@ -239,14 +252,26 @@ 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),
|
||||
@@ -260,11 +285,17 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
||||
Provider<SearchRepository>.value(value: _searchRepository),
|
||||
Provider<Haptics>.value(value: widget.haptics),
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => CatalogController(_catalogRepository)..load(),
|
||||
),
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => CategoryController(_categoryRepository)..load(),
|
||||
create: (_) {
|
||||
final catalog = CatalogController(_catalogRepository);
|
||||
if (widget.catalogRepository != null) catalog.load();
|
||||
return catalog;
|
||||
},
|
||||
),
|
||||
ChangeNotifierProvider(create: (_) => _createCategories()),
|
||||
if (playlists != null)
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => PlaylistController(playlists),
|
||||
),
|
||||
ChangeNotifierProvider.value(value: _favoriteController),
|
||||
ChangeNotifierProvider.value(value: _downloadController),
|
||||
ChangeNotifierProvider.value(value: _walletController),
|
||||
|
||||
@@ -1,17 +1,30 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// 服务端内容分类。id 按契约保持字符串,避免雪花 ID 精度丢失。
|
||||
class ContentCategory {
|
||||
const ContentCategory({required this.id, required this.name});
|
||||
const ContentCategory({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.locales = const {},
|
||||
});
|
||||
|
||||
final String id;
|
||||
|
||||
/// 中文名称,与 locales 里的 zh 相同。
|
||||
final String name;
|
||||
final Map<String, String> locales;
|
||||
|
||||
/// 解析 `GET /app/categories` 的单项。
|
||||
factory ContentCategory.fromJson(Map<String, dynamic> json) {
|
||||
return ContentCategory(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
name: json['name'] as String? ?? '',
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'json_numbers.dart';
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// 短剧与剧集,字段与后端 `/app/**` 的下发结构对应。
|
||||
///
|
||||
@@ -76,7 +79,14 @@ 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,
|
||||
@@ -94,9 +104,16 @@ 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;
|
||||
@@ -127,19 +144,26 @@ 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: json['title'] as String? ?? '',
|
||||
synopsis: json['synopsis'] as String? ?? '',
|
||||
title: text.title,
|
||||
synopsis: text.synopsis,
|
||||
titleLocales: text.titleLocales,
|
||||
synopsisLocales: text.synopsisLocales,
|
||||
tag: text.tag,
|
||||
tagLocales: text.tagLocales,
|
||||
tagColor: json['tagColor'] as String? ?? '',
|
||||
posterUrl: json['cover'] as String? ?? '',
|
||||
episodes: preview is Map<String, dynamic>
|
||||
? [Episode.fromJson(preview)]
|
||||
: const [],
|
||||
category: json['category'] as String? ?? '',
|
||||
genre: json['genre'] as String? ?? '',
|
||||
category: text.category,
|
||||
categoryLocales: text.categoryLocales,
|
||||
types: text.types,
|
||||
genre: text.genre,
|
||||
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']),
|
||||
@@ -152,13 +176,21 @@ class Drama {
|
||||
|
||||
/// 详情:带剧集列表。
|
||||
factory Drama.fromDetailJson(Map<String, dynamic> json) {
|
||||
final text = _DramaText.fromJson(json);
|
||||
return Drama(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
title: json['title'] as String? ?? '',
|
||||
synopsis: json['synopsis'] as String? ?? '',
|
||||
title: text.title,
|
||||
synopsis: text.synopsis,
|
||||
titleLocales: text.titleLocales,
|
||||
synopsisLocales: text.synopsisLocales,
|
||||
tag: text.tag,
|
||||
tagLocales: text.tagLocales,
|
||||
tagColor: json['tagColor'] as String? ?? '',
|
||||
posterUrl: json['cover'] as String? ?? '',
|
||||
category: json['category'] as String? ?? '',
|
||||
genre: json['genre'] as String? ?? '',
|
||||
category: text.category,
|
||||
categoryLocales: text.categoryLocales,
|
||||
types: text.types,
|
||||
genre: text.genre,
|
||||
totalEpisodes: (json['totalEpisodes'] as num?)?.toInt() ?? 0,
|
||||
freeEpisodes: (json['freeEpisodes'] as num?)?.toInt() ?? 0,
|
||||
isHot: json['isHot'] == true,
|
||||
@@ -176,6 +208,37 @@ 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);
|
||||
@@ -184,3 +247,81 @@ 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 : '';
|
||||
}
|
||||
@@ -48,7 +48,7 @@ class FeedSection {
|
||||
factory FeedSection.fromJson(Map<String, dynamic> json) {
|
||||
return FeedSection(
|
||||
code: json['code'] as String? ?? '',
|
||||
title: json['title'] as String? ?? '',
|
||||
title: _sectionTitle(json),
|
||||
dramas: (json['dramas'] as List? ?? const [])
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map(Drama.fromCardJson)
|
||||
@@ -84,3 +84,12 @@ 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? ?? '';
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ class PlayTicket {
|
||||
this.unlockCoin = 0,
|
||||
this.previewSeconds = 0,
|
||||
this.qualities = const [],
|
||||
this.tracks = const [],
|
||||
this.thumbnailsUrl,
|
||||
this.likeCount,
|
||||
this.commentCount,
|
||||
@@ -39,8 +40,11 @@ class PlayTicket {
|
||||
/// 试看秒数:仅 `COIN_REQUIRED` 时有意义(付费解锁在 B2 做)。
|
||||
final int previewSeconds;
|
||||
|
||||
/// 后端下发的清晰度档位(如 AUTO / 720P / 1080P),HLS 由播放器自动切换。
|
||||
/// 后端下发的清晰度档位(如 AUTO / 720p / 1080p)。
|
||||
final List<String> qualities;
|
||||
|
||||
/// 各档签名地址。AUTO 是主列表,点选其它档位时换成对应地址。
|
||||
final List<PlayQualityTrack> tracks;
|
||||
final String? thumbnailsUrl;
|
||||
final int? likeCount;
|
||||
final int? commentCount;
|
||||
@@ -64,6 +68,7 @@ class PlayTicket {
|
||||
.whereType<String>()
|
||||
.where((quality) => quality.isNotEmpty)
|
||||
.toList(),
|
||||
tracks: _tracks(json['tracks'], json['playUrl'] as String? ?? ''),
|
||||
thumbnailsUrl: _optionalString(json['thumbnailsUrl']),
|
||||
likeCount: json['likeCount'] == null
|
||||
? null
|
||||
@@ -75,6 +80,67 @@ class PlayTicket {
|
||||
}
|
||||
}
|
||||
|
||||
List<PlayQualityTrack> _tracks(dynamic raw, String playUrl) {
|
||||
final tracks = <PlayQualityTrack>[];
|
||||
if (raw is List) {
|
||||
for (final item in raw) {
|
||||
if (item is! Map) continue;
|
||||
final quality = item['quality'] as String? ?? '';
|
||||
final url = item['playUrl'] as String? ?? '';
|
||||
if (quality.isEmpty || url.isEmpty) continue;
|
||||
tracks.add(PlayQualityTrack(quality: quality, playUrl: url));
|
||||
}
|
||||
}
|
||||
if (tracks.isEmpty && playUrl.isNotEmpty) {
|
||||
tracks.add(PlayQualityTrack(quality: 'AUTO', playUrl: playUrl));
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// 按票据里的分轨地址取播放地址;没有分轨时,从主列表路径推出同目录的单档地址。
|
||||
String? qualityPlayUrl({
|
||||
required String quality,
|
||||
required List<PlayQualityTrack> tracks,
|
||||
required String currentUrl,
|
||||
}) {
|
||||
final wanted = quality.toUpperCase();
|
||||
for (final track in tracks) {
|
||||
if (track.quality.toUpperCase() == wanted && track.playUrl.isNotEmpty) {
|
||||
return track.playUrl;
|
||||
}
|
||||
}
|
||||
return siblingRenditionUrl(currentUrl, wanted);
|
||||
}
|
||||
|
||||
/// `.../master.m3u8` 与 `.../720p/index.m3u8` 互相换算,查询参数原样保留。
|
||||
String? siblingRenditionUrl(String currentUrl, String quality) {
|
||||
final uri = Uri.tryParse(currentUrl);
|
||||
if (uri == null || uri.path.isEmpty) return null;
|
||||
final path = uri.path;
|
||||
const masterSuffix = '/master.m3u8';
|
||||
String? root;
|
||||
if (path.endsWith(masterSuffix)) {
|
||||
root = path.substring(0, path.length - masterSuffix.length);
|
||||
} else {
|
||||
final match = RegExp(r'/(\d+p)/index\.m3u8$').firstMatch(path);
|
||||
if (match == null) return null;
|
||||
root = path.substring(0, match.start);
|
||||
}
|
||||
final next = quality.toUpperCase() == 'AUTO'
|
||||
? '$root$masterSuffix'
|
||||
: '$root/${quality.toLowerCase()}/index.m3u8';
|
||||
if (next == path) return currentUrl;
|
||||
return uri.replace(path: next).toString();
|
||||
}
|
||||
|
||||
/// 一档清晰度的签名播放地址。
|
||||
class PlayQualityTrack {
|
||||
const PlayQualityTrack({required this.quality, required this.playUrl});
|
||||
|
||||
final String quality;
|
||||
final String playUrl;
|
||||
}
|
||||
|
||||
String? _optionalString(dynamic value) {
|
||||
final text = value is String ? value.trim() : '';
|
||||
return text.isEmpty ? null : text;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'json_numbers.dart';
|
||||
import 'locale_text.dart';
|
||||
|
||||
/// 服务端续看记录:`GET /app/watch/progress?dramaId=` 与 `/app/watch/recent` 的下发结构。
|
||||
///
|
||||
@@ -13,17 +14,20 @@ class WatchProgress {
|
||||
required this.position,
|
||||
required this.duration,
|
||||
this.dramaTitle,
|
||||
this.titleLocales = const {},
|
||||
this.dramaCover,
|
||||
this.episodeNumber,
|
||||
this.totalEpisodes,
|
||||
this.finished = false,
|
||||
this.playCount = 0,
|
||||
this.viewCount,
|
||||
this.updatedAt,
|
||||
});
|
||||
|
||||
final String dramaId;
|
||||
final String episodeId;
|
||||
final String? dramaTitle;
|
||||
final Map<String, String> titleLocales;
|
||||
final String? dramaCover;
|
||||
final int? episodeNumber;
|
||||
final int? totalEpisodes;
|
||||
@@ -31,6 +35,9 @@ class WatchProgress {
|
||||
final Duration duration;
|
||||
final bool finished;
|
||||
final int playCount;
|
||||
|
||||
/// 短剧热度。历史列表没下发时为空,不能拿用户自己的 playCount 冒充。
|
||||
final int? viewCount;
|
||||
final DateTime? updatedAt;
|
||||
|
||||
bool get hasPosition => position > Duration.zero;
|
||||
@@ -41,11 +48,17 @@ 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
|
||||
@@ -57,6 +70,9 @@ class WatchProgress {
|
||||
duration: Duration(milliseconds: jsonToInt(json['durationMs'])),
|
||||
finished: json['finished'] == true,
|
||||
playCount: jsonToInt(json['playCount']),
|
||||
viewCount: json['viewCount'] == null
|
||||
? null
|
||||
: jsonToInt(json['viewCount']),
|
||||
updatedAt: DateTime.tryParse(json['updatedAt'] as String? ?? ''),
|
||||
);
|
||||
}
|
||||
@@ -65,6 +81,7 @@ 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,
|
||||
@@ -72,6 +89,7 @@ class WatchProgress {
|
||||
'durationMs': duration.inMilliseconds,
|
||||
'finished': finished,
|
||||
'playCount': playCount,
|
||||
if (viewCount != null) 'viewCount': viewCount,
|
||||
if (updatedAt != null) 'updatedAt': updatedAt!.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,9 +31,13 @@ class WatchRecord {
|
||||
}
|
||||
|
||||
/// 服务端分页标题优先,详情标题作为回退。
|
||||
String get displayTitle {
|
||||
final pageTitle = progress.dramaTitle?.trim() ?? '';
|
||||
return pageTitle.isNotEmpty ? pageTitle : drama?.title.trim() ?? '';
|
||||
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() ?? '';
|
||||
}
|
||||
|
||||
/// 服务端分页封面优先,详情封面作为回退。
|
||||
|
||||
@@ -148,7 +148,8 @@ class ApiClient {
|
||||
skipAuthRetry: skipAuthRetry,
|
||||
);
|
||||
}
|
||||
onUnauthorized?.call();
|
||||
final token = accessTokenReader?.call();
|
||||
if (token == null || token.isEmpty) onUnauthorized?.call();
|
||||
throw ApiException(401, cause.message ?? '登录已过期');
|
||||
}
|
||||
if (cause is ApiException) {
|
||||
|
||||
@@ -33,6 +33,7 @@ class AuthApi {
|
||||
required String code,
|
||||
required String deviceId,
|
||||
String platform = '',
|
||||
String osVersion = '',
|
||||
String appVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
@@ -43,6 +44,7 @@ class AuthApi {
|
||||
'code': code,
|
||||
'deviceId': deviceId,
|
||||
'platform': platform,
|
||||
'osVersion': osVersion,
|
||||
'appVersion': appVersion,
|
||||
},
|
||||
);
|
||||
@@ -55,6 +57,7 @@ class AuthApi {
|
||||
required String code,
|
||||
required String deviceId,
|
||||
String platform = '',
|
||||
String osVersion = '',
|
||||
String appVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
@@ -65,6 +68,7 @@ class AuthApi {
|
||||
'code': code,
|
||||
'deviceId': deviceId,
|
||||
'platform': platform,
|
||||
'osVersion': osVersion,
|
||||
'appVersion': appVersion,
|
||||
},
|
||||
);
|
||||
@@ -76,6 +80,7 @@ class AuthApi {
|
||||
required String password,
|
||||
required String deviceId,
|
||||
String platform = '',
|
||||
String osVersion = '',
|
||||
String appVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
@@ -87,6 +92,7 @@ class AuthApi {
|
||||
'countryCode': 'ID',
|
||||
'deviceId': deviceId,
|
||||
'platform': platform,
|
||||
'osVersion': osVersion,
|
||||
'appVersion': appVersion,
|
||||
},
|
||||
);
|
||||
@@ -98,6 +104,7 @@ class AuthApi {
|
||||
required String password,
|
||||
required String deviceId,
|
||||
String platform = '',
|
||||
String osVersion = '',
|
||||
String appVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
@@ -108,18 +115,25 @@ class AuthApi {
|
||||
'password': password,
|
||||
'deviceId': deviceId,
|
||||
'platform': platform,
|
||||
'osVersion': osVersion,
|
||||
'appVersion': appVersion,
|
||||
},
|
||||
);
|
||||
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
||||
}
|
||||
|
||||
Future<AuthSession> refresh(String refreshToken) async {
|
||||
Future<AuthSession> refresh(
|
||||
String refreshToken, {
|
||||
String platform = '',
|
||||
String osVersion = '',
|
||||
}) async {
|
||||
final data = await _client.post(
|
||||
'/app/auth/refresh',
|
||||
body: {'refreshToken': refreshToken},
|
||||
// 刷新请求本身不带旧令牌重试,失败就是失败
|
||||
skipAuthRetry: true,
|
||||
body: {
|
||||
'refreshToken': refreshToken,
|
||||
'platform': platform,
|
||||
'osVersion': osVersion,
|
||||
},
|
||||
);
|
||||
return AuthSession.fromJson((data as Map).cast<String, dynamic>());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
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';
|
||||
|
||||
@@ -58,12 +61,95 @@ 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, '返回数据格式异常');
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
// 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 全程按字符串解析。
|
||||
@@ -18,4 +22,20 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -36,4 +36,9 @@ class LibraryApi {
|
||||
Future<void> removeFavorite(String dramaId) async {
|
||||
await _client.delete('/app/favorites/$dramaId');
|
||||
}
|
||||
|
||||
/// 一次取消多部短剧,请求体为 dramaIds 数组。
|
||||
Future<void> removeFavorites(List<String> dramaIds) async {
|
||||
await _client.post('/app/favorites/remove', body: {'dramaIds': dramaIds});
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,9 @@ abstract interface class FavoriteRepository {
|
||||
Future<PageResult<Drama>> page({int pageIndex = 1, int pageSize = 20});
|
||||
|
||||
Future<void> remove(String dramaId);
|
||||
|
||||
/// 一次取消多部短剧。
|
||||
Future<void> removeMany(List<String> dramaIds);
|
||||
}
|
||||
|
||||
class HttpFavoriteRepository implements FavoriteRepository {
|
||||
@@ -36,6 +39,10 @@ class HttpFavoriteRepository implements FavoriteRepository {
|
||||
|
||||
@override
|
||||
Future<void> remove(String dramaId) => _api.removeFavorite(dramaId);
|
||||
|
||||
@override
|
||||
Future<void> removeMany(List<String> dramaIds) =>
|
||||
_api.removeFavorites(dramaIds);
|
||||
}
|
||||
|
||||
/// 内存实现:单测与 widget 测试注入用。
|
||||
@@ -51,6 +58,7 @@ class InMemoryFavoriteRepository implements FavoriteRepository {
|
||||
bool failRemove = false;
|
||||
int toggleCalls = 0;
|
||||
int pageCalls = 0;
|
||||
int removeManyCalls = 0;
|
||||
|
||||
@override
|
||||
Future<bool> toggle(String dramaId) async {
|
||||
@@ -80,4 +88,11 @@ class InMemoryFavoriteRepository implements FavoriteRepository {
|
||||
if (failRemove) throw StateError('favorite unavailable');
|
||||
_saved.remove(dramaId);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> removeMany(List<String> dramaIds) async {
|
||||
removeManyCalls += 1;
|
||||
if (failRemove) throw StateError('favorite unavailable');
|
||||
_saved.removeAll(dramaIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/auth_session.dart';
|
||||
@@ -9,7 +11,7 @@ import 'auth_session_store.dart';
|
||||
///
|
||||
/// 职责:本地会话的读写([AuthSessionStore])、注册/登录/登出、令牌刷新;
|
||||
/// 也是 [ApiClient] 的 `accessTokenReader` / `tokenRefresher` / `onUnauthorized` 实现方 ——
|
||||
/// 401 → 刷新 → 重试失败就清会话,UI 通过 [isSignedIn] 自动回到未登录态。
|
||||
/// 401 → 刷新 → 重试。令牌被拒绝才清会话,服务中断时保持登录。
|
||||
class AuthController extends ChangeNotifier {
|
||||
AuthController(this._api, this._store);
|
||||
|
||||
@@ -19,6 +21,10 @@ class AuthController extends ChangeNotifier {
|
||||
AuthSession? _session;
|
||||
String _deviceId = '';
|
||||
bool _loaded = false;
|
||||
Future<bool>? _refreshing;
|
||||
|
||||
/// 登录已过期、账号停用才清本地会话。服务不可达不能当成退出登录。
|
||||
static const Set<int> _rejectedSessionCodes = {401, 100001};
|
||||
|
||||
bool get isLoaded => _loaded;
|
||||
bool get isSignedIn => _session != null;
|
||||
@@ -43,6 +49,7 @@ class AuthController extends ChangeNotifier {
|
||||
password: password,
|
||||
deviceId: await _store.deviceId(),
|
||||
platform: _platform,
|
||||
osVersion: _osVersion,
|
||||
);
|
||||
await _apply(session);
|
||||
}
|
||||
@@ -53,14 +60,12 @@ class AuthController extends ChangeNotifier {
|
||||
password: password,
|
||||
deviceId: await _store.deviceId(),
|
||||
platform: _platform,
|
||||
osVersion: _osVersion,
|
||||
);
|
||||
await _apply(session);
|
||||
}
|
||||
|
||||
Future<void> sendOtp({
|
||||
required String target,
|
||||
String scene = 'LOGIN',
|
||||
}) async {
|
||||
Future<void> sendOtp({required String target, String scene = 'LOGIN'}) async {
|
||||
await _api.sendOtp(
|
||||
target: target,
|
||||
scene: scene,
|
||||
@@ -77,6 +82,7 @@ class AuthController extends ChangeNotifier {
|
||||
code: code,
|
||||
deviceId: await _store.deviceId(),
|
||||
platform: _platform,
|
||||
osVersion: _osVersion,
|
||||
);
|
||||
await _apply(session);
|
||||
}
|
||||
@@ -90,10 +96,17 @@ class AuthController extends ChangeNotifier {
|
||||
code: code,
|
||||
deviceId: await _store.deviceId(),
|
||||
platform: _platform,
|
||||
osVersion: _osVersion,
|
||||
);
|
||||
await _apply(session);
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
_session = null;
|
||||
await _store.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> signOut() async {
|
||||
final refreshToken = _session?.refreshToken ?? '';
|
||||
_session = null;
|
||||
@@ -107,29 +120,43 @@ class AuthController extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// 供 [ApiClient] 调用:刷新令牌并落盘。失败时清本地会话。
|
||||
Future<bool> refresh() async {
|
||||
/// 供 [ApiClient] 调用:刷新令牌并落盘。
|
||||
///
|
||||
/// 同一时刻只刷新一次,避免重启期间并发 401 把新令牌轮换掉。
|
||||
/// 网络失败或 5xx 保留本地会话;只有令牌被拒绝才退出登录。
|
||||
Future<bool> refresh() {
|
||||
final current = _refreshing;
|
||||
if (current != null) return current;
|
||||
final run = _refreshSingle();
|
||||
_refreshing = run;
|
||||
return run.whenComplete(() {
|
||||
if (identical(_refreshing, run)) _refreshing = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> _refreshSingle() async {
|
||||
final refreshToken = _session?.refreshToken ?? '';
|
||||
if (refreshToken.isEmpty) {
|
||||
await clear();
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await _apply(await _api.refresh(refreshToken));
|
||||
await _apply(
|
||||
await _api.refresh(
|
||||
refreshToken,
|
||||
platform: _platform,
|
||||
osVersion: _osVersion,
|
||||
),
|
||||
);
|
||||
return true;
|
||||
} on ApiException catch (error) {
|
||||
if (_rejectedSessionCodes.contains(error.code)) await clear();
|
||||
return false;
|
||||
} catch (_) {
|
||||
await clear();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clear() async {
|
||||
if (_session == null) return;
|
||||
_session = null;
|
||||
await _store.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 资料保存成功后同步登录态摘要,保留当前令牌。
|
||||
Future<void> applyProfile(AuthUser user) async {
|
||||
final current = _session;
|
||||
@@ -154,4 +181,9 @@ class AuthController extends ChangeNotifier {
|
||||
if (kIsWeb) return 'WEB';
|
||||
return defaultTargetPlatform == TargetPlatform.iOS ? 'IOS' : 'ANDROID';
|
||||
}
|
||||
|
||||
String get _osVersion {
|
||||
if (kIsWeb) return '';
|
||||
return Platform.operatingSystemVersion;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ 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。
|
||||
@@ -14,13 +16,80 @@ 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';
|
||||
@@ -30,19 +99,23 @@ class CategoryController extends ChangeNotifier {
|
||||
return const [];
|
||||
}
|
||||
|
||||
/// 加载分类与发现 feed;失败保留可重试错误态。
|
||||
/// 首页只拉分类,再拉第一个分类的短剧。发现页聚合留到没有短剧分页时再取。
|
||||
Future<void> load() async {
|
||||
loading = true;
|
||||
error = null;
|
||||
debugError = null;
|
||||
_notify();
|
||||
try {
|
||||
final results = await Future.wait<Object>([
|
||||
_repository.fetchCategories(),
|
||||
_repository.fetchDiscoverFeed(),
|
||||
]);
|
||||
categories = results[0] as List<ContentCategory>;
|
||||
feed = results[1] as HomeFeed;
|
||||
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;
|
||||
}
|
||||
} catch (exception) {
|
||||
error = 'categoriesError';
|
||||
debugError = exception.toString();
|
||||
@@ -53,6 +126,9 @@ class CategoryController extends ChangeNotifier {
|
||||
loading = false;
|
||||
_notify();
|
||||
}
|
||||
if (error == null && dramaPageLoader != null && categories.isNotEmpty) {
|
||||
await openCategory(categories.first.id);
|
||||
}
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
@@ -65,3 +141,14 @@ 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;
|
||||
}
|
||||
@@ -161,6 +161,37 @@ class FavoriteController extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次取消多部收藏。失败时整批回滚。
|
||||
Future<bool> removeMany(List<String> dramaIds) async {
|
||||
final ids = dramaIds.toSet();
|
||||
if (ids.isEmpty) return true;
|
||||
final previousCards = cards;
|
||||
final previousTotal = total;
|
||||
final previousHasMore = hasMore;
|
||||
final removed = cards.where((drama) => ids.contains(drama.id)).toList();
|
||||
if (removed.isEmpty) return true;
|
||||
cards = cards.where((drama) => !ids.contains(drama.id)).toList();
|
||||
for (final id in ids) {
|
||||
_saved.remove(id);
|
||||
}
|
||||
total = total > removed.length ? total - removed.length : 0;
|
||||
hasMore = cards.length < total;
|
||||
notify();
|
||||
try {
|
||||
await _repository.removeMany(dramaIds);
|
||||
return true;
|
||||
} catch (_) {
|
||||
cards = previousCards;
|
||||
total = previousTotal;
|
||||
hasMore = previousHasMore;
|
||||
for (final drama in removed) {
|
||||
_saved.add(drama.id);
|
||||
}
|
||||
notify();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消收藏("我的"页列表里删除某条)。
|
||||
Future<bool> remove(String dramaId) async {
|
||||
final index = cards.indexWhere((drama) => drama.id == dramaId);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -5,42 +5,18 @@ import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/drama.dart';
|
||||
import '../models/player_port.dart';
|
||||
import 'video_player_port.dart';
|
||||
|
||||
part 'playback_neighbors.dart';
|
||||
|
||||
/// 新纹理第一帧常是黑的,旧画面只盖住这一小段。
|
||||
const Duration _qualityHandoffHold = Duration(milliseconds: 200);
|
||||
|
||||
typedef PlayerFactory = PlayerPort Function(Episode episode);
|
||||
typedef PlayerPreparation =
|
||||
Future<void> Function(Episode episode, PlayerPort player);
|
||||
|
||||
/// 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.
|
||||
/// Owns current plus previous/next frames; allocation stays serialized.
|
||||
class PlaybackSession extends ChangeNotifier {
|
||||
PlaybackSession({
|
||||
required this.episodes,
|
||||
@@ -66,11 +42,14 @@ 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;
|
||||
@@ -115,7 +94,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]) {
|
||||
for (final slot in [_active, _next, _previous]) {
|
||||
if (slot == null ||
|
||||
slot.retiring ||
|
||||
slot.index != index ||
|
||||
@@ -127,25 +106,46 @@ class PlaybackSession extends ChangeNotifier {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 清晰度切换时盖住黑帧的旧播放器。只在仍由会话持有时交给界面。
|
||||
PlayerPort? handoffAt(int index) {
|
||||
final slot = _handoff;
|
||||
if (_closed || slot == null || slot.retiring || slot.index != index) {
|
||||
return null;
|
||||
}
|
||||
return slot.player;
|
||||
}
|
||||
|
||||
/// 队列重排后把当前仍在播放的 slot 映射到新索引,不重新创建播放器。
|
||||
void remapCurrentIndex(int index, {int? preloadIndex}) {
|
||||
void remapCurrentIndex(int index, {int? preloadIndex, int? previousIndex}) {
|
||||
if (_closed || index < 0 || index >= episodes.length) return;
|
||||
final activeSlot = _active;
|
||||
if (activeSlot == null || activeSlot.index != _currentIndex) {
|
||||
_currentIndex = index;
|
||||
_nextIndex = preloadIndex;
|
||||
_rememberNeighbors(preloadIndex, previousIndex);
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
_generation++;
|
||||
activeSlot.index = index;
|
||||
_currentIndex = index;
|
||||
_nextIndex = preloadIndex;
|
||||
_rememberNeighbors(preloadIndex, previousIndex);
|
||||
final staleNext = _next;
|
||||
final stalePrevious = _previous;
|
||||
_next = null;
|
||||
_previous = null;
|
||||
_notify();
|
||||
unawaited(_enqueue(() async => _retire(staleNext)));
|
||||
if (_visible && !_overlayOpen) _schedulePreload();
|
||||
unawaited(
|
||||
_enqueue(() async {
|
||||
await _retire(staleNext);
|
||||
await _retire(stalePrevious);
|
||||
}),
|
||||
);
|
||||
if (_visible && !_overlayOpen) _warmNeighbors(this);
|
||||
}
|
||||
|
||||
void _rememberNeighbors(int? preloadIndex, int? previousIndex) {
|
||||
_nextIndex = preloadIndex;
|
||||
_previousIndex = previousIndex;
|
||||
}
|
||||
|
||||
Future<void> _enqueue(Future<void> Function() operation) {
|
||||
@@ -162,7 +162,9 @@ class PlaybackSession extends ChangeNotifier {
|
||||
}
|
||||
|
||||
_PlayerSlot _create(int index) {
|
||||
if (_live.length >= 2) throw StateError('Playback resource limit reached');
|
||||
if (_live.length >= maxLivePlayers) {
|
||||
throw StateError('Playback resource limit reached');
|
||||
}
|
||||
final slot = _PlayerSlot(index, factory(episodes[index]));
|
||||
_live.add(slot);
|
||||
slot.ready = () async {
|
||||
@@ -184,9 +186,15 @@ 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;
|
||||
final cleared =
|
||||
_active == slot ||
|
||||
_next == slot ||
|
||||
_previous == 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();
|
||||
await slot.ready;
|
||||
@@ -200,7 +208,11 @@ 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}) async {
|
||||
Future<void> select(
|
||||
int index, {
|
||||
int? preloadIndex,
|
||||
int? previousIndex,
|
||||
}) async {
|
||||
if (_closed || index < 0 || index >= episodes.length) return;
|
||||
// 切到另一集时,上一集按下的暂停不跟着走:滑过去就应该自动播放。
|
||||
// 重复选中同一集(例如页面重新可见)不在这里恢复,尊重用户按下的暂停。
|
||||
@@ -210,7 +222,7 @@ class PlaybackSession extends ChangeNotifier {
|
||||
final request = ++_generation;
|
||||
_selected = true;
|
||||
_currentIndex = index;
|
||||
_nextIndex = preloadIndex;
|
||||
_rememberNeighbors(preloadIndex, previousIndex);
|
||||
_error = null;
|
||||
if (!_visible) {
|
||||
_loading = false;
|
||||
@@ -235,6 +247,7 @@ class PlaybackSession extends ChangeNotifier {
|
||||
_PlayerSlot? target;
|
||||
await _enqueue(() async {
|
||||
if (_closed || request != _generation) return;
|
||||
await _retire(_handoff);
|
||||
final old = _active;
|
||||
if (old != null &&
|
||||
old.index == index &&
|
||||
@@ -244,19 +257,22 @@ class PlaybackSession extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
if (old != null) await old.player.pause();
|
||||
final warm = _next;
|
||||
final warmNext = _next;
|
||||
final warmPrevious = _previous;
|
||||
_active = null;
|
||||
_next = null;
|
||||
final hit = warm?.index == index && warm?.failure == null && !isLocked;
|
||||
if (hit) {
|
||||
_previous = null;
|
||||
final warm =
|
||||
_usableWarm(this, warmNext, index) ??
|
||||
_usableWarm(this, warmPrevious, index);
|
||||
if (warm != null) {
|
||||
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 _retire(old);
|
||||
if (!hit) await _retire(warm);
|
||||
await _parkNeighbors(this, old, warmNext, warmPrevious);
|
||||
if (_closed || request != _generation || isLocked) return;
|
||||
if (target == null) {
|
||||
target = _active = _create(index);
|
||||
@@ -269,7 +285,109 @@ class PlaybackSession extends ChangeNotifier {
|
||||
await slot.ready;
|
||||
if (_closed || request != _generation || _active != slot) return;
|
||||
await _enqueue(() => _start(slot, request));
|
||||
if (!_closed && request == _generation) _schedulePreload();
|
||||
if (!_closed && request == _generation) _warmNeighbors(this);
|
||||
}
|
||||
|
||||
/// 后台准备新片源,成功后再替换当前播放器。失败时原播放器保持不动。
|
||||
Future<bool> replaceCurrent() async {
|
||||
if (_closed || !_selected) return false;
|
||||
final index = _currentIndex;
|
||||
if (index < 0 || index >= episodes.length || isLocked) return false;
|
||||
if (!canPlay(episodes[index])) return false;
|
||||
final request = _generation;
|
||||
final slot = await _prepareReplacement(index, request);
|
||||
if (slot == null) {
|
||||
await _resumeActive();
|
||||
return false;
|
||||
}
|
||||
await slot.ready;
|
||||
if (!_replacementReady(slot, request)) {
|
||||
await _dropReplacement(slot);
|
||||
await _resumeActive();
|
||||
return false;
|
||||
}
|
||||
final previous = await _showReplacement(slot, request);
|
||||
if (_active != slot) {
|
||||
await _dropReplacement(slot);
|
||||
return false;
|
||||
}
|
||||
await _enqueue(() => _start(slot, request));
|
||||
await Future<void>.delayed(_qualityHandoffHold);
|
||||
if (previous != null && _handoff == previous && _active == slot) {
|
||||
await _enqueue(() => _retire(previous));
|
||||
}
|
||||
if (!_closed && request == _generation) _warmNeighbors(this);
|
||||
return _active == slot && slot.failure == null;
|
||||
}
|
||||
|
||||
Future<_PlayerSlot?> _prepareReplacement(int index, int request) async {
|
||||
_PlayerSlot? created;
|
||||
await _enqueue(() async {
|
||||
if (_closed || request != _generation || _active == null) return;
|
||||
final warm = _next;
|
||||
_next = null;
|
||||
await _retire(_handoff);
|
||||
await _retire(warm);
|
||||
if (_closed || request != _generation || _active == null) return;
|
||||
try {
|
||||
created = _create(index);
|
||||
} catch (_) {
|
||||
created = null;
|
||||
}
|
||||
});
|
||||
return created;
|
||||
}
|
||||
|
||||
bool _replacementReady(_PlayerSlot slot, int request) {
|
||||
return !_closed &&
|
||||
request == _generation &&
|
||||
_active != null &&
|
||||
slot.failure == null &&
|
||||
slot.prepared;
|
||||
}
|
||||
|
||||
Future<void> _resumeActive() async {
|
||||
final slot = _active;
|
||||
if (slot == null || !_userWantsPlay || _closed) return;
|
||||
await _enqueue(() => _applyPlayback(slot));
|
||||
}
|
||||
|
||||
Future<void> _dropReplacement(_PlayerSlot slot) {
|
||||
return _enqueue(() async {
|
||||
if (_live.contains(slot)) await _retire(slot);
|
||||
});
|
||||
}
|
||||
|
||||
/// 先把已出画的新播放器交到界面上,旧播放器留给调用方稍后释放。
|
||||
Future<_PlayerSlot?> _showReplacement(_PlayerSlot slot, int request) async {
|
||||
_PlayerSlot? previous;
|
||||
var shown = false;
|
||||
await _enqueue(() async {
|
||||
if (!_replacementReady(slot, request)) return;
|
||||
previous = _active;
|
||||
await _catchUp(slot, previous);
|
||||
_handoff = previous;
|
||||
_active = slot;
|
||||
shown = true;
|
||||
if (previous != null) await previous!.player.pause();
|
||||
_notify();
|
||||
});
|
||||
if (!shown || _active != slot) return null;
|
||||
return previous;
|
||||
}
|
||||
|
||||
/// 旧片仍在播,把新片对齐到当前进度,盖住时画面才接得上。
|
||||
Future<void> _catchUp(_PlayerSlot slot, _PlayerSlot? previous) async {
|
||||
final next = slot.player;
|
||||
final current = previous?.player;
|
||||
if (next is! VideoPlayerPort || current is! VideoPlayerPort) return;
|
||||
final position = current.controller.value.position;
|
||||
if (position <= Duration.zero) return;
|
||||
try {
|
||||
await next.seekTo(position);
|
||||
} catch (_) {
|
||||
// 对齐失败仍用准备阶段的进度,不因此放弃切换。
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _start(_PlayerSlot slot, int request) async {
|
||||
@@ -304,54 +422,6 @@ 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();
|
||||
@@ -376,18 +446,24 @@ class PlaybackSession extends ChangeNotifier {
|
||||
void _syncPlayback() {
|
||||
if (_closed) return;
|
||||
if (_visible && _selected && active == null) {
|
||||
unawaited(select(_currentIndex, preloadIndex: _nextIndex));
|
||||
unawaited(
|
||||
select(
|
||||
_currentIndex,
|
||||
preloadIndex: _nextIndex,
|
||||
previousIndex: _previousIndex,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final slot = _active;
|
||||
if (slot != null) unawaited(_enqueue(() => _applyPlayback(slot)));
|
||||
if (_visible && !_overlayOpen && !_loading) _schedulePreload();
|
||||
if (_visible && !_overlayOpen && !_loading) _warmNeighbors(this);
|
||||
}
|
||||
|
||||
Future<void> _releasePlayers() {
|
||||
_generation++;
|
||||
return _enqueue(() async {
|
||||
_active = _next = null;
|
||||
_active = _next = _previous = _handoff = null;
|
||||
_loading = false;
|
||||
_notify();
|
||||
for (final slot in _live.toList()) {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// 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,6 +2,37 @@
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
/// 按后端 `ErrorCode` 取当前语言文案。未收录的业务码回退服务端 message。
|
||||
String userFacingApiMessage(AppLocalizations l10n, int code, String message) {
|
||||
final localized = _apiMessage(l10n, code);
|
||||
if (localized != null) return localized;
|
||||
if (message.isEmpty) return l10n.authServerError;
|
||||
return message;
|
||||
}
|
||||
|
||||
/// 已定义错误码。500 用服务繁忙,不展示「系统异常」。
|
||||
String? _apiMessage(AppLocalizations l10n, int code) {
|
||||
return switch (code) {
|
||||
400 => l10n.apiErrorBadRequest,
|
||||
401 => l10n.apiErrorUnauthorized,
|
||||
403 => l10n.apiErrorForbidden,
|
||||
404 => l10n.apiErrorNotFound,
|
||||
429 => l10n.apiErrorTooManyRequests,
|
||||
500 => l10n.authServerError,
|
||||
100000 => l10n.apiErrorLoginFailed,
|
||||
100001 => l10n.apiErrorAccountDisabled,
|
||||
100002 => l10n.apiErrorCoinNotEnough,
|
||||
100003 => l10n.apiErrorEpisodeUnavailable,
|
||||
100004 => l10n.apiErrorEpisodeUnlocked,
|
||||
100005 => l10n.apiErrorOrderInvalid,
|
||||
100006 => l10n.apiErrorVipExpired,
|
||||
200001 => l10n.apiErrorDataExists,
|
||||
200002 => l10n.apiErrorDataNotFound,
|
||||
200003 => l10n.apiErrorNotAllowed,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// logic 里的错误在两种情况下是"哨兵值":本地网络异常(读不到后端提示语)与
|
||||
/// 我们自己包装的失败。这里统一翻译成当前语言的文案;服务端给的中文提示原样展示。
|
||||
String errorText(AppLocalizations l10n, String? code, String fallback) {
|
||||
|
||||
@@ -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.title,
|
||||
_ => drama.localizedTitle(l10n.localeName.split(RegExp(r'[_-]')).first),
|
||||
};
|
||||
|
||||
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.synopsis,
|
||||
_ => drama.localizedSynopsis(l10n.localeName.split(RegExp(r'[_-]')).first),
|
||||
};
|
||||
|
||||
String localizedEpisodeTitle(AppLocalizations l10n, int number) =>
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:html/dom.dart' as dom;
|
||||
import 'package:html/parser.dart' as html_parser;
|
||||
|
||||
import '../theme/app_colors.dart';
|
||||
|
||||
const double _bodySize = 16;
|
||||
const double _headingSize = 18;
|
||||
const double _blockGap = 12;
|
||||
const double _lineHeight = 1.7;
|
||||
|
||||
const TextStyle _bodyStyle = TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: _bodySize,
|
||||
height: _lineHeight,
|
||||
);
|
||||
|
||||
/// 把协议页的 HTML 正文画成普通控件。
|
||||
class LegalArticleView extends StatelessWidget {
|
||||
const LegalArticleView({super.key, required this.html});
|
||||
|
||||
final String html;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fragment = html_parser.parseFragment(html);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (final node in fragment.nodes) _block(node),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _block(dom.Node node) {
|
||||
if (node is! dom.Element) {
|
||||
return _paragraph(node.text ?? '');
|
||||
}
|
||||
switch (node.localName) {
|
||||
case 'h1':
|
||||
case 'h2':
|
||||
case 'h3':
|
||||
return _heading(node.text);
|
||||
case 'ul':
|
||||
case 'ol':
|
||||
return _list(node);
|
||||
case 'pre':
|
||||
return _paragraph(node.text);
|
||||
case 'blockquote':
|
||||
return _paragraph(node.text);
|
||||
default:
|
||||
return _paragraphSpan(node);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _heading(String text) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: _blockGap),
|
||||
child: Text(
|
||||
text.trim(),
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: _headingSize,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _list(dom.Element element) {
|
||||
final items = element.children.where((child) => child.localName == 'li');
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: _blockGap),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (final item in items)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text('• ${item.text.trim()}', style: _bodyStyle),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _paragraph(String text) {
|
||||
final value = text.trim();
|
||||
if (value.isEmpty) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: _blockGap),
|
||||
child: Text(value, style: _bodyStyle),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _paragraphSpan(dom.Element element) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: _blockGap),
|
||||
child: Text.rich(TextSpan(style: _bodyStyle, children: _inlines(element))),
|
||||
);
|
||||
}
|
||||
|
||||
List<InlineSpan> _inlines(dom.Node node) {
|
||||
if (node is dom.Text) {
|
||||
return [TextSpan(text: node.text)];
|
||||
}
|
||||
if (node is! dom.Element) return const [];
|
||||
final children = node.nodes.expand(_inlines).toList();
|
||||
switch (node.localName) {
|
||||
case 'strong':
|
||||
case 'b':
|
||||
return [TextSpan(style: const TextStyle(fontWeight: FontWeight.w700), children: children)];
|
||||
case 'em':
|
||||
case 'i':
|
||||
return [TextSpan(style: const TextStyle(fontStyle: FontStyle.italic), children: children)];
|
||||
case 'a':
|
||||
return [TextSpan(style: const TextStyle(color: AppColors.blue), children: children)];
|
||||
case 'br':
|
||||
return const [TextSpan(text: '\n')];
|
||||
default:
|
||||
return children;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../config/app_config.dart';
|
||||
|
||||
final RegExp _articlePattern = RegExp(
|
||||
'<article>([\\s\\S]*)</article>',
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
/// 从协议页里取出正文。没有 article 时退回整页。
|
||||
String legalArticle(String html) {
|
||||
final match = _articlePattern.firstMatch(html);
|
||||
final body = match?.group(1);
|
||||
if (body == null || body.trim().isEmpty) return html;
|
||||
return body.trim();
|
||||
}
|
||||
|
||||
/// 拉取协议页 HTML。不走业务 JSON 包装。
|
||||
Future<String> fetchLegalArticle(String url) async {
|
||||
final dio = Dio(
|
||||
BaseOptions(
|
||||
connectTimeout: AppConfig.requestTimeout,
|
||||
receiveTimeout: AppConfig.requestTimeout,
|
||||
responseType: ResponseType.plain,
|
||||
validateStatus: (code) => code != null && code >= 200 && code < 300,
|
||||
),
|
||||
);
|
||||
final response = await dio.get<String>(url);
|
||||
final body = response.data;
|
||||
if (body == null || body.trim().isEmpty) {
|
||||
throw StateError('empty legal page');
|
||||
}
|
||||
return legalArticle(body);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'legal_web_page.dart';
|
||||
|
||||
/// 在当前 App 里打开协议地址。
|
||||
Future<void> openLegalUrlOrNotify(BuildContext context, String url) {
|
||||
return Navigator.of(context).push<void>(
|
||||
MaterialPageRoute<void>(builder: (_) => LegalWebPage(url: url)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../config/app_config.dart';
|
||||
|
||||
/// 隐私协议公开路径,对应 `/privacy/{语言}`。
|
||||
const String legalPrivacyPath = 'privacy';
|
||||
|
||||
/// 服务条款公开路径,对应 `/terms/{语言}`。
|
||||
const String legalTermsPath = 'terms';
|
||||
|
||||
const Set<String> _legalLanguages = {'zh', 'en', 'id'};
|
||||
|
||||
/// 界面语言落到协议页支持的三种语言。其余语言用英文。
|
||||
String legalLanguageCode(Locale locale) {
|
||||
final code = locale.languageCode;
|
||||
if (_legalLanguages.contains(code)) return code;
|
||||
return 'en';
|
||||
}
|
||||
|
||||
/// 拼出当前服务器上的协议页地址。
|
||||
String legalPageUrl(String path, Locale locale) {
|
||||
final base = AppConfig.apiBaseUrl;
|
||||
final root = base.endsWith('/') ? base.substring(0, base.length - 1) : base;
|
||||
return '$root/$path/${legalLanguageCode(locale)}';
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../theme/app_colors.dart';
|
||||
import '../widgets/plain_page_scaffold.dart';
|
||||
import 'legal_article_view.dart';
|
||||
import 'legal_html.dart';
|
||||
|
||||
const double _pagePadding = 20;
|
||||
|
||||
/// 在应用内展示协议页,不使用系统 WebView。
|
||||
class LegalWebPage extends StatefulWidget {
|
||||
const LegalWebPage({super.key, required this.url, this.load});
|
||||
|
||||
final String url;
|
||||
|
||||
/// 测试时可替换网络请求。
|
||||
final Future<String> Function(String url)? load;
|
||||
|
||||
@override
|
||||
State<LegalWebPage> createState() => _LegalWebPageState();
|
||||
}
|
||||
|
||||
class _LegalWebPageState extends State<LegalWebPage> {
|
||||
String? _html;
|
||||
var _failed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_html = null;
|
||||
_failed = false;
|
||||
});
|
||||
try {
|
||||
final loader = widget.load ?? fetchLegalArticle;
|
||||
final html = await loader(widget.url);
|
||||
if (!mounted) return;
|
||||
setState(() => _html = html);
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
setState(() => _failed = true);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return PlainPageScaffold(
|
||||
pageKey: const Key('legal-web-page'),
|
||||
backKey: const Key('legal-web-back'),
|
||||
title: '',
|
||||
child: _body(context),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context) {
|
||||
final html = _html;
|
||||
if (html != null) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(_pagePadding, 8, _pagePadding, 28),
|
||||
children: [
|
||||
LegalArticleView(html: html),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_failed) return _failure(context);
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(
|
||||
key: Key('legal-web-loading'),
|
||||
color: AppColors.blue,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _failure(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(l10n.legalOpenFailed, style: const TextStyle(color: AppColors.muted)),
|
||||
TextButton(
|
||||
key: const Key('legal-web-retry'),
|
||||
onPressed: _load,
|
||||
child: Text(l10n.retry),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// 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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,12 +105,16 @@ abstract final class AppColors {
|
||||
static const mineIconSupport = Color(0xFFA78BFA);
|
||||
static const mineIconLanguage = Color(0xFF22D3EE);
|
||||
static const mineIconSettings = Color(0xFFA1A1AA);
|
||||
static const mineIconNotices = Color(0xFFFF8A4C);
|
||||
static const recommendPlaylistGlow = Color(0x26FF6B2C);
|
||||
|
||||
/// 次级文字与列表 chevron。
|
||||
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);
|
||||
|
||||
@@ -187,7 +187,7 @@ abstract final class AppDimens {
|
||||
static const double followingAddIconStroke = 1.5;
|
||||
static const double followingGridGap = 6;
|
||||
static const double followingGridRowGap = 12;
|
||||
static const double followingCardTextExtent = 66;
|
||||
static const double followingCardTextExtent = 70;
|
||||
static const double followingSubtitleFont = 12;
|
||||
static const double followingSubtitleGap = 4;
|
||||
static const double followingProgressHeight = 2;
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../theme/app_colors.dart';
|
||||
import '../theme/app_dimens.dart';
|
||||
|
||||
class DramaGridSkeleton extends StatelessWidget {
|
||||
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 {
|
||||
const DramaGridSkeleton({
|
||||
super.key,
|
||||
required this.columns,
|
||||
@@ -23,61 +32,133 @@ class DramaGridSkeleton extends StatelessWidget {
|
||||
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 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(),
|
||||
),
|
||||
],
|
||||
final grid = _grid(constraints.maxWidth, constraints.maxHeight);
|
||||
return AnimatedBuilder(
|
||||
animation: _shimmer,
|
||||
builder: (context, child) => ShaderMask(
|
||||
blendMode: BlendMode.srcATop,
|
||||
shaderCallback: (bounds) => _shader(bounds),
|
||||
child: child,
|
||||
),
|
||||
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 {
|
||||
|
||||
@@ -115,7 +115,6 @@ class _EmptyCopy extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -126,10 +125,10 @@ class _EmptyCopy extends StatelessWidget {
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: scheme.onSurface,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textTertiary,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontWeight: FontWeight.w400,
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -8,19 +8,27 @@ 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)!;
|
||||
@@ -58,6 +66,17 @@ 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();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../theme/app_colors.dart';
|
||||
import '../theme/app_dimens.dart';
|
||||
|
||||
@@ -71,10 +72,14 @@ 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) {
|
||||
@@ -93,6 +98,18 @@ 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();
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,9 @@ const double _titleFontSize = 18;
|
||||
const double _subtitleFontSize = 12;
|
||||
const double _actionGap = 8;
|
||||
const double _iconSize = 22;
|
||||
const double _backIconSize = 34;
|
||||
const double _iconWeight = 600;
|
||||
const double _backIconWeight = 400;
|
||||
const double _shadowBlur = 8;
|
||||
|
||||
/// 二级页面统一圆形操作按钮,返回、分享和更多共用同一尺寸与表面样式。
|
||||
@@ -24,6 +26,8 @@ class AppSubpageCircleButton extends StatelessWidget {
|
||||
required this.tooltip,
|
||||
required this.icon,
|
||||
required this.onPressed,
|
||||
this.iconSize = _iconSize,
|
||||
this.iconWeight = _iconWeight,
|
||||
this.dark = false,
|
||||
});
|
||||
|
||||
@@ -31,6 +35,8 @@ class AppSubpageCircleButton extends StatelessWidget {
|
||||
final String tooltip;
|
||||
final IconData icon;
|
||||
final VoidCallback onPressed;
|
||||
final double iconSize;
|
||||
final double iconWeight;
|
||||
final bool dark;
|
||||
|
||||
@override
|
||||
@@ -65,8 +71,8 @@ class AppSubpageCircleButton extends StatelessWidget {
|
||||
child: Icon(
|
||||
icon,
|
||||
color: dark ? AppColors.onSurface : AppColors.textPrimary,
|
||||
size: _iconSize,
|
||||
weight: _iconWeight,
|
||||
size: iconSize,
|
||||
weight: iconWeight,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -96,6 +102,8 @@ class AppSubpageBackButton extends StatelessWidget {
|
||||
buttonKey: backKey,
|
||||
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
|
||||
icon: Icons.chevron_left_rounded,
|
||||
iconSize: _backIconSize,
|
||||
iconWeight: _backIconWeight,
|
||||
dark: dark,
|
||||
onPressed: onBack ?? () => Navigator.of(context).maybePop(),
|
||||
);
|
||||
|
||||
+33
-4
@@ -23,6 +23,13 @@
|
||||
"authLandingSubtitle": "Sign in to sync progress, favorites and coins",
|
||||
"comingSoon": "Coming soon",
|
||||
"authLegal": "By continuing, you agree to the Terms of Service and Privacy Policy.",
|
||||
"authLegalLead": "By continuing, you agree to the",
|
||||
"authTerms": "Terms of Service",
|
||||
"authLegalJoin": "and",
|
||||
"authPrivacy": "Privacy Policy",
|
||||
"legalTerms": "Terms of Service",
|
||||
"legalPrivacy": "Privacy Policy",
|
||||
"legalOpenFailed": "Can't open this page right now",
|
||||
"authContinueGoogle": "Continue with Google",
|
||||
"authPhoneSignIn": "Phone sign in",
|
||||
"authEmailSignIn": "Email sign in",
|
||||
@@ -212,6 +219,7 @@
|
||||
"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",
|
||||
@@ -430,6 +438,22 @@
|
||||
"authPasswordLength": "Password must be 8-64 characters",
|
||||
"authPasswordWeak": "Password needs both letters and numbers",
|
||||
"authNetworkError": "Network error, please try again",
|
||||
"authServerError": "The service is busy. Please try again shortly.",
|
||||
"apiErrorBadRequest": "Invalid request",
|
||||
"apiErrorUnauthorized": "Sign in to continue",
|
||||
"apiErrorForbidden": "You don't have permission",
|
||||
"apiErrorNotFound": "Not found",
|
||||
"apiErrorTooManyRequests": "Too many requests. Please try again later.",
|
||||
"apiErrorLoginFailed": "Incorrect account or password",
|
||||
"apiErrorAccountDisabled": "This account has been disabled",
|
||||
"apiErrorCoinNotEnough": "Not enough coins",
|
||||
"apiErrorEpisodeUnavailable": "This episode is unavailable",
|
||||
"apiErrorEpisodeUnlocked": "This episode is already unlocked",
|
||||
"apiErrorOrderInvalid": "This order is already paid or closed",
|
||||
"apiErrorVipExpired": "Membership has expired",
|
||||
"apiErrorDataExists": "This record already exists",
|
||||
"apiErrorDataNotFound": "Not found",
|
||||
"apiErrorNotAllowed": "This action isn't available right now",
|
||||
"authSwitchToSignUp": "New here? Create an account",
|
||||
"authSwitchToSignIn": "Already have an account? Sign in",
|
||||
"authGateTitle": "Sign in to continue",
|
||||
@@ -586,7 +610,7 @@
|
||||
"accountUnverified": "Unverified",
|
||||
"accountDeactivateWarning": "Requests enter a 15-day cooling-off period. All devices are signed out immediately.",
|
||||
"accountDeactivateReason": "Reason (optional)",
|
||||
"accountDeactivateReasonHint": "Tell us why you are leaving",
|
||||
"accountDeactivateReasonHint": "Add more detail here",
|
||||
"accountRequestDeactivate": "Request account deletion",
|
||||
"accountConfirmDeactivateTitle": "Request account deletion?",
|
||||
"accountConfirmDeactivateMessage": "All devices will be signed out immediately. You can cancel during the 15-day cooling-off period after signing in again.",
|
||||
@@ -666,6 +690,8 @@
|
||||
"paymentPending": "Waiting for payment.",
|
||||
"orderCreateFailed": "Could not create the order.",
|
||||
"playbackQuality": "Quality",
|
||||
"qualitySwitched": "Switched to {quality}",
|
||||
"@qualitySwitched": { "placeholders": { "quality": { "type": "String" } } },
|
||||
"qualityAuto": "Auto",
|
||||
"qualityAutoHint": "HLS adjusts the bitrate automatically for your connection.",
|
||||
"searchFailed": "Search failed. Please try again.",
|
||||
@@ -708,8 +734,7 @@
|
||||
"homeBadgeHot": "Hot",
|
||||
"homeBadgeNew": "New",
|
||||
"homeBadgeAnime": "Anime",
|
||||
"homeGridFilterEmpty": "No dramas match these filters",
|
||||
"homeGridClearFilter": "Clear filters",
|
||||
"emptyContent": "No content yet",
|
||||
"recommendTopTab": "Recommend",
|
||||
"playlistTopTab": "Playlists",
|
||||
"allDramasTopTab": "All Dramas",
|
||||
@@ -728,6 +753,10 @@
|
||||
"modernFilter": "Modern",
|
||||
"edit": "Edit",
|
||||
"done": "Done",
|
||||
"selectAll": "Select all",
|
||||
"deselectAll": "Deselect all",
|
||||
"cancelFollowing": "Unfollow",
|
||||
"confirmCancelFollowing": "Unfollow the selected dramas?",
|
||||
"visitor": "Visitor",
|
||||
"copyUid": "Copy UID",
|
||||
"uidCopied": "UID copied",
|
||||
@@ -746,7 +775,7 @@
|
||||
"watchedToEpisode": "Watched to Episode {episode}",
|
||||
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
|
||||
"homeWatchAll": "Watch all",
|
||||
"confirmRemove": "Remove this item?",
|
||||
"confirmRemove": "Remove this watch history?",
|
||||
"followingCountLabel": "Following",
|
||||
"watchRecordsCountLabel": "Watch records",
|
||||
"dataUnavailable": "—",
|
||||
|
||||
+33
-4
@@ -23,6 +23,13 @@
|
||||
"authLandingSubtitle": "Masuk untuk menyinkronkan progres, favorit, dan koin",
|
||||
"comingSoon": "Segera hadir",
|
||||
"authLegal": "Dengan melanjutkan, Anda menyetujui Ketentuan Layanan dan Kebijakan Privasi.",
|
||||
"authLegalLead": "Dengan melanjutkan, Anda menyetujui",
|
||||
"authTerms": "Ketentuan Layanan",
|
||||
"authLegalJoin": "dan",
|
||||
"authPrivacy": "Kebijakan Privasi",
|
||||
"legalTerms": "Ketentuan Layanan",
|
||||
"legalPrivacy": "Kebijakan Privasi",
|
||||
"legalOpenFailed": "Halaman ini belum bisa dibuka",
|
||||
"authContinueGoogle": "Lanjutkan dengan Google",
|
||||
"authPhoneSignIn": "Masuk dengan ponsel",
|
||||
"authEmailSignIn": "Masuk dengan email",
|
||||
@@ -186,6 +193,7 @@
|
||||
"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",
|
||||
@@ -404,6 +412,22 @@
|
||||
"authPasswordLength": "Kata sandi harus 8-64 karakter",
|
||||
"authPasswordWeak": "Kata sandi perlu huruf dan angka",
|
||||
"authNetworkError": "Jaringan bermasalah, coba lagi",
|
||||
"authServerError": "Layanan sedang sibuk. Coba lagi sebentar.",
|
||||
"apiErrorBadRequest": "Permintaan tidak valid",
|
||||
"apiErrorUnauthorized": "Masuk untuk melanjutkan",
|
||||
"apiErrorForbidden": "Anda tidak memiliki izin",
|
||||
"apiErrorNotFound": "Tidak ditemukan",
|
||||
"apiErrorTooManyRequests": "Terlalu banyak permintaan. Coba lagi nanti.",
|
||||
"apiErrorLoginFailed": "Akun atau kata sandi salah",
|
||||
"apiErrorAccountDisabled": "Akun ini telah dinonaktifkan",
|
||||
"apiErrorCoinNotEnough": "Koin tidak cukup",
|
||||
"apiErrorEpisodeUnavailable": "Episode ini tidak tersedia",
|
||||
"apiErrorEpisodeUnlocked": "Episode ini sudah terbuka",
|
||||
"apiErrorOrderInvalid": "Pesanan ini sudah dibayar atau ditutup",
|
||||
"apiErrorVipExpired": "Keanggotaan telah berakhir",
|
||||
"apiErrorDataExists": "Data sudah ada",
|
||||
"apiErrorDataNotFound": "Data tidak ditemukan",
|
||||
"apiErrorNotAllowed": "Tindakan ini tidak tersedia saat ini",
|
||||
"authSwitchToSignUp": "Baru di sini? Buat akun",
|
||||
"authSwitchToSignIn": "Sudah punya akun? Masuk",
|
||||
"authGateTitle": "Masuk untuk melanjutkan",
|
||||
@@ -550,7 +574,7 @@
|
||||
"accountUnverified": "Belum terverifikasi",
|
||||
"accountDeactivateWarning": "Permintaan masuk masa tenang 15 hari. Semua perangkat langsung keluar.",
|
||||
"accountDeactivateReason": "Alasan (opsional)",
|
||||
"accountDeactivateReasonHint": "Beri tahu alasan kamu",
|
||||
"accountDeactivateReasonHint": "Tambahkan penjelasan di sini",
|
||||
"accountRequestDeactivate": "Ajukan penghapusan akun",
|
||||
"accountConfirmDeactivateTitle": "Ajukan penghapusan akun?",
|
||||
"accountConfirmDeactivateMessage": "Semua perangkat akan langsung keluar. Setelah masuk lagi, kamu dapat membatalkannya selama masa tenang 15 hari.",
|
||||
@@ -623,6 +647,8 @@
|
||||
"paymentPending": "Menunggu pembayaran.",
|
||||
"orderCreateFailed": "Gagal membuat pesanan.",
|
||||
"playbackQuality": "Kualitas",
|
||||
"qualitySwitched": "Beralih ke {quality}",
|
||||
"@qualitySwitched": { "placeholders": { "quality": { "type": "String" } } },
|
||||
"qualityAuto": "Otomatis",
|
||||
"qualityAutoHint": "HLS menyesuaikan bitrate secara otomatis dengan koneksi Anda.",
|
||||
"searchFailed": "Pencarian gagal. Coba lagi.",
|
||||
@@ -665,8 +691,7 @@
|
||||
"homeBadgeHot": "Populer",
|
||||
"homeBadgeNew": "Baru",
|
||||
"homeBadgeAnime": "Anime",
|
||||
"homeGridFilterEmpty": "Tidak ada drama yang cocok dengan filter",
|
||||
"homeGridClearFilter": "Hapus filter",
|
||||
"emptyContent": "Belum ada konten",
|
||||
"recommendTopTab": "Rekomendasi",
|
||||
"playlistTopTab": "Daftar Putar",
|
||||
"allDramasTopTab": "Semua",
|
||||
@@ -685,6 +710,10 @@
|
||||
"modernFilter": "Modern",
|
||||
"edit": "Edit",
|
||||
"done": "Selesai",
|
||||
"selectAll": "Pilih semua",
|
||||
"deselectAll": "Batal pilih",
|
||||
"cancelFollowing": "Berhenti mengikuti",
|
||||
"confirmCancelFollowing": "Berhenti mengikuti drama yang dipilih?",
|
||||
"visitor": "Pengunjung",
|
||||
"copyUid": "Salin UID",
|
||||
"uidCopied": "UID disalin",
|
||||
@@ -703,7 +732,7 @@
|
||||
"watchedToEpisode": "Ditonton hingga Episode {episode}",
|
||||
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
|
||||
"homeWatchAll": "Tonton semua",
|
||||
"confirmRemove": "Hapus item ini?",
|
||||
"confirmRemove": "Hapus riwayat tontonan ini?",
|
||||
"followingCountLabel": "Mengikuti",
|
||||
"watchRecordsCountLabel": "Riwayat tontonan",
|
||||
"dataUnavailable": "—",
|
||||
|
||||
+179
-11
@@ -238,6 +238,48 @@ abstract class AppLocalizations {
|
||||
/// **'By continuing, you agree to the Terms of Service and Privacy Policy.'**
|
||||
String get authLegal;
|
||||
|
||||
/// No description provided for @authLegalLead.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'By continuing, you agree to the'**
|
||||
String get authLegalLead;
|
||||
|
||||
/// No description provided for @authTerms.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Terms of Service'**
|
||||
String get authTerms;
|
||||
|
||||
/// No description provided for @authLegalJoin.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'and'**
|
||||
String get authLegalJoin;
|
||||
|
||||
/// No description provided for @authPrivacy.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Privacy Policy'**
|
||||
String get authPrivacy;
|
||||
|
||||
/// No description provided for @legalTerms.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Terms of Service'**
|
||||
String get legalTerms;
|
||||
|
||||
/// No description provided for @legalPrivacy.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Privacy Policy'**
|
||||
String get legalPrivacy;
|
||||
|
||||
/// No description provided for @legalOpenFailed.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Can\'t open this page right now'**
|
||||
String get legalOpenFailed;
|
||||
|
||||
/// No description provided for @authContinueGoogle.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -952,6 +994,12 @@ 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:
|
||||
@@ -1858,6 +1906,102 @@ abstract class AppLocalizations {
|
||||
/// **'Network error, please try again'**
|
||||
String get authNetworkError;
|
||||
|
||||
/// No description provided for @authServerError.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'The service is busy. Please try again shortly.'**
|
||||
String get authServerError;
|
||||
|
||||
/// No description provided for @apiErrorBadRequest.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Invalid request'**
|
||||
String get apiErrorBadRequest;
|
||||
|
||||
/// No description provided for @apiErrorUnauthorized.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Sign in to continue'**
|
||||
String get apiErrorUnauthorized;
|
||||
|
||||
/// No description provided for @apiErrorForbidden.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'You don\'t have permission'**
|
||||
String get apiErrorForbidden;
|
||||
|
||||
/// No description provided for @apiErrorNotFound.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Not found'**
|
||||
String get apiErrorNotFound;
|
||||
|
||||
/// No description provided for @apiErrorTooManyRequests.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Too many requests. Please try again later.'**
|
||||
String get apiErrorTooManyRequests;
|
||||
|
||||
/// No description provided for @apiErrorLoginFailed.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Incorrect account or password'**
|
||||
String get apiErrorLoginFailed;
|
||||
|
||||
/// No description provided for @apiErrorAccountDisabled.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'This account has been disabled'**
|
||||
String get apiErrorAccountDisabled;
|
||||
|
||||
/// No description provided for @apiErrorCoinNotEnough.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Not enough coins'**
|
||||
String get apiErrorCoinNotEnough;
|
||||
|
||||
/// No description provided for @apiErrorEpisodeUnavailable.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'This episode is unavailable'**
|
||||
String get apiErrorEpisodeUnavailable;
|
||||
|
||||
/// No description provided for @apiErrorEpisodeUnlocked.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'This episode is already unlocked'**
|
||||
String get apiErrorEpisodeUnlocked;
|
||||
|
||||
/// No description provided for @apiErrorOrderInvalid.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'This order is already paid or closed'**
|
||||
String get apiErrorOrderInvalid;
|
||||
|
||||
/// No description provided for @apiErrorVipExpired.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Membership has expired'**
|
||||
String get apiErrorVipExpired;
|
||||
|
||||
/// No description provided for @apiErrorDataExists.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'This record already exists'**
|
||||
String get apiErrorDataExists;
|
||||
|
||||
/// No description provided for @apiErrorDataNotFound.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Not found'**
|
||||
String get apiErrorDataNotFound;
|
||||
|
||||
/// No description provided for @apiErrorNotAllowed.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'This action isn\'t available right now'**
|
||||
String get apiErrorNotAllowed;
|
||||
|
||||
/// No description provided for @authSwitchToSignUp.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -2437,7 +2581,7 @@ abstract class AppLocalizations {
|
||||
/// No description provided for @accountDeactivateReasonHint.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Tell us why you are leaving'**
|
||||
/// **'Add more detail here'**
|
||||
String get accountDeactivateReasonHint;
|
||||
|
||||
/// No description provided for @accountRequestDeactivate.
|
||||
@@ -2824,6 +2968,12 @@ abstract class AppLocalizations {
|
||||
/// **'Quality'**
|
||||
String get playbackQuality;
|
||||
|
||||
/// No description provided for @qualitySwitched.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Switched to {quality}'**
|
||||
String qualitySwitched(String quality);
|
||||
|
||||
/// No description provided for @qualityAuto.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -3058,17 +3208,11 @@ abstract class AppLocalizations {
|
||||
/// **'Anime'**
|
||||
String get homeBadgeAnime;
|
||||
|
||||
/// No description provided for @homeGridFilterEmpty.
|
||||
/// No description provided for @emptyContent.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'No dramas match these filters'**
|
||||
String get homeGridFilterEmpty;
|
||||
|
||||
/// No description provided for @homeGridClearFilter.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Clear filters'**
|
||||
String get homeGridClearFilter;
|
||||
/// **'No content yet'**
|
||||
String get emptyContent;
|
||||
|
||||
/// No description provided for @recommendTopTab.
|
||||
///
|
||||
@@ -3178,6 +3322,30 @@ abstract class AppLocalizations {
|
||||
/// **'Done'**
|
||||
String get done;
|
||||
|
||||
/// No description provided for @selectAll.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Select all'**
|
||||
String get selectAll;
|
||||
|
||||
/// No description provided for @deselectAll.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Deselect all'**
|
||||
String get deselectAll;
|
||||
|
||||
/// No description provided for @cancelFollowing.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Unfollow'**
|
||||
String get cancelFollowing;
|
||||
|
||||
/// No description provided for @confirmCancelFollowing.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Unfollow the selected dramas?'**
|
||||
String get confirmCancelFollowing;
|
||||
|
||||
/// No description provided for @visitor.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
@@ -3247,7 +3415,7 @@ abstract class AppLocalizations {
|
||||
/// No description provided for @confirmRemove.
|
||||
///
|
||||
/// In en, this message translates to:
|
||||
/// **'Remove this item?'**
|
||||
/// **'Remove this watch history?'**
|
||||
String get confirmRemove;
|
||||
|
||||
/// No description provided for @followingCountLabel.
|
||||
|
||||
@@ -80,6 +80,27 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
String get authLegal =>
|
||||
'By continuing, you agree to the Terms of Service and Privacy Policy.';
|
||||
|
||||
@override
|
||||
String get authLegalLead => 'By continuing, you agree to the';
|
||||
|
||||
@override
|
||||
String get authTerms => 'Terms of Service';
|
||||
|
||||
@override
|
||||
String get authLegalJoin => 'and';
|
||||
|
||||
@override
|
||||
String get authPrivacy => 'Privacy Policy';
|
||||
|
||||
@override
|
||||
String get legalTerms => 'Terms of Service';
|
||||
|
||||
@override
|
||||
String get legalPrivacy => 'Privacy Policy';
|
||||
|
||||
@override
|
||||
String get legalOpenFailed => 'Can\'t open this page right now';
|
||||
|
||||
@override
|
||||
String get authContinueGoogle => 'Continue with Google';
|
||||
|
||||
@@ -465,6 +486,9 @@ 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.';
|
||||
|
||||
@@ -943,6 +967,56 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get authNetworkError => 'Network error, please try again';
|
||||
|
||||
@override
|
||||
String get authServerError =>
|
||||
'The service is busy. Please try again shortly.';
|
||||
|
||||
@override
|
||||
String get apiErrorBadRequest => 'Invalid request';
|
||||
|
||||
@override
|
||||
String get apiErrorUnauthorized => 'Sign in to continue';
|
||||
|
||||
@override
|
||||
String get apiErrorForbidden => 'You don\'t have permission';
|
||||
|
||||
@override
|
||||
String get apiErrorNotFound => 'Not found';
|
||||
|
||||
@override
|
||||
String get apiErrorTooManyRequests =>
|
||||
'Too many requests. Please try again later.';
|
||||
|
||||
@override
|
||||
String get apiErrorLoginFailed => 'Incorrect account or password';
|
||||
|
||||
@override
|
||||
String get apiErrorAccountDisabled => 'This account has been disabled';
|
||||
|
||||
@override
|
||||
String get apiErrorCoinNotEnough => 'Not enough coins';
|
||||
|
||||
@override
|
||||
String get apiErrorEpisodeUnavailable => 'This episode is unavailable';
|
||||
|
||||
@override
|
||||
String get apiErrorEpisodeUnlocked => 'This episode is already unlocked';
|
||||
|
||||
@override
|
||||
String get apiErrorOrderInvalid => 'This order is already paid or closed';
|
||||
|
||||
@override
|
||||
String get apiErrorVipExpired => 'Membership has expired';
|
||||
|
||||
@override
|
||||
String get apiErrorDataExists => 'This record already exists';
|
||||
|
||||
@override
|
||||
String get apiErrorDataNotFound => 'Not found';
|
||||
|
||||
@override
|
||||
String get apiErrorNotAllowed => 'This action isn\'t available right now';
|
||||
|
||||
@override
|
||||
String get authSwitchToSignUp => 'New here? Create an account';
|
||||
|
||||
@@ -1262,7 +1336,7 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
String get accountDeactivateReason => 'Reason (optional)';
|
||||
|
||||
@override
|
||||
String get accountDeactivateReasonHint => 'Tell us why you are leaving';
|
||||
String get accountDeactivateReasonHint => 'Add more detail here';
|
||||
|
||||
@override
|
||||
String get accountRequestDeactivate => 'Request account deletion';
|
||||
@@ -1472,6 +1546,11 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get playbackQuality => 'Quality';
|
||||
|
||||
@override
|
||||
String qualitySwitched(String quality) {
|
||||
return 'Switched to $quality';
|
||||
}
|
||||
|
||||
@override
|
||||
String get qualityAuto => 'Auto';
|
||||
|
||||
@@ -1597,10 +1676,7 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
String get homeBadgeAnime => 'Anime';
|
||||
|
||||
@override
|
||||
String get homeGridFilterEmpty => 'No dramas match these filters';
|
||||
|
||||
@override
|
||||
String get homeGridClearFilter => 'Clear filters';
|
||||
String get emptyContent => 'No content yet';
|
||||
|
||||
@override
|
||||
String get recommendTopTab => 'Recommend';
|
||||
@@ -1656,6 +1732,18 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
@override
|
||||
String get done => 'Done';
|
||||
|
||||
@override
|
||||
String get selectAll => 'Select all';
|
||||
|
||||
@override
|
||||
String get deselectAll => 'Deselect all';
|
||||
|
||||
@override
|
||||
String get cancelFollowing => 'Unfollow';
|
||||
|
||||
@override
|
||||
String get confirmCancelFollowing => 'Unfollow the selected dramas?';
|
||||
|
||||
@override
|
||||
String get visitor => 'Visitor';
|
||||
|
||||
@@ -1694,7 +1782,7 @@ class AppLocalizationsEn extends AppLocalizations {
|
||||
String get homeWatchAll => 'Watch all';
|
||||
|
||||
@override
|
||||
String get confirmRemove => 'Remove this item?';
|
||||
String get confirmRemove => 'Remove this watch history?';
|
||||
|
||||
@override
|
||||
String get followingCountLabel => 'Following';
|
||||
|
||||
@@ -80,6 +80,27 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get authLegal =>
|
||||
'Dengan melanjutkan, Anda menyetujui Ketentuan Layanan dan Kebijakan Privasi.';
|
||||
|
||||
@override
|
||||
String get authLegalLead => 'Dengan melanjutkan, Anda menyetujui';
|
||||
|
||||
@override
|
||||
String get authTerms => 'Ketentuan Layanan';
|
||||
|
||||
@override
|
||||
String get authLegalJoin => 'dan';
|
||||
|
||||
@override
|
||||
String get authPrivacy => 'Kebijakan Privasi';
|
||||
|
||||
@override
|
||||
String get legalTerms => 'Ketentuan Layanan';
|
||||
|
||||
@override
|
||||
String get legalPrivacy => 'Kebijakan Privasi';
|
||||
|
||||
@override
|
||||
String get legalOpenFailed => 'Halaman ini belum bisa dibuka';
|
||||
|
||||
@override
|
||||
String get authContinueGoogle => 'Lanjutkan dengan Google';
|
||||
|
||||
@@ -466,6 +487,9 @@ 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.';
|
||||
|
||||
@@ -947,6 +971,55 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get authNetworkError => 'Jaringan bermasalah, coba lagi';
|
||||
|
||||
@override
|
||||
String get authServerError => 'Layanan sedang sibuk. Coba lagi sebentar.';
|
||||
|
||||
@override
|
||||
String get apiErrorBadRequest => 'Permintaan tidak valid';
|
||||
|
||||
@override
|
||||
String get apiErrorUnauthorized => 'Masuk untuk melanjutkan';
|
||||
|
||||
@override
|
||||
String get apiErrorForbidden => 'Anda tidak memiliki izin';
|
||||
|
||||
@override
|
||||
String get apiErrorNotFound => 'Tidak ditemukan';
|
||||
|
||||
@override
|
||||
String get apiErrorTooManyRequests =>
|
||||
'Terlalu banyak permintaan. Coba lagi nanti.';
|
||||
|
||||
@override
|
||||
String get apiErrorLoginFailed => 'Akun atau kata sandi salah';
|
||||
|
||||
@override
|
||||
String get apiErrorAccountDisabled => 'Akun ini telah dinonaktifkan';
|
||||
|
||||
@override
|
||||
String get apiErrorCoinNotEnough => 'Koin tidak cukup';
|
||||
|
||||
@override
|
||||
String get apiErrorEpisodeUnavailable => 'Episode ini tidak tersedia';
|
||||
|
||||
@override
|
||||
String get apiErrorEpisodeUnlocked => 'Episode ini sudah terbuka';
|
||||
|
||||
@override
|
||||
String get apiErrorOrderInvalid => 'Pesanan ini sudah dibayar atau ditutup';
|
||||
|
||||
@override
|
||||
String get apiErrorVipExpired => 'Keanggotaan telah berakhir';
|
||||
|
||||
@override
|
||||
String get apiErrorDataExists => 'Data sudah ada';
|
||||
|
||||
@override
|
||||
String get apiErrorDataNotFound => 'Data tidak ditemukan';
|
||||
|
||||
@override
|
||||
String get apiErrorNotAllowed => 'Tindakan ini tidak tersedia saat ini';
|
||||
|
||||
@override
|
||||
String get authSwitchToSignUp => 'Baru di sini? Buat akun';
|
||||
|
||||
@@ -1262,7 +1335,7 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get accountDeactivateReason => 'Alasan (opsional)';
|
||||
|
||||
@override
|
||||
String get accountDeactivateReasonHint => 'Beri tahu alasan kamu';
|
||||
String get accountDeactivateReasonHint => 'Tambahkan penjelasan di sini';
|
||||
|
||||
@override
|
||||
String get accountRequestDeactivate => 'Ajukan penghapusan akun';
|
||||
@@ -1472,6 +1545,11 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get playbackQuality => 'Kualitas';
|
||||
|
||||
@override
|
||||
String qualitySwitched(String quality) {
|
||||
return 'Beralih ke $quality';
|
||||
}
|
||||
|
||||
@override
|
||||
String get qualityAuto => 'Otomatis';
|
||||
|
||||
@@ -1598,10 +1676,7 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get homeBadgeAnime => 'Anime';
|
||||
|
||||
@override
|
||||
String get homeGridFilterEmpty => 'Tidak ada drama yang cocok dengan filter';
|
||||
|
||||
@override
|
||||
String get homeGridClearFilter => 'Hapus filter';
|
||||
String get emptyContent => 'Belum ada konten';
|
||||
|
||||
@override
|
||||
String get recommendTopTab => 'Rekomendasi';
|
||||
@@ -1659,6 +1734,18 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
@override
|
||||
String get done => 'Selesai';
|
||||
|
||||
@override
|
||||
String get selectAll => 'Pilih semua';
|
||||
|
||||
@override
|
||||
String get deselectAll => 'Batal pilih';
|
||||
|
||||
@override
|
||||
String get cancelFollowing => 'Berhenti mengikuti';
|
||||
|
||||
@override
|
||||
String get confirmCancelFollowing => 'Berhenti mengikuti drama yang dipilih?';
|
||||
|
||||
@override
|
||||
String get visitor => 'Pengunjung';
|
||||
|
||||
@@ -1697,7 +1784,7 @@ class AppLocalizationsId extends AppLocalizations {
|
||||
String get homeWatchAll => 'Tonton semua';
|
||||
|
||||
@override
|
||||
String get confirmRemove => 'Hapus item ini?';
|
||||
String get confirmRemove => 'Hapus riwayat tontonan ini?';
|
||||
|
||||
@override
|
||||
String get followingCountLabel => 'Mengikuti';
|
||||
|
||||
@@ -77,6 +77,27 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get authLegal => '继续即代表同意《用户协议》与《隐私政策》';
|
||||
|
||||
@override
|
||||
String get authLegalLead => '继续即代表同意';
|
||||
|
||||
@override
|
||||
String get authTerms => '《用户协议》';
|
||||
|
||||
@override
|
||||
String get authLegalJoin => '与';
|
||||
|
||||
@override
|
||||
String get authPrivacy => '《隐私政策》';
|
||||
|
||||
@override
|
||||
String get legalTerms => '服务条款';
|
||||
|
||||
@override
|
||||
String get legalPrivacy => '隐私协议';
|
||||
|
||||
@override
|
||||
String get legalOpenFailed => '暂时无法打开协议页面';
|
||||
|
||||
@override
|
||||
String get authContinueGoogle => '使用 Google 继续';
|
||||
|
||||
@@ -460,6 +481,9 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get loadMore => '加载更多';
|
||||
|
||||
@override
|
||||
String get noMoreItems => '没有更多了';
|
||||
|
||||
@override
|
||||
String get commentsLoadFailed => '评论加载失败,请重试。';
|
||||
|
||||
@@ -931,6 +955,54 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get authNetworkError => '网络异常,请稍后重试';
|
||||
|
||||
@override
|
||||
String get authServerError => '服务繁忙,请稍后再试';
|
||||
|
||||
@override
|
||||
String get apiErrorBadRequest => '参数校验失败';
|
||||
|
||||
@override
|
||||
String get apiErrorUnauthorized => '未登录或登录已过期';
|
||||
|
||||
@override
|
||||
String get apiErrorForbidden => '无权限';
|
||||
|
||||
@override
|
||||
String get apiErrorNotFound => '资源不存在';
|
||||
|
||||
@override
|
||||
String get apiErrorTooManyRequests => '请求过于频繁,请稍后再试';
|
||||
|
||||
@override
|
||||
String get apiErrorLoginFailed => '账号或密码错误';
|
||||
|
||||
@override
|
||||
String get apiErrorAccountDisabled => '账号已停用';
|
||||
|
||||
@override
|
||||
String get apiErrorCoinNotEnough => '金币余额不足';
|
||||
|
||||
@override
|
||||
String get apiErrorEpisodeUnavailable => '剧集未发布或不存在';
|
||||
|
||||
@override
|
||||
String get apiErrorEpisodeUnlocked => '剧集已解锁';
|
||||
|
||||
@override
|
||||
String get apiErrorOrderInvalid => '订单已支付或已关闭';
|
||||
|
||||
@override
|
||||
String get apiErrorVipExpired => '会员已过期';
|
||||
|
||||
@override
|
||||
String get apiErrorDataExists => '数据已存在';
|
||||
|
||||
@override
|
||||
String get apiErrorDataNotFound => '数据不存在';
|
||||
|
||||
@override
|
||||
String get apiErrorNotAllowed => '当前状态不允许该操作';
|
||||
|
||||
@override
|
||||
String get authSwitchToSignUp => '还没有账号?去注册';
|
||||
|
||||
@@ -1240,7 +1312,7 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
String get accountDeactivateReason => '注销原因(选填)';
|
||||
|
||||
@override
|
||||
String get accountDeactivateReasonHint => '告诉我们你离开的原因';
|
||||
String get accountDeactivateReasonHint => '也可以在这里补充说明';
|
||||
|
||||
@override
|
||||
String get accountRequestDeactivate => '申请注销账号';
|
||||
@@ -1449,6 +1521,11 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get playbackQuality => '清晰度';
|
||||
|
||||
@override
|
||||
String qualitySwitched(String quality) {
|
||||
return '已切换至$quality';
|
||||
}
|
||||
|
||||
@override
|
||||
String get qualityAuto => '自动';
|
||||
|
||||
@@ -1573,10 +1650,7 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
String get homeBadgeAnime => '漫剧';
|
||||
|
||||
@override
|
||||
String get homeGridFilterEmpty => '没有符合筛选条件的短剧';
|
||||
|
||||
@override
|
||||
String get homeGridClearFilter => '清除筛选';
|
||||
String get emptyContent => '暂无内容';
|
||||
|
||||
@override
|
||||
String get recommendTopTab => '推荐';
|
||||
@@ -1632,6 +1706,18 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
@override
|
||||
String get done => '完成';
|
||||
|
||||
@override
|
||||
String get selectAll => '全选';
|
||||
|
||||
@override
|
||||
String get deselectAll => '取消全选';
|
||||
|
||||
@override
|
||||
String get cancelFollowing => '取消追剧';
|
||||
|
||||
@override
|
||||
String get confirmCancelFollowing => '确定取消已选短剧的追剧吗?';
|
||||
|
||||
@override
|
||||
String get visitor => '访客';
|
||||
|
||||
@@ -1670,7 +1756,7 @@ class AppLocalizationsZh extends AppLocalizations {
|
||||
String get homeWatchAll => '观看全集';
|
||||
|
||||
@override
|
||||
String get confirmRemove => '确定移除这条内容吗?';
|
||||
String get confirmRemove => '确定要移除该条观看记录吗?';
|
||||
|
||||
@override
|
||||
String get followingCountLabel => '追剧数';
|
||||
|
||||
+33
-4
@@ -23,6 +23,13 @@
|
||||
"authLandingSubtitle": "登录后同步进度、收藏与金币权益",
|
||||
"comingSoon": "即将上线",
|
||||
"authLegal": "继续即代表同意《用户协议》与《隐私政策》",
|
||||
"authLegalLead": "继续即代表同意",
|
||||
"authTerms": "《用户协议》",
|
||||
"authLegalJoin": "与",
|
||||
"authPrivacy": "《隐私政策》",
|
||||
"legalTerms": "服务条款",
|
||||
"legalPrivacy": "隐私协议",
|
||||
"legalOpenFailed": "暂时无法打开协议页面",
|
||||
"authContinueGoogle": "使用 Google 继续",
|
||||
"authPhoneSignIn": "手机号登录",
|
||||
"authEmailSignIn": "邮箱登录",
|
||||
@@ -186,6 +193,7 @@
|
||||
"postComment": "发布",
|
||||
"commentPostSuccess": "发表成功",
|
||||
"loadMore": "加载更多",
|
||||
"noMoreItems": "没有更多了",
|
||||
"commentsLoadFailed": "评论加载失败,请重试。",
|
||||
"commentPostFailed": "评论发布失败,请重试。",
|
||||
"delete": "删除",
|
||||
@@ -366,6 +374,22 @@
|
||||
"authPasswordLength": "密码长度需在 8-64 位之间",
|
||||
"authPasswordWeak": "密码需同时包含字母和数字",
|
||||
"authNetworkError": "网络异常,请稍后重试",
|
||||
"authServerError": "服务繁忙,请稍后再试",
|
||||
"apiErrorBadRequest": "参数校验失败",
|
||||
"apiErrorUnauthorized": "未登录或登录已过期",
|
||||
"apiErrorForbidden": "无权限",
|
||||
"apiErrorNotFound": "资源不存在",
|
||||
"apiErrorTooManyRequests": "请求过于频繁,请稍后再试",
|
||||
"apiErrorLoginFailed": "账号或密码错误",
|
||||
"apiErrorAccountDisabled": "账号已停用",
|
||||
"apiErrorCoinNotEnough": "金币余额不足",
|
||||
"apiErrorEpisodeUnavailable": "剧集未发布或不存在",
|
||||
"apiErrorEpisodeUnlocked": "剧集已解锁",
|
||||
"apiErrorOrderInvalid": "订单已支付或已关闭",
|
||||
"apiErrorVipExpired": "会员已过期",
|
||||
"apiErrorDataExists": "数据已存在",
|
||||
"apiErrorDataNotFound": "数据不存在",
|
||||
"apiErrorNotAllowed": "当前状态不允许该操作",
|
||||
"authSwitchToSignUp": "还没有账号?去注册",
|
||||
"authSwitchToSignIn": "已有账号?去登录",
|
||||
"authGateTitle": "登录后可继续",
|
||||
@@ -512,7 +536,7 @@
|
||||
"accountUnverified": "未验证",
|
||||
"accountDeactivateWarning": "提交后进入 15 天冷静期,所有设备会立即退出登录。",
|
||||
"accountDeactivateReason": "注销原因(选填)",
|
||||
"accountDeactivateReasonHint": "告诉我们你离开的原因",
|
||||
"accountDeactivateReasonHint": "也可以在这里补充说明",
|
||||
"accountRequestDeactivate": "申请注销账号",
|
||||
"accountConfirmDeactivateTitle": "确认申请注销?",
|
||||
"accountConfirmDeactivateMessage": "所有设备会立即退出登录。重新登录后,可在 15 天冷静期内撤销申请。",
|
||||
@@ -585,6 +609,8 @@
|
||||
"paymentPending": "等待支付。",
|
||||
"orderCreateFailed": "订单创建失败。",
|
||||
"playbackQuality": "清晰度",
|
||||
"qualitySwitched": "已切换至{quality}",
|
||||
"@qualitySwitched": { "placeholders": { "quality": { "type": "String" } } },
|
||||
"qualityAuto": "自动",
|
||||
"qualityAutoHint": "HLS 会根据当前网络自动切换码率。",
|
||||
"searchFailed": "搜索失败,请重试。",
|
||||
@@ -627,8 +653,7 @@
|
||||
"homeBadgeHot": "热剧",
|
||||
"homeBadgeNew": "新剧",
|
||||
"homeBadgeAnime": "漫剧",
|
||||
"homeGridFilterEmpty": "没有符合筛选条件的短剧",
|
||||
"homeGridClearFilter": "清除筛选",
|
||||
"emptyContent": "暂无内容",
|
||||
"recommendTopTab": "推荐",
|
||||
"playlistTopTab": "剧单",
|
||||
"allDramasTopTab": "全部短剧",
|
||||
@@ -647,6 +672,10 @@
|
||||
"modernFilter": "现代",
|
||||
"edit": "编辑",
|
||||
"done": "完成",
|
||||
"selectAll": "全选",
|
||||
"deselectAll": "取消全选",
|
||||
"cancelFollowing": "取消追剧",
|
||||
"confirmCancelFollowing": "确定取消已选短剧的追剧吗?",
|
||||
"visitor": "访客",
|
||||
"copyUid": "复制 UID",
|
||||
"uidCopied": "UID 已复制",
|
||||
@@ -665,7 +694,7 @@
|
||||
"watchedToEpisode": "已看至 第 {episode} 集",
|
||||
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
|
||||
"homeWatchAll": "观看全集",
|
||||
"confirmRemove": "确定移除这条内容吗?",
|
||||
"confirmRemove": "确定要移除该条观看记录吗?",
|
||||
"followingCountLabel": "追剧数",
|
||||
"watchRecordsCountLabel": "观看记录",
|
||||
"dataUnavailable": "—",
|
||||
|
||||
+5
-1
@@ -2,17 +2,21 @@
|
||||
|
||||
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 = AppConfig.probeAndApplyBaseUrl();
|
||||
AppConfig.ready = WirelessDataPrompt.awaitDecision(
|
||||
enabled: !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS,
|
||||
).then((_) => AppConfig.probeAndApplyBaseUrl());
|
||||
runApp(const LumaDramaApp());
|
||||
unawaited(
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
|
||||
|
||||
@@ -119,7 +119,10 @@ 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,
|
||||
),
|
||||
|
||||
@@ -10,132 +10,119 @@ import 'account_devices_page.dart';
|
||||
import 'account_export_page.dart';
|
||||
import 'account_profile_page.dart';
|
||||
|
||||
const _accountTitleWidth = 64.0;
|
||||
|
||||
/// 我的页账号入口卡;只在登录态由父页面展示。
|
||||
/// 设置页账号入口,登录后按列表展示。
|
||||
class AccountEntryCard extends StatelessWidget {
|
||||
const AccountEntryCard({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final rows = <_AccountRow>[
|
||||
_AccountRow(
|
||||
key: const Key('mine-account-profile'),
|
||||
icon: Icons.person_outline_rounded,
|
||||
title: l10n.accountProfile,
|
||||
page: const AccountProfilePage(),
|
||||
),
|
||||
_AccountRow(
|
||||
key: const Key('mine-account-devices'),
|
||||
icon: Icons.devices_other_rounded,
|
||||
title: l10n.accountDevices,
|
||||
page: const AccountDevicesPage(),
|
||||
),
|
||||
_AccountRow(
|
||||
key: const Key('mine-account-export'),
|
||||
icon: Icons.file_download_outlined,
|
||||
title: l10n.accountDataExport,
|
||||
page: const AccountExportPage(),
|
||||
),
|
||||
_AccountRow(
|
||||
key: const Key('mine-account-deactivate'),
|
||||
icon: Icons.person_remove_outlined,
|
||||
title: l10n.accountDeactivate,
|
||||
page: const AccountDeactivatePage(),
|
||||
),
|
||||
];
|
||||
return Material(
|
||||
key: const Key('mine-account-card'),
|
||||
color: AppColors.card,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
borderRadius: BorderRadius.circular(AppDimens.cardRadius),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: SizedBox(
|
||||
height: AppDimens.accountCardHeight,
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: _accountTitleWidth,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 12),
|
||||
child: Text(
|
||||
l10n.accountCenter,
|
||||
style: const TextStyle(
|
||||
fontSize: AppDimens.caption,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const VerticalDivider(
|
||||
width: 1,
|
||||
color: AppColors.outlineVariantDark,
|
||||
),
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
_entry(
|
||||
context,
|
||||
key: const Key('mine-account-profile'),
|
||||
icon: Icons.person_outline_rounded,
|
||||
title: l10n.accountProfile,
|
||||
page: const AccountProfilePage(),
|
||||
divider: true,
|
||||
),
|
||||
_entry(
|
||||
context,
|
||||
key: const Key('mine-account-devices'),
|
||||
icon: Icons.devices_other_rounded,
|
||||
title: l10n.accountDevices,
|
||||
page: const AccountDevicesPage(),
|
||||
divider: true,
|
||||
),
|
||||
_entry(
|
||||
context,
|
||||
key: const Key('mine-account-export'),
|
||||
icon: Icons.file_download_outlined,
|
||||
title: l10n.accountDataExport,
|
||||
page: const AccountExportPage(),
|
||||
divider: true,
|
||||
),
|
||||
_entry(
|
||||
context,
|
||||
key: const Key('mine-account-deactivate'),
|
||||
icon: Icons.person_remove_outlined,
|
||||
title: l10n.accountDeactivate,
|
||||
page: const AccountDeactivatePage(),
|
||||
divider: false,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _entry(
|
||||
BuildContext context, {
|
||||
required Key key,
|
||||
required IconData icon,
|
||||
required String title,
|
||||
required Widget page,
|
||||
required bool divider,
|
||||
}) {
|
||||
return Expanded(
|
||||
child: Row(
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: InkWell(
|
||||
key: key,
|
||||
onTap: () => Navigator.of(
|
||||
context,
|
||||
).push<void>(MaterialPageRoute(builder: (_) => page)),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
color: AppColors.blueSoft,
|
||||
size: AppDimens.accountIcon,
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
title,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
fontSize: AppDimens.accountLabel,
|
||||
height: 1.15,
|
||||
),
|
||||
),
|
||||
],
|
||||
for (var index = 0; index < rows.length; index++) ...[
|
||||
if (index > 0)
|
||||
const Divider(
|
||||
height: AppDimens.mineGridDividerWidth,
|
||||
thickness: AppDimens.mineGridDividerWidth,
|
||||
color: AppColors.outlineVariantDark,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (divider)
|
||||
const VerticalDivider(
|
||||
width: 1,
|
||||
color: AppColors.outlineVariantDark,
|
||||
),
|
||||
_AccountListTile(row: rows[index]),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AccountRow {
|
||||
const _AccountRow({
|
||||
required this.key,
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.page,
|
||||
});
|
||||
|
||||
final Key key;
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final Widget page;
|
||||
}
|
||||
|
||||
class _AccountListTile extends StatelessWidget {
|
||||
const _AccountListTile({required this.row});
|
||||
|
||||
final _AccountRow row;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
key: row.key,
|
||||
onTap: () => Navigator.of(
|
||||
context,
|
||||
).push<void>(MaterialPageRoute(builder: (_) => row.page)),
|
||||
child: SizedBox(
|
||||
height: AppDimens.mineMoreRowHeight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: AppDimens.spaceLg),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
row.icon,
|
||||
color: AppColors.blueSoft,
|
||||
size: AppDimens.accountIcon,
|
||||
),
|
||||
const SizedBox(width: AppDimens.spaceMd),
|
||||
Expanded(
|
||||
child: Text(
|
||||
row.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: AppDimens.listTitle,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right_rounded,
|
||||
color: AppColors.textSecondary,
|
||||
size: AppDimens.accountIcon,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -336,7 +336,6 @@ class _AuthBrand extends StatelessWidget {
|
||||
key: const Key('auth-brand-mark'),
|
||||
size: compact ? _compactBrandMarkSize : _brandMarkSize,
|
||||
radius: compact ? _compactBrandMarkRadius : _brandMarkRadius,
|
||||
iconSize: compact ? _compactBrandIconSize : _brandIconSize,
|
||||
);
|
||||
|
||||
Widget _brandCopy(BuildContext context, {required bool centered}) => Column(
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/legal/legal_opener.dart';
|
||||
import '../../core/legal/legal_page.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
const double _legalFontSize = 12;
|
||||
|
||||
/// 登录页底部的协议入口。点用户协议或隐私政策会打开对应语言的页面。
|
||||
class AuthLegalLinks extends StatefulWidget {
|
||||
const AuthLegalLinks({super.key, this.open});
|
||||
|
||||
/// 测试时可替换真正的跳转。
|
||||
final Future<void> Function(String url)? open;
|
||||
|
||||
@override
|
||||
State<AuthLegalLinks> createState() => _AuthLegalLinksState();
|
||||
}
|
||||
|
||||
class _AuthLegalLinksState extends State<AuthLegalLinks> {
|
||||
late final TapGestureRecognizer _termsTap = TapGestureRecognizer()
|
||||
..onTap = () => _open(legalTermsPath);
|
||||
late final TapGestureRecognizer _privacyTap = TapGestureRecognizer()
|
||||
..onTap = () => _open(legalPrivacyPath);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_termsTap.dispose();
|
||||
_privacyTap.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _open(String path) {
|
||||
final url = legalPageUrl(path, Localizations.localeOf(context));
|
||||
final custom = widget.open;
|
||||
if (custom != null) {
|
||||
unawaited(custom(url));
|
||||
return;
|
||||
}
|
||||
unawaited(openLegalUrlOrNotify(context, url));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final muted = TextStyle(color: AppColors.muted, fontSize: _legalFontSize, height: 1.6);
|
||||
final link = muted.copyWith(color: AppColors.blue);
|
||||
return Text.rich(
|
||||
TextSpan(
|
||||
style: muted,
|
||||
children: [
|
||||
TextSpan(text: l10n.authLegalLead),
|
||||
const TextSpan(text: ' '),
|
||||
TextSpan(text: l10n.authTerms, style: link, recognizer: _termsTap),
|
||||
const TextSpan(text: ' '),
|
||||
TextSpan(text: l10n.authLegalJoin),
|
||||
const TextSpan(text: ' '),
|
||||
TextSpan(
|
||||
text: l10n.authPrivacy,
|
||||
style: link,
|
||||
recognizer: _privacyTap,
|
||||
),
|
||||
],
|
||||
),
|
||||
key: const Key('auth-legal'),
|
||||
textAlign: TextAlign.center,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../core/data/remote/api_client.dart';
|
||||
import '../../core/formatting/error_text.dart';
|
||||
import '../../core/data/services/auth_controller.dart';
|
||||
import '../../core/platform/haptics.dart';
|
||||
import '../../core/platform/keyboard_inset.dart';
|
||||
@@ -15,6 +16,7 @@ import '../../core/theme/app_theme.dart';
|
||||
import '../../core/widgets/centered_toast.dart';
|
||||
import '../../core/widgets/subpage_header.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import 'auth_legal_links.dart';
|
||||
import 'auth_logic.dart';
|
||||
import 'phone_auth_sheet.dart';
|
||||
|
||||
@@ -26,8 +28,8 @@ const double _brandMarkSize = 72;
|
||||
const double _compactBrandMarkSize = 48;
|
||||
const double _brandMarkRadius = 20;
|
||||
const double _compactBrandMarkRadius = 14;
|
||||
const double _brandIconSize = 36;
|
||||
const double _compactBrandIconSize = 26;
|
||||
const double _landingLogoTopGap = 28;
|
||||
const String _appLogoAsset = 'assets/icon/fruitshorts.png';
|
||||
const double _contentMaxWidth = 440;
|
||||
// Auth keeps its approved 20px card silhouette.
|
||||
const double _cardRadius = AppDimens.authCardRadius;
|
||||
@@ -58,31 +60,15 @@ Widget _brandMarkWidget({
|
||||
Key? key,
|
||||
required double size,
|
||||
required double radius,
|
||||
required double iconSize,
|
||||
}) {
|
||||
return Container(
|
||||
return ClipRRect(
|
||||
key: key,
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(radius),
|
||||
gradient: const LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [AppColors.blue, AppColors.secondary],
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: AppColors.blue.withValues(alpha: 0.24),
|
||||
blurRadius: 20,
|
||||
offset: const Offset(0, 8),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
Icons.play_arrow_rounded,
|
||||
color: AppColors.onPrimary,
|
||||
size: iconSize,
|
||||
borderRadius: BorderRadius.circular(radius),
|
||||
child: Image.asset(
|
||||
_appLogoAsset,
|
||||
width: size,
|
||||
height: size,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -257,7 +243,7 @@ class _AuthPageState extends State<AuthPage> {
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).maybePop();
|
||||
} on ApiException catch (error) {
|
||||
failureMessage = error.message;
|
||||
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
|
||||
} catch (_) {
|
||||
failureMessage = l10n.authNetworkError;
|
||||
} finally {
|
||||
@@ -431,12 +417,12 @@ class _AuthPageState extends State<AuthPage> {
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: _landingLogoTopGap),
|
||||
Center(
|
||||
child: _brandMarkWidget(
|
||||
key: const Key('auth-brand-logo'),
|
||||
size: _brandMarkSize,
|
||||
radius: _brandMarkRadius,
|
||||
iconSize: _brandIconSize,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
@@ -473,16 +459,7 @@ class _AuthPageState extends State<AuthPage> {
|
||||
onTap: () => setState(() => _emailEntryOpen = true),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Text(
|
||||
l10n.authLegal,
|
||||
key: const Key('auth-legal'),
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: AppColors.muted,
|
||||
fontSize: 9,
|
||||
height: 1.6,
|
||||
),
|
||||
),
|
||||
const AuthLegalLinks(),
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import 'package:provider/provider.dart';
|
||||
|
||||
import '../../core/data/remote/api_client.dart';
|
||||
import '../../core/data/services/auth_controller.dart';
|
||||
import '../../core/formatting/error_text.dart';
|
||||
import '../../core/platform/haptics.dart';
|
||||
import '../../core/platform/keyboard_inset.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
|
||||
@@ -23,30 +23,18 @@ 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);
|
||||
@@ -295,7 +283,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
List<Widget> _theaterBlocks(AppLocalizations l10n) {
|
||||
final dramas = theater.dramas;
|
||||
return [
|
||||
_toolbar(l10n),
|
||||
_toolbar(),
|
||||
if (dramas.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 40),
|
||||
@@ -318,6 +306,16 @@ 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),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -335,8 +333,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_categoryTab(
|
||||
key: const Key('theater-category-all'),
|
||||
DiscoverCategoryTab(
|
||||
anchorKey: _anchorFor('all'),
|
||||
id: 'all',
|
||||
label: l10n.all,
|
||||
@@ -345,8 +342,7 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
),
|
||||
for (final category in categories.categories) ...[
|
||||
const SizedBox(width: _categoryTabGap),
|
||||
_categoryTab(
|
||||
key: Key('theater-category-${category.id}'),
|
||||
DiscoverCategoryTab(
|
||||
anchorKey: _anchorFor(category.id),
|
||||
id: category.id,
|
||||
label: category.name,
|
||||
@@ -360,52 +356,6 @@ 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);
|
||||
}
|
||||
@@ -444,97 +394,8 @@ class _DiscoverPageState extends State<DiscoverPage> {
|
||||
return true;
|
||||
}
|
||||
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget _toolbar() {
|
||||
return DiscoverToolbar(onOpen: (page) => _openPage(context, page));
|
||||
}
|
||||
|
||||
void _openPage(BuildContext context, Widget page) {
|
||||
@@ -601,27 +462,3 @@ 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;
|
||||
}
|
||||
@@ -20,6 +20,11 @@ import 'discover_binding.dart';
|
||||
import 'discover_logic.dart';
|
||||
import 'widgets/search_result_card.dart';
|
||||
|
||||
const double _clearHit = 20;
|
||||
const double _clearIconSize = 16;
|
||||
const double _clearEndGap = 10;
|
||||
const double _loadingInset = 2;
|
||||
|
||||
class SearchPage extends StatefulWidget {
|
||||
const SearchPage({super.key});
|
||||
|
||||
@@ -119,11 +124,10 @@ class _SearchPageState extends State<SearchPage> {
|
||||
}
|
||||
|
||||
Widget _field(AppLocalizations l10n) {
|
||||
final hasText = _logic.search.text.isNotEmpty;
|
||||
return Container(
|
||||
key: const Key('search-field'),
|
||||
height: AppDimens.searchHeight,
|
||||
padding: const EdgeInsets.symmetric(horizontal: AppDimens.spaceMd),
|
||||
padding: const EdgeInsets.only(left: AppDimens.spaceMd),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.contentSurface,
|
||||
borderRadius: BorderRadius.circular(AppDimens.searchRadius),
|
||||
@@ -143,7 +147,9 @@ class _SearchPageState extends State<SearchPage> {
|
||||
focusNode: _logic.searchFocus,
|
||||
autofocus: true,
|
||||
onChanged: (_) => _logic.onSearchChanged(),
|
||||
onTapOutside: (_) => _logic.searchFocus.unfocus(),
|
||||
textInputAction: TextInputAction.search,
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: 14,
|
||||
@@ -163,35 +169,64 @@ class _SearchPageState extends State<SearchPage> {
|
||||
scrollPadding: EdgeInsets.zero,
|
||||
),
|
||||
),
|
||||
if (_logic.searchLoading)
|
||||
const SizedBox.square(
|
||||
dimension: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
)
|
||||
else if (hasText)
|
||||
IconButton(
|
||||
key: const Key('search-clear'),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints.tightFor(width: 24, height: 24),
|
||||
onPressed: () {
|
||||
_logic.search.clear();
|
||||
_logic.onSearchChanged();
|
||||
_logic.searchFocus.requestFocus();
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.close_rounded,
|
||||
color: AppColors.textSecondary,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
_fieldTrailing(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 有内容时把清除按钮放在输入框内部右侧,并留出一点边距。
|
||||
/// 刷新时不拿转圈替换叉号,避免宽度变化把按钮抖开。
|
||||
Widget _fieldTrailing() {
|
||||
final hasText = _logic.search.text.isNotEmpty;
|
||||
if (!hasText && !_logic.searchLoading) {
|
||||
return const SizedBox(width: AppDimens.spaceMd);
|
||||
}
|
||||
return SizedBox(
|
||||
width: _clearHit + _clearEndGap,
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: _clearEndGap),
|
||||
child: hasText ? _clearButton() : _loadingMark(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _clearButton() {
|
||||
return GestureDetector(
|
||||
key: const Key('search-clear'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () {
|
||||
_logic.search.clear();
|
||||
_logic.onSearchChanged();
|
||||
_logic.searchFocus.requestFocus();
|
||||
},
|
||||
child: const SizedBox.square(
|
||||
dimension: _clearHit,
|
||||
child: Icon(
|
||||
Icons.close_rounded,
|
||||
color: AppColors.textSecondary,
|
||||
size: _clearIconSize,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _loadingMark() {
|
||||
return const SizedBox.square(
|
||||
dimension: _clearHit,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(_loadingInset),
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(AppLocalizations l10n) {
|
||||
if (!_logic.hasSearchQuery) {
|
||||
return _stateScroll(
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// 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,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -96,9 +96,9 @@ class DramaGridCard extends StatelessWidget {
|
||||
children: [
|
||||
_cover(),
|
||||
const SizedBox(height: _titleGap),
|
||||
_title(),
|
||||
_title(context),
|
||||
const SizedBox(height: _tagsGap),
|
||||
_tags(),
|
||||
_tags(context),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -151,9 +151,9 @@ class DramaGridCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _title() {
|
||||
Widget _title(BuildContext context) {
|
||||
return Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
key: Key('home-drama-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -166,8 +166,8 @@ class DramaGridCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _tags() {
|
||||
final tags = _tagValues();
|
||||
Widget _tags(BuildContext context) {
|
||||
final tags = _tagValues(context);
|
||||
if (tags.isEmpty) return const SizedBox.shrink();
|
||||
return Wrap(
|
||||
spacing: 6,
|
||||
@@ -193,7 +193,9 @@ class DramaGridCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _tagValues() {
|
||||
List<String> _tagValues(BuildContext context) {
|
||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
||||
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();
|
||||
final tags = _tags(context);
|
||||
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.title,
|
||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
key: Key('search-result-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -92,7 +92,9 @@ class SearchResultCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _tags() {
|
||||
List<String> _tags(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(RegExp(r'[,/、·]')))
|
||||
|
||||
@@ -163,8 +163,8 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
||||
synopsis: localizedDramaSynopsis(l10n, drama),
|
||||
),
|
||||
),
|
||||
if (_tagValues(drama).isNotEmpty)
|
||||
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(drama))),
|
||||
if (_tagValues(context, drama).isNotEmpty)
|
||||
SliverToBoxAdapter(child: DramaTags(tags: _tagValues(context, drama))),
|
||||
SliverToBoxAdapter(child: _episodes(l10n, drama, continueIndex)),
|
||||
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
||||
],
|
||||
@@ -442,13 +442,18 @@ class _DramaDetailPageState extends State<DramaDetailPage> {
|
||||
return record.fraction;
|
||||
}
|
||||
|
||||
List<String> _tagValues(Drama drama) {
|
||||
List<String> _tagValues(BuildContext context, Drama drama) {
|
||||
final localized = drama.localizedTypeLabels(Localizations.localeOf(context).languageCode);
|
||||
final result = <String>[];
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
final language = drama.language.trim();
|
||||
|
||||
@@ -176,6 +176,8 @@ 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),
|
||||
@@ -265,8 +267,9 @@ class _FavoriteCard extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final tags = _tags();
|
||||
final synopsis = drama.synopsis.trim();
|
||||
final languageCode = Localizations.localeOf(context).languageCode;
|
||||
final tags = _tags(languageCode);
|
||||
final synopsis = drama.localizedSynopsis(languageCode).trim();
|
||||
return Container(
|
||||
key: ValueKey('favorite-card-${drama.id}'),
|
||||
decoration: BoxDecoration(
|
||||
@@ -309,7 +312,7 @@ class _FavoriteCard extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(languageCode),
|
||||
key: ValueKey('favorite-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -444,7 +447,9 @@ class _FavoriteCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _tags() {
|
||||
List<String> _tags(String languageCode) {
|
||||
final localized = drama.localizedTypeLabels(languageCode);
|
||||
if (localized.isNotEmpty) return localized.take(_maxTags).toList();
|
||||
final values = <String>[];
|
||||
for (final source in [drama.genre, drama.category]) {
|
||||
for (final part in source.split(_tagSplitter)) {
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/data/services/favorite_controller.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
enum FollowingTab { favorites, history }
|
||||
|
||||
/// 编辑底栏的全选与取消动作。
|
||||
class FollowingEditActions {
|
||||
const FollowingEditActions({
|
||||
required this.onToggleAll,
|
||||
required this.onRemove,
|
||||
});
|
||||
|
||||
final void Function(Set<String> ids) onToggleAll;
|
||||
final VoidCallback onRemove;
|
||||
}
|
||||
|
||||
const double _barHeight = 48;
|
||||
const double _barHorizontal = 16;
|
||||
const double _barFontSize = 13;
|
||||
const double _barButtonHeight = 30;
|
||||
const double _removeDialogButtonHeight = 32;
|
||||
const double _removeDialogRadius = 6;
|
||||
const double _removeDialogBottomInset = 8;
|
||||
|
||||
/// 播放历史移除确认。只把移除按钮压矮。
|
||||
Future<bool> confirmHistoryRemove(BuildContext context) async {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
actionsPadding: const EdgeInsets.fromLTRB(
|
||||
24,
|
||||
0,
|
||||
16,
|
||||
_removeDialogBottomInset,
|
||||
),
|
||||
content: Text(l10n.confirmRemove),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
minimumSize: const Size(0, _removeDialogButtonHeight),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(_removeDialogRadius),
|
||||
),
|
||||
),
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.remove),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
|
||||
/// 确认后返回是否取消已选追剧。
|
||||
Future<bool> confirmCancelFollowing(BuildContext context) async {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
content: Text(l10n.confirmCancelFollowing),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.cancelFollowing),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
|
||||
/// 只在追剧编辑中显示底栏。
|
||||
class FollowingEditSlot extends StatelessWidget {
|
||||
const FollowingEditSlot({
|
||||
super.key,
|
||||
required this.tab,
|
||||
required this.editing,
|
||||
required this.favorites,
|
||||
required this.selected,
|
||||
required this.actions,
|
||||
});
|
||||
|
||||
final ValueListenable<FollowingTab> tab;
|
||||
final ValueListenable<bool> editing;
|
||||
final FavoriteController favorites;
|
||||
final ValueListenable<Set<String>> selected;
|
||||
final FollowingEditActions actions;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<FollowingTab>(
|
||||
valueListenable: tab,
|
||||
builder: (context, current, _) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: editing,
|
||||
builder: (context, isEditing, _) {
|
||||
if (!isEditing || current != FollowingTab.favorites) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return _bar();
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _bar() {
|
||||
return ListenableBuilder(
|
||||
listenable: favorites,
|
||||
builder: (context, _) {
|
||||
return ValueListenableBuilder<Set<String>>(
|
||||
valueListenable: selected,
|
||||
builder: (context, picked, _) {
|
||||
final ids = favorites.cards.map((drama) => drama.id).toSet();
|
||||
return FollowingEditBar(
|
||||
allSelected: ids.isNotEmpty && ids.every(picked.contains),
|
||||
canRemove: picked.isNotEmpty,
|
||||
onToggleAll: () => actions.onToggleAll(ids),
|
||||
onRemove: actions.onRemove,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 追剧编辑底栏:全选,以及取消已选追剧。
|
||||
class FollowingEditBar extends StatelessWidget {
|
||||
const FollowingEditBar({
|
||||
super.key,
|
||||
required this.allSelected,
|
||||
required this.canRemove,
|
||||
required this.onToggleAll,
|
||||
required this.onRemove,
|
||||
});
|
||||
|
||||
final bool allSelected;
|
||||
final bool canRemove;
|
||||
final VoidCallback onToggleAll;
|
||||
final VoidCallback onRemove;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Material(
|
||||
key: const Key('following-edit-bar'),
|
||||
color: AppColors.card,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: SizedBox(
|
||||
height: _barHeight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: _barHorizontal),
|
||||
child: Row(
|
||||
children: [
|
||||
TextButton(
|
||||
key: const Key('following-select-all'),
|
||||
style: TextButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
minimumSize: const Size(0, _barButtonHeight),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4),
|
||||
textStyle: const TextStyle(
|
||||
fontSize: _barFontSize,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
onPressed: onToggleAll,
|
||||
child: Text(
|
||||
allSelected ? l10n.deselectAll : l10n.selectAll,
|
||||
style: const TextStyle(
|
||||
fontSize: _barFontSize,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
FilledButton(
|
||||
key: const Key('following-cancel-follow'),
|
||||
style: FilledButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
minimumSize: const Size(0, _removeDialogButtonHeight),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(_removeDialogRadius),
|
||||
),
|
||||
textStyle: const TextStyle(
|
||||
fontSize: _barFontSize,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
onPressed: canRemove ? onRemove : null,
|
||||
child: Text(
|
||||
l10n.cancelFollowing,
|
||||
style: const TextStyle(
|
||||
fontSize: _barFontSize,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/data/services/favorite_controller.dart';
|
||||
import '../../core/formatting/error_text.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../player/open_player.dart';
|
||||
import 'following_grid_card.dart';
|
||||
import 'following_paged_grid.dart';
|
||||
|
||||
/// 追剧编辑中的选中状态。
|
||||
class FollowingFavoriteSelection {
|
||||
const FollowingFavoriteSelection({
|
||||
required this.editing,
|
||||
required this.selected,
|
||||
required this.onToggle,
|
||||
});
|
||||
|
||||
final ValueListenable<bool> editing;
|
||||
final ValueListenable<Set<String>> selected;
|
||||
final ValueChanged<String> onToggle;
|
||||
}
|
||||
|
||||
/// 追剧列表。编辑时点卡片只切换选中,不进入播放。
|
||||
class FollowingFavoritesGrid extends StatelessWidget {
|
||||
const FollowingFavoritesGrid({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.selection,
|
||||
required this.scrollController,
|
||||
required this.onGoHome,
|
||||
});
|
||||
|
||||
final FavoriteController controller;
|
||||
final FollowingFavoriteSelection selection;
|
||||
final ScrollController scrollController;
|
||||
final VoidCallback onGoHome;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: selection.editing,
|
||||
builder: (context, isEditing, _) {
|
||||
return ValueListenableBuilder<Set<String>>(
|
||||
valueListenable: selection.selected,
|
||||
builder: (context, picked, _) {
|
||||
return ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, _) => _grid(context, isEditing, picked),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _grid(BuildContext context, bool isEditing, Set<String> picked) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final extra = isEditing ? 0 : 1;
|
||||
return FollowingPagedGrid(
|
||||
key: const Key('following-favorites-grid'),
|
||||
scrollController: scrollController,
|
||||
loading: controller.loading,
|
||||
loadingMore: controller.loadingMore,
|
||||
hasMore: controller.hasMore,
|
||||
hasItems: controller.cards.isNotEmpty,
|
||||
showInitialLoading: false,
|
||||
errorMessage: controller.error == null
|
||||
? null
|
||||
: errorText(l10n, controller.error, l10n.favoritesError),
|
||||
loadMoreError: controller.loadMoreError == null
|
||||
? null
|
||||
: errorText(l10n, controller.loadMoreError, l10n.favoritesError),
|
||||
onRefresh: controller.load,
|
||||
onLoadMore: controller.loadMore,
|
||||
itemCount: controller.cards.length + extra,
|
||||
empty: const SizedBox.shrink(),
|
||||
itemBuilder: (context, index) => _item(context, index, isEditing, picked),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _item(
|
||||
BuildContext context,
|
||||
int index,
|
||||
bool isEditing,
|
||||
Set<String> picked,
|
||||
) {
|
||||
if (index == controller.cards.length) {
|
||||
return FollowingAddCard(onTap: onGoHome);
|
||||
}
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final drama = controller.cards[index];
|
||||
final episode = drama.episodes.isEmpty ? 1 : drama.episodes.first.number;
|
||||
return FollowingGridCard(
|
||||
dramaId: drama.id,
|
||||
title: drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
posterUrl: drama.posterUrl,
|
||||
viewCount: drama.viewCount,
|
||||
editing: isEditing,
|
||||
selected: isEditing ? picked.contains(drama.id) : null,
|
||||
subtitle: l10n.favoriteEpisodeProgress(episode, drama.episodeCount),
|
||||
onTap: () => _openOrToggle(context, drama.id, isEditing),
|
||||
);
|
||||
}
|
||||
|
||||
void _openOrToggle(BuildContext context, String dramaId, bool isEditing) {
|
||||
if (isEditing) {
|
||||
selection.onToggle(dramaId);
|
||||
return;
|
||||
}
|
||||
final drama = controller.cards.firstWhere((item) => item.id == dramaId);
|
||||
unawaited(playDramaFromCatalog(context, drama));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,11 @@ import '../../core/theme/app_dimens.dart';
|
||||
import '../../core/widgets/cover_play_count.dart';
|
||||
import '../../core/widgets/remote_image.dart';
|
||||
|
||||
const double _selectMarkSize = 22;
|
||||
const double _selectMarkInset = 6;
|
||||
const double _selectMarkIconSize = 16;
|
||||
const double _selectBorderWidth = 1.5;
|
||||
|
||||
class FollowingGridCard extends StatelessWidget {
|
||||
const FollowingGridCard({
|
||||
super.key,
|
||||
@@ -18,6 +23,7 @@ class FollowingGridCard extends StatelessWidget {
|
||||
required this.onTap,
|
||||
this.progress,
|
||||
this.editing = false,
|
||||
this.selected,
|
||||
this.onRemove,
|
||||
});
|
||||
|
||||
@@ -29,6 +35,7 @@ class FollowingGridCard extends StatelessWidget {
|
||||
final VoidCallback onTap;
|
||||
final double? progress;
|
||||
final bool editing;
|
||||
final bool? selected;
|
||||
final VoidCallback? onRemove;
|
||||
|
||||
@override
|
||||
@@ -59,7 +66,16 @@ class FollowingGridCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
if (editing)
|
||||
if (selected != null)
|
||||
Positioned(
|
||||
top: _selectMarkInset,
|
||||
right: _selectMarkInset,
|
||||
child: _SelectMark(
|
||||
key: Key('following-select-$dramaId'),
|
||||
selected: selected!,
|
||||
),
|
||||
)
|
||||
else if (editing)
|
||||
Positioned(
|
||||
top: -2,
|
||||
right: -2,
|
||||
@@ -141,6 +157,35 @@ class FollowingGridCard extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _SelectMark extends StatelessWidget {
|
||||
const _SelectMark({super.key, required this.selected});
|
||||
|
||||
final bool selected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: _selectMarkSize,
|
||||
height: _selectMarkSize,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: selected ? AppColors.blue : AppColors.transparent,
|
||||
border: Border.all(
|
||||
color: selected ? AppColors.blue : AppColors.textPrimary,
|
||||
width: _selectBorderWidth,
|
||||
),
|
||||
),
|
||||
child: selected
|
||||
? const Icon(
|
||||
Icons.check_rounded,
|
||||
size: _selectMarkIconSize,
|
||||
color: AppColors.onPrimary,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class FollowingAddCard extends StatelessWidget {
|
||||
const FollowingAddCard({super.key, required this.onTap});
|
||||
|
||||
|
||||
@@ -19,12 +19,14 @@ import '../../core/widgets/auth_gate.dart';
|
||||
import '../../core/widgets/empty_state.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import '../player/open_player.dart';
|
||||
import 'following_grid_card.dart';
|
||||
import 'following_edit_bar.dart';
|
||||
import 'following_favorites_grid.dart';
|
||||
import 'following_history_card.dart';
|
||||
import 'following_keep_alive_tab.dart';
|
||||
import 'following_paged_grid.dart';
|
||||
|
||||
enum FollowingTab { favorites, history }
|
||||
const double _doneFontSize = 14;
|
||||
const double _doneTextGap = 12;
|
||||
|
||||
class FollowingPage extends StatefulWidget {
|
||||
const FollowingPage({
|
||||
@@ -50,21 +52,33 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
FollowingTab.favorites,
|
||||
);
|
||||
final ValueNotifier<bool> _editing = ValueNotifier(false);
|
||||
final ValueNotifier<Set<String>> _selected = ValueNotifier({});
|
||||
late final WatchRecordsController _history;
|
||||
late final AuthController _auth;
|
||||
bool _wasSignedIn = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_auth = context.read<AuthController>();
|
||||
_wasSignedIn = _auth.isSignedIn;
|
||||
_auth.addListener(_onAuthChanged);
|
||||
_history = WatchRecordsController(
|
||||
history: context.read<WatchHistoryRepository>(),
|
||||
catalog: context.read<CatalogRepository>(),
|
||||
);
|
||||
unawaited(_history.load());
|
||||
if (_wasSignedIn) unawaited(_history.load());
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) unawaited(widget.favoriteController.load());
|
||||
});
|
||||
}
|
||||
|
||||
void _onAuthChanged() {
|
||||
final signedIn = _auth.isSignedIn;
|
||||
if (signedIn && !_wasSignedIn) unawaited(_history.load());
|
||||
_wasSignedIn = signedIn;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pageController.dispose();
|
||||
@@ -72,6 +86,8 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
_historyScroll.dispose();
|
||||
_tab.dispose();
|
||||
_editing.dispose();
|
||||
_selected.dispose();
|
||||
_auth.removeListener(_onAuthChanged);
|
||||
_history.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
@@ -106,12 +122,15 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
onPageChanged: _onPageChanged,
|
||||
children: [
|
||||
FollowingKeepAliveTab(
|
||||
child: _FavoritesGrid(
|
||||
child: FollowingFavoritesGrid(
|
||||
controller: widget.favoriteController,
|
||||
editing: _editing,
|
||||
selection: FollowingFavoriteSelection(
|
||||
editing: _editing,
|
||||
selected: _selected,
|
||||
onToggle: _toggleDrama,
|
||||
),
|
||||
scrollController: _favoriteScroll,
|
||||
onGoHome: widget.onGoHome,
|
||||
onListEmptied: _exitEditingIfEmpty,
|
||||
),
|
||||
),
|
||||
FollowingKeepAliveTab(
|
||||
@@ -125,6 +144,17 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
],
|
||||
),
|
||||
),
|
||||
if (signedIn)
|
||||
FollowingEditSlot(
|
||||
tab: _tab,
|
||||
editing: _editing,
|
||||
favorites: widget.favoriteController,
|
||||
selected: _selected,
|
||||
actions: FollowingEditActions(
|
||||
onToggleAll: _toggleAll,
|
||||
onRemove: () => unawaited(_cancelSelected()),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -147,36 +177,43 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
builder: (context, editing, _) {
|
||||
return Row(
|
||||
children: [
|
||||
_tabButton(
|
||||
FollowingTab.favorites,
|
||||
l10n.followingTab,
|
||||
'favorites',
|
||||
selectedTab == FollowingTab.favorites,
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: _tabButton(
|
||||
FollowingTab.favorites,
|
||||
l10n.followingTab,
|
||||
'favorites',
|
||||
selectedTab == FollowingTab.favorites,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppDimens.followingTabGap),
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: _tabButton(
|
||||
FollowingTab.history,
|
||||
l10n.watchHistory,
|
||||
'history',
|
||||
selectedTab == FollowingTab.history,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppDimens.followingTabGap),
|
||||
_tabButton(
|
||||
FollowingTab.history,
|
||||
l10n.watchHistory,
|
||||
'history',
|
||||
selectedTab == FollowingTab.history,
|
||||
),
|
||||
const Spacer(),
|
||||
if (editing)
|
||||
SizedBox(
|
||||
width: AppDimens.followingEditHitSize,
|
||||
height: AppDimens.followingEditHitSize,
|
||||
child: InkWell(
|
||||
key: const Key('following-edit'),
|
||||
onTap: _toggleEditing,
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Text(
|
||||
l10n.done,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: AppDimens.followingTabFont,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
InkWell(
|
||||
key: const Key('following-edit'),
|
||||
onTap: _toggleEditing,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: _doneTextGap),
|
||||
child: Text(
|
||||
l10n.done,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textPrimary,
|
||||
fontSize: _doneFontSize,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -223,7 +260,9 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
onTap: () => _selectTab(tab),
|
||||
child: SizedBox(
|
||||
height: AppDimens.followingHeaderHeight,
|
||||
child: Center(
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
widthFactor: 1,
|
||||
child: AnimatedDefaultTextStyle(
|
||||
duration: AppDimens.followingTabAnimationDuration,
|
||||
style: TextStyle(
|
||||
@@ -233,7 +272,7 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
fontSize: AppDimens.followingTabFont,
|
||||
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
|
||||
),
|
||||
child: Text(label, maxLines: 1),
|
||||
child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -241,7 +280,7 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
}
|
||||
|
||||
void _selectTab(FollowingTab tab) {
|
||||
_editing.value = false;
|
||||
_leaveEditing();
|
||||
_tab.value = tab;
|
||||
if (_pageController.hasClients) {
|
||||
unawaited(
|
||||
@@ -256,99 +295,50 @@ class _FollowingPageState extends State<FollowingPage> {
|
||||
|
||||
void _onPageChanged(int index) {
|
||||
final tab = FollowingTab.values[index];
|
||||
_editing.value = false;
|
||||
_leaveEditing();
|
||||
_tab.value = tab;
|
||||
if (tab == FollowingTab.history && _auth.isSignedIn) {
|
||||
unawaited(_history.load());
|
||||
}
|
||||
}
|
||||
|
||||
void _toggleEditing() {
|
||||
_editing.value = !_editing.value;
|
||||
if (!_editing.value) _selected.value = {};
|
||||
}
|
||||
|
||||
void _leaveEditing() {
|
||||
_editing.value = false;
|
||||
_selected.value = {};
|
||||
}
|
||||
|
||||
void _toggleDrama(String id) {
|
||||
final next = {..._selected.value};
|
||||
if (!next.add(id)) next.remove(id);
|
||||
_selected.value = next;
|
||||
}
|
||||
|
||||
void _toggleAll(Set<String> ids) {
|
||||
final picked = _selected.value;
|
||||
final all = ids.isNotEmpty && ids.every(picked.contains);
|
||||
_selected.value = all ? {} : ids;
|
||||
}
|
||||
|
||||
Future<void> _cancelSelected() async {
|
||||
final ids = _selected.value.toList();
|
||||
if (ids.isEmpty || !mounted || !await confirmCancelFollowing(context)) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
final removed = await widget.favoriteController.removeMany(ids);
|
||||
if (!removed || !mounted) return;
|
||||
_selected.value = {};
|
||||
if (widget.favoriteController.cards.isEmpty) _editing.value = false;
|
||||
}
|
||||
|
||||
void _exitEditingIfEmpty() => _editing.value = false;
|
||||
}
|
||||
|
||||
class _FavoritesGrid extends StatelessWidget {
|
||||
const _FavoritesGrid({
|
||||
required this.controller,
|
||||
required this.editing,
|
||||
required this.scrollController,
|
||||
required this.onGoHome,
|
||||
required this.onListEmptied,
|
||||
});
|
||||
|
||||
final FavoriteController controller;
|
||||
final ValueListenable<bool> editing;
|
||||
final ScrollController scrollController;
|
||||
final VoidCallback onGoHome;
|
||||
final VoidCallback onListEmptied;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: editing,
|
||||
builder: (context, isEditing, _) {
|
||||
return ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, _) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return FollowingPagedGrid(
|
||||
key: const Key('following-favorites-grid'),
|
||||
scrollController: scrollController,
|
||||
loading: controller.loading,
|
||||
loadingMore: controller.loadingMore,
|
||||
hasMore: controller.hasMore,
|
||||
hasItems: controller.cards.isNotEmpty,
|
||||
showInitialLoading: false,
|
||||
errorMessage: controller.error == null
|
||||
? null
|
||||
: errorText(l10n, controller.error, l10n.favoritesError),
|
||||
loadMoreError: controller.loadMoreError == null
|
||||
? null
|
||||
: errorText(
|
||||
l10n,
|
||||
controller.loadMoreError,
|
||||
l10n.favoritesError,
|
||||
),
|
||||
onRefresh: controller.load,
|
||||
onLoadMore: controller.loadMore,
|
||||
itemCount: controller.cards.length + 1,
|
||||
empty: const SizedBox.shrink(),
|
||||
itemBuilder: (context, index) {
|
||||
if (index == controller.cards.length) {
|
||||
return FollowingAddCard(onTap: onGoHome);
|
||||
}
|
||||
final drama = controller.cards[index];
|
||||
final episode = drama.episodes.isEmpty
|
||||
? 1
|
||||
: drama.episodes.first.number;
|
||||
return FollowingGridCard(
|
||||
dramaId: drama.id,
|
||||
title: drama.title,
|
||||
posterUrl: drama.posterUrl,
|
||||
viewCount: drama.viewCount,
|
||||
editing: isEditing,
|
||||
subtitle: l10n.favoriteEpisodeProgress(
|
||||
episode,
|
||||
drama.episodeCount,
|
||||
),
|
||||
onTap: () => unawaited(playDramaFromCatalog(context, drama)),
|
||||
onRemove: () async {
|
||||
if (await _confirmRemove(context) &&
|
||||
await controller.remove(drama.id) &&
|
||||
controller.cards.isEmpty) {
|
||||
onListEmptied();
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HistoryList extends StatelessWidget {
|
||||
const _HistoryList({
|
||||
required this.controller,
|
||||
@@ -412,10 +402,16 @@ class _HistoryList extends StatelessWidget {
|
||||
|
||||
return FollowingHistoryCard(
|
||||
dramaId: record.dramaId,
|
||||
title: _historyTitle(l10n, record),
|
||||
title: _historyTitle(
|
||||
l10n,
|
||||
record,
|
||||
Localizations.localeOf(context).languageCode,
|
||||
),
|
||||
posterUrl: record.displayCover,
|
||||
viewCount:
|
||||
record.drama?.viewCount ?? record.progress.playCount,
|
||||
record.progress.viewCount ??
|
||||
record.drama?.viewCount ??
|
||||
record.progress.playCount,
|
||||
progress: hasProgress ? progress : null,
|
||||
progressLabel: hasProgress
|
||||
? l10n.watchedPercent(watchedPercent)
|
||||
@@ -425,7 +421,7 @@ class _HistoryList extends StatelessWidget {
|
||||
onTap: openRecord,
|
||||
onContinue: openRecord,
|
||||
onRemove: () async {
|
||||
if (await _confirmRemove(context) &&
|
||||
if (await confirmHistoryRemove(context) &&
|
||||
await controller.remove(record.dramaId) &&
|
||||
controller.records.isEmpty) {
|
||||
onListEmptied();
|
||||
@@ -441,10 +437,13 @@ class _HistoryList extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
String _historyTitle(AppLocalizations l10n, WatchRecord record) {
|
||||
return record.displayTitle.isEmpty
|
||||
? l10n.episodeLabel(record.episodeNumber)
|
||||
: record.displayTitle;
|
||||
String _historyTitle(
|
||||
AppLocalizations l10n,
|
||||
WatchRecord record,
|
||||
String languageCode,
|
||||
) {
|
||||
final title = record.localizedDisplayTitle(languageCode);
|
||||
return title.isEmpty ? l10n.episodeLabel(record.episodeNumber) : title;
|
||||
}
|
||||
|
||||
String _historySubtitle(AppLocalizations l10n, WatchRecord record) {
|
||||
@@ -469,24 +468,3 @@ Future<void> _openHistory(
|
||||
episodeId: record.progress.episodeId,
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> _confirmRemove(BuildContext context) async {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
content: Text(l10n.confirmRemove),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(l10n.remove),
|
||||
),
|
||||
],
|
||||
),
|
||||
) ??
|
||||
false;
|
||||
}
|
||||
@@ -130,6 +130,8 @@ class FollowingPagedGrid extends StatelessWidget {
|
||||
SliverToBoxAdapter(
|
||||
child: PagedListFooter(
|
||||
loading: loadingMore,
|
||||
hasMore: hasMore,
|
||||
hasItems: hasItems,
|
||||
errorMessage: loadMoreError,
|
||||
onRetry: onLoadMore,
|
||||
),
|
||||
|
||||
@@ -7,6 +7,7 @@ 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';
|
||||
@@ -174,17 +175,21 @@ class _HomeTabsState extends State<_HomeTabs> {
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context) {
|
||||
final pages = <Widget>[
|
||||
_homeGrid(context),
|
||||
_recommend(context),
|
||||
FollowingPage(
|
||||
onGoHome: () => logic.select(0),
|
||||
favoriteController: context.read<FavoriteController>(),
|
||||
historyRequest: logic.followingHistoryRequest,
|
||||
),
|
||||
_my(context),
|
||||
];
|
||||
return IndexedStack(
|
||||
index: logic.tab,
|
||||
children: [
|
||||
_homeGrid(context),
|
||||
_recommend(context),
|
||||
FollowingPage(
|
||||
onGoHome: () => logic.select(0),
|
||||
favoriteController: context.read<FavoriteController>(),
|
||||
historyRequest: logic.followingHistoryRequest,
|
||||
),
|
||||
_my(context),
|
||||
for (var index = 0; index < pages.length; index++)
|
||||
TickerMode(enabled: logic.tab == index, child: pages[index]),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -205,11 +210,22 @@ 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,
|
||||
onSearch: () => _openSearch(context),
|
||||
);
|
||||
}
|
||||
|
||||
CatalogApi? _catalogApi(BuildContext context) {
|
||||
try {
|
||||
return context.read<CatalogApi>();
|
||||
} on ProviderNotFoundException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _openSearch(BuildContext context) {
|
||||
Navigator.of(
|
||||
context,
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// 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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -99,9 +99,9 @@ class HomeDramaCard extends StatelessWidget {
|
||||
children: [
|
||||
_cover(),
|
||||
const SizedBox(height: _coverTitleGap),
|
||||
_title(),
|
||||
_title(context),
|
||||
const SizedBox(height: _lineGap),
|
||||
_genre(),
|
||||
_genre(context),
|
||||
const SizedBox(height: _lineGap),
|
||||
_metadata(),
|
||||
],
|
||||
@@ -211,9 +211,9 @@ class HomeDramaCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _title() {
|
||||
Widget _title(BuildContext context) {
|
||||
return Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
key: Key('home-drama-title-${drama.id}'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -225,8 +225,11 @@ class HomeDramaCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _genre() {
|
||||
final genre = drama.genre.isEmpty ? drama.category : drama.genre;
|
||||
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(' / ');
|
||||
return Text(
|
||||
genre.isEmpty ? l10n.videoPending : genre,
|
||||
key: Key('home-drama-genre-${drama.id}'),
|
||||
|
||||
@@ -8,28 +8,21 @@ 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,
|
||||
@@ -40,7 +33,7 @@ class HomeFeedCard extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
_cover(l10n),
|
||||
_cover(context),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
@@ -51,7 +44,7 @@ class HomeFeedCard extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
drama.title,
|
||||
drama.localizedTitle(Localizations.localeOf(context).languageCode),
|
||||
key: Key('home-feed-title-${drama.id}'),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
@@ -64,7 +57,7 @@ class HomeFeedCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppDimens.cardTitleTagGap),
|
||||
_tags(),
|
||||
_tags(context),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -75,8 +68,8 @@ class HomeFeedCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cover(AppLocalizations l10n) {
|
||||
final badge = _badge();
|
||||
Widget _cover(BuildContext context) {
|
||||
final label = drama.localizedTag(Localizations.localeOf(context).languageCode);
|
||||
return ClipRRect(
|
||||
key: Key('home-feed-cover-clip-${drama.id}'),
|
||||
borderRadius: BorderRadius.circular(AppDimens.cardCoverRadius),
|
||||
@@ -92,14 +85,14 @@ class HomeFeedCard extends StatelessWidget {
|
||||
showFallbackIcon: true,
|
||||
fallbackColor: AppColors.contentSurface,
|
||||
),
|
||||
if (badge != null)
|
||||
if (label.isNotEmpty)
|
||||
Positioned(
|
||||
top: 0,
|
||||
right: 0,
|
||||
child: DramaCoverBadgeRibbon(
|
||||
label: _badgeLabel(l10n, badge),
|
||||
color: _badgeColor(badge),
|
||||
keyPrefix: '${drama.id}-${badge.name}',
|
||||
label: label,
|
||||
color: drama.tagRibbonColor(AppColors.badgeHot),
|
||||
keyPrefix: '${drama.id}-tag',
|
||||
),
|
||||
),
|
||||
const Positioned(
|
||||
@@ -122,35 +115,8 @@ class HomeFeedCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
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();
|
||||
Widget _tags(BuildContext context) {
|
||||
final tags = _cardTags(context);
|
||||
if (tags.isEmpty) return const SizedBox.shrink();
|
||||
return Text(
|
||||
tags.join(' | '),
|
||||
@@ -166,7 +132,9 @@ class HomeFeedCard extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _cardTags() {
|
||||
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))
|
||||
|
||||
@@ -14,20 +14,16 @@ 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 '../../ranking/ranking_page.dart';
|
||||
import 'home_drama_classification.dart';
|
||||
import 'home_category_dramas.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({
|
||||
@@ -46,21 +42,15 @@ class HomeFeedGrid extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
HomePrimaryTab _selectedPrimary = HomePrimaryTab.featured;
|
||||
int _sectionIndex = 0;
|
||||
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(_selectedPrimary.index);
|
||||
_pageController.jumpToPage(_sectionIndex);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -68,9 +58,6 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
@override
|
||||
void dispose() {
|
||||
_pageController.dispose();
|
||||
for (final controller in _scrollControllers.values) {
|
||||
controller.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -81,17 +68,16 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
final catalog = context.watch<CatalogController>();
|
||||
final auth = context.watch<AuthController>();
|
||||
final wallet = context.watch<WalletController>();
|
||||
final shortcuts = _categoryShortcuts(categories, l10n);
|
||||
final shortcuts = _categoryShortcuts(
|
||||
categories,
|
||||
Localizations.localeOf(context).languageCode,
|
||||
);
|
||||
final walletBadge = auth.isSignedIn && wallet.snapshot != null
|
||||
? wallet.balance
|
||||
: null;
|
||||
final ranking = _selectedPrimary == HomePrimaryTab.ranking;
|
||||
return DecoratedBox(
|
||||
key: const Key('home-grid'),
|
||||
decoration: BoxDecoration(
|
||||
color: ranking ? null : AppColors.appBackground,
|
||||
gradient: ranking ? AppTheme.pageGradient : null,
|
||||
),
|
||||
decoration: const BoxDecoration(color: AppColors.appBackground),
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: Column(
|
||||
@@ -100,8 +86,8 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
HomeGridHeader(
|
||||
callbacks: widget.callbacks,
|
||||
categories: shortcuts,
|
||||
selectedPrimary: _selectedPrimary,
|
||||
onPrimarySelected: _selectPrimary,
|
||||
selectedIndex: _sectionIndex,
|
||||
onSectionSelected: _selectSection,
|
||||
walletBadge: walletBadge,
|
||||
),
|
||||
Expanded(
|
||||
@@ -110,22 +96,29 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
builder: (context, _) => PageView.builder(
|
||||
key: const Key('home-primary-page-view'),
|
||||
controller: _pageController,
|
||||
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,
|
||||
),
|
||||
),
|
||||
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,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -135,28 +128,54 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
);
|
||||
}
|
||||
|
||||
void _selectPrimary(HomePrimaryTab tab) {
|
||||
if (tab == _selectedPrimary) return;
|
||||
void _selectSection(int index) {
|
||||
if (index == _sectionIndex) return;
|
||||
if (!_pageController.hasClients) {
|
||||
setState(() => _selectedPrimary = tab);
|
||||
setState(() => _sectionIndex = index);
|
||||
return;
|
||||
}
|
||||
unawaited(
|
||||
_pageController.animateToPage(
|
||||
tab.index,
|
||||
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 HomePrimaryTab tab,
|
||||
required HomeGridCategoryShortcut category,
|
||||
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);
|
||||
}
|
||||
@@ -170,11 +189,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
mainAxisSpacing: AppDimens.homeGridRowGap,
|
||||
);
|
||||
}
|
||||
if (tab == HomePrimaryTab.ranking) {
|
||||
return const RankingPage(embedded: true);
|
||||
}
|
||||
final tag = _selectedTags[tab];
|
||||
final dramas = _dramasFor(tab, tag, shortcuts);
|
||||
final dramas = _dramasFor(category);
|
||||
if (widget.feedController.loadingFirstPage && dramas.isEmpty) {
|
||||
return const DramaGridSkeleton(
|
||||
key: Key('home-grid-skeleton'),
|
||||
@@ -201,13 +216,13 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
onRefresh: _refresh,
|
||||
child: CustomScrollView(
|
||||
key: const Key('home-grid-scroll'),
|
||||
controller: _scrollControllers[tab],
|
||||
controller: null,
|
||||
physics: AppPullToRefresh.physics,
|
||||
slivers: [
|
||||
if (dramas.isEmpty)
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: _emptyState(l10n, tab, tag),
|
||||
child: _emptyState(l10n),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
@@ -237,6 +252,8 @@ 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,
|
||||
@@ -289,78 +306,34 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
|
||||
List<HomeGridCategoryShortcut> _categoryShortcuts(
|
||||
List<ContentCategory> categories,
|
||||
AppLocalizations l10n,
|
||||
String languageCode,
|
||||
) {
|
||||
final costume = _findCategory(categories, _costumeAliases);
|
||||
final community = _findCategory(categories, _communityAliases);
|
||||
return [
|
||||
HomeGridCategoryShortcut(
|
||||
label: l10n.homeSectionCostume,
|
||||
categoryName: costume?.name ?? '',
|
||||
tab: HomePrimaryTab.costume,
|
||||
),
|
||||
HomeGridCategoryShortcut(
|
||||
label: l10n.homeSectionCommunity,
|
||||
categoryName: community?.name ?? '',
|
||||
tab: HomePrimaryTab.community,
|
||||
),
|
||||
for (final category in categories)
|
||||
HomeGridCategoryShortcut(
|
||||
label: category.localizedName(languageCode),
|
||||
categoryName: category.name,
|
||||
categoryId: category.id,
|
||||
tab: HomePrimaryTab.categories,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
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(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;
|
||||
}
|
||||
|
||||
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, HomePrimaryTab tab, String? tag) {
|
||||
Widget _emptyState(AppLocalizations l10n) {
|
||||
if (widget.feedController.lastError != null) {
|
||||
return EmptyState(
|
||||
key: const Key('home-grid-error'),
|
||||
@@ -370,19 +343,10 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
|
||||
onAction: () => unawaited(widget.feedController.refreshCurrent()),
|
||||
);
|
||||
}
|
||||
final filtered =
|
||||
tab == HomePrimaryTab.costume ||
|
||||
tab == HomePrimaryTab.community ||
|
||||
tag != null;
|
||||
return EmptyState(
|
||||
key: const Key('home-grid-empty'),
|
||||
icon: Icons.movie_filter_outlined,
|
||||
title: filtered ? l10n.homeGridFilterEmpty : l10n.noStories,
|
||||
subtitle: filtered ? null : l10n.emptyHint,
|
||||
actionLabel: filtered ? l10n.homeGridClearFilter : null,
|
||||
onAction: filtered
|
||||
? () => setState(() => _selectedTags[tab] = null)
|
||||
: null,
|
||||
title: l10n.emptyContent,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,11 +20,13 @@ 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;
|
||||
}
|
||||
|
||||
@@ -47,15 +49,15 @@ class HomeGridHeader extends StatelessWidget {
|
||||
super.key,
|
||||
required this.callbacks,
|
||||
required this.categories,
|
||||
required this.selectedPrimary,
|
||||
required this.onPrimarySelected,
|
||||
required this.selectedIndex,
|
||||
required this.onSectionSelected,
|
||||
this.walletBadge,
|
||||
});
|
||||
|
||||
final HomeGridCallbacks callbacks;
|
||||
final List<HomeGridCategoryShortcut> categories;
|
||||
final HomePrimaryTab selectedPrimary;
|
||||
final ValueChanged<HomePrimaryTab> onPrimarySelected;
|
||||
final int selectedIndex;
|
||||
final ValueChanged<int> onSectionSelected;
|
||||
final int? walletBadge;
|
||||
|
||||
@override
|
||||
@@ -67,7 +69,7 @@ class HomeGridHeader extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
_searchRow(l10n),
|
||||
_primaryRow(l10n),
|
||||
_primaryRow(),
|
||||
const SizedBox(height: AppDimens.homeSecondaryGridGap),
|
||||
],
|
||||
);
|
||||
@@ -225,7 +227,73 @@ class HomeGridHeader extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _primaryRow(AppLocalizations l10n) {
|
||||
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) {
|
||||
return SingleChildScrollView(
|
||||
key: const Key('home-primary-sections'),
|
||||
scrollDirection: Axis.horizontal,
|
||||
@@ -234,60 +302,29 @@ class HomeGridHeader extends StatelessWidget {
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
_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,
|
||||
),
|
||||
for (var index = 0; index < widget.categories.length; index++)
|
||||
_item(index),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _primaryItem({
|
||||
required Key key,
|
||||
required String label,
|
||||
required HomePrimaryTab tab,
|
||||
}) {
|
||||
final selected = selectedPrimary == tab;
|
||||
Widget _item(int index) {
|
||||
final category = widget.categories[index];
|
||||
final selected = widget.selectedIndex == index;
|
||||
return InkWell(
|
||||
key: key,
|
||||
onTap: () => onPrimarySelected(tab),
|
||||
key: _itemKeys[index],
|
||||
onTap: () => widget.onSectionSelected(index),
|
||||
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-${tab.name}'),
|
||||
key: Key('home-primary-label-${category.categoryId}'),
|
||||
duration: AppDimens.homePrimaryTabAnimationDuration,
|
||||
curve: Curves.easeOut,
|
||||
style: TextStyle(
|
||||
@@ -300,7 +337,7 @@ class HomeGridHeader extends StatelessWidget {
|
||||
fontWeight: selected ? FontWeight.w700 : FontWeight.w400,
|
||||
letterSpacing: 0,
|
||||
),
|
||||
child: Text(label, textAlign: TextAlign.left),
|
||||
child: Text(category.label, textAlign: TextAlign.left),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -12,8 +12,6 @@ enum MineDestination {
|
||||
wallet,
|
||||
vip,
|
||||
preferences,
|
||||
works,
|
||||
creatorCenter,
|
||||
notices,
|
||||
settings,
|
||||
help,
|
||||
|
||||
@@ -158,7 +158,10 @@ class _MyPageState extends State<MyPage> {
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppDimens.pageHorizontal,
|
||||
),
|
||||
child: MineHeader(onLogin: _openLogin, onEdit: _openEditActions),
|
||||
child: MineHeader(
|
||||
onLogin: _openLogin,
|
||||
onEdit: () => _push(const AccountProfilePage()),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
@@ -202,7 +205,7 @@ class _MyPageState extends State<MyPage> {
|
||||
horizontal: AppDimens.mineGridHorizontal,
|
||||
),
|
||||
child: MineMoreServices(
|
||||
onCommonQuestions: () => _pushPlaceholder(MinePlaceholderKind.help),
|
||||
onCommonQuestions: _pushPlaceholder,
|
||||
onAbout: () => _push(const MineAboutPage()),
|
||||
),
|
||||
),
|
||||
@@ -222,16 +225,12 @@ class _MyPageState extends State<MyPage> {
|
||||
_openVip();
|
||||
case MineDestination.preferences:
|
||||
_push(const FilterPage());
|
||||
case MineDestination.works:
|
||||
_pushPlaceholder(MinePlaceholderKind.works);
|
||||
case MineDestination.creatorCenter:
|
||||
_pushPlaceholder(MinePlaceholderKind.creator);
|
||||
case MineDestination.notices:
|
||||
_push(const NoticesPage());
|
||||
case MineDestination.settings:
|
||||
_push(const SettingsPage());
|
||||
case MineDestination.help:
|
||||
_pushPlaceholder(MinePlaceholderKind.help);
|
||||
_pushPlaceholder();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,66 +247,12 @@ class _MyPageState extends State<MyPage> {
|
||||
_push(const WatchRecordsPage());
|
||||
}
|
||||
|
||||
Future<void> _openEditActions() async {
|
||||
final selected = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
backgroundColor: AppColors.transparent,
|
||||
showDragHandle: false,
|
||||
builder: (sheetContext) => Material(
|
||||
color: AppColors.mineCard,
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(AppDimens.mineCardRadius),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ListTile(
|
||||
key: const Key('mine-edit-profile'),
|
||||
title: Text(AppLocalizations.of(sheetContext)!.accountProfile),
|
||||
onTap: () => Navigator.pop(sheetContext, 'profile'),
|
||||
),
|
||||
ListTile(
|
||||
key: const Key('mine-edit-works'),
|
||||
title: Text(AppLocalizations.of(sheetContext)!.myWorks),
|
||||
onTap: () => Navigator.pop(sheetContext, 'works'),
|
||||
),
|
||||
ListTile(
|
||||
key: const Key('mine-edit-creator'),
|
||||
title: Text(AppLocalizations.of(sheetContext)!.creatorCenter),
|
||||
onTap: () => Navigator.pop(sheetContext, 'creator'),
|
||||
),
|
||||
ListTile(
|
||||
key: const Key('mine-edit-notices'),
|
||||
title: Text(AppLocalizations.of(sheetContext)!.notices),
|
||||
onTap: () => Navigator.pop(sheetContext, 'notices'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!mounted || selected == null) return;
|
||||
switch (selected) {
|
||||
case 'profile':
|
||||
_push(const AccountProfilePage());
|
||||
case 'works':
|
||||
_pushPlaceholder(MinePlaceholderKind.works);
|
||||
case 'creator':
|
||||
_pushPlaceholder(MinePlaceholderKind.creator);
|
||||
case 'notices':
|
||||
_push(const NoticesPage());
|
||||
}
|
||||
}
|
||||
|
||||
void _push(Widget page) {
|
||||
Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => page));
|
||||
}
|
||||
|
||||
void _pushPlaceholder(MinePlaceholderKind kind) {
|
||||
_push(_MinePlaceholderPage(kind: kind));
|
||||
void _pushPlaceholder() {
|
||||
_push(const _MinePlaceholderPage());
|
||||
}
|
||||
|
||||
Future<void> _openProtected(Widget page) async {
|
||||
@@ -431,21 +376,13 @@ class _LanguageSheet extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
enum MinePlaceholderKind { works, creator, help }
|
||||
|
||||
class _MinePlaceholderPage extends StatelessWidget {
|
||||
const _MinePlaceholderPage({required this.kind});
|
||||
|
||||
final MinePlaceholderKind kind;
|
||||
const _MinePlaceholderPage();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final title = switch (kind) {
|
||||
MinePlaceholderKind.works => l10n.myWorks,
|
||||
MinePlaceholderKind.creator => l10n.creatorCenter,
|
||||
MinePlaceholderKind.help => l10n.helpFeedback,
|
||||
};
|
||||
final title = l10n.helpFeedback;
|
||||
return PlainPageScaffold(
|
||||
pageKey: const Key('mine-placeholder-page'),
|
||||
backKey: const Key('mine-placeholder-back'),
|
||||
|
||||
@@ -82,7 +82,11 @@ class MineContinueWatching extends StatelessWidget {
|
||||
const SizedBox(width: AppDimens.spaceMd),
|
||||
itemBuilder: (_, index) {
|
||||
final record = visible[index];
|
||||
return _card(l10n, record);
|
||||
return _card(
|
||||
l10n,
|
||||
record,
|
||||
Localizations.localeOf(context).languageCode,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -90,8 +94,8 @@ class MineContinueWatching extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _card(AppLocalizations l10n, WatchProgress record) {
|
||||
final title = record.dramaTitle?.trim() ?? '';
|
||||
Widget _card(AppLocalizations l10n, WatchProgress record, String languageCode) {
|
||||
final title = record.localizedTitle(languageCode).trim();
|
||||
final episode = record.episodeNumber;
|
||||
final hasProgress = record.duration > Duration.zero;
|
||||
return SizedBox(
|
||||
|
||||
@@ -14,7 +14,7 @@ import '../../../core/widgets/remote_image.dart';
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
|
||||
const double _buttonHeight = 34;
|
||||
const double _buttonRadius = 20;
|
||||
const double _buttonRadius = 6;
|
||||
|
||||
/// 「我的」页用户区。
|
||||
class MineHeader extends StatelessWidget {
|
||||
|
||||
@@ -209,7 +209,14 @@ class MineMenuList extends StatelessWidget {
|
||||
label: l10n.settings,
|
||||
onTap: () => onOpen(MineDestination.settings),
|
||||
),
|
||||
_cell(index: 7),
|
||||
_cell(
|
||||
index: 7,
|
||||
actionKey: const Key('mine-notices'),
|
||||
icon: Icons.notifications_none_rounded,
|
||||
iconColor: AppColors.mineIconNotices,
|
||||
label: l10n.notices,
|
||||
onTap: () => onOpen(MineDestination.notices),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
|
||||
@@ -192,6 +192,8 @@ class _NewReleasesPageState extends State<NewReleasesPage> {
|
||||
),
|
||||
PagedLoadFooter(
|
||||
loading: pager.loading,
|
||||
hasMore: pager.hasMore,
|
||||
hasItems: visible.isNotEmpty,
|
||||
loadMoreKey: const Key(
|
||||
'new-releases-load-more',
|
||||
),
|
||||
|
||||
@@ -171,6 +171,17 @@ 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();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
@@ -88,6 +89,9 @@ class PlayerLogic extends ChangeNotifier {
|
||||
String? blockedEpisodeId;
|
||||
List<Episode> sessionEpisodes = const [];
|
||||
List<String> qualities = const [];
|
||||
List<PlayQualityTrack> qualityTracks = const [];
|
||||
String selectedQuality = 'AUTO';
|
||||
Duration? _qualitySeek;
|
||||
int pageRequest = 0;
|
||||
bool muted = false;
|
||||
double playbackSpeed = 1.0;
|
||||
@@ -295,6 +299,7 @@ class PlayerLogic extends ChangeNotifier {
|
||||
session.remapCurrentIndex(
|
||||
keepIndex,
|
||||
preloadIndex: nextVisibleIndex(keepIndex),
|
||||
previousIndex: previousVisibleIndex(keepIndex),
|
||||
);
|
||||
_jumpToFeedPage(keepIndex);
|
||||
_notifyAfterFrameIfNeeded();
|
||||
@@ -426,6 +431,7 @@ class PlayerLogic extends ChangeNotifier {
|
||||
blockedTicket = null;
|
||||
blockedEpisodeId = null;
|
||||
qualities = const [];
|
||||
qualityTracks = const [];
|
||||
sessionEpisodes[index] = episode.withVideoUrl(_fileUrl(localPath));
|
||||
return true;
|
||||
}
|
||||
@@ -437,10 +443,18 @@ class PlayerLogic extends ChangeNotifier {
|
||||
blockedTicket = null;
|
||||
blockedEpisodeId = null;
|
||||
qualities = ticket.qualities;
|
||||
if (ticket.accessible && ticket.playUrl.isNotEmpty) {
|
||||
qualityTracks = ticket.tracks;
|
||||
final preferred = qualityPlayUrl(
|
||||
quality: selectedQuality,
|
||||
tracks: qualityTracks,
|
||||
currentUrl: ticket.playUrl,
|
||||
);
|
||||
final playUrl = preferred ?? ticket.playUrl;
|
||||
if (preferred == null) selectedQuality = 'AUTO';
|
||||
if (ticket.accessible && playUrl.isNotEmpty) {
|
||||
// 签名地址原样写回,不做任何拼接/改写(AppConfig.mediaUrl 只补 host)
|
||||
sessionEpisodes[index] = episode.withVideoUrl(
|
||||
ticket.playUrl,
|
||||
playUrl,
|
||||
likeCount: ticket.likeCount,
|
||||
commentCount: ticket.commentCount,
|
||||
thumbnailsUrl: ticket.thumbnailsUrl,
|
||||
@@ -470,6 +484,65 @@ class PlayerLogic extends ChangeNotifier {
|
||||
String _fileUrl(String path) =>
|
||||
path.startsWith('file:') ? path : Uri.file(path).toString();
|
||||
|
||||
/// 切到指定清晰度。新片源出画后再替换,失败则继续播原来的。
|
||||
Future<bool> selectQuality(String quality) async {
|
||||
final index = session.currentIndex;
|
||||
if (index < 0 || index >= sessionEpisodes.length) return false;
|
||||
final current = sessionEpisodes[index];
|
||||
final url = qualityPlayUrl(
|
||||
quality: quality,
|
||||
tracks: qualityTracks,
|
||||
currentUrl: current.videoUrl,
|
||||
);
|
||||
if (url == null || url.isEmpty) return false;
|
||||
if (selectedQuality.toUpperCase() == quality.toUpperCase() &&
|
||||
current.videoUrl == url) {
|
||||
return true;
|
||||
}
|
||||
final previousQuality = selectedQuality;
|
||||
final active = session.active;
|
||||
if (active is VideoPlayerPort && active.controller.value.isInitialized) {
|
||||
_qualitySeek = active.controller.value.position;
|
||||
}
|
||||
selectedQuality = quality.toUpperCase();
|
||||
sessionEpisodes[index] = current.withVideoUrl(url);
|
||||
final switched = await session.replaceCurrent();
|
||||
if (switched) {
|
||||
if (isMounted()) notify();
|
||||
return true;
|
||||
}
|
||||
_qualitySeek = null;
|
||||
selectedQuality = previousQuality;
|
||||
if (index < sessionEpisodes.length) {
|
||||
sessionEpisodes[index] = current;
|
||||
}
|
||||
if (isMounted()) notify();
|
||||
return false;
|
||||
}
|
||||
|
||||
Future<void> _waitUntilFrameReady(VideoPlayerController controller) async {
|
||||
if (controller.value.hasError) {
|
||||
throw StateError('quality source failed');
|
||||
}
|
||||
if (!controller.value.isBuffering) return;
|
||||
final done = Completer<void>();
|
||||
void onChange() {
|
||||
final value = controller.value;
|
||||
if (done.isCompleted) return;
|
||||
if (value.hasError || !value.isBuffering) done.complete();
|
||||
}
|
||||
|
||||
controller.addListener(onChange);
|
||||
try {
|
||||
await done.future.timeout(const Duration(seconds: 4));
|
||||
} finally {
|
||||
controller.removeListener(onChange);
|
||||
}
|
||||
if (controller.value.hasError) {
|
||||
throw StateError('quality source failed');
|
||||
}
|
||||
}
|
||||
|
||||
/// 重试当前集的票据(失败态的"重试"按钮)。
|
||||
Future<void> retryTicket() async {
|
||||
ticketError = null;
|
||||
@@ -495,7 +568,7 @@ class PlayerLogic extends ChangeNotifier {
|
||||
}
|
||||
final ready = await ensureTicket(index, forceRefresh: true);
|
||||
if (ready) {
|
||||
await session.select(index, preloadIndex: nextVisibleIndex(index));
|
||||
await _selectVisible(index);
|
||||
}
|
||||
return ready;
|
||||
} finally {
|
||||
@@ -667,6 +740,15 @@ class PlayerLogic extends ChangeNotifier {
|
||||
if (player is! VideoPlayerPort) return;
|
||||
try {
|
||||
await player.controller.setPlaybackSpeed(playbackSpeed);
|
||||
final override = _qualitySeek;
|
||||
_qualitySeek = null;
|
||||
if (override != null && override > Duration.zero) {
|
||||
await player.seekTo(
|
||||
clampResumePosition(override, player.controller.value.duration),
|
||||
);
|
||||
await _waitUntilFrameReady(player.controller);
|
||||
return;
|
||||
}
|
||||
await pendingWrite;
|
||||
// 服务端每剧只记一条:只有"记录里的那一集"才定位,其它集从头播
|
||||
if (resumePoint == null) await loadResumePoint();
|
||||
@@ -689,7 +771,7 @@ class PlayerLogic extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
// 续看位置取不到不影响播放:从头播。
|
||||
// 续看或清晰度定位失败时仍用已初始化的播放器,不把切换判失败。
|
||||
}
|
||||
}
|
||||
|
||||
@@ -888,7 +970,16 @@ class PlayerLogic extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
if (!ready && ticketError != null) return;
|
||||
await session.select(index, preloadIndex: nextVisibleIndex(index));
|
||||
await _selectVisible(index);
|
||||
}
|
||||
|
||||
/// 按可见队列选择一集,并预热上一集与下一集。
|
||||
Future<void> _selectVisible(int index) {
|
||||
return session.select(
|
||||
index,
|
||||
preloadIndex: nextVisibleIndex(index),
|
||||
previousIndex: previousVisibleIndex(index),
|
||||
);
|
||||
}
|
||||
|
||||
int? nextVisibleIndex(int index) {
|
||||
@@ -898,6 +989,13 @@ 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 {
|
||||
|
||||
@@ -41,6 +41,7 @@ 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';
|
||||
@@ -363,7 +364,7 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
final lastDoubleTapAt = _lastDoubleTapAt;
|
||||
return lastDoubleTapAt != null &&
|
||||
DateTime.now().difference(lastDoubleTapAt) <
|
||||
const Duration(milliseconds: 350);
|
||||
const Duration(milliseconds: 500);
|
||||
}
|
||||
|
||||
void _handleDoubleTapLike(
|
||||
@@ -545,14 +546,20 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
(selected ? logic.session.active : null) ??
|
||||
logic.session.preparedPlayerAt(index);
|
||||
final videoPort = port is VideoPlayerPort ? port : null;
|
||||
final ready = videoPort?.controller.value.isInitialized ?? false;
|
||||
final handoff = selected ? logic.session.handoffAt(index) : null;
|
||||
final handoffPort = handoff is VideoPlayerPort ? handoff : null;
|
||||
// 测试播放器没有纹理。有播放器但不是视频控制器时视为已就绪,避免加载圈一直转。
|
||||
final videoReady = videoPort?.controller.value.isInitialized ?? false;
|
||||
final ready = videoReady || port != null;
|
||||
final theater = logic.pip || logic.pipPreparing;
|
||||
final locked = logic.session.isLocked || episode.locked;
|
||||
if (selected && ready) {
|
||||
if (selected &&
|
||||
videoPort != null &&
|
||||
videoPort.controller.value.isInitialized) {
|
||||
unawaited(
|
||||
_spriteAxisService.prepareAt(
|
||||
episode.thumbnailsUrl,
|
||||
videoPort!.controller.value.position,
|
||||
videoPort.controller.value.position,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -567,11 +574,31 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
),
|
||||
PlayerVideoSurface(
|
||||
controller: videoPort?.controller,
|
||||
handoff: handoffPort?.controller,
|
||||
videoUrl: videoPort?.controller.dataSource ?? episode.videoUrl,
|
||||
theater: theater,
|
||||
openingFrame: playerOpeningFrame(episode.thumbnailsUrl),
|
||||
),
|
||||
if (selected &&
|
||||
!theater &&
|
||||
!ready &&
|
||||
!logic.ticketLoading &&
|
||||
logic.ticketError == null &&
|
||||
logic.session.error == null &&
|
||||
logic.blockedEpisodeId != episode.id &&
|
||||
!logic.session.isLocked)
|
||||
const Center(
|
||||
child: SizedBox.square(
|
||||
dimension: _playerLoadingSize,
|
||||
child: CircularProgressIndicator(
|
||||
key: Key('player-video-loading'),
|
||||
color: AppColors.blue,
|
||||
strokeWidth: _playerLoadingStrokeWidth,
|
||||
),
|
||||
),
|
||||
),
|
||||
// 票据三态之一:起播前正在向后端要签名地址
|
||||
if (selected && logic.ticketLoading)
|
||||
if (selected && !theater && logic.ticketLoading)
|
||||
const Center(
|
||||
child: SizedBox.square(
|
||||
dimension: _playerLoadingSize,
|
||||
@@ -583,7 +610,10 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
),
|
||||
),
|
||||
// 票据三态之二:拿票失败(断网/服务异常)→ 可重试,不假装在加载
|
||||
if (selected && !logic.ticketLoading && logic.ticketError != null)
|
||||
if (selected &&
|
||||
!theater &&
|
||||
!logic.ticketLoading &&
|
||||
logic.ticketError != null)
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 36),
|
||||
@@ -610,7 +640,7 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
),
|
||||
),
|
||||
),
|
||||
if (selected && !ready && logic.session.error != null)
|
||||
if (selected && !theater && !ready && logic.session.error != null)
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 36),
|
||||
@@ -634,6 +664,7 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
),
|
||||
// 没有票据信息时的兜底(例如详情里就没地址、也没走票据流程)
|
||||
if (selected &&
|
||||
!theater &&
|
||||
!ready &&
|
||||
logic.blockedEpisodeId != episode.id &&
|
||||
logic.session.error == null &&
|
||||
@@ -668,7 +699,7 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
l10n: l10n,
|
||||
drama: drama,
|
||||
episode: episode,
|
||||
controller: ready ? videoPort!.controller : null,
|
||||
controller: videoReady ? videoPort!.controller : null,
|
||||
locked: locked,
|
||||
visible: _chromeVisible,
|
||||
boosting: _boosting,
|
||||
@@ -699,11 +730,13 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
},
|
||||
onEpisodes: () => logic.showEpisodes(context),
|
||||
onMore: _openCurrentMore,
|
||||
onScrubStart: ready ? () => logic.beginScrub(videoPort!) : null,
|
||||
onScrubStart: videoReady
|
||||
? () => logic.beginScrub(videoPort!)
|
||||
: null,
|
||||
onScrubEnd: _finishFeedScrub,
|
||||
onScrubVisibilityChanged: _setScrubbing,
|
||||
cancelScrubRequest: widget.scrubCancelRequest,
|
||||
onSeek: ready
|
||||
onSeek: videoReady
|
||||
? (position) => logic.endScrub(context, videoPort!, position)
|
||||
: null,
|
||||
thumbnailService: _thumbnailService,
|
||||
@@ -715,7 +748,7 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
l10n: l10n,
|
||||
drama: drama,
|
||||
episode: episode,
|
||||
controller: ready ? videoPort!.controller : null,
|
||||
controller: videoReady ? videoPort!.controller : null,
|
||||
locked: locked,
|
||||
liked: interactions.isEpisodeLiked(episode.id),
|
||||
likeCount:
|
||||
@@ -751,14 +784,14 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
onSave: () => unawaited(_toggleSave(context, drama)),
|
||||
onShare: () => logic.shareDrama(context, drama),
|
||||
onMore: () => _openMore(context, episode),
|
||||
onScrubStart: ready
|
||||
onScrubStart: videoReady
|
||||
? () {
|
||||
_setScrubbing(true);
|
||||
logic.beginScrub(videoPort!);
|
||||
}
|
||||
: null,
|
||||
onScrubEnd: () => _setScrubbing(false),
|
||||
onSeek: ready
|
||||
onSeek: videoReady
|
||||
? (position) => logic.seekTo(context, videoPort!, position)
|
||||
: null,
|
||||
onLongPressCenter: () => _openMore(context, episode),
|
||||
@@ -768,7 +801,10 @@ class _PlayerPageState extends State<PlayerPage>
|
||||
controlsVisible: _chromeVisible,
|
||||
),
|
||||
// 票据三态之三:后端判定不可播放 —— 用 accessType 驱动文案,不在前端猜
|
||||
if (selected && !ready && logic.blockedEpisodeId == episode.id)
|
||||
if (selected &&
|
||||
!theater &&
|
||||
!ready &&
|
||||
logic.blockedEpisodeId == episode.id)
|
||||
PlayerBlockedNotice(
|
||||
l10n: l10n,
|
||||
episode: episode,
|
||||
|
||||
@@ -27,12 +27,14 @@ extension _PlayerViewActions on _PlayerPageState {
|
||||
state: PlayerMoreState(
|
||||
speed: _playbackSpeed,
|
||||
qualities: logic.qualities,
|
||||
selectedQuality: logic.selectedQuality,
|
||||
),
|
||||
actions: PlayerMoreActions(
|
||||
onSpeedChanged: (value) {
|
||||
_updatePlaybackSpeed(value);
|
||||
unawaited(logic.setPlaybackSpeed(value));
|
||||
},
|
||||
onQualityChanged: (quality) => _switchQuality(context, l10n, quality),
|
||||
onClear: _hideChrome,
|
||||
onDownload: () => requestEpisodeDownload(context, episode.id),
|
||||
onPip: logic.pictureInPicture.isPlatformSupported
|
||||
@@ -43,6 +45,19 @@ extension _PlayerViewActions on _PlayerPageState {
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> _switchQuality(
|
||||
BuildContext context,
|
||||
AppLocalizations l10n,
|
||||
String quality,
|
||||
) async {
|
||||
Navigator.of(context).pop();
|
||||
final switched = await logic.selectQuality(quality);
|
||||
if (!context.mounted || !switched) return false;
|
||||
final label = quality.toUpperCase() == 'AUTO' ? l10n.qualityAuto : quality;
|
||||
showCenteredToast(context, l10n.qualitySwitched(label));
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _openUnlockSheet(
|
||||
BuildContext context,
|
||||
int index,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
// 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,6 +19,7 @@ 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;
|
||||
@@ -26,7 +27,6 @@ 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,6 +338,17 @@ 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);
|
||||
}
|
||||
|
||||
@@ -401,11 +412,12 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: SafeArea(
|
||||
child: Align(
|
||||
alignment: const Alignment(0, 0.55),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: Align(
|
||||
alignment: const Alignment(0, -0.4),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: Material(
|
||||
type: MaterialType.transparency,
|
||||
child: Container(
|
||||
key: const Key('comment-post-success-snackbar'),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
@@ -422,6 +434,8 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
|
||||
style: const TextStyle(
|
||||
color: AppColors.onPrimary,
|
||||
fontSize: 14,
|
||||
decoration: TextDecoration.none,
|
||||
decorationColor: AppColors.transparent,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -432,100 +446,3 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -110,12 +110,16 @@ class HomeFeedOverlay extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
||||
static const Duration _singleTapDelay = Duration(milliseconds: 320);
|
||||
static const Duration _singleTapDelay = Duration(milliseconds: 400);
|
||||
|
||||
bool _scrubbing = false;
|
||||
bool _wasVisibleBeforeScrub = true;
|
||||
Timer? _singleTapTimer;
|
||||
DateTime? _lastTapAt;
|
||||
DateTime? _lastDownAt;
|
||||
DateTime? _blockSingleTapUntil;
|
||||
bool _doubleTapDown = false;
|
||||
bool _likedThisPair = false;
|
||||
int _downSerial = 0;
|
||||
int _tapSeq = 0;
|
||||
int _nextHeartBurstId = 0;
|
||||
final List<({int id, Offset position})> _heartBursts = [];
|
||||
@@ -146,6 +150,7 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
||||
builder: (context, constraints) => Listener(
|
||||
onPointerUp: (_) => widget.onBoostEnd(),
|
||||
onPointerCancel: (_) => widget.onBoostEnd(),
|
||||
onPointerDown: _handlePointerDown,
|
||||
child: GestureDetector(
|
||||
key: const Key('home-feed-gesture'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
@@ -258,38 +263,66 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
||||
widget.onScrubEnd?.call(wasVisible);
|
||||
}
|
||||
|
||||
void _handleTapUp(TapUpDetails details) {
|
||||
final tapSeq = ++_tapSeq;
|
||||
final now = widget.now?.call() ?? DateTime.now();
|
||||
final lastTap = _lastTapAt;
|
||||
if (lastTap != null && now.difference(lastTap) <= _singleTapDelay) {
|
||||
_tapSeq++;
|
||||
_singleTapTimer?.cancel();
|
||||
_singleTapTimer = null;
|
||||
_lastTapAt = null;
|
||||
_showHearts(details.localPosition);
|
||||
DateTime _now() => widget.now?.call() ?? DateTime.now();
|
||||
|
||||
void _handlePointerDown(PointerDownEvent event) {
|
||||
final now = _now();
|
||||
final previous = _lastDownAt;
|
||||
_downSerial++;
|
||||
_lastDownAt = now;
|
||||
final repeated =
|
||||
previous != null && now.difference(previous) <= _singleTapDelay;
|
||||
if (!repeated) {
|
||||
if (_singleTapBlocked(now)) return;
|
||||
_doubleTapDown = false;
|
||||
_likedThisPair = false;
|
||||
return;
|
||||
}
|
||||
_lastTapAt = now;
|
||||
_doubleTapDown = true;
|
||||
_blockSingleTapUntil = now.add(_singleTapDelay);
|
||||
_cancelPendingSingleTap();
|
||||
}
|
||||
|
||||
bool _singleTapBlocked(DateTime now) {
|
||||
final blockedUntil = _blockSingleTapUntil;
|
||||
return blockedUntil != null && now.isBefore(blockedUntil);
|
||||
}
|
||||
|
||||
void _cancelPendingSingleTap() {
|
||||
_tapSeq++;
|
||||
_singleTapTimer?.cancel();
|
||||
_singleTapTimer = null;
|
||||
}
|
||||
|
||||
void _handleTapUp(TapUpDetails details) {
|
||||
final now = _now();
|
||||
if (_doubleTapDown || _singleTapBlocked(now)) {
|
||||
_showDoubleTapLike(details.localPosition);
|
||||
return;
|
||||
}
|
||||
final serial = _downSerial;
|
||||
final tapSeq = ++_tapSeq;
|
||||
_singleTapTimer?.cancel();
|
||||
late final Timer pending;
|
||||
pending = Timer(_singleTapDelay, () {
|
||||
if (identical(_singleTapTimer, pending)) {
|
||||
_singleTapTimer = null;
|
||||
}
|
||||
if (tapSeq != _tapSeq) return;
|
||||
final latestTap = _lastTapAt;
|
||||
if (latestTap != null &&
|
||||
(widget.now?.call() ?? DateTime.now()).difference(latestTap) <
|
||||
_singleTapDelay) {
|
||||
return;
|
||||
}
|
||||
_lastTapAt = null;
|
||||
if (mounted) widget.onTogglePlay();
|
||||
if (!identical(_singleTapTimer, pending)) return;
|
||||
_singleTapTimer = null;
|
||||
if (!mounted || tapSeq != _tapSeq || serial != _downSerial) return;
|
||||
if (_doubleTapDown || _singleTapBlocked(_now())) return;
|
||||
_lastDownAt = null;
|
||||
widget.onTogglePlay();
|
||||
});
|
||||
_singleTapTimer = pending;
|
||||
}
|
||||
|
||||
void _showDoubleTapLike(Offset position) {
|
||||
if (_likedThisPair) return;
|
||||
_likedThisPair = true;
|
||||
_blockSingleTapUntil = _now().add(_singleTapDelay);
|
||||
_cancelPendingSingleTap();
|
||||
_showHearts(position);
|
||||
}
|
||||
|
||||
void _showHearts(Offset position) {
|
||||
final id = _nextHeartBurstId++;
|
||||
setState(() => _heartBursts.add((id: id, position: position)));
|
||||
@@ -302,11 +335,11 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
||||
}
|
||||
|
||||
void _handleLongPressStart(LongPressStartDetails details, double width) {
|
||||
_tapSeq++;
|
||||
_singleTapTimer?.cancel();
|
||||
_singleTapTimer = null;
|
||||
_lastTapAt = null;
|
||||
final third = width / 3;
|
||||
_tapSeq++;
|
||||
_cancelPendingSingleTap();
|
||||
_doubleTapDown = false;
|
||||
_lastDownAt = null;
|
||||
final dx = details.localPosition.dx;
|
||||
if (dx < third || dx > width - third) {
|
||||
widget.onBoostStart();
|
||||
|
||||
@@ -316,9 +316,13 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
||||
final dragging = _preview != null;
|
||||
final trackHeight = dragging ? _trackActiveHeight : widget.height;
|
||||
final size = dragging ? _thumbActiveSize : _thumbSize;
|
||||
final thumbSlotLeft = (width * fraction - _thumbActiveSize / 2)
|
||||
.clamp(0.0, width - _thumbActiveSize)
|
||||
.toDouble();
|
||||
final finger = (width * fraction).clamp(0.0, width).toDouble();
|
||||
final thumbSlotLeft = dragging
|
||||
? finger - _thumbActiveSize / 2
|
||||
: (finger - _thumbActiveSize / 2)
|
||||
.clamp(0.0, width - _thumbActiveSize)
|
||||
.toDouble();
|
||||
final playedWidth = dragging ? finger : width * fraction;
|
||||
final trackSlotBottom = _lineCenterFromBottom - _trackActiveHeight / 2;
|
||||
final thumbSlotBottom = _lineCenterFromBottom - _thumbActiveSize / 2;
|
||||
return SizedBox(
|
||||
@@ -348,9 +352,10 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: AnimatedContainer(
|
||||
duration: _trackResizeDuration,
|
||||
key: const Key('home-feed-progress-played'),
|
||||
duration: dragging ? Duration.zero : _trackResizeDuration,
|
||||
curve: Curves.easeOut,
|
||||
width: width * fraction,
|
||||
width: playedWidth,
|
||||
height: trackHeight,
|
||||
color: AppColors.blue,
|
||||
),
|
||||
|
||||
@@ -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();
|
||||
final genres = _genreValues(Localizations.localeOf(context).languageCode);
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -132,17 +132,19 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
l10n.favoriteEpisodeProgress(
|
||||
widget.episode.number,
|
||||
widget.drama.episodeCount,
|
||||
),
|
||||
key: const Key('home-feed-episode-progress'),
|
||||
maxLines: 1,
|
||||
softWrap: false,
|
||||
style: const TextStyle(
|
||||
color: AppColors.overlayLabel,
|
||||
fontSize: _tagFont,
|
||||
Flexible(
|
||||
child: Text(
|
||||
l10n.favoriteEpisodeProgress(
|
||||
widget.episode.number,
|
||||
widget.drama.episodeCount,
|
||||
),
|
||||
key: const Key('home-feed-episode-progress'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: AppColors.overlayLabel,
|
||||
fontSize: _tagFont,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -283,7 +285,9 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _genreValues() {
|
||||
List<String> _genreValues(String languageCode) {
|
||||
final localized = widget.drama.localizedTypeLabels(languageCode);
|
||||
if (localized.isNotEmpty) return localized.take(3).toList(growable: false);
|
||||
final result = <String>[];
|
||||
for (final value in [widget.drama.genre, widget.drama.category]) {
|
||||
for (final part in value.split(_tagSplitter)) {
|
||||
|
||||
@@ -1,11 +1,39 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
|
||||
const int _heartDurationMs = 680;
|
||||
const double _heartPopPortion = 0.18;
|
||||
const double _heartStartScale = 0.7;
|
||||
const double _heartHoldPortion = 0.45;
|
||||
|
||||
const List<_HeartParticle> _hearts = [
|
||||
_HeartParticle(
|
||||
delay: 0,
|
||||
travel: 108,
|
||||
drift: 0,
|
||||
size: 48,
|
||||
color: AppColors.doubleTapHeartRed,
|
||||
),
|
||||
_HeartParticle(
|
||||
delay: 50,
|
||||
travel: 96,
|
||||
drift: -28,
|
||||
size: 36,
|
||||
color: AppColors.doubleTapHeartPink,
|
||||
),
|
||||
_HeartParticle(
|
||||
delay: 90,
|
||||
travel: 118,
|
||||
drift: 26,
|
||||
size: 40,
|
||||
color: AppColors.doubleTapHeartRed,
|
||||
),
|
||||
];
|
||||
|
||||
/// 双击点赞时,在点击位置飘出一小簇心。
|
||||
class PlayerDoubleTapHeartBurst extends StatefulWidget {
|
||||
const PlayerDoubleTapHeartBurst({super.key, required this.onCompleted});
|
||||
|
||||
@@ -19,30 +47,14 @@ class PlayerDoubleTapHeartBurst extends StatefulWidget {
|
||||
class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller;
|
||||
late final List<_HeartParticle> _particles;
|
||||
bool _completed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final random = Random();
|
||||
var delay = 0;
|
||||
_particles = List.generate(3 + random.nextInt(2), (index) {
|
||||
if (index > 0) delay += 40 + random.nextInt(21);
|
||||
return _HeartParticle(
|
||||
delay: delay,
|
||||
duration: 600 + random.nextInt(101),
|
||||
travel: 90 + random.nextInt(31),
|
||||
drift: -18 + random.nextInt(37),
|
||||
size: (20 + random.nextInt(7)).toDouble(),
|
||||
color: random.nextBool()
|
||||
? AppColors.doubleTapHeartRed
|
||||
: AppColors.doubleTapHeartPink,
|
||||
);
|
||||
});
|
||||
final total = _particles
|
||||
.map((particle) => particle.delay + particle.duration)
|
||||
.reduce(max);
|
||||
final total = _hearts
|
||||
.map((heart) => heart.delay + _heartDurationMs)
|
||||
.reduce((left, right) => left > right ? left : right);
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: Duration(milliseconds: total),
|
||||
@@ -76,7 +88,8 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
for (final particle in _particles) _particle(particle, elapsed),
|
||||
for (var index = 0; index < _hearts.length; index++)
|
||||
_heart(_hearts[index], elapsed, index),
|
||||
],
|
||||
);
|
||||
},
|
||||
@@ -85,27 +98,32 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
|
||||
);
|
||||
}
|
||||
|
||||
Widget _particle(_HeartParticle particle, double elapsed) {
|
||||
final progress = ((elapsed - particle.delay) / particle.duration).clamp(
|
||||
Widget _heart(_HeartParticle heart, double elapsed, int index) {
|
||||
final progress = ((elapsed - heart.delay) / _heartDurationMs).clamp(
|
||||
0.0,
|
||||
1.0,
|
||||
);
|
||||
if (progress <= 0) return const SizedBox.shrink();
|
||||
final move = Curves.easeOutCubic.transform(progress);
|
||||
final scale = progress < 0.3
|
||||
? 0.55 + (1.15 - 0.55) * (progress / 0.3)
|
||||
: 1.15 - (1.15 - 0.2) * ((progress - 0.3) / 0.7);
|
||||
final scale = progress < _heartPopPortion
|
||||
? _heartStartScale +
|
||||
(1 - _heartStartScale) * (progress / _heartPopPortion)
|
||||
: 1.0;
|
||||
final opacity = progress < _heartHoldPortion
|
||||
? 1.0
|
||||
: 1 - ((progress - _heartHoldPortion) / (1 - _heartHoldPortion));
|
||||
return Positioned(
|
||||
left: particle.drift * move - particle.size / 2,
|
||||
top: -particle.travel * move,
|
||||
left: heart.drift * move - heart.size / 2,
|
||||
top: -heart.size / 2 - heart.travel * move,
|
||||
child: Opacity(
|
||||
opacity: 1 - Curves.easeIn.transform(progress),
|
||||
opacity: opacity.clamp(0.0, 1.0),
|
||||
child: Transform.scale(
|
||||
scale: scale,
|
||||
child: Icon(
|
||||
key: Key('double-tap-heart-$index'),
|
||||
Icons.favorite_rounded,
|
||||
color: particle.color,
|
||||
size: particle.size,
|
||||
color: heart.color,
|
||||
size: heart.size,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -116,7 +134,6 @@ class _PlayerDoubleTapHeartBurstState extends State<PlayerDoubleTapHeartBurst>
|
||||
class _HeartParticle {
|
||||
const _HeartParticle({
|
||||
required this.delay,
|
||||
required this.duration,
|
||||
required this.travel,
|
||||
required this.drift,
|
||||
required this.size,
|
||||
@@ -124,9 +141,8 @@ class _HeartParticle {
|
||||
});
|
||||
|
||||
final int delay;
|
||||
final int duration;
|
||||
final int travel;
|
||||
final int drift;
|
||||
final double travel;
|
||||
final double drift;
|
||||
final double size;
|
||||
final Color color;
|
||||
}
|
||||
@@ -22,19 +22,25 @@ const double _segmentTrackRadius = 10;
|
||||
const double _segmentTrackPadding = 4;
|
||||
const double _segmentPadding = 10;
|
||||
const List<double> _speedOptions = [0.75, 1.0, 1.25, 1.5, 2.0, 3.0];
|
||||
const List<String> _qualityOptions = ['AUTO', '720P', '1080P'];
|
||||
const String _autoQuality = 'AUTO';
|
||||
const List<String> _qualityOptions = ['AUTO', '360P', '480P', '720P', '1080P'];
|
||||
|
||||
/// 更多面板运行状态。
|
||||
class PlayerMoreState {
|
||||
/// 创建更多面板状态。
|
||||
const PlayerMoreState({required this.speed, required this.qualities});
|
||||
const PlayerMoreState({
|
||||
required this.speed,
|
||||
required this.qualities,
|
||||
this.selectedQuality = 'AUTO',
|
||||
});
|
||||
|
||||
/// 当前倍速。
|
||||
final double speed;
|
||||
|
||||
/// 后端下发的清晰度档位。
|
||||
final List<String> qualities;
|
||||
|
||||
/// 当前选中的档位,如 AUTO / 720P。
|
||||
final String selectedQuality;
|
||||
}
|
||||
|
||||
/// 更多面板动作集合。
|
||||
@@ -44,6 +50,7 @@ class PlayerMoreActions {
|
||||
required this.onSpeedChanged,
|
||||
required this.onClear,
|
||||
required this.onDownload,
|
||||
required this.onQualityChanged,
|
||||
this.onPip,
|
||||
});
|
||||
|
||||
@@ -56,6 +63,9 @@ class PlayerMoreActions {
|
||||
/// 离线缓存当前集。
|
||||
final VoidCallback onDownload;
|
||||
|
||||
/// 切换清晰度。成功返回 true;失败时面板恢复到上一档。
|
||||
final Future<bool> Function(String quality) onQualityChanged;
|
||||
|
||||
/// 进入小窗播放;平台不支持时为 null。
|
||||
final VoidCallback? onPip;
|
||||
}
|
||||
@@ -85,6 +95,7 @@ class PlayerMoreSheet extends StatefulWidget {
|
||||
|
||||
class _PlayerMoreSheetState extends State<PlayerMoreSheet> {
|
||||
late double _speed = widget.state.speed;
|
||||
late String _quality = widget.state.selectedQuality.toUpperCase();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -247,19 +258,31 @@ class _PlayerMoreSheetState extends State<PlayerMoreSheet> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _chooseQuality(String quality) async {
|
||||
if (_quality == quality) return;
|
||||
final previous = _quality;
|
||||
setState(() => _quality = quality);
|
||||
final switched = await widget.actions.onQualityChanged(quality);
|
||||
if (!mounted || switched) return;
|
||||
setState(() => _quality = previous);
|
||||
}
|
||||
|
||||
bool _hasQuality(String quality) {
|
||||
final wanted = quality.toUpperCase();
|
||||
for (final item in widget.state.qualities) {
|
||||
if (item.toUpperCase() == wanted) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Widget _qualitySegment(AppLocalizations l10n, String quality) {
|
||||
final enabled = widget.state.qualities.contains(quality);
|
||||
final selected =
|
||||
quality == _autoQuality && enabled ||
|
||||
!widget.state.qualities.contains(_autoQuality) &&
|
||||
widget.state.qualities.isNotEmpty &&
|
||||
widget.state.qualities.first == quality;
|
||||
final enabled = _hasQuality(quality);
|
||||
return _SegmentButton(
|
||||
key: Key('player-more-quality-$quality'),
|
||||
label: enabled ? quality : '$quality · ${l10n.qualityUnavailable}',
|
||||
selected: selected,
|
||||
selected: enabled && _quality == quality,
|
||||
enabled: enabled,
|
||||
onTap: enabled ? () {} : null,
|
||||
onTap: enabled ? () => _chooseQuality(quality) : null,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// 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();
|
||||
}
|
||||
}
|
||||
@@ -220,11 +220,12 @@ class PlayerPlaybackOverlay extends StatelessWidget {
|
||||
),
|
||||
if (data.boosting) _boostHint(),
|
||||
_bottomProgress(),
|
||||
// 加速或拖动进度时只留进度条,避免挡住画面。
|
||||
Offstage(
|
||||
offstage: data.boosting || scrubbing,
|
||||
child: _bottomActions(),
|
||||
),
|
||||
// 加速时收起底栏。拖动进度时底栏只隐藏,占位保留,进度条不挪位。
|
||||
scrubbing
|
||||
? IgnorePointer(
|
||||
child: Opacity(opacity: 0, child: _bottomActions()),
|
||||
)
|
||||
: Offstage(offstage: data.boosting, child: _bottomActions()),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
|
||||
import '../../../core/data/models/drama.dart';
|
||||
|
||||
@@ -10,16 +10,22 @@ const Duration _videoFadeDuration = Duration(milliseconds: 200);
|
||||
const double _errorHorizontal = 32;
|
||||
const int _errorMaxLines = 3;
|
||||
|
||||
/// 黑色底层与视频层共用同一控制器,视频首帧就绪后再淡入。
|
||||
/// 黑色底层与视频层共用同一控制器。清晰度切换时用仍在播放的旧画面盖住新纹理的黑帧。
|
||||
class PlayerVideoSurface extends StatefulWidget {
|
||||
const PlayerVideoSurface({
|
||||
super.key,
|
||||
required this.controller,
|
||||
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;
|
||||
|
||||
@@ -48,7 +54,8 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
|
||||
|
||||
Widget _frame(VideoPlayerValue? value) {
|
||||
final controller = widget.controller;
|
||||
final reveal = _shouldReveal(value);
|
||||
final handoff = _liveHandoff(controller);
|
||||
final reveal = _shouldReveal(value, handoff != null);
|
||||
_logStateChange(value);
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
@@ -57,10 +64,15 @@ 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,
|
||||
duration: _videoFadeDuration,
|
||||
duration: handoff != null ? Duration.zero : _videoFadeDuration,
|
||||
curve: Curves.easeOut,
|
||||
child: reveal && controller != null
|
||||
? _VideoLayer(
|
||||
@@ -70,6 +82,13 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
|
||||
)
|
||||
: const SizedBox.expand(),
|
||||
),
|
||||
if (handoff != null)
|
||||
_VideoLayer(
|
||||
key: const Key('player-video-handoff'),
|
||||
controller: handoff,
|
||||
value: handoff.value,
|
||||
theater: widget.theater,
|
||||
),
|
||||
if (kDebugMode && value?.hasError == true)
|
||||
Center(
|
||||
child: Padding(
|
||||
@@ -88,12 +107,17 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
|
||||
);
|
||||
}
|
||||
|
||||
bool _shouldReveal(VideoPlayerValue? value) {
|
||||
return value != null &&
|
||||
!value.hasError &&
|
||||
value.isInitialized &&
|
||||
value.size.width > 0 &&
|
||||
(value.position > Duration.zero || value.isPlaying);
|
||||
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;
|
||||
}
|
||||
|
||||
/// 只画会话仍持有的旧画面,控制器一旦被换掉就不再引用。
|
||||
VideoPlayerController? _liveHandoff(VideoPlayerController? controller) {
|
||||
final handoff = widget.handoff;
|
||||
if (handoff == null || identical(handoff, controller)) return null;
|
||||
return handoff;
|
||||
}
|
||||
|
||||
void _logStateChange(VideoPlayerValue? value) {
|
||||
@@ -135,6 +159,7 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
|
||||
|
||||
class _VideoLayer extends StatelessWidget {
|
||||
const _VideoLayer({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.value,
|
||||
required this.theater,
|
||||
|
||||
@@ -13,6 +13,8 @@ import 'loading_progress_track.dart';
|
||||
import 'scrub_preview_card.dart';
|
||||
|
||||
const Key _inactiveTrackKey = Key('progress-inactive');
|
||||
const double _compactTrackSlot = 20;
|
||||
const double _trackSlot = 44;
|
||||
|
||||
/// Keeps seeks within the playable range so dragging to the edge does not
|
||||
/// trigger the player's completion callback before playback resumes.
|
||||
@@ -241,11 +243,7 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
|
||||
widget.thumbnailService != null &&
|
||||
(widget.episodeId?.isNotEmpty ?? false);
|
||||
final trackHeight = scrubbing ? 6.0 : 2.0;
|
||||
final trackAreaHeight = loading
|
||||
? (widget.compact ? 20.0 : 44.0)
|
||||
: widget.compact
|
||||
? (scrubbing ? 32.0 : 20.0)
|
||||
: (scrubbing ? 48.0 : 44.0);
|
||||
final trackAreaHeight = widget.compact ? _compactTrackSlot : _trackSlot;
|
||||
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
|
||||
@@ -153,6 +153,8 @@ class _RankingPageState extends State<RankingPage> {
|
||||
],
|
||||
PagedLoadFooter(
|
||||
loading: _pager!.loading,
|
||||
hasMore: _pager!.hasMore,
|
||||
hasItems: _pager!.visibleItems.isNotEmpty,
|
||||
loadMoreKey: const Key('ranking-load-more'),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -6,8 +6,11 @@ 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';
|
||||
@@ -23,14 +26,22 @@ class RecommendPage extends StatefulWidget {
|
||||
const RecommendPage({
|
||||
super.key,
|
||||
required this.feedController,
|
||||
this.catalogApi,
|
||||
required this.active,
|
||||
required this.onSearch,
|
||||
this.videoOnly = false,
|
||||
this.onImmersiveChanged,
|
||||
});
|
||||
|
||||
final HomeFeedController feedController;
|
||||
final CatalogApi? catalogApi;
|
||||
final bool active;
|
||||
final VoidCallback onSearch;
|
||||
|
||||
/// 画中画时只留视频,不画顶栏。
|
||||
final bool videoOnly;
|
||||
final ValueChanged<bool>? onImmersiveChanged;
|
||||
|
||||
@override
|
||||
State<RecommendPage> createState() => _RecommendPageState();
|
||||
}
|
||||
@@ -40,6 +51,32 @@ 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();
|
||||
@@ -76,6 +113,7 @@ class _RecommendPageState extends State<RecommendPage> {
|
||||
child: _withTopNavSpace(
|
||||
AllDramasFilterGrid(
|
||||
feedController: widget.feedController,
|
||||
catalogApi: widget.catalogApi,
|
||||
onOpenDrama: _openDrama,
|
||||
),
|
||||
),
|
||||
@@ -84,40 +122,42 @@ class _RecommendPageState extends State<RecommendPage> {
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: IgnorePointer(
|
||||
child: SizedBox(
|
||||
height: 72,
|
||||
child: DecoratedBox(
|
||||
key: const Key('recommend-top-gradient'),
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [AppColors.mediaBlack, AppColors.transparent],
|
||||
if (!widget.videoOnly)
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: IgnorePointer(
|
||||
child: SizedBox(
|
||||
height: 72,
|
||||
child: DecoratedBox(
|
||||
key: const Key('recommend-top-gradient'),
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [AppColors.mediaBlack, AppColors.transparent],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: RecommendTopNav(
|
||||
selected: _tab,
|
||||
onVideo: _tab == RecommendInnerTab.feed,
|
||||
onSelected: _selectTab,
|
||||
onSearch: _handleSearch,
|
||||
if (!widget.videoOnly)
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: RecommendTopNav(
|
||||
selected: _tab,
|
||||
onVideo: _tab == RecommendInnerTab.feed,
|
||||
onSelected: _selectTab,
|
||||
onSearch: _handleSearch,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -155,10 +195,27 @@ class _RecommendPageState extends State<RecommendPage> {
|
||||
_openDrama(drama, episodeId: episode.id),
|
||||
onRefreshFeed: widget.feedController.refreshCurrent,
|
||||
onLoadMore: widget.feedController.loadMore,
|
||||
onImmersiveChanged: widget.onImmersiveChanged,
|
||||
scrubCancelRequest: _scrubCancelRequest,
|
||||
);
|
||||
}
|
||||
|
||||
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'),
|
||||
@@ -196,6 +253,8 @@ class _RecommendPageState extends State<RecommendPage> {
|
||||
categories: categories,
|
||||
onOpenDrama: _openDrama,
|
||||
onMore: _handleMore,
|
||||
playlists: _watchPlaylists(context),
|
||||
onOpenPlaylist: _openPlaylist,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -243,6 +302,36 @@ 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,10 +1,14 @@
|
||||
// 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';
|
||||
@@ -12,21 +16,24 @@ 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 List<String> _modernTerms = ['现代', 'modern', 'moderno'];
|
||||
const List<String> _reversalTerms = ['逆袭', 'comeback', 'balas'];
|
||||
const int _gridColumns = 3;
|
||||
|
||||
/// 推荐页「全部短剧」筛选和三列列表。
|
||||
class AllDramasFilterGrid extends StatefulWidget {
|
||||
const AllDramasFilterGrid({
|
||||
super.key,
|
||||
required this.feedController,
|
||||
required this.onOpenDrama,
|
||||
this.feedController,
|
||||
this.catalogApi,
|
||||
this.controller,
|
||||
});
|
||||
|
||||
final HomeFeedController feedController;
|
||||
final HomeFeedController? feedController;
|
||||
final CatalogApi? catalogApi;
|
||||
final AllDramasController? controller;
|
||||
final ValueChanged<Drama> onOpenDrama;
|
||||
|
||||
@override
|
||||
@@ -34,108 +41,143 @@ class AllDramasFilterGrid extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
||||
String _region = 'all';
|
||||
String _audio = 'all';
|
||||
String? _genre;
|
||||
bool _newest = false;
|
||||
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;
|
||||
|
||||
@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: 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.homeGridFilterEmpty,
|
||||
actionLabel: l10n.homeGridClearFilter,
|
||||
onAction: () => setState(() {
|
||||
_region = 'all';
|
||||
_audio = 'all';
|
||||
_genre = null;
|
||||
}),
|
||||
),
|
||||
)
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(child: _dramaList(l10n, _itemExtent(constraints.maxWidth))),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
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 genres = _availableGenres(l10n);
|
||||
final languageCode = Localizations.localeOf(context).languageCode;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppDimens.allDramasHorizontal,
|
||||
@@ -146,60 +188,75 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
||||
child: Column(
|
||||
key: const Key('all-dramas-filters'),
|
||||
children: [
|
||||
_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: 0,
|
||||
group: 'classification',
|
||||
options: _library.classifications,
|
||||
selected: _library.selectedClassifications,
|
||||
onToggle: _library.toggleClassification,
|
||||
),
|
||||
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),
|
||||
_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,
|
||||
),
|
||||
_genreRow(2, genres, l10n),
|
||||
_sortRow(l10n),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _selectableRow(
|
||||
int row,
|
||||
List<({String id, String label})> options, {
|
||||
required String selected,
|
||||
required ValueChanged<String> onSelected,
|
||||
}) {
|
||||
Widget _optionRow(_FilterRow spec, String languageCode, AppLocalizations l10n) {
|
||||
return _filterRow(
|
||||
row: row,
|
||||
row: spec.row,
|
||||
child: _horizontalChipScroll(
|
||||
scrollKey: Key('all-filter-scroll-$row'),
|
||||
scrollKey: Key('all-filter-scroll-${spec.row}'),
|
||||
chips: [
|
||||
for (var index = 0; index < options.length; index++) ...[
|
||||
_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),
|
||||
_chip(
|
||||
key: Key('all-filter-${options[index].id}'),
|
||||
label: options[index].label,
|
||||
selected: selected == options[index].id,
|
||||
onTap: () => onSelected(options[index].id),
|
||||
key: Key('all-filter-${spec.group}-${option.id}'),
|
||||
label: option.localizedName(languageCode),
|
||||
selected: spec.selected.contains(option.id),
|
||||
onTap: () => _select(spec.onToggle, option.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,
|
||||
@@ -211,43 +268,17 @@ class _AllDramasFilterGridState extends State<AllDramasFilterGrid> {
|
||||
physics: const BouncingScrollPhysics(),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(minWidth: constraints.maxWidth),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: chips,
|
||||
),
|
||||
child: Row(children: chips),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _filterRow({
|
||||
required int row,
|
||||
required Widget child,
|
||||
double height = AppDimens.filterChipHeight,
|
||||
}) {
|
||||
Widget _filterRow({required int row, required Widget child}) {
|
||||
return Padding(
|
||||
key: Key('all-filter-row-$row'),
|
||||
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),
|
||||
padding: EdgeInsets.only(bottom: row < 2 ? AppDimens.filterRowGap : 0),
|
||||
child: SizedBox(height: AppDimens.filterChipHeight, child: child),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -268,9 +299,7 @@ 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(
|
||||
@@ -288,84 +317,32 @@ 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;
|
||||
final reachedBottom =
|
||||
notification.metrics.extentAfter <= _loadMoreThreshold;
|
||||
if (notification.metrics.pixels <= 0) return false;
|
||||
final reachedBottom = notification.metrics.extentAfter <= _loadMoreThreshold;
|
||||
if (reachedBottom &&
|
||||
(notification is ScrollUpdateNotification ||
|
||||
notification is ScrollEndNotification ||
|
||||
notification is OverscrollNotification)) {
|
||||
unawaited(widget.feedController.loadMore());
|
||||
unawaited(_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;
|
||||
}
|
||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user