Author SHA1 Message Date
Zhou Weidong 67e178c89d chore(merge): 将 develop 同步到 release/v1.0.0 2026-10-23 13:07:33 +08:00
Zhou Weidong 8481611372 chore(merge): 合并错误码三语文案 2026-10-23 13:05:29 +08:00
Zhou Weidong b1e95b370c feat(app): 按错误码展示中英印尼文案 2026-10-23 13:05:29 +08:00
Zhou Weidong 0ef0d46919 chore(merge): 合并未使用注销原因清理 2026-10-23 12:45:30 +08:00
Zhou Weidong b4d38f8e10 refactor(app): 删除未使用的注销原因组件 2026-10-23 12:45:30 +08:00
Zhou Weidong c034627fdb chore(merge): 合并播放协议搜索与空状态 2026-10-23 12:38:47 +08:00
Zhou Weidong ef29fc5f15 feat(app): 完善播放协议搜索与空状态 2026-10-23 12:38:47 +08:00
Zhou Weidong 671e0ce143 merge: 将远程 main 同步到 develop 2026-10-23 08:09:24 +08:00
Zhou Weidong 0f1f64a09f merge: 将 release/v1.0.0 同步到 main 2026-10-23 03:22:26 +08:00
Zhou Weidong d29ae20491 merge: 将客户端调整同步到 release/v1.0.0 2026-10-23 03:21:53 +08:00
Zhou Weidong 12e08a89a4 fix(player): 提高解锁金币标签对比度 2026-10-23 03:18:24 +08:00
Zhou Weidong e0ba54f23b fix(cover): 封面占位改为品牌标识 2026-10-23 03:18:24 +08:00
Zhou Weidong 5043d6c25b fix(l10n): 缩短印尼语全部短剧文案 2026-10-23 03:18:24 +08:00
Zhou Weidong ab6800aba2 fix(search): 避免键盘顶起搜索页 2026-10-23 03:18:24 +08:00
Zhou Weidong f8500bbaca fix(player): 完善进度预览清屏与下拉刷新 2026-10-23 03:18:24 +08:00
Zhou Weidong 9b1afbdb36 feat(recommend): 剧单更多进入两列详情页 2026-10-23 03:18:24 +08:00
Zhou Weidong f4cf7bc2dd fix(home): 调整榜单版式并去掉二级分类 2026-10-23 03:18:24 +08:00
Zhou Weidong 60489d6dca fix(ios): 修复逐帧请求头编译失败 2026-10-23 03:18:23 +08:00
Zhou Weidong 44d3bcba18 style(empty): 放大空状态图标并降低亮度 2026-10-23 01:10:59 +08:00
Zhou Weidong f206977ad8 fix(config): 开发服务地址改为当前局域网 2026-10-23 01:10:59 +08:00
Zhou Weidong f3d64f6fb5 fix(auth): 登录页靠上排列并支持外部失焦 2026-10-23 01:10:59 +08:00
Zhou Weidong 6318ca24ec feat(splash): 缩短开屏停留并统一开屏图 2026-10-23 01:06:07 +08:00
Zhou Weidong b513ac0a9c merge: 调整品牌开屏与纯黑原生启动 2026-10-22 23:15:36 +08:00
Zhou Weidong 25d90e1383 feat: 调整品牌开屏与纯黑原生启动 2026-10-22 23:15:27 +08:00
Zhou Weidong 7804809d83 merge: 开屏后直接展示首页骨架 2026-10-22 23:11:13 +08:00
Zhou Weidong 5f278a3510 feat: 开屏后直接展示首页骨架 2026-10-22 23:11:03 +08:00
Vicky a1c0af3f00 merge: 将 release/v1.0.0 同步到 main 2026-10-21 20:07:35 +08:00
Vicky b5bfc1d7b2 merge: 将 develop 同步到 release/v1.0.0 2026-10-21 20:07:30 +08:00
Vicky 1d2ba93e48 merge: 同步 release 剔除 x86_64 到 main 2026-10-21 19:13:33 +08:00
Vicky c08df9af40 merge: 同步 release 剔除 x86_64 到 release/v1.0.0 2026-10-21 19:13:28 +08:00
Vicky be166f5856 merge: 同步生产包 ABI 约束到 main 2026-10-21 19:10:11 +08:00
Vicky e531c78997 merge: 同步生产包 ABI 约束到 release/v1.0.0 2026-10-21 19:10:10 +08:00
Vicky 8ed6cd9fd6 merge: 同步生产打包单包说明到 main 2026-10-21 19:07:03 +08:00
Vicky c1d55b91a2 merge: 同步生产打包单包说明到 release/v1.0.0 2026-10-21 19:06:57 +08:00
Vicky 3dcfa02372 merge: 同步 README 生产打包说明到 main 2026-10-21 19:03:06 +08:00
Vicky b6826f7483 merge: 同步 README 生产打包说明到 release/v1.0.0 2026-10-21 19:03:01 +08:00
Vicky cd3d84cf9a merge: 将 release/v1.0.0 同步到 main 2026-10-21 18:58:26 +08:00
Vicky 010ce326ea merge: 将 develop 同步到 release/v1.0.0 2026-10-21 18:58:12 +08:00
Zhou Weidong 2577797772 merge: 将 C3 埋点同步到 main 2026-10-21 09:09:34 +08:00
Zhou Weidong 05e2952815 merge: 将 C3 埋点同步到 release/v1.0.0 2026-10-21 09:07:42 +08:00
Zhou Weidong 6ae9e8e043 merge: 将 release/v1.0.0 同步到 main 2026-10-20 22:26:48 +08:00
Zhou Weidong 182b7e3ac2 merge: 将 develop 同步到 release/v1.0.0 2026-10-20 22:23:32 +08:00
Zhou Weidong 8bb365db2a merge: 将 release/v1.0.0 合入 main 2026-10-20 20:38:58 +08:00
Zhou Weidong 0cb57d084d merge: 将 develop 合入 release/v1.0.0
# Conflicts:
#	lib/core/config/app_config.dart
#	lib/main.dart
#	test/config/server_endpoint_test.dart
2026-10-20 20:36:43 +08:00
jianghaifeng 5c174b007c Merge pull request 'Release/v1.0.0' (#1) from release/v1.0.0 into main
Reviewed-on: #1
2026-10-19 13:42:16 +00:00
Zhou Weidong 35364c949a chore(release): 合并 develop 到 release/v1.0.0 2026-10-19 21:39:21 +08:00
Zhou Weidong 814b2c0b7b chore(config): 默认服务地址改为公网 39.162.50.99:8081 2026-10-19 21:12:16 +08:00
Zhou Weidong 3d0e0804ca fix(app): 修复视频播放明文HTTP与双网络访问切换 2026-10-19 18:37:38 +08:00
145 changed files with 4991 additions and 1658 deletions

No files matched your search

@@ -36,6 +36,9 @@ class MainActivity : FlutterActivity() {
private var imeInset = 0
override fun onCreate(savedInstanceState: Bundle?) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
splashScreen.setOnExitAnimationListener { screen -> screen.remove() }
}
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

@@ -1,4 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Author: fruit.com.cn -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splash_background" />
<item>
<bitmap
android:gravity="center"
android:src="@drawable/splash_screen" />
</item>
</layer-list>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

@@ -1,4 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Author: fruit.com.cn -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splash_background" />
<item>
<bitmap
android:gravity="center"
android:src="@drawable/splash_screen" />
</item>
</layer-list>
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -1,9 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Author: fruit.com.cn -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splash_background" />
<item>
<bitmap android:gravity="fill" android:src="@drawable/background"/>
</item>
<item>
<bitmap android:gravity="center" android:src="@drawable/splash"/>
<bitmap
android:gravity="center"
android:src="@drawable/splash_screen" />
</item>
</layer-list>
@@ -1,6 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Author: fruit.com.cn -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splash_background" />
<item>
<bitmap
android:gravity="center"
android:src="@drawable/splash_screen" />
</item>
</layer-list>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

@@ -1,9 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Author: fruit.com.cn -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splash_background" />
<item>
<bitmap android:gravity="fill" android:src="@drawable/background"/>
</item>
<item>
<bitmap android:gravity="center" android:src="@drawable/splash"/>
<bitmap
android:gravity="center"
android:src="@drawable/splash_screen" />
</item>
</layer-list>
@@ -8,7 +8,8 @@
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
<item name="android:windowSplashScreenBackground">#000000</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_brand</item>
<item name="android:windowSplashScreenAnimationDuration">0</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@color/splash_background</item>
@@ -8,7 +8,8 @@
<item name="android:windowDrawsSystemBarBackgrounds">false</item>
<item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
<item name="android:windowSplashScreenBackground">#000000</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/android12splash</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/splash_brand</item>
<item name="android:windowSplashScreenAnimationDuration">0</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">@color/splash_background</item>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 24 KiB

+4 -2
View File
@@ -2,6 +2,8 @@ import Flutter
import UIKit
import AVFoundation
private let thumbnailHTTPHeaderFieldsKey = "AVURLAssetHTTPHeaderFieldsKey"
private final class ThumbnailResponseGate {
private let lock = NSLock()
private var completed = false
@@ -29,7 +31,7 @@ final class RunnerFlutterViewController: FlutterViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 16.0 / 255.0, green: 12.0 / 255.0, blue: 10.0 / 255.0, alpha: 1)
view.backgroundColor = .black
}
}
@@ -104,7 +106,7 @@ final class RunnerFlutterViewController: FlutterViewController {
let options: [String: Any]? = headers.isEmpty
? nil
: [AVURLAssetHTTPHeaderFieldsKey: headers]
: [thumbnailHTTPHeaderFieldsKey: headers]
let asset = AVURLAsset(url: assetUrl, options: options)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 24 KiB

@@ -16,18 +16,13 @@
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleToFill" image="LaunchBackground" translatesAutoresizingMaskIntoConstraints="NO" id="tWc-Dq-wcI"/>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4"></imageView>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4"/>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<color key="backgroundColor" red="0" green="0" blue="0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" id="3T2-ad-Qdv"/>
<constraint firstItem="tWc-Dq-wcI" firstAttribute="bottom" secondItem="Ze5-6b-2t3" secondAttribute="bottom" id="RPx-PI-7Xg"/>
<constraint firstItem="tWc-Dq-wcI" firstAttribute="top" secondItem="Ze5-6b-2t3" secondAttribute="top" id="SdS-ul-q2q"/>
<constraint firstAttribute="trailing" secondItem="tWc-Dq-wcI" secondAttribute="trailing" id="Swv-Gf-Rwn"/>
<constraint firstAttribute="trailing" secondItem="YRO-k0-Ey4" secondAttribute="trailing" id="TQA-XW-tRk"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="bottom" secondItem="Ze5-6b-2t3" secondAttribute="bottom" id="duK-uY-Gun"/>
<constraint firstItem="tWc-Dq-wcI" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" id="kV7-tw-vXt"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="top" secondItem="Ze5-6b-2t3" secondAttribute="top" id="xPn-NY-SIU"/>
</constraints>
</view>
@@ -38,7 +33,6 @@
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="1400" height="1400"/>
<image name="LaunchBackground" width="1" height="1"/>
<image name="LaunchImage" width="390" height="844"/>
</resources>
</document>
+1 -1
View File
@@ -48,7 +48,7 @@
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>192.168.31.187</key>
<key>10.43.47.1</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
+1 -1
View File
@@ -14,7 +14,7 @@ class AppConfig {
/// 开发调试默认服务地址,当前指向本机局域网 IP。
///
/// 换网络时只改这一行,地址不要带结尾斜杠。
static const String devHostBaseUrl = 'http://192.168.31.187:8081';
static const String devHostBaseUrl = 'http://10.43.47.1:8081';
/// 本机后端地址:通过 `adb reverse tcp:8081 tcp:8081` 映射到开发机,
/// 探测可达时 App 直连本机服务;不可达时回落到公网地址。
+67 -1
View File
@@ -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;
+8
View File
@@ -18,6 +18,7 @@ class WatchProgress {
this.totalEpisodes,
this.finished = false,
this.playCount = 0,
this.viewCount,
this.updatedAt,
});
@@ -31,6 +32,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;
@@ -57,6 +61,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? ?? ''),
);
}
@@ -72,6 +79,7 @@ class WatchProgress {
'durationMs': duration.inMilliseconds,
'finished': finished,
'playCount': playCount,
if (viewCount != null) 'viewCount': viewCount,
if (updatedAt != null) 'updatedAt': updatedAt!.toIso8601String(),
};
}
+2 -1
View File
@@ -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) {
+18 -4
View File
@@ -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>());
}
+5
View File
@@ -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);
}
}
+48 -16
View File
@@ -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;
}
}
@@ -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);
+120 -2
View File
@@ -5,6 +5,10 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/drama.dart';
import '../models/player_port.dart';
import 'video_player_port.dart';
/// 新纹理第一帧常是黑的,旧画面只盖住这一小段。
const Duration _qualityHandoffHold = Duration(milliseconds: 200);
typedef PlayerFactory = PlayerPort Function(Episode episode);
typedef PlayerPreparation =
@@ -66,6 +70,7 @@ class PlaybackSession extends ChangeNotifier {
final Set<_PlayerSlot> _live = {};
_PlayerSlot? _active;
_PlayerSlot? _next;
_PlayerSlot? _handoff;
Future<void> _operations = Future<void>.value();
Future<void> _preloadTask = Future<void>.value();
int _generation = 0;
@@ -127,6 +132,15 @@ 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}) {
if (_closed || index < 0 || index >= episodes.length) return;
@@ -184,9 +198,10 @@ 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 || _handoff == slot;
if (_active == slot) _active = null;
if (_next == slot) _next = null;
if (_handoff == slot) _handoff = null;
if (cleared) _notify();
await waitForFrame?.call();
await slot.ready;
@@ -235,6 +250,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 &&
@@ -272,6 +288,108 @@ class PlaybackSession extends ChangeNotifier {
if (!_closed && request == _generation) _schedulePreload();
}
/// 后台准备新片源,成功后再替换当前播放器。失败时原播放器保持不动。
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) _schedulePreload();
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 {
bool valid() => !_closed && request == _generation && _active == slot;
if (!valid()) return;
@@ -387,7 +505,7 @@ class PlaybackSession extends ChangeNotifier {
Future<void> _releasePlayers() {
_generation++;
return _enqueue(() async {
_active = _next = null;
_active = _next = _handoff = null;
_loading = false;
_notify();
for (final slot in _live.toList()) {
@@ -122,6 +122,8 @@ abstract interface class SpriteThumbnailAxisSource implements Listenable {
SpriteThumbnailFrame? cachedFrameAt(String? thumbnailsUrl, Duration position);
bool hasAxis(String? thumbnailsUrl);
Future<void> prepareAt(String? thumbnailsUrl, Duration position);
}
/// VTT 时间轴、cue 二分与 sprite ui.Image LRU 缓存。
@@ -153,6 +155,7 @@ class SpriteThumbnailAxisService extends ChangeNotifier
List<String> get spriteCacheKeys => _spriteCache.keys.toList();
/// 播放器就绪时预取当前 cue 与相邻 sprite,拖动帧不触发网络或解码。
@override
Future<void> prepareAt(String? thumbnailsUrl, Duration position) async {
final url = _normalizeUrl(thumbnailsUrl);
if (_disposed || url == null) return;
+31
View File
@@ -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) {
+127
View File
@@ -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;
}
}
+36
View File
@@ -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);
}
+12
View File
@@ -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)),
);
}
+27
View File
@@ -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)}';
}
+96
View File
@@ -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),
),
],
),
);
}
}
+2
View File
@@ -78,6 +78,7 @@ abstract final class AppColors {
/// 中性深灰卡片与控件表面。
static const contentCard = Color(0xFF16161A);
static const contentSurface = Color(0xFF1C1C1E);
static const skeletonSurface = Color(0xFF141414);
static const contentChip = Color(0xFF2C2C2E);
static const contentBorder = Color(0x1AFFFFFF);
static const filterChipSelected = Color(0xFF21090E);
@@ -104,6 +105,7 @@ 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。
+6 -1
View File
@@ -110,6 +110,11 @@ abstract final class AppDimens {
static const double cardBadgeFont = 9;
static const double cardCoverTitleGap = 6;
static const double cardTitleTagGap = 6;
static const double skeletonBarHeight = 10;
static const double skeletonBarRadius = 4;
static const double skeletonBarGap = 4;
static const double skeletonTitleBarGap = 3;
static const double skeletonBodyExtent = 34;
static const double cardCoverAspectRatio = 3 / 4;
static const double homeCardBodyExtent = 84;
static const double homePrimaryTabFont = 18;
@@ -182,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;
+96
View File
@@ -0,0 +1,96 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
class DramaGridSkeleton extends StatelessWidget {
const DramaGridSkeleton({
super.key,
required this.columns,
required this.horizontalPadding,
required this.crossAxisSpacing,
required this.mainAxisSpacing,
this.itemCount = 9,
this.physics = const NeverScrollableScrollPhysics(),
});
final int columns;
final double horizontalPadding;
final double crossAxisSpacing;
final double mainAxisSpacing;
final int itemCount;
final ScrollPhysics physics;
@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(),
),
],
),
);
},
);
}
}
class _SkeletonBar extends StatelessWidget {
const _SkeletonBar();
@override
Widget build(BuildContext context) {
return Container(
height: AppDimens.skeletonBarHeight,
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
borderRadius: BorderRadius.circular(AppDimens.skeletonBarRadius),
),
);
}
}
+7 -8
View File
@@ -5,8 +5,8 @@ import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_dimens.dart';
const double _regularIconSize = 48;
const double _compactIconSize = 32;
const double _regularIconSize = 72;
const double _compactIconSize = 44;
const double _maxContentWidth = 260;
const double _regularHorizontal = 24;
const double _regularVertical = 28;
@@ -78,7 +78,7 @@ class EmptyState extends StatelessWidget {
}
}
/// 空状态只留一枚图标,不加水印底和描边。
/// 空列表只放一枚大图标,不画线框,也不铺底色。
class _EmptyMark extends StatelessWidget {
const _EmptyMark({required this.icon, required this.compact});
@@ -91,7 +91,7 @@ class _EmptyMark extends StatelessWidget {
icon,
key: const Key('empty-state-icon'),
size: compact ? _compactIconSize : _regularIconSize,
color: AppColors.blueSoft,
color: AppColors.subtle,
);
}
}
@@ -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,
),
),
+24 -13
View File
@@ -31,34 +31,45 @@ class RemoteImage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final url = AppConfig.mediaUrl(path);
if (url.isEmpty) return _fallback();
if (url.isEmpty) return _fallback(brand: showFallbackIcon);
return Image.network(
url,
width: width,
height: height,
fit: fit,
errorBuilder: (_, _, _) => _fallback(),
gaplessPlayback: true,
errorBuilder: (_, _, _) => _fallback(brand: showFallbackIcon),
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded || frame != null) return child;
return _fallback();
return _fallback(brand: showFallbackIcon);
},
);
}
Widget _fallback() {
Widget _fallback({required bool brand}) {
final mark = brand
? LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth.isFinite
? constraints.maxWidth
: 120.0;
return Center(
child: Image.asset(
'assets/icon/splash_logo.png',
key: fallbackIconKey,
width: width * 0.72,
fit: BoxFit.contain,
),
);
},
)
: null;
final fallback = Container(
width: width,
height: height,
color: fallbackColor,
color: brand ? AppColors.mediaBlack : fallbackColor,
alignment: Alignment.center,
child: showFallbackIcon
? Icon(
Icons.image_not_supported_outlined,
key: fallbackIconKey,
color: AppColors.muted,
size: 32,
)
: null,
child: mark,
);
final ratio = fallbackAspectRatio;
if (ratio == null) return fallback;
+10 -2
View File
@@ -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(),
);
+32 -4
View File
@@ -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",
@@ -430,6 +437,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 +609,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 +689,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 +733,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 +752,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 +774,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 -5
View File
@@ -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",
@@ -404,6 +411,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 +573,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 +646,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,11 +690,10 @@
"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 Drama",
"allDramasTopTab": "Semua",
"weeklyHitsTitle": "Hits Minggu Ini",
"weeklyHitsSubtitle": "Drama terpopuler minggu ini, tonton sekaligus!",
"weeklyNewTitle": "Drama Baru Minggu Ini",
@@ -685,6 +709,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 +731,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": "—",
+173 -11
View File
@@ -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:
@@ -1858,6 +1900,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 +2575,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 +2962,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 +3202,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 +3316,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 +3409,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.
+91 -6
View File
@@ -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';
@@ -943,6 +964,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 +1333,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 +1543,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 +1673,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 +1729,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 +1779,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';
+91 -7
View File
@@ -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';
@@ -947,6 +968,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 +1332,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 +1542,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 +1673,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';
@@ -1610,7 +1682,7 @@ class AppLocalizationsId extends AppLocalizations {
String get playlistTopTab => 'Daftar Putar';
@override
String get allDramasTopTab => 'Semua Drama';
String get allDramasTopTab => 'Semua';
@override
String get weeklyHitsTitle => 'Hits Minggu Ini';
@@ -1659,6 +1731,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 +1781,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';
+89 -6
View File
@@ -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 继续';
@@ -931,6 +952,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 +1309,7 @@ class AppLocalizationsZh extends AppLocalizations {
String get accountDeactivateReason => '注销原因(选填)';
@override
String get accountDeactivateReasonHint => '告诉我们你离开的原因';
String get accountDeactivateReasonHint => '也可以在这里补充说明';
@override
String get accountRequestDeactivate => '申请注销账号';
@@ -1449,6 +1518,11 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get playbackQuality => '清晰度';
@override
String qualitySwitched(String quality) {
return '已切换至$quality';
}
@override
String get qualityAuto => '自动';
@@ -1573,10 +1647,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 +1703,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 +1753,7 @@ class AppLocalizationsZh extends AppLocalizations {
String get homeWatchAll => '观看全集';
@override
String get confirmRemove => '确定移除这条内容吗?';
String get confirmRemove => '确定要移除该条观看记录吗?';
@override
String get followingCountLabel => '追剧数';
+32 -4
View File
@@ -23,6 +23,13 @@
"authLandingSubtitle": "登录后同步进度、收藏与金币权益",
"comingSoon": "即将上线",
"authLegal": "继续即代表同意《用户协议》与《隐私政策》",
"authLegalLead": "继续即代表同意",
"authTerms": "《用户协议》",
"authLegalJoin": "与",
"authPrivacy": "《隐私政策》",
"legalTerms": "服务条款",
"legalPrivacy": "隐私协议",
"legalOpenFailed": "暂时无法打开协议页面",
"authContinueGoogle": "使用 Google 继续",
"authPhoneSignIn": "手机号登录",
"authEmailSignIn": "邮箱登录",
@@ -366,6 +373,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 +535,7 @@
"accountUnverified": "未验证",
"accountDeactivateWarning": "提交后进入 15 天冷静期,所有设备会立即退出登录。",
"accountDeactivateReason": "注销原因(选填)",
"accountDeactivateReasonHint": "告诉我们你离开的原因",
"accountDeactivateReasonHint": "也可以在这里补充说明",
"accountRequestDeactivate": "申请注销账号",
"accountConfirmDeactivateTitle": "确认申请注销?",
"accountConfirmDeactivateMessage": "所有设备会立即退出登录。重新登录后,可在 15 天冷静期内撤销申请。",
@@ -585,6 +608,8 @@
"paymentPending": "等待支付。",
"orderCreateFailed": "订单创建失败。",
"playbackQuality": "清晰度",
"qualitySwitched": "已切换至{quality}",
"@qualitySwitched": { "placeholders": { "quality": { "type": "String" } } },
"qualityAuto": "自动",
"qualityAutoHint": "HLS 会根据当前网络自动切换码率。",
"searchFailed": "搜索失败,请重试。",
@@ -627,8 +652,7 @@
"homeBadgeHot": "热剧",
"homeBadgeNew": "新剧",
"homeBadgeAnime": "漫剧",
"homeGridFilterEmpty": "没有符合筛选条件的短剧",
"homeGridClearFilter": "清除筛选",
"emptyContent": "暂无内容",
"recommendTopTab": "推荐",
"playlistTopTab": "剧单",
"allDramasTopTab": "全部短剧",
@@ -647,6 +671,10 @@
"modernFilter": "现代",
"edit": "编辑",
"done": "完成",
"selectAll": "全选",
"deselectAll": "取消全选",
"cancelFollowing": "取消追剧",
"confirmCancelFollowing": "确定取消已选短剧的追剧吗?",
"visitor": "访客",
"copyUid": "复制 UID",
"uidCopied": "UID 已复制",
@@ -665,7 +693,7 @@
"watchedToEpisode": "已看至 第 {episode} 集",
"@watchedToEpisode": { "placeholders": { "episode": { "type": "int" } } },
"homeWatchAll": "观看全集",
"confirmRemove": "确定移除这条内容吗?",
"confirmRemove": "确定要移除该条观看记录吗?",
"followingCountLabel": "追剧数",
"watchRecordsCountLabel": "观看记录",
"dataUnavailable": "—",
+6 -4
View File
@@ -1,5 +1,7 @@
// Author: fruit.com.cn
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -9,10 +11,10 @@ import 'core/config/server_endpoint.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Future.wait([
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
ServerEndpoint.load(),
]);
await ServerEndpoint.load();
AppConfig.ready = AppConfig.probeAndApplyBaseUrl();
runApp(const LumaDramaApp());
unawaited(
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]),
);
}
+99 -112
View File
@@ -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,
),
],
),
),
),
);
}
}
-1
View File
@@ -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(
+75
View File
@@ -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,
);
}
}
+54 -59
View File
@@ -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;
@@ -40,9 +42,9 @@ const double _buttonRadius = 25;
const double _errorOpacity = 0.10;
const double _errorBorderOpacity = 0.28;
const double _enterSlideDistance = 16;
const double _topContentPadding = 64;
const double _topContentPadding = 56;
const double _bottomContentPadding = 28;
const double _compactTopContentPadding = 48;
const double _compactTopContentPadding = 40;
const double _compactHeightBreakpoint = 720;
const double _compactBrandGap = 16;
const double _glowSize = 280;
@@ -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,
),
);
}
@@ -159,6 +145,19 @@ class _AuthPageState extends State<AuthPage> {
}
}
/// 点在当前邮箱或密码框之外时取消焦点。
void _releaseFieldFocus(PointerDownEvent event) {
final focus = FocusManager.instance.primaryFocus;
if (focus != _emailFocus && focus != _passwordFocus) return;
final renderObject = focus?.context?.findRenderObject();
if (renderObject is! RenderBox || !renderObject.hasSize) {
focus?.unfocus();
return;
}
final bounds = renderObject.localToGlobal(Offset.zero) & renderObject.size;
if (!bounds.contains(event.position)) focus?.unfocus();
}
void _scheduleRevealFocusedField() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _revealFocusedField();
@@ -244,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 {
@@ -325,26 +324,31 @@ class _AuthPageState extends State<AuthPage> {
effectiveKeyboardInset(context, _keyboardInset);
final available = constraints.maxHeight - top - bottom;
final minHeight = available > 0 ? available : 0.0;
return AutofillGroup(
child: SingleChildScrollView(
key: const Key('auth-scroll'),
controller: _scrollController,
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB(
AppDimens.pageHorizontal,
top,
AppDimens.pageHorizontal,
bottom,
),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: minHeight),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: _contentMaxWidth,
return Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: _releaseFieldFocus,
child: AutofillGroup(
child: SingleChildScrollView(
key: const Key('auth-scroll'),
controller: _scrollController,
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB(
AppDimens.pageHorizontal,
top,
AppDimens.pageHorizontal,
bottom,
),
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: minHeight),
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: _contentMaxWidth,
),
child: _content(l10n, compact: compact),
),
child: _content(l10n, compact: compact),
),
),
),
@@ -410,15 +414,15 @@ class _AuthPageState extends State<AuthPage> {
Widget _landing(AppLocalizations l10n) => Column(
key: const Key('auth-landing'),
mainAxisAlignment: MainAxisAlignment.center,
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),
@@ -455,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(),
],
);
+3 -2
View File
@@ -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';
@@ -180,7 +181,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
).showSnackBar(SnackBar(content: Text(l10n.authCodeSent)));
_codeFocus.requestFocus();
} on ApiException catch (error) {
failureMessage = error.message;
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
@@ -228,7 +229,7 @@ class _PhoneAuthSheetState extends State<PhoneAuthSheet> {
}
if (mounted) Navigator.of(context).pop(true);
} on ApiException catch (error) {
failureMessage = error.message;
failureMessage = userFacingApiMessage(l10n, error.code, error.message);
} catch (_) {
failureMessage = l10n.authNetworkError;
} finally {
+91 -52
View File
@@ -12,6 +12,7 @@ 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 '../../l10n/app_localizations.dart';
import '../player/open_player.dart';
@@ -19,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});
@@ -34,9 +40,6 @@ class _SearchPageState extends State<SearchPage> {
super.initState();
_logic = DiscoverBinding().create(search: context.read<SearchRepository>());
_logic.addListener(_rebuild);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _logic.searchFocus.requestFocus();
});
}
void _rebuild() {
@@ -58,21 +61,27 @@ class _SearchPageState extends State<SearchPage> {
value: SystemUiOverlayStyle.light,
child: Theme(
data: AppTheme.dark(),
child: Scaffold(
key: const Key('search-page'),
backgroundColor: AppColors.appBackground,
body: SafeArea(
child: Column(
children: [
_header(l10n),
Expanded(
child: AppPullToRefresh(
key: const Key('search-refresh'),
onRefresh: _logic.refreshSearch,
child: _body(l10n),
child: MediaQuery.removeViewInsets(
context: context,
removeBottom: true,
child: Scaffold(
key: const Key('search-page'),
backgroundColor: AppColors.appBackground,
resizeToAvoidBottomInset: false,
body: SafeArea(
bottom: false,
child: Column(
children: [
_header(l10n),
Expanded(
child: AppPullToRefresh(
key: const Key('search-refresh'),
onRefresh: _logic.refreshSearch,
child: _body(l10n),
),
),
),
],
],
),
),
),
),
@@ -115,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),
@@ -139,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,
@@ -156,37 +166,67 @@ class _SearchPageState extends State<SearchPage> {
focusedBorder: InputBorder.none,
contentPadding: EdgeInsets.zero,
),
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(
@@ -201,15 +241,14 @@ class _SearchPageState extends State<SearchPage> {
return _resultsGrid();
}
if (_logic.searchLoading) {
return _stateScroll(
const SizedBox.square(
key: Key('search-loading'),
dimension: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.textPrimary,
),
),
return const DramaGridSkeleton(
key: Key('search-loading-skeleton'),
columns: 2,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.searchResultGap,
mainAxisSpacing: AppDimens.searchResultRowGap,
itemCount: 6,
physics: AppPullToRefresh.physics,
);
}
if (_logic.searchError != null) {
+228
View File
@@ -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.title,
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));
}
}
+46 -1
View File
@@ -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});
+114 -143
View File
@@ -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,
@@ -415,7 +405,9 @@ class _HistoryList extends StatelessWidget {
title: _historyTitle(l10n, record),
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 +417,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();
@@ -469,24 +461,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;
}
+6 -3
View File
@@ -12,10 +12,11 @@ import '../player/open_player.dart';
import '../watch_records/watch_records_page.dart';
class HomeLogic extends ChangeNotifier {
HomeLogic(List<Drama> dramas) : currentDrama = dramas.first;
HomeLogic(List<Drama> dramas)
: currentDrama = dramas.isEmpty ? null : dramas.first;
final scaffoldKey = GlobalKey<ScaffoldState>();
Drama currentDrama;
Drama? currentDrama;
int tab = 0;
int resumeRequest = 0;
int backRequest = 0;
@@ -44,13 +45,15 @@ class HomeLogic extends ChangeNotifier {
}
Future<void> openCurrentSeries(BuildContext context) async {
final drama = currentDrama;
if (drama == null) return;
detailOpen = true;
notify();
await WidgetsBinding.instance.endOfFrame;
if (!context.mounted) return;
try {
await Navigator.of(context).push<void>(
MaterialPageRoute(builder: (_) => DramaDetailPage(drama: currentDrama)),
MaterialPageRoute(builder: (_) => DramaDetailPage(drama: drama)),
);
} finally {
if (context.mounted) {
+17 -66
View File
@@ -9,7 +9,6 @@ import 'package:provider/provider.dart';
import '../../core/config/app_config.dart';
import '../../core/data/services/home_feed_controller.dart';
import '../../core/data/services/catalog_controller.dart';
import '../../core/data/services/catalog_retry.dart';
import '../../core/data/services/category_controller.dart';
import '../../core/data/services/favorite_controller.dart';
import '../../core/data/services/wallet_controller.dart';
@@ -18,9 +17,6 @@ import '../../core/theme/app_colors.dart';
import '../../core/theme/app_theme.dart';
import '../../core/widgets/auth_gate.dart';
import '../../core/widgets/app_root_tab.dart';
import '../../core/widgets/catalog_endpoint_editor.dart';
import '../../core/widgets/empty_state.dart';
import '../../l10n/app_localizations.dart';
import '../discover/search_page.dart';
import '../following/following_page.dart';
import '../filter/filter_page.dart';
@@ -32,7 +28,6 @@ import '../wallet/wallet_page.dart';
import 'home_binding.dart';
import 'home_logic.dart';
import 'widgets/home_feed_grid.dart';
import 'widgets/home_failure_view.dart';
import 'widgets/home_grid_header.dart';
class HomePage extends StatefulWidget {
@@ -85,58 +80,18 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
}
}
Future<void> _retryHome(CatalogController catalog) {
return retryCatalogLoad(reload: catalog.load);
}
Future<void> _editHomeEndpoint(CatalogController catalog) {
return showCatalogEndpointEditor(context, reload: catalog.load);
}
@override
Widget build(BuildContext context) {
final catalog = context.watch<CatalogController>();
final l10n = AppLocalizations.of(context)!;
return Theme(
data: AppTheme.dark(),
child: _buildHome(context, catalog, l10n),
child: _buildHome(context, catalog),
);
}
Widget _buildHome(
BuildContext context,
CatalogController catalog,
AppLocalizations l10n,
) {
if (catalog.loading) {
return _retryLoading();
}
if (catalog.error != null) {
return Scaffold(
backgroundColor: AppColors.transparent,
body: HomeFailureView(
error: catalog.debugError ?? catalog.error,
onRetry: () => unawaited(_retryHome(catalog)),
onEditEndpoint: () => unawaited(_editHomeEndpoint(catalog)),
),
);
}
if (catalog.dramas.isEmpty) {
return Scaffold(
backgroundColor: AppColors.transparent,
body: EmptyState(
key: const Key('home-empty'),
icon: Icons.movie_outlined,
title: l10n.noStories,
subtitle: l10n.emptyHint,
actionLabel: l10n.retry,
onAction: catalog.load,
),
);
}
Widget _buildHome(BuildContext context, CatalogController catalog) {
final homeFeed = _ensureHomeFeed(catalog);
if (!_recommendSeeded) {
if (!_recommendSeeded && catalog.dramas.isNotEmpty) {
_recommendSeeded = true;
homeFeed.seedRecommend(catalog.dramas);
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -155,16 +110,6 @@ class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
await homeFeed.prefetchChannels();
}
}
Widget _retryLoading() {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: const Scaffold(
backgroundColor: AppColors.splashInk,
body: Center(child: CircularProgressIndicator(color: AppColors.blue)),
),
);
}
}
/// 四个根页面共享同一路由并保持各自状态。
@@ -229,17 +174,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]),
],
);
}
@@ -261,6 +210,8 @@ class _HomeTabsState extends State<_HomeTabs> {
return RecommendPage(
feedController: widget.feedController,
active: logic.tab == 1,
videoOnly: logic.videoImmersive,
onImmersiveChanged: logic.onImmersiveChanged,
onSearch: () => _openSearch(context),
);
}
+55 -42
View File
@@ -8,12 +8,15 @@ import 'package:provider/provider.dart';
import '../../../core/data/models/content_category.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/services/auth_controller.dart';
import '../../../core/data/services/catalog_controller.dart';
import '../../../core/data/services/category_controller.dart';
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';
@@ -75,20 +78,20 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final categories = context.watch<CategoryController>().categories;
final catalog = context.watch<CatalogController>();
final auth = context.watch<AuthController>();
final wallet = context.watch<WalletController>();
final shortcuts = _categoryShortcuts(categories, l10n);
final tags = _availableTags(l10n);
final activeTag =
tags.any((tag) => tag.id == _selectedTags[_selectedPrimary])
? _selectedTags[_selectedPrimary]
: null;
final walletBadge = auth.isSignedIn && wallet.snapshot != null
? wallet.balance
: null;
return ColoredBox(
final ranking = _selectedPrimary == HomePrimaryTab.ranking;
return DecoratedBox(
key: const Key('home-grid'),
color: AppColors.appBackground,
decoration: BoxDecoration(
color: ranking ? null : AppColors.appBackground,
gradient: ranking ? AppTheme.pageGradient : null,
),
child: SafeArea(
bottom: false,
child: Column(
@@ -97,12 +100,8 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
HomeGridHeader(
callbacks: widget.callbacks,
categories: shortcuts,
tags: tags,
selectedPrimary: _selectedPrimary,
selectedTag: activeTag,
onPrimarySelected: _selectPrimary,
onTagSelected: (tag) =>
setState(() => _selectedTags[_selectedPrimary] = tag),
walletBadge: walletBadge,
),
Expanded(
@@ -123,6 +122,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
context,
l10n,
tab: HomePrimaryTab.values[index],
catalog: catalog,
shortcuts: shortcuts,
),
),
@@ -154,21 +154,36 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
BuildContext context,
AppLocalizations l10n, {
required HomePrimaryTab tab,
required CatalogController catalog,
required List<HomeGridCategoryShortcut> shortcuts,
}) {
if (catalog.error != null && widget.feedController.dramas.isEmpty) {
return _catalogErrorState(l10n, catalog);
}
if ((!catalog.settled || catalog.loading) &&
widget.feedController.dramas.isEmpty) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
columns: 3,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
if (tab == HomePrimaryTab.ranking) {
return const RankingPage(embedded: true);
}
if (widget.feedController.loadingFirstPage) {
return const Center(
child: SizedBox.square(
dimension: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
final tag = _selectedTags[tab];
final dramas = _dramasFor(tab, tag, shortcuts);
if (widget.feedController.loadingFirstPage && dramas.isEmpty) {
return const DramaGridSkeleton(
key: Key('home-grid-skeleton'),
columns: 3,
horizontalPadding: AppDimens.feedPageHorizontal,
crossAxisSpacing: AppDimens.homeGridGap,
mainAxisSpacing: AppDimens.homeGridRowGap,
);
}
return LayoutBuilder(
builder: (context, constraints) {
final itemWidth =
@@ -192,7 +207,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
if (dramas.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: _emptyState(l10n, tab, tag),
child: _emptyState(l10n),
)
else
SliverPadding(
@@ -237,6 +252,24 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
);
}
Widget _catalogErrorState(AppLocalizations l10n, CatalogController catalog) {
final theme = Theme.of(context);
return Theme(
data: theme.copyWith(
colorScheme: theme.colorScheme.copyWith(
onSurface: AppColors.textTertiary,
),
),
child: EmptyState(
key: const Key('home-grid-error'),
icon: Icons.cloud_off_rounded,
title: l10n.catalogError,
actionLabel: l10n.retry,
onAction: catalog.load,
),
);
}
Future<void> _refresh() async {
await widget.feedController.refreshCurrent();
}
@@ -285,17 +318,6 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
return null;
}
List<HomeGridTagOption> _availableTags(AppLocalizations l10n) {
// UI 先完整展示筛选维度;后续接口补齐题材字段时只替换数据来源。
return [
HomeGridTagOption(id: 'hot', label: l10n.homeTagHot),
HomeGridTagOption(id: 'uplifting', label: l10n.homeTagUplifting),
HomeGridTagOption(id: 'sweet', label: l10n.homeTagSweet),
HomeGridTagOption(id: 'faceSlap', label: l10n.homeTagFaceSlap),
HomeGridTagOption(id: 'angst', label: l10n.homeTagAngst),
];
}
List<Drama> _dramasFor(
HomePrimaryTab tab,
String? tag,
@@ -338,7 +360,7 @@ class _HomeFeedGridState extends State<HomeFeedGrid> {
}
}
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'),
@@ -348,19 +370,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,
);
}
}
+1 -132
View File
@@ -28,13 +28,6 @@ class HomeGridCategoryShortcut {
final HomePrimaryTab tab;
}
class HomeGridTagOption {
const HomeGridTagOption({required this.id, required this.label});
final String id;
final String label;
}
class HomeGridCallbacks {
const HomeGridCallbacks({
required this.onSearch,
@@ -54,21 +47,15 @@ class HomeGridHeader extends StatelessWidget {
super.key,
required this.callbacks,
required this.categories,
required this.tags,
required this.selectedPrimary,
required this.selectedTag,
required this.onPrimarySelected,
required this.onTagSelected,
this.walletBadge,
});
final HomeGridCallbacks callbacks;
final List<HomeGridCategoryShortcut> categories;
final List<HomeGridTagOption> tags;
final HomePrimaryTab selectedPrimary;
final String? selectedTag;
final ValueChanged<HomePrimaryTab> onPrimarySelected;
final ValueChanged<String?> onTagSelected;
final int? walletBadge;
@override
@@ -81,10 +68,7 @@ class HomeGridHeader extends StatelessWidget {
children: [
_searchRow(l10n),
_primaryRow(l10n),
if (selectedPrimary == HomePrimaryTab.featured)
_tagRow(l10n)
else
const SizedBox(height: AppDimens.homeSecondaryGridGap),
const SizedBox(height: AppDimens.homeSecondaryGridGap),
],
);
}
@@ -323,119 +307,4 @@ class HomeGridHeader extends StatelessWidget {
),
);
}
Widget _tagRow(AppLocalizations l10n) {
return Padding(
padding: const EdgeInsets.fromLTRB(
AppDimens.feedPageHorizontal,
AppDimens.homePrimarySecondaryGap,
AppDimens.feedPageHorizontal,
AppDimens.homeSecondaryGridGap,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: SingleChildScrollView(
key: const Key('home-secondary-tags'),
scrollDirection: Axis.horizontal,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
for (final tag in tags) ...[
_tagChip(tag),
const SizedBox(width: AppDimens.homeSecondaryTagGap),
],
],
),
),
),
const SizedBox(width: AppDimens.homeSecondaryFilterGap),
Tooltip(
message: l10n.filter,
child: SizedBox.square(
dimension: AppDimens.homeSecondaryFilterVisualSize,
child: Material(
color: AppColors.transparent,
child: InkWell(
key: const Key('home-grid-filter'),
onTap: callbacks.onOpenFilter,
child: Center(
child: SizedBox.square(
key: const Key('home-secondary-filter-visual'),
dimension: AppDimens.homeSecondaryFilterVisualSize,
child: const Center(
child: CustomPaint(
key: Key('home-secondary-filter-icon'),
size: Size.square(AppDimens.homeSecondaryFilterIcon),
painter: _ThreeLineFilterPainter(),
),
),
),
),
),
),
),
),
],
),
);
}
Widget _tagChip(HomeGridTagOption tag) {
final selected = selectedTag == tag.id;
final label = Text(
tag.label,
style: TextStyle(
color: selected ? AppColors.navSelected : AppColors.textTertiary,
fontSize: AppDimens.homeSecondaryTagFont,
fontWeight: FontWeight.w600,
letterSpacing: 0,
),
);
return InkWell(
key: Key('home-tag-${tag.id}'),
borderRadius: BorderRadius.circular(AppDimens.pillRadius),
onTap: () => onTagSelected(selected ? null : tag.id),
child: AnimatedContainer(
key: Key('home-tag-animated-${tag.id}'),
duration: AppDimens.homeSecondaryTagAnimationDuration,
curve: Curves.easeOut,
height: AppDimens.homeSecondaryTagHeight,
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.homeSecondaryTagHorizontalPadding,
),
alignment: Alignment.center,
decoration: BoxDecoration(
color: selected ? AppColors.contentSurface : AppColors.transparent,
borderRadius: BorderRadius.circular(AppDimens.homeSecondaryTagRadius),
),
child: label,
),
);
}
}
class _ThreeLineFilterPainter extends CustomPainter {
const _ThreeLineFilterPainter();
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = AppColors.textFilterIcon
..strokeWidth = AppDimens.homeSecondaryFilterStroke
..strokeCap = StrokeCap.butt;
for (final y in [
size.height * 0.25,
size.height * 0.5,
size.height * 0.75,
]) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
}
}
@override
bool shouldRepaint(_ThreeLineFilterPainter oldDelegate) => false;
}
-2
View File
@@ -12,8 +12,6 @@ enum MineDestination {
wallet,
vip,
preferences,
works,
creatorCenter,
notices,
settings,
help,
+10 -73
View File
@@ -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'),
+1 -1
View File
@@ -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 {
+8 -1
View File
@@ -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),
),
],
),
],
+83 -3
View File
@@ -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;
@@ -426,6 +430,7 @@ class PlayerLogic extends ChangeNotifier {
blockedTicket = null;
blockedEpisodeId = null;
qualities = const [];
qualityTracks = const [];
sessionEpisodes[index] = episode.withVideoUrl(_fileUrl(localPath));
return true;
}
@@ -437,10 +442,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 +483,64 @@ 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;
@@ -667,6 +738,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 +769,7 @@ class PlayerLogic extends ChangeNotifier {
);
}
} catch (_) {
// 续看位置取不到不影响播放:从头播。
// 续看或清晰度定位失败时仍用已初始化的播放器,不把切换判失败。
}
}
+101 -33
View File
@@ -34,6 +34,7 @@ import 'player_logic.dart';
import 'widgets/home_feed_header.dart';
import 'widgets/home_feed_overlay.dart';
import 'widgets/exit_clear_screen_button.dart';
import 'widgets/feed_pull_refresh.dart';
import 'widgets/player_center_toggle.dart';
import 'widgets/player_more_sheet.dart';
import 'widgets/player_overlay.dart';
@@ -49,6 +50,7 @@ part 'player_view_actions.dart';
const double _boostPlaybackSpeed = 2.0;
const double _playerLoadingSize = 24;
const double _playerLoadingStrokeWidth = 2;
const double _feedRefreshTopGap = 56;
class PlayerPage extends StatefulWidget {
const PlayerPage({
@@ -305,6 +307,16 @@ class _PlayerPageState extends State<PlayerPage>
unawaited(logic.setPlaybackSpeed(speed));
}
Future<void> _refreshHomeFeed() async {
final refresh = widget.onRefreshFeed;
if (refresh == null) return;
final ok = await refresh();
if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context)!.catalogError)),
);
}
void _setScrubbing(bool value) {
if (!mounted) return;
if (_scrubbing == value) return;
@@ -351,7 +363,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(
@@ -404,26 +416,37 @@ class _PlayerPageState extends State<PlayerPage>
final interactions = context.watch<InteractionController>();
final l10n = AppLocalizations.of(context)!;
final indices = logic.visibleIndices;
final pages = logic.pages;
final content = AnimatedBuilder(
animation: logic.session,
builder: (context, _) => PageView.builder(
controller: pages,
scrollDirection: Axis.vertical,
allowImplicitScrolling: true,
itemCount: indices.length,
onPageChanged: (position) {
final index = indices[position];
widget.onDramaChanged?.call(logic.queue.entryAt(index).drama);
unawaited(logic.selectEpisode(index));
if (position >= indices.length - 3) {
final loadMore = widget.onLoadMore;
if (loadMore != null) unawaited(loadMore());
}
},
itemBuilder: (context, position) =>
_buildEpisode(context, indices[position], interactions),
),
builder: (context, _) {
final pages = PageView.builder(
controller: logic.pages,
scrollDirection: Axis.vertical,
allowImplicitScrolling: true,
physics: widget.onRefreshFeed == null
? null
: const FeedRefreshPhysics(),
itemCount: indices.length,
onPageChanged: (position) {
final index = indices[position];
widget.onDramaChanged?.call(logic.queue.entryAt(index).drama);
unawaited(logic.selectEpisode(index));
if (position >= indices.length - 3) {
final loadMore = widget.onLoadMore;
if (loadMore != null) unawaited(loadMore());
}
},
itemBuilder: (context, position) =>
_buildEpisode(context, indices[position], interactions),
);
if (widget.onRefreshFeed == null) return pages;
return FeedPullRefresh(
pageController: logic.pages,
topInset: MediaQuery.paddingOf(context).top + _feedRefreshTopGap,
onRefresh: _refreshHomeFeed,
child: pages,
);
},
);
final body = Stack(
fit: StackFit.expand,
@@ -504,9 +527,17 @@ class _PlayerPageState extends State<PlayerPage>
final sessionEpisode = index >= 0 && index < logic.sessionEpisodes.length
? logic.sessionEpisodes[index]
: entry.episode;
final episode = widget.homeMode
final displayed = widget.homeMode
? logic.displayEpisode(drama, sessionEpisode)
: sessionEpisode;
final episode =
(displayed.thumbnailsUrl == null || displayed.thumbnailsUrl!.isEmpty) &&
sessionEpisode.thumbnailsUrl != null
? displayed.withVideoUrl(
displayed.videoUrl,
thumbnailsUrl: sessionEpisode.thumbnailsUrl,
)
: displayed;
final selected = index == logic.session.currentIndex;
// Selection changes before the prepared slot is promoted. Use its controller
// throughout the handoff instead of briefly falling back to a placeholder.
@@ -514,14 +545,18 @@ 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,
),
);
}
@@ -536,11 +571,30 @@ class _PlayerPageState extends State<PlayerPage>
),
PlayerVideoSurface(
controller: videoPort?.controller,
handoff: handoffPort?.controller,
videoUrl: videoPort?.controller.dataSource ?? episode.videoUrl,
theater: theater,
),
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,
@@ -552,7 +606,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),
@@ -579,7 +636,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),
@@ -603,6 +660,7 @@ class _PlayerPageState extends State<PlayerPage>
),
// 没有票据信息时的兜底(例如详情里就没地址、也没走票据流程)
if (selected &&
!theater &&
!ready &&
logic.blockedEpisodeId != episode.id &&
logic.session.error == null &&
@@ -637,7 +695,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,
@@ -668,11 +726,11 @@ 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,
@@ -684,7 +742,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:
@@ -702,6 +760,7 @@ class _PlayerPageState extends State<PlayerPage>
thumbnailService: _thumbnailService,
spriteAxisService: _spriteAxisService,
),
scrubbing: _scrubbing,
actions: PlayerOverlayActions(
onBack: widget.embedded
? null
@@ -719,8 +778,14 @@ class _PlayerPageState extends State<PlayerPage>
onSave: () => unawaited(_toggleSave(context, drama)),
onShare: () => logic.shareDrama(context, drama),
onMore: () => _openMore(context, episode),
onScrubStart: ready ? () => logic.beginScrub(videoPort!) : null,
onSeek: ready
onScrubStart: videoReady
? () {
_setScrubbing(true);
logic.beginScrub(videoPort!);
}
: null,
onScrubEnd: () => _setScrubbing(false),
onSeek: videoReady
? (position) => logic.seekTo(context, videoPort!, position)
: null,
onLongPressCenter: () => _openMore(context, episode),
@@ -730,7 +795,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,
+15
View File
@@ -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,
@@ -401,11 +401,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 +423,8 @@ class _CommentPostSuccessOverlay extends StatelessWidget {
style: const TextStyle(
color: AppColors.onPrimary,
fontSize: 14,
decoration: TextDecoration.none,
decorationColor: AppColors.transparent,
),
),
),
@@ -0,0 +1,180 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
const double _maxPull = 96;
const double _refreshThreshold = 56;
const double _firstPageEpsilon = 0.01;
/// 第一条已经到顶时,向下的拖动不再翻页。
class FeedRefreshPhysics extends PageScrollPhysics {
const FeedRefreshPhysics({super.parent});
@override
FeedRefreshPhysics applyTo(ScrollPhysics? ancestor) {
return FeedRefreshPhysics(parent: buildParent(ancestor));
}
@override
double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
if (position.pixels <= position.minScrollExtent && offset > 0) {
return 0;
}
return super.applyPhysicsToUserOffset(position, offset);
}
@override
Simulation? createBallisticSimulation(
ScrollMetrics position,
double velocity,
) {
if (position.pixels <= position.minScrollExtent && velocity < 0) {
return super.createBallisticSimulation(position, 0);
}
return super.createBallisticSimulation(position, velocity);
}
}
/// 竖滑到第一条后继续下拉时刷新,其它页仍交给翻页。
class FeedPullRefresh extends StatefulWidget {
const FeedPullRefresh({
super.key,
required this.pageController,
required this.onRefresh,
required this.child,
this.topInset = 0,
});
final PageController pageController;
final Future<void> Function() onRefresh;
final Widget child;
final double topInset;
@override
State<FeedPullRefresh> createState() => _FeedPullRefreshState();
}
class _FeedPullRefreshState extends State<FeedPullRefresh> {
Offset? _origin;
double _pull = 0;
bool _tracking = false;
bool _refreshing = false;
bool _atFirstPage() {
final controller = widget.pageController;
if (!controller.hasClients) return false;
return (controller.page ?? 0) <= _firstPageEpsilon;
}
void _setPull(double value) {
final next = value.clamp(0.0, _maxPull);
if (next == _pull) return;
setState(() => _pull = next);
}
void _onPointerDown(PointerDownEvent event) {
if (_refreshing || !_atFirstPage()) {
_tracking = false;
return;
}
_origin = event.position;
_tracking = true;
}
void _onPointerMove(PointerMoveEvent event) {
final origin = _origin;
if (!_tracking || origin == null || _refreshing) return;
final delta = event.position - origin;
if (delta.dx.abs() > delta.dy.abs() && delta.dy < _refreshThreshold) {
_tracking = false;
_setPull(0);
return;
}
if (delta.dy > 0) _holdFirstPage();
_setPull(delta.dy);
}
void _holdFirstPage() {
final controller = widget.pageController;
if (!controller.hasClients) return;
final position = controller.position;
if (position.pixels <= position.minScrollExtent) return;
controller.jumpTo(position.minScrollExtent);
}
void _onPointerEnd() {
final shouldRefresh = _tracking && _pull >= _refreshThreshold;
_origin = null;
_tracking = false;
if (shouldRefresh) {
_refresh();
return;
}
_setPull(0);
}
Future<void> _refresh() async {
if (_refreshing) return;
_refreshing = true;
_setPull(_refreshThreshold);
try {
await widget.onRefresh();
} finally {
_refreshing = false;
if (mounted) _setPull(0);
}
}
@override
Widget build(BuildContext context) {
return Listener(
onPointerDown: _onPointerDown,
onPointerMove: _onPointerMove,
onPointerUp: (_) => _onPointerEnd(),
onPointerCancel: (_) => _onPointerEnd(),
child: Stack(
fit: StackFit.expand,
children: [
widget.child,
if (_pull > 0)
Positioned(
top: widget.topInset,
left: 0,
right: 0,
child: IgnorePointer(
child: Align(
alignment: Alignment.topCenter,
child: Container(
key: const Key('pull-refresh-indicator'),
width: AppDimens.refreshIndicatorSize,
height: AppDimens.refreshIndicatorSize,
padding: const EdgeInsets.all(
(AppDimens.refreshIndicatorSize -
AppDimens.refreshSpinnerSize) /
2,
),
decoration: BoxDecoration(
color: AppColors.refreshIndicatorSurface,
borderRadius: BorderRadius.circular(
AppDimens.refreshIndicatorRadius,
),
),
child: const SizedBox.square(
dimension: AppDimens.refreshSpinnerSize,
child: CircularProgressIndicator(
strokeWidth: AppDimens.refreshSpinnerStroke,
color: AppColors.textPrimary,
),
),
),
),
),
),
],
),
);
}
}
+68 -29
View File
@@ -16,6 +16,7 @@ import 'home_feed_recommend_panel.dart';
import 'loading_progress_track.dart';
import 'player_double_tap_hearts.dart';
import 'seek_progress_bar.dart';
import 'scrub_preview_card.dart';
part 'home_feed_overlay_parts.dart';
@@ -109,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 = [];
@@ -145,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,
@@ -207,6 +213,11 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
height: _progressHeight,
hitHeight: _progressHitHeight,
cancelScrubRequest: widget.cancelScrubRequest,
thumbnailService: widget.thumbnailService,
spriteAxisService: widget.spriteAxisService,
thumbnailsUrl: widget.episode.thumbnailsUrl,
episodeId: widget.episode.id,
posterUrl: widget.drama.posterUrl,
onScrubStart: _startScrub,
onScrubEnd: _endScrub,
onSeek: widget.onSeek,
@@ -252,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)));
@@ -296,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();
@@ -19,6 +19,11 @@ class _FeedProgressBar extends StatefulWidget {
required this.height,
required this.hitHeight,
this.cancelScrubRequest = 0,
this.thumbnailService,
this.spriteAxisService,
this.thumbnailsUrl,
this.episodeId,
this.posterUrl = '',
this.onScrubStart,
this.onScrubEnd,
this.onSeek,
@@ -29,6 +34,11 @@ class _FeedProgressBar extends StatefulWidget {
final double height;
final double hitHeight;
final int cancelScrubRequest;
final PlaybackThumbnailService? thumbnailService;
final SpriteThumbnailAxisSource? spriteAxisService;
final String? thumbnailsUrl;
final String? episodeId;
final String posterUrl;
final VoidCallback? onScrubStart;
final VoidCallback? onScrubEnd;
final ValueChanged<Duration>? onSeek;
@@ -142,7 +152,26 @@ class _FeedProgressBarState extends State<_FeedProgressBar> {
clipBehavior: Clip.none,
children: [
track,
if (showPreview)
if (showPreview &&
widget.thumbnailService != null &&
widget.episodeId != null)
Positioned(
left: scrubPreviewLeft(
trackWidth: width,
fraction: _preview!,
),
bottom: _lineCenterFromBottom + 16,
child: ScrubPreviewCard(
service: widget.thumbnailService!,
spriteAxisService: widget.spriteAxisService,
thumbnailsUrl: widget.thumbnailsUrl,
episodeId: widget.episodeId!,
posterUrl: widget.posterUrl,
position: previewPosition,
duration: video!.duration,
),
)
else if (showPreview)
Positioned(
left: _timeBubbleLeft(width, _preview!),
bottom: _lineCenterFromBottom + 16,
@@ -287,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(
@@ -319,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,
),
@@ -11,7 +11,6 @@ import '../../../core/theme/app_colors.dart';
import '../../../l10n/app_localizations.dart';
import '../../home/widgets/home_drama_classification.dart';
const double _headlineFont = 26;
const double _seriesFont = 19;
const double _tagFont = 13;
const double _synopsisFont = 13;
@@ -49,34 +48,12 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final dramaTitle = localizedDramaTitle(l10n, widget.drama);
final episodeTitle = widget.episode.title.trim();
final headline = _headline(l10n, dramaTitle, episodeTitle);
final synopsis = localizedDramaSynopsis(l10n, widget.drama).trim();
final genres = _genreValues();
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
key: const Key('home-feed-title-open'),
behavior: HitTestBehavior.opaque,
onTap: widget.onOpenFullPlayer,
child: Text(
headline,
key: const Key('home-feed-title'),
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.textPrimary,
fontSize: _headlineFont,
fontWeight: FontWeight.w700,
height: 1.2,
letterSpacing: 0,
shadows: _textShadows,
),
),
),
const SizedBox(height: 8),
GestureDetector(
key: const Key('home-feed-series-name'),
behavior: HitTestBehavior.opaque,
@@ -119,23 +96,6 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
);
}
String _headline(
AppLocalizations l10n,
String dramaTitle,
String episodeTitle,
) {
if (episodeTitle.isEmpty) return dramaTitle;
final normalized = episodeTitle.toLowerCase().replaceAll(' ', '');
final localizedEpisode = l10n
.episodeLabel(widget.episode.number)
.toLowerCase()
.replaceAll(' ', '');
final episodeOnly = RegExp(r'^(第?\d+集|episode\d+)$').hasMatch(normalized);
return normalized == localizedEpisode || episodeOnly
? dramaTitle
: episodeTitle;
}
Widget _tagMetaRow(AppLocalizations l10n, List<String> genres) {
return Row(
key: const Key('home-feed-tags'),
@@ -172,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,
),
),
),
],
@@ -213,21 +175,7 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
);
}
if (_synopsisExpanded) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
synopsis,
key: const Key('home-feed-synopsis'),
style: style,
),
const SizedBox(height: 2),
_synopsisToggle(
key: const Key('home-feed-synopsis-more'),
label: l10n.showLess,
),
],
);
return _expandedSynopsis(constraints.maxWidth, synopsis, style, l10n);
}
return Stack(
children: [
@@ -255,6 +203,30 @@ class _HomeFeedInfoPanelState extends State<HomeFeedInfoPanel> {
);
}
Widget _expandedSynopsis(
double maxWidth,
String synopsis,
TextStyle style,
AppLocalizations l10n,
) {
return SizedBox(
width: maxWidth,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(synopsis, key: const Key('home-feed-synopsis'), style: style),
Align(
alignment: Alignment.centerRight,
child: _synopsisToggle(
key: const Key('home-feed-synopsis-more'),
label: l10n.showLess,
),
),
],
),
);
}
Widget _synopsisToggle({required Key key, required String label}) {
return GestureDetector(
key: key,
@@ -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;
}
+34 -11
View File
@@ -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,
);
}
+122 -88
View File
@@ -1,7 +1,12 @@
// Author: fruit.com.cn
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../core/data/models/drama.dart';
import '../../../core/data/services/catalog_controller.dart';
import '../../../core/formatting/localized_content.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/theme/app_dimens.dart';
@@ -17,6 +22,7 @@ const double _topButtonSize = 36;
const double _topBarHeight = 58;
const double _boostHintIconSize = 16;
const double _boostHintFontSize = 13;
const double _synopsisRailInset = 54;
const List<Shadow> _playerTextShadows = [
Shadow(color: AppColors.shadow, blurRadius: 5, offset: Offset(0, 1)),
];
@@ -29,6 +35,7 @@ class PlayerPlaybackOverlay extends StatelessWidget {
required this.data,
required this.actions,
required this.controlsVisible,
required this.scrubbing,
});
/// 展示数据。
@@ -40,6 +47,9 @@ class PlayerPlaybackOverlay extends StatelessWidget {
/// 控制层是否可见。
final bool controlsVisible;
/// 正在拖动进度条。拖动期间清屏,只留进度条。
final bool scrubbing;
@override
Widget build(BuildContext context) {
return SafeArea(
@@ -61,7 +71,7 @@ class PlayerPlaybackOverlay extends StatelessWidget {
_top(context),
_bottom(context),
if (controlsVisible) _rail(context),
if (!data.playing)
if (!data.playing && !scrubbing)
Center(
child: PlayerCenterToggle(
key: const Key('player-play-toggle'),
@@ -79,49 +89,55 @@ class PlayerPlaybackOverlay extends StatelessWidget {
top: 0,
left: 0,
right: 0,
child: Container(
key: const Key('player-controls-top'),
height: _topBarHeight,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
child: Row(
children: [
if (actions.onBack != null)
_TopButton(
key: const Key('player-back'),
tooltip: data.l10n.backToSeries,
icon: Icons.chevron_left_rounded,
onPressed: actions.onBack!,
)
else
const SizedBox(width: _topButtonSize),
const SizedBox(width: 8),
Expanded(
child: Text(
data.l10n.episodeLabel(data.episode.number),
key: const Key('player-episode-heading'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.onPrimary,
fontSize: 15,
fontWeight: FontWeight.w700,
shadows: _playerTextShadows,
child: IgnorePointer(
ignoring: scrubbing,
child: Opacity(
opacity: scrubbing ? 0 : 1,
child: Container(
key: const Key('player-controls-top'),
height: _topBarHeight,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
child: Row(
children: [
if (actions.onBack != null)
_TopButton(
key: const Key('player-back'),
tooltip: data.l10n.backToSeries,
icon: Icons.chevron_left_rounded,
onPressed: actions.onBack!,
)
else
const SizedBox(width: _topButtonSize),
const SizedBox(width: 8),
Expanded(
child: Text(
data.l10n.episodeLabel(data.episode.number),
key: const Key('player-episode-heading'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.onPrimary,
fontSize: 15,
fontWeight: FontWeight.w700,
shadows: _playerTextShadows,
),
),
),
),
_SpeedEntry(
key: const Key('player-speed-entry'),
speed: data.playbackSpeed,
onTap: actions.onSpeed,
),
const SizedBox(width: 8),
_TopButton(
key: const Key('player-more'),
tooltip: data.l10n.more,
icon: Icons.more_vert_rounded,
onPressed: actions.onMore,
),
],
),
_SpeedEntry(
key: const Key('player-speed-entry'),
speed: data.playbackSpeed,
onTap: actions.onSpeed,
),
const SizedBox(width: 8),
_TopButton(
key: const Key('player-more'),
tooltip: data.l10n.more,
icon: Icons.more_vert_rounded,
onPressed: actions.onMore,
),
],
),
),
),
);
@@ -143,43 +159,49 @@ class PlayerPlaybackOverlay extends StatelessWidget {
return Positioned(
right: AppDimens.spaceMd,
top: MediaQuery.sizeOf(context).height * (compact ? 0.30 : 0.43),
child: InteractionRail(
key: const Key('player-interaction-rail'),
items: [
InteractionRailItem(
key: const Key('player-rail-save'),
asset: 'assets/icon/rail/rail_save.png',
label: data.l10n.favorite,
count: data.favoriteCount,
countKey: const Key('player-rail-save-count'),
selected: data.saved,
onTap: actions.onSave,
child: IgnorePointer(
ignoring: scrubbing,
child: Opacity(
opacity: scrubbing ? 0 : 1,
child: InteractionRail(
key: const Key('player-interaction-rail'),
items: [
InteractionRailItem(
key: const Key('player-rail-save'),
asset: 'assets/icon/rail/rail_save.png',
label: data.l10n.favorite,
count: data.favoriteCount,
countKey: const Key('player-rail-save-count'),
selected: data.saved,
onTap: actions.onSave,
),
InteractionRailItem(
key: const Key('player-rail-comments'),
asset: 'assets/icon/rail/rail_comment.png',
label: data.l10n.comments,
count: data.commentCount,
countKey: const Key('player-rail-comments-count'),
onTap: actions.onComments,
),
InteractionRailItem(
key: const Key('player-rail-like'),
asset: 'assets/icon/rail/rail_like.png',
label: data.l10n.like,
count: data.likeCount,
countKey: const Key('player-rail-like-count'),
selected: data.liked,
selectedColor: AppColors.doubleTapHeartRed,
onTap: actions.onLike,
),
InteractionRailItem(
key: const Key('player-rail-share'),
asset: 'assets/icon/rail/rail_share.png',
label: data.l10n.share,
onTap: actions.onShare,
),
],
),
InteractionRailItem(
key: const Key('player-rail-comments'),
asset: 'assets/icon/rail/rail_comment.png',
label: data.l10n.comments,
count: data.commentCount,
countKey: const Key('player-rail-comments-count'),
onTap: actions.onComments,
),
InteractionRailItem(
key: const Key('player-rail-like'),
asset: 'assets/icon/rail/rail_like.png',
label: data.l10n.like,
count: data.likeCount,
countKey: const Key('player-rail-like-count'),
selected: data.liked,
selectedColor: AppColors.doubleTapHeartRed,
onTap: actions.onLike,
),
InteractionRailItem(
key: const Key('player-rail-share'),
asset: 'assets/icon/rail/rail_share.png',
label: data.l10n.share,
onTap: actions.onShare,
),
],
),
),
);
}
@@ -192,11 +214,18 @@ class PlayerPlaybackOverlay extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (controlsVisible) _bottomInfo(context),
Offstage(
offstage: !controlsVisible || scrubbing,
child: _bottomInfo(context),
),
if (data.boosting) _boostHint(),
_bottomProgress(),
// 加速态只保留进度条与提示,便于全屏快进时看清画面。
if (!data.boosting) _bottomActions(),
// 加速时收起底栏。拖动进度时底栏只隐藏,占位保留,进度条不挪位。
scrubbing
? IgnorePointer(
child: Opacity(opacity: 0, child: _bottomActions()),
)
: Offstage(offstage: data.boosting, child: _bottomActions()),
],
),
);
@@ -243,12 +272,16 @@ class PlayerPlaybackOverlay extends StatelessWidget {
children: [
_detailRow(series),
const SizedBox(height: 4),
_EpisodeSynopsis(
key: const Key('player-episode-synopsis'),
l10n: data.l10n,
episodeNumber: data.episode.number,
synopsis: synopsis,
authorNote: data.authorNote,
Padding(
padding: const EdgeInsets.only(right: _synopsisRailInset),
child: _EpisodeSynopsis(
key: const Key('player-episode-synopsis'),
l10n: data.l10n,
drama: data.drama,
episodeNumber: data.episode.number,
synopsis: synopsis,
authorNote: data.authorNote,
),
),
],
),
@@ -273,6 +306,7 @@ class PlayerPlaybackOverlay extends StatelessWidget {
posterUrl: data.drama.posterUrl,
inactiveTrackColor: AppColors.inactiveTrack,
onScrubStart: actions.onScrubStart,
onScrubEnd: actions.onScrubEnd,
onSeek: actions.onSeek,
),
);
@@ -1,6 +1,6 @@
// Author: fruit.com.cn
import 'package:flutter/widgets.dart';
import 'package:flutter/foundation.dart';
import 'package:video_player/video_player.dart';
import '../../../core/data/models/drama.dart';
@@ -40,8 +40,8 @@ class PlayerOverlayData {
/// 当前剧集。
final Episode episode;
/// 当前播放器。
final VideoPlayerController? controller;
/// 当前播放器进度。
final ValueListenable<VideoPlayerValue>? controller;
/// 是否已点赞。
final bool liked;
@@ -98,6 +98,7 @@ class PlayerOverlayActions {
required this.onShare,
required this.onMore,
required this.onScrubStart,
required this.onScrubEnd,
required this.onSeek,
required this.onLongPressCenter,
required this.onBoostStart,
@@ -143,6 +144,9 @@ class PlayerOverlayActions {
/// 开始拖动进度。
final VoidCallback? onScrubStart;
/// 结束拖动进度。
final VoidCallback? onScrubEnd;
/// 提交进度跳转。
final Future<void> Function(Duration)? onSeek;
@@ -109,12 +109,14 @@ class _EpisodeSynopsis extends StatefulWidget {
const _EpisodeSynopsis({
super.key,
required this.l10n,
required this.drama,
required this.episodeNumber,
required this.synopsis,
required this.authorNote,
});
final AppLocalizations l10n;
final Drama drama;
final int episodeNumber;
final String synopsis;
final String authorNote;
@@ -125,6 +127,9 @@ class _EpisodeSynopsis extends StatefulWidget {
class _EpisodeSynopsisState extends State<_EpisodeSynopsis> {
bool _expanded = false;
String? _fullSynopsis;
int _detailRequest = 0;
bool _detailRequested = false;
/// 「第 n 集」、分隔符与简介正文共用同一套灰字规格。
static const TextStyle _lineStyle = TextStyle(
@@ -134,53 +139,114 @@ class _EpisodeSynopsisState extends State<_EpisodeSynopsis> {
height: 1.35,
shadows: _playerTextShadows,
);
static const TextStyle _linkStyle = TextStyle(
color: AppColors.textPrimary,
fontSize: 12,
fontWeight: FontWeight.w700,
shadows: _playerTextShadows,
);
static const int _collapsedMaxLines = 2;
static const double _expandGap = 6;
static const double _expandTrailing = 28;
static const double _separatorGap = 6;
String get _synopsis => _fullSynopsis ?? widget.synopsis;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_detailRequested || widget.drama.detailLoaded) return;
_detailRequested = true;
unawaited(_loadFullSynopsis());
}
@override
void didUpdateWidget(covariant _EpisodeSynopsis oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.drama.id == widget.drama.id &&
oldWidget.synopsis == widget.synopsis) {
return;
}
_fullSynopsis = null;
_expanded = false;
_detailRequested = !widget.drama.detailLoaded;
if (_detailRequested) unawaited(_loadFullSynopsis());
}
Future<void> _loadFullSynopsis() async {
if (widget.drama.detailLoaded) return;
final request = ++_detailRequest;
final CatalogController catalog;
try {
catalog = context.read<CatalogController>();
} catch (_) {
return;
}
try {
final detail = await catalog.requireDetail(widget.drama);
if (!mounted || request != _detailRequest) return;
final full = localizedDramaSynopsis(widget.l10n, detail);
if (full == widget.synopsis) return;
setState(() => _fullSynopsis = full);
} catch (_) {
// 详情失败时继续用列表里的简介。
}
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
return LayoutBuilder(
builder: (context, constraints) => _block(constraints.maxWidth),
);
}
Widget _block(double maxWidth) {
final label = widget.l10n.episodeLabel(widget.episodeNumber);
if (_expanded) return _expandedBlock(label, maxWidth);
return _collapsedBlock(label, maxWidth);
}
Widget _collapsedBlock(String label, double maxWidth) {
final link = widget.l10n.expandSynopsis;
final body = _collapsedBody(label, maxWidth, link);
final text = _synopsisText(label, body, link: null, expanded: false);
if (body == _synopsis) return text;
final caret = _caret(label, body, maxWidth);
return Stack(
clipBehavior: Clip.none,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Text(
widget.l10n.episodeLabel(widget.episodeNumber),
key: const Key('player-episode-label'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _lineStyle,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'|',
maxLines: 1,
style: _lineStyle.copyWith(
color: AppColors.playerMuted.withValues(alpha: 0.6),
),
),
),
Flexible(
child: Text(
widget.synopsis,
key: const Key('player-synopsis'),
maxLines: _expanded ? null : 1,
overflow: _expanded ? TextOverflow.clip : TextOverflow.ellipsis,
style: _lineStyle,
),
),
if (!_expanded) _toggle(widget.l10n.expandSynopsis),
],
text,
Positioned(
left: caret.dx,
top: caret.dy,
child: Padding(
key: const Key('player-synopsis-gap'),
padding: const EdgeInsets.only(left: _expandGap),
child: _toggle(link),
),
),
if (_expanded) ...[
],
);
}
Widget _expandedBlock(String label, double maxWidth) {
return SizedBox(
width: maxWidth,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_synopsisText(label, _synopsis, link: null, expanded: true),
Align(
alignment: Alignment.centerRight,
child: _toggle(widget.l10n.showLess),
),
if (widget.authorNote.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
widget.authorNote,
key: const Key('player-author-note'),
maxLines: 2,
maxLines: _collapsedMaxLines,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.playerMuted,
@@ -189,31 +255,181 @@ class _EpisodeSynopsisState extends State<_EpisodeSynopsis> {
),
),
],
_toggle(widget.l10n.showLess),
],
],
),
);
}
Widget _synopsisText(
String label,
String body, {
required String? link,
required bool expanded,
}) {
return Text.rich(
TextSpan(
style: _lineStyle,
children: _spans(label, body, link),
),
key: const Key('player-synopsis'),
style: _lineStyle,
maxLines: expanded ? null : _collapsedMaxLines,
overflow: expanded ? TextOverflow.clip : TextOverflow.ellipsis,
);
}
List<InlineSpan> _spans(String label, String body, String? link) {
return [
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: Text(
label,
key: const Key('player-episode-label'),
style: _lineStyle,
),
),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: _separatorGap),
child: Text(
'|',
style: _lineStyle.copyWith(
color: AppColors.playerMuted.withValues(alpha: 0.6),
),
),
),
),
TextSpan(text: body, style: _lineStyle),
if (link != null)
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: Padding(
key: const Key('player-synopsis-gap'),
padding: const EdgeInsets.only(left: _expandGap),
child: _toggle(link),
),
),
];
}
String _collapsedBody(String label, double maxWidth, String link) {
if (_fits(label, _synopsis, maxWidth, reserve: 0)) {
return _synopsis;
}
final reserve =
_textWidth(link, _linkStyle) + _expandGap + _expandTrailing;
var low = 0;
var high = _synopsis.length;
var best = '…';
while (low <= high) {
final mid = (low + high) >> 1;
final slice = '${_synopsis.substring(0, mid)}…';
if (_fits(label, slice, maxWidth, reserve: reserve)) {
best = slice;
low = mid + 1;
} else {
high = mid - 1;
}
}
return best;
}
bool _fits(
String label,
String body,
double maxWidth, {
required double reserve,
}) {
final painter = TextPainter(
text: TextSpan(
children: [
TextSpan(text: label, style: _lineStyle),
const WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: _separatorGap),
),
TextSpan(
text: '|',
style: _lineStyle.copyWith(
color: AppColors.playerMuted.withValues(alpha: 0.6),
),
),
const WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: _separatorGap),
),
TextSpan(text: body, style: _lineStyle),
if (reserve > 0)
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: reserve),
),
],
),
maxLines: _collapsedMaxLines,
textDirection: TextDirection.ltr,
);
painter.setPlaceholderDimensions(_slots(reserve));
painter.layout(maxWidth: maxWidth);
return !painter.didExceedMaxLines;
}
List<PlaceholderDimensions> _slots(double reserve) {
return [
const PlaceholderDimensions(
size: Size(_separatorGap, 1),
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
),
const PlaceholderDimensions(
size: Size(_separatorGap, 1),
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
),
if (reserve > 0)
PlaceholderDimensions(
size: Size(reserve, _lineStyle.fontSize ?? 12),
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
),
];
}
Offset _caret(String label, String body, double maxWidth) {
final painter = TextPainter(
text: TextSpan(children: _spans(label, body, null)),
maxLines: _collapsedMaxLines,
textDirection: TextDirection.ltr,
);
painter.setPlaceholderDimensions(_slots(0));
painter.layout(maxWidth: maxWidth);
return painter.getOffsetForCaret(
TextPosition(offset: painter.plainText.length),
Rect.zero,
);
}
double _textWidth(String text, TextStyle style) {
final painter = TextPainter(
text: TextSpan(text: text, style: style),
maxLines: 1,
textDirection: TextDirection.ltr,
)..layout();
return painter.width;
}
Widget _toggle(String label) {
return InkWell(
key: const Key('player-synopsis-toggle'),
onTap: () => setState(() => _expanded = !_expanded),
borderRadius: BorderRadius.circular(4),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.blue,
fontSize: 12,
fontWeight: FontWeight.w700,
shadows: _playerTextShadows,
),
),
),
child: Text(label, maxLines: 1, style: _linkStyle),
);
}
}
@@ -134,7 +134,7 @@ class PlayerBlockedNotice extends StatelessWidget {
Widget _coinLabel(AppLocalizations l10n) => DecoratedBox(
decoration: BoxDecoration(
color: AppColors.goldCard,
color: AppColors.homeCrownGold,
borderRadius: BorderRadius.circular(999),
),
child: Padding(
@@ -10,16 +10,18 @@ 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,
});
final VideoPlayerController? controller;
final VideoPlayerController? handoff;
final String videoUrl;
final bool theater;
@@ -48,7 +50,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,
@@ -60,7 +63,7 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
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 +73,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 +98,18 @@ 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 (value == null || value.hasError || !value.isInitialized) return false;
if (value.size.width <= 0) return false;
if (covered) return true;
return value.position > Duration.zero || value.isPlaying;
}
/// 只画会话仍持有的旧画面,控制器一旦被换掉就不再引用。
VideoPlayerController? _liveHandoff(VideoPlayerController? controller) {
final handoff = widget.handoff;
if (handoff == null || identical(handoff, controller)) return null;
return handoff;
}
void _logStateChange(VideoPlayerValue? value) {
@@ -135,6 +151,7 @@ class _PlayerVideoSurfaceState extends State<PlayerVideoSurface> {
class _VideoLayer extends StatelessWidget {
const _VideoLayer({
super.key,
required this.controller,
required this.value,
required this.theater,
@@ -11,8 +11,9 @@ import '../../../core/data/services/sprite_thumbnail_axis.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/widgets/remote_image.dart';
const double scrubPreviewWidth = 120;
const double scrubPreviewWidth = 96;
const double scrubPreviewSafeMargin = 12;
const double _portraitFrameAspect = 9 / 16;
/// 把预览卡片限制在进度条可用宽度内。
double scrubPreviewLeft({
@@ -64,6 +65,7 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
void initState() {
super.initState();
widget.spriteAxisService?.addListener(_handleSpriteAxisChanged);
_prepareSprite();
_syncFallbackSource();
}
@@ -74,6 +76,10 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
oldWidget.spriteAxisService?.removeListener(_handleSpriteAxisChanged);
widget.spriteAxisService?.addListener(_handleSpriteAxisChanged);
}
if (oldWidget.thumbnailsUrl != widget.thumbnailsUrl ||
oldWidget.position != widget.position) {
_prepareSprite();
}
if (oldWidget.service != widget.service ||
oldWidget.episodeId != widget.episodeId ||
oldWidget.thumbnailsUrl != widget.thumbnailsUrl) {
@@ -97,6 +103,12 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
super.dispose();
}
void _prepareSprite() {
final service = widget.spriteAxisService;
if (service == null) return;
unawaited(service.prepareAt(widget.thumbnailsUrl, widget.position));
}
void _handleSpriteAxisChanged() {
if (!mounted) return;
if (_spriteFrame != null) {
@@ -190,7 +202,8 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
),
),
AspectRatio(
aspectRatio: 16 / 9,
key: const Key('scrub-preview-frame-box'),
aspectRatio: _frameAspect(spriteFrame),
child: Stack(
fit: StackFit.expand,
children: [
@@ -229,6 +242,14 @@ class _ScrubPreviewCardState extends State<ScrubPreviewCard> {
}
}
double _frameAspect(SpriteThumbnailFrame? frame) {
final rect = frame?.sourceRect;
if (rect == null || rect.width <= 0 || rect.height <= 0) {
return _portraitFrameAspect;
}
return rect.width / rect.height;
}
/// 对已解码 sprite 做 sourceRect 裁剪,不触发再次解码。
class SpriteCropPreview extends StatelessWidget {
const SpriteCropPreview({
+23 -20
View File
@@ -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.
@@ -170,11 +172,28 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
setState(() => _buffering = buffering);
}
void _endPointerDrag() {
if (!_dragging) {
_pointerMoved = false;
_pointerStart = null;
_dragStartFraction = null;
return;
}
final duration = widget.valueListenable?.value.duration ?? Duration.zero;
final fraction = _previewFraction.value ?? _dragStartFraction ?? 0;
unawaited(_finish(fraction, duration));
}
Future<void> _finish(double fraction, Duration duration) async {
final startedAt = _dragStartFraction;
_dragStartFraction = null;
if (widget.locked || !_dragging || startedAt == null) return;
setState(() => _dragging = false);
_dragging = false;
if (!mounted) {
widget.onScrubEnd?.call();
return;
}
setState(() {});
_pointerMoved = false;
_pointerStart = null;
widget.thumbnailService?.cancelPending();
@@ -224,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) {
@@ -287,20 +302,8 @@ class _SeekProgressBarState extends State<SeekProgressBar> {
_pointerMoved = true;
}
},
onPointerUp: (_) {
if (!_dragging) {
_pointerMoved = false;
_pointerStart = null;
_dragStartFraction = null;
}
},
onPointerCancel: (_) {
if (!_dragging) {
_pointerMoved = false;
_pointerStart = null;
_dragStartFraction = null;
}
},
onPointerUp: (_) => _endPointerDrag(),
onPointerCancel: (_) => _endPointerDrag(),
child: Slider(
value: fraction,
// 轨道与上方文案共用同一层水平内边距,避免 Slider 默认内缩。
+61 -43
View File
@@ -10,7 +10,6 @@ import '../../core/data/services/catalog_controller.dart';
import '../../core/formatting/count_format.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/empty_state.dart';
import '../../core/widgets/paged_local_list.dart';
@@ -20,7 +19,12 @@ import '../../l10n/app_localizations.dart';
import '../player/open_player.dart';
const int _topCount = 50;
const double _loadMoreThreshold = 200, _championLift = 12;
const double _loadMoreThreshold = 200;
const double _championLift = 12;
const double _podiumGap = 8;
const double _podiumHorizontal = 8;
const double _championScale = 1.18;
const double _coverAspect = 146 / 110;
/// 剧场榜单页:前三名领奖台,第 4 名起为单列排行行。
class RankingPage extends StatefulWidget {
@@ -117,7 +121,7 @@ class _RankingPageState extends State<RankingPage> {
if (podium.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppDimens.feedPageHorizontal,
horizontal: _podiumHorizontal,
),
child: _Podium(podium: podium, l10n: l10n),
),
@@ -156,11 +160,7 @@ class _RankingPageState extends State<RankingPage> {
),
);
if (widget.embedded) {
return DecoratedBox(
key: const Key('ranking-page'),
decoration: const BoxDecoration(gradient: AppTheme.pageGradient),
child: SafeArea(bottom: false, child: content),
);
return KeyedSubtree(key: const Key('ranking-page'), child: content);
}
return PlainPageScaffold(
pageKey: const Key('ranking-page'),
@@ -233,33 +233,55 @@ class _Podium extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
SizedBox(
width: AppDimens.rankingPodiumWidth,
child: podium.length > 1
? _PodiumCard(rank: 2, drama: podium[1], l10n: l10n)
: const SizedBox.shrink(),
),
const Spacer(),
SizedBox(
width: AppDimens.rankingPodiumChampionWidth,
child: podium.isNotEmpty
? Transform.translate(
offset: const Offset(0, -_championLift),
child: _PodiumCard(rank: 1, drama: podium.first, l10n: l10n),
)
: const SizedBox.shrink(),
),
const Spacer(),
SizedBox(
width: AppDimens.rankingPodiumWidth,
child: podium.length > 2
? _PodiumCard(rank: 3, drama: podium[2], l10n: l10n)
: const SizedBox.shrink(),
),
],
return LayoutBuilder(
builder: (context, constraints) {
final available = constraints.maxWidth - _podiumGap * 2;
final side = available / (2 + _championScale);
final champion = side * _championScale;
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
SizedBox(
width: side,
child: podium.length > 1
? _PodiumCard(
rank: 2,
drama: podium[1],
l10n: l10n,
coverWidth: side,
)
: const SizedBox.shrink(),
),
const SizedBox(width: _podiumGap),
SizedBox(
width: champion,
child: podium.isNotEmpty
? Transform.translate(
offset: const Offset(0, -_championLift),
child: _PodiumCard(
rank: 1,
drama: podium.first,
l10n: l10n,
coverWidth: champion,
),
)
: const SizedBox.shrink(),
),
const SizedBox(width: _podiumGap),
SizedBox(
width: side,
child: podium.length > 2
? _PodiumCard(
rank: 3,
drama: podium[2],
l10n: l10n,
coverWidth: side,
)
: const SizedBox.shrink(),
),
],
);
},
);
}
}
@@ -269,19 +291,15 @@ class _PodiumCard extends StatelessWidget {
required this.rank,
required this.drama,
required this.l10n,
required this.coverWidth,
});
final int rank;
final Drama drama;
final AppLocalizations l10n;
final double coverWidth;
double get _coverWidth => rank == 1
? AppDimens.rankingPodiumChampionWidth
: AppDimens.rankingPodiumWidth;
double get _coverHeight => rank == 1
? AppDimens.rankingPodiumChampionHeight
: AppDimens.rankingPodiumHeight;
double get _coverHeight => coverWidth * _coverAspect;
Color get _badgeColor => switch (rank) {
1 => AppColors.homeCrownGold,
@@ -303,7 +321,7 @@ class _PodiumCard extends StatelessWidget {
borderRadius: BorderRadius.circular(AppDimens.rankingPodiumRadius),
child: SizedBox(
key: Key('ranking-cover-$rank'),
width: _coverWidth,
width: coverWidth,
height: _coverHeight,
child: Stack(
fit: StackFit.expand,
+135 -37
View File
@@ -15,6 +15,7 @@ import '../player/open_player.dart';
import '../player/player_view.dart';
import 'recommend_types.dart';
import 'widgets/all_dramas_filter_grid.dart';
import 'widgets/playlist_detail_page.dart';
import 'widgets/recommend_sections_view.dart';
import 'widgets/recommend_top_nav.dart';
@@ -24,12 +25,18 @@ class RecommendPage extends StatefulWidget {
required this.feedController,
required this.active,
required this.onSearch,
this.videoOnly = false,
this.onImmersiveChanged,
});
final HomeFeedController feedController;
final bool active;
final VoidCallback onSearch;
/// 画中画时只留视频,不画顶栏。
final bool videoOnly;
final ValueChanged<bool>? onImmersiveChanged;
@override
State<RecommendPage> createState() => _RecommendPageState();
}
@@ -83,40 +90,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,
),
),
),
),
],
),
);
@@ -127,15 +136,7 @@ class _RecommendPageState extends State<RecommendPage> {
if (dramas.isEmpty) {
final l10n = AppLocalizations.of(context)!;
if (widget.feedController.loadingFirstPage) {
return const ColoredBox(
color: AppColors.mediaBlack,
child: Center(
child: CircularProgressIndicator(
key: Key('recommend-feed-loading'),
color: AppColors.muted,
),
),
);
return const _RecommendFeedSkeleton();
}
return ColoredBox(
color: AppColors.mediaBlack,
@@ -162,6 +163,7 @@ class _RecommendPageState extends State<RecommendPage> {
_openDrama(drama, episodeId: episode.id),
onRefreshFeed: widget.feedController.refreshCurrent,
onLoadMore: widget.feedController.loadMore,
onImmersiveChanged: widget.onImmersiveChanged,
scrubCancelRequest: _scrubCancelRequest,
);
}
@@ -251,7 +253,41 @@ class _RecommendPageState extends State<RecommendPage> {
}
void _handleMore(RecommendSectionKind section) {
_selectTab(RecommendInnerTab.allDramas);
final l10n = AppLocalizations.of(context)!;
final copy = _sectionCopy(l10n, section);
Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (_) => PlaylistDetailPage(
title: copy.$1,
subtitle: copy.$2,
dramas: recommendSectionDramas(
kind: section,
source: widget.feedController.dramas,
categories: context.read<CategoryController>(),
),
),
),
);
}
(String, String) _sectionCopy(
AppLocalizations l10n,
RecommendSectionKind section,
) {
return switch (section) {
RecommendSectionKind.hits => (
l10n.weeklyHitsTitle,
l10n.weeklyHitsSubtitle,
),
RecommendSectionKind.newReleases => (
l10n.weeklyNewTitle,
l10n.weeklyNewSubtitle,
),
RecommendSectionKind.costume => (
l10n.costumeAwardsTitle,
l10n.costumeAwardsSubtitle,
),
};
}
Future<void> _openDrama(Drama drama, {String? episodeId}) async {
@@ -259,6 +295,68 @@ class _RecommendPageState extends State<RecommendPage> {
}
}
class _RecommendFeedSkeleton extends StatelessWidget {
const _RecommendFeedSkeleton();
@override
Widget build(BuildContext context) {
return const ColoredBox(
key: Key('recommend-feed-skeleton'),
color: AppColors.mediaBlack,
child: Stack(
children: [
Center(
child: SizedBox(
width: 132,
height: 176,
child: DecoratedBox(
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
borderRadius: BorderRadius.all(Radius.circular(12)),
),
),
),
),
Positioned(
left: 14,
right: 72,
bottom: 42,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_SkeletonLine(width: 190, height: 18),
SizedBox(height: 10),
_SkeletonLine(width: 140, height: 12),
SizedBox(height: 8),
_SkeletonLine(width: 220, height: 10),
],
),
),
],
),
);
}
}
class _SkeletonLine extends StatelessWidget {
const _SkeletonLine({required this.width, required this.height});
final double width;
final double height;
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
decoration: BoxDecoration(
color: AppColors.skeletonSurface,
borderRadius: BorderRadius.circular(6),
),
);
}
}
class _KeepAliveTab extends StatefulWidget {
const _KeepAliveTab({super.key, required this.child});
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more