feat: add HTML providers for Realbooru and Paheal, hidden posts screen, and UI/search enhancements
This commit is contained in:
@@ -54,6 +54,8 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
OverlayEntry? _suggestionsOverlay;
|
||||
Timer? _debounce;
|
||||
List<String> _tags = [];
|
||||
String _lastExternalValue = '';
|
||||
bool _localDirty = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -62,15 +64,20 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
_focusNode = FocusNode();
|
||||
_tagScrollController = ScrollController();
|
||||
_focusNode.addListener(_handleFocusChanged);
|
||||
_setFromQuery(widget.initialValue ?? '');
|
||||
_lastExternalValue = widget.initialValue ?? '';
|
||||
_setFromQuery(_lastExternalValue);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant TagInputSearchBar oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
final next = widget.initialValue ?? '';
|
||||
if (!_focusNode.hasFocus && oldWidget.initialValue != next) {
|
||||
final externalChanged = next != _lastExternalValue;
|
||||
final externalCleared = next.isEmpty && _lastExternalValue.isNotEmpty;
|
||||
if (externalChanged && (externalCleared || !_isEditing)) {
|
||||
_setFromQuery(next);
|
||||
_lastExternalValue = next;
|
||||
_localDirty = false;
|
||||
}
|
||||
if (oldWidget.suggestions != widget.suggestions) {
|
||||
_syncSuggestionsOverlay();
|
||||
@@ -90,6 +97,13 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
|
||||
void _handleFocusChanged() {
|
||||
if (!mounted) return;
|
||||
if (!_focusNode.hasFocus && !_localDirty) {
|
||||
final next = widget.initialValue ?? '';
|
||||
if (next != _lastExternalValue) {
|
||||
_setFromQuery(next);
|
||||
_lastExternalValue = next;
|
||||
}
|
||||
}
|
||||
setState(() {});
|
||||
_syncSuggestionsOverlay();
|
||||
}
|
||||
@@ -193,7 +207,11 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
}
|
||||
|
||||
void _syncSuggestionsOverlay() {
|
||||
if (!_focusNode.hasFocus || widget.suggestions.isEmpty) {
|
||||
final token = _activeToken;
|
||||
final suggestions = widget.suggestions
|
||||
.where((item) => item.name.toLowerCase().startsWith(token))
|
||||
.toList(growable: false);
|
||||
if (!_focusNode.hasFocus || token.isEmpty || suggestions.isEmpty) {
|
||||
_removeSuggestionsOverlay();
|
||||
return;
|
||||
}
|
||||
@@ -203,20 +221,17 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
if (overlay == null || renderBox == null || !renderBox.hasSize) return;
|
||||
|
||||
final size = renderBox.size;
|
||||
if (_suggestionsOverlay == null) {
|
||||
_suggestionsOverlay = OverlayEntry(
|
||||
builder: (context) => _TagSuggestionOverlay(
|
||||
link: _layerLink,
|
||||
width: size.width,
|
||||
yOffset: size.height + 8,
|
||||
suggestions: widget.suggestions,
|
||||
onSelected: _applySuggestion,
|
||||
),
|
||||
);
|
||||
overlay.insert(_suggestionsOverlay!);
|
||||
return;
|
||||
}
|
||||
_suggestionsOverlay?.markNeedsBuild();
|
||||
_removeSuggestionsOverlay();
|
||||
_suggestionsOverlay = OverlayEntry(
|
||||
builder: (context) => _TagSuggestionOverlay(
|
||||
link: _layerLink,
|
||||
width: size.width,
|
||||
yOffset: size.height + 8,
|
||||
suggestions: suggestions,
|
||||
onSelected: _applySuggestion,
|
||||
),
|
||||
);
|
||||
overlay.insert(_suggestionsOverlay!);
|
||||
}
|
||||
|
||||
void _removeSuggestionsOverlay() {
|
||||
@@ -268,6 +283,7 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
}
|
||||
|
||||
void _handleDraftChanged(String value) {
|
||||
_localDirty = true;
|
||||
final composing = _controller.value.composing;
|
||||
if (!composing.isValid &&
|
||||
value.isNotEmpty &&
|
||||
@@ -286,6 +302,7 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
void _commitDraft(String value) {
|
||||
final additions = _parseTags(value);
|
||||
if (additions.isEmpty) return;
|
||||
_localDirty = true;
|
||||
setState(() {
|
||||
for (final tag in additions) {
|
||||
if (!_tags.contains(tag)) _tags.add(tag);
|
||||
@@ -299,11 +316,14 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
_debounce?.cancel();
|
||||
_commitDraft(_controller.text);
|
||||
_removeSuggestionsOverlay();
|
||||
_lastExternalValue = _query;
|
||||
_localDirty = false;
|
||||
widget.onSubmitted(_query);
|
||||
}
|
||||
|
||||
void _clear() {
|
||||
_debounce?.cancel();
|
||||
_localDirty = true;
|
||||
setState(() {
|
||||
_tags = [];
|
||||
_controller.clear();
|
||||
@@ -313,6 +333,7 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
}
|
||||
|
||||
void _editTag(String tag) {
|
||||
_localDirty = true;
|
||||
setState(() {
|
||||
_tags = _tags.where((item) => item != tag).toList(growable: true);
|
||||
_controller.value = TextEditingValue(
|
||||
@@ -325,6 +346,7 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
}
|
||||
|
||||
void _removeTag(String tag) {
|
||||
_localDirty = true;
|
||||
setState(() {
|
||||
_tags = _tags.where((item) => item != tag).toList(growable: true);
|
||||
});
|
||||
@@ -333,6 +355,7 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
|
||||
void _applySuggestion(String suggestion) {
|
||||
final draft = _controller.text.trim();
|
||||
_localDirty = true;
|
||||
setState(() {
|
||||
if (draft.isNotEmpty) {
|
||||
final draftTags = _parseTags(draft);
|
||||
@@ -353,7 +376,9 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
}
|
||||
|
||||
void _notifyChanged() {
|
||||
_localDirty = true;
|
||||
widget.onChanged?.call(_query);
|
||||
_syncSuggestionsOverlay();
|
||||
}
|
||||
|
||||
List<String> _parseTags(String query) {
|
||||
@@ -372,6 +397,14 @@ class _TagInputSearchBarState extends State<TagInputSearchBar> {
|
||||
final all = [..._tags, if (draft.isNotEmpty) draft];
|
||||
return all.join(' ');
|
||||
}
|
||||
|
||||
String get _activeToken {
|
||||
final draft = _controller.text.trim().toLowerCase();
|
||||
if (draft.isEmpty) return '';
|
||||
return draft.split(RegExp(r'\s+')).last;
|
||||
}
|
||||
|
||||
bool get _isEditing => _focusNode.hasFocus || _localDirty;
|
||||
}
|
||||
|
||||
class _TagSuggestionOverlay extends StatelessWidget {
|
||||
@@ -396,11 +429,14 @@ class _TagSuggestionOverlay extends StatelessWidget {
|
||||
link: link,
|
||||
showWhenUnlinked: false,
|
||||
offset: Offset(0, yOffset),
|
||||
child: SizedBox(
|
||||
width: width.clamp(280, 620).toDouble(),
|
||||
child: _TagSuggestionDropdown(
|
||||
suggestions: suggestions,
|
||||
onSelected: onSelected,
|
||||
child: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: SizedBox(
|
||||
width: width.clamp(280, 620).toDouble(),
|
||||
child: _TagSuggestionDropdown(
|
||||
suggestions: suggestions,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -420,62 +456,59 @@ class _TagSuggestionDropdown extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
return Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 620),
|
||||
child: Material(
|
||||
elevation: 8,
|
||||
shadowColor: Colors.black.withValues(alpha: 0.18),
|
||||
color: scheme.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
itemCount: suggestions.length > 8 ? 8 : suggestions.length,
|
||||
separatorBuilder: (_, __) => Divider(
|
||||
height: 1,
|
||||
indent: 52,
|
||||
color: scheme.outlineVariant.withValues(alpha: 0.55),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final suggestion = suggestions[index];
|
||||
return InkWell(
|
||||
onTap: () => onSelected(suggestion.name),
|
||||
child: Padding(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.tag_rounded, color: scheme.primary, size: 20),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Text(
|
||||
suggestion.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
_TagSuggestionBadge(suggestion.categoryLabel),
|
||||
if (suggestion.postCount > 0) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
_compactCount(suggestion.postCount),
|
||||
style:
|
||||
Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
return ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 620),
|
||||
child: Material(
|
||||
elevation: 8,
|
||||
shadowColor: Colors.black.withValues(alpha: 0.18),
|
||||
color: scheme.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
itemCount: suggestions.length > 8 ? 8 : suggestions.length,
|
||||
separatorBuilder: (_, __) => Divider(
|
||||
height: 1,
|
||||
indent: 52,
|
||||
color: scheme.outlineVariant.withValues(alpha: 0.55),
|
||||
),
|
||||
itemBuilder: (context, index) {
|
||||
final suggestion = suggestions[index];
|
||||
return InkWell(
|
||||
onTap: () => onSelected(suggestion.name),
|
||||
child: Padding(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.tag_rounded, color: scheme.primary, size: 20),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Text(
|
||||
suggestion.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
_TagSuggestionBadge(suggestion.categoryLabel),
|
||||
if (suggestion.postCount > 0) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
_compactCount(suggestion.postCount),
|
||||
style:
|
||||
Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -287,7 +287,9 @@ class _MobileShell extends StatelessWidget {
|
||||
? null
|
||||
: FloatingActionButton.small(
|
||||
heroTag: 'mobile-settings',
|
||||
tooltip: ru ? 'Настройки' : 'Settings',
|
||||
tooltip: ru
|
||||
? '\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438'
|
||||
: 'Settings',
|
||||
onPressed: () => context.go('/settings'),
|
||||
child: const Icon(Icons.settings_rounded),
|
||||
),
|
||||
@@ -325,14 +327,15 @@ class _Destination {
|
||||
String labelFor(bool ru) {
|
||||
if (!ru) return label;
|
||||
return switch (id) {
|
||||
'feed' => 'Лента',
|
||||
'search' => 'Поиск',
|
||||
'favorites' => 'Избранное',
|
||||
'viewed' => 'История',
|
||||
'collections' => 'Коллекции',
|
||||
'artists' => 'Артисты',
|
||||
'providers' => 'Провайдеры',
|
||||
'settings' => 'Настройки',
|
||||
'feed' => '\u041b\u0435\u043d\u0442\u0430',
|
||||
'search' => '\u041f\u043e\u0438\u0441\u043a',
|
||||
'favorites' => '\u0418\u0437\u0431\u0440\u0430\u043d\u043d\u043e\u0435',
|
||||
'viewed' => '\u0418\u0441\u0442\u043e\u0440\u0438\u044f',
|
||||
'collections' => '\u041a\u043e\u043b\u043b\u0435\u043a\u0446\u0438\u0438',
|
||||
'artists' => '\u0410\u0440\u0442\u0438\u0441\u0442\u044b',
|
||||
'providers' =>
|
||||
'\u041f\u0440\u043e\u0432\u0430\u0439\u0434\u0435\u0440\u044b',
|
||||
'settings' => '\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438',
|
||||
_ => label,
|
||||
};
|
||||
}
|
||||
@@ -340,8 +343,8 @@ class _Destination {
|
||||
String mobileLabelFor(bool ru) {
|
||||
if (!ru) return mobileLabel;
|
||||
return switch (id) {
|
||||
'collections' => 'Доски',
|
||||
'favorites' => 'Любимое',
|
||||
'collections' => '\u0414\u043e\u0441\u043a\u0438',
|
||||
'favorites' => '\u041b\u044e\u0431\u0438\u043c\u043e\u0435',
|
||||
_ => labelFor(true),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import 'dart:async';
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:media_kit/media_kit.dart';
|
||||
import 'package:media_kit_video/media_kit_video.dart';
|
||||
|
||||
import '../../app/motion.dart';
|
||||
import '../../backend/backend.dart';
|
||||
import '../../core/utils/result.dart';
|
||||
import 'blur_content.dart';
|
||||
import 'loading_skeleton.dart';
|
||||
import 'rating_badge.dart';
|
||||
|
||||
class PostCard extends StatefulWidget {
|
||||
class PostCard extends ConsumerStatefulWidget {
|
||||
const PostCard({
|
||||
required this.post,
|
||||
required this.blurExplicit,
|
||||
@@ -44,25 +51,40 @@ class PostCard extends StatefulWidget {
|
||||
final bool selected;
|
||||
|
||||
@override
|
||||
State<PostCard> createState() => _PostCardState();
|
||||
ConsumerState<PostCard> createState() => _PostCardState();
|
||||
}
|
||||
|
||||
class _PostCardState extends State<PostCard> {
|
||||
class _PostCardState extends ConsumerState<PostCard> {
|
||||
static final Map<String, Post> _resolvedRealbooruPosts = {};
|
||||
|
||||
bool _hovered = false;
|
||||
Post? _resolvedPost;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_resolvedPost = _resolvedRealbooruPosts[widget.post.cacheKey];
|
||||
_maybeResolveRealbooruPost();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant PostCard oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.post.cacheKey != widget.post.cacheKey) {
|
||||
_resolvedPost = _resolvedRealbooruPosts[widget.post.cacheKey];
|
||||
_maybeResolveRealbooruPost();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final post = widget.post;
|
||||
final post = _resolvedPost ?? widget.post;
|
||||
final sensitive = _isSensitive(post.rating);
|
||||
final aspect = post.width > 0 && post.height > 0
|
||||
? post.width / post.height
|
||||
: _fallbackAspect(post.fileType);
|
||||
final mobile = MediaQuery.sizeOf(context).width < 700;
|
||||
final urls = MediaUrlSelector.feed(
|
||||
post,
|
||||
mode: widget.mediaQualityMode,
|
||||
mobile: mobile,
|
||||
);
|
||||
final urls = _feedUrls(post, mobile: mobile);
|
||||
final imageUrl = urls.isEmpty ? post.previewUrl : urls.first;
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hovered = true),
|
||||
@@ -130,8 +152,21 @@ class _PostCardState extends State<PostCard> {
|
||||
final dpr = MediaQuery.devicePixelRatioOf(context);
|
||||
final cacheWidth =
|
||||
(constraints.maxWidth * dpr).round().clamp(320, 1800);
|
||||
final headers = _headersFor(post);
|
||||
final videoUrls = MediaUrlSelector.video(post);
|
||||
if (_resolvedPost != null &&
|
||||
MediaUrlSelector.isVideo(post) &&
|
||||
videoUrls.isNotEmpty) {
|
||||
return _FeedVideoPreview(
|
||||
videoUrl: videoUrls.first,
|
||||
headers: headers,
|
||||
fallbackImageUrl: imageUrl,
|
||||
cacheWidth: cacheWidth,
|
||||
);
|
||||
}
|
||||
return CachedNetworkImage(
|
||||
imageUrl: imageUrl,
|
||||
httpHeaders: headers,
|
||||
memCacheWidth: cacheWidth,
|
||||
maxWidthDiskCache: cacheWidth,
|
||||
fit: BoxFit.cover,
|
||||
@@ -291,6 +326,236 @@ class _PostCardState extends State<PostCard> {
|
||||
if (normalized.contains('gif')) return 1;
|
||||
return 0.72;
|
||||
}
|
||||
|
||||
List<String> _feedUrls(Post post, {required bool mobile}) {
|
||||
if ((post.providerId == 'realbooru' || post.providerId == 'paheal') &&
|
||||
!MediaUrlSelector.isVideo(post)) {
|
||||
return [
|
||||
post.sampleUrl,
|
||||
post.fileUrl,
|
||||
post.previewUrl,
|
||||
].where((url) => url.trim().isNotEmpty).toSet().toList(growable: false);
|
||||
}
|
||||
return MediaUrlSelector.feed(
|
||||
post,
|
||||
mode: widget.mediaQualityMode,
|
||||
mobile: mobile,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, String> _headersFor(Post post) {
|
||||
final lower = '${post.providerId} ${post.providerName} '
|
||||
'${post.previewUrl} ${post.sampleUrl} ${post.fileUrl}'
|
||||
.toLowerCase();
|
||||
return {
|
||||
'User-Agent': 'Lunaris/2.0.1 Flutter local booru browser',
|
||||
'Accept': '*/*',
|
||||
if (lower.contains('gelbooru')) 'Referer': 'https://gelbooru.com/',
|
||||
if (lower.contains('realbooru'))
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/125 Mobile Safari/537.36',
|
||||
if (lower.contains('realbooru'))
|
||||
'Accept':
|
||||
'video/webm,video/mp4,image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
if (lower.contains('realbooru'))
|
||||
'Referer':
|
||||
'https://realbooru.com/index.php?page=post&s=view&id=${post.id}',
|
||||
if (lower.contains('paheal'))
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/125 Mobile Safari/537.36',
|
||||
if (lower.contains('paheal'))
|
||||
'Accept':
|
||||
'video/webm,video/mp4,image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
||||
if (lower.contains('paheal'))
|
||||
'Referer': 'https://rule34.paheal.net/post/view/${post.id}',
|
||||
if (lower.contains('rule34') && !lower.contains('paheal'))
|
||||
'Referer': 'https://rule34.xxx/',
|
||||
};
|
||||
}
|
||||
|
||||
void _maybeResolveRealbooruPost() {
|
||||
final post = widget.post;
|
||||
if (!_needsRealbooruDetails(post) ||
|
||||
_resolvedRealbooruPosts.containsKey(post.cacheKey)) {
|
||||
return;
|
||||
}
|
||||
Future<void>(() async {
|
||||
final result = await ref
|
||||
.read(providerManagerProvider)
|
||||
.getPost(post.providerId, post.id);
|
||||
if (!mounted) return;
|
||||
if (result is Success<Post?> && result.data != null) {
|
||||
final resolved = result.data!;
|
||||
_resolvedRealbooruPosts[post.cacheKey] = resolved;
|
||||
setState(() => _resolvedPost = resolved);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
bool _needsRealbooruDetails(Post post) {
|
||||
if (post.providerId != 'realbooru') return false;
|
||||
final preview = post.previewUrl.toLowerCase();
|
||||
final sample = post.sampleUrl.toLowerCase();
|
||||
return post.fileUrl.isEmpty ||
|
||||
post.fileUrl == post.previewUrl ||
|
||||
post.fileUrl == post.sampleUrl ||
|
||||
preview.contains('/thumbnails/') ||
|
||||
sample.contains('/thumbnails/');
|
||||
}
|
||||
}
|
||||
|
||||
class _FeedVideoPreview extends StatefulWidget {
|
||||
const _FeedVideoPreview({
|
||||
required this.videoUrl,
|
||||
required this.headers,
|
||||
required this.fallbackImageUrl,
|
||||
required this.cacheWidth,
|
||||
});
|
||||
|
||||
final String videoUrl;
|
||||
final Map<String, String> headers;
|
||||
final String fallbackImageUrl;
|
||||
final int cacheWidth;
|
||||
|
||||
@override
|
||||
State<_FeedVideoPreview> createState() => _FeedVideoPreviewState();
|
||||
}
|
||||
|
||||
class _FeedVideoPreviewState extends State<_FeedVideoPreview> {
|
||||
late final Player _player;
|
||||
late final VideoController _controller;
|
||||
bool _failed = false;
|
||||
bool _ready = false;
|
||||
int _requestId = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
MediaKit.ensureInitialized();
|
||||
_player = Player();
|
||||
_controller = VideoController(_player);
|
||||
_player.stream.error.listen((_) {
|
||||
if (mounted) setState(() => _failed = true);
|
||||
});
|
||||
_open();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _FeedVideoPreview oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.videoUrl != widget.videoUrl) {
|
||||
_open();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_player.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fallback = CachedNetworkImage(
|
||||
imageUrl: widget.fallbackImageUrl,
|
||||
httpHeaders: widget.headers,
|
||||
memCacheWidth: widget.cacheWidth,
|
||||
maxWidthDiskCache: widget.cacheWidth,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => const LoadingSkeleton(),
|
||||
errorWidget: (context, url, error) => ColoredBox(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: const Center(child: Icon(Icons.videocam_off_rounded)),
|
||||
),
|
||||
);
|
||||
if (_failed) return fallback;
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
fallback,
|
||||
AnimatedOpacity(
|
||||
opacity: _ready ? 1 : 0,
|
||||
duration: AppMotion.duration(context, 180),
|
||||
child: ColoredBox(
|
||||
color: Colors.black,
|
||||
child: Video(
|
||||
controller: _controller,
|
||||
fit: BoxFit.cover,
|
||||
controls: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final requestId = ++_requestId;
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_failed = false;
|
||||
_ready = false;
|
||||
});
|
||||
}
|
||||
try {
|
||||
await _VideoPreviewOpenQueue.run(() async {
|
||||
if (!mounted || requestId != _requestId) return;
|
||||
await _player.stop();
|
||||
await _player
|
||||
.open(
|
||||
Media(widget.videoUrl, httpHeaders: widget.headers),
|
||||
play: false,
|
||||
)
|
||||
.timeout(const Duration(seconds: 8));
|
||||
if (!mounted || requestId != _requestId) return;
|
||||
await _player
|
||||
.seek(const Duration(milliseconds: 300))
|
||||
.timeout(const Duration(seconds: 3));
|
||||
await _player.pause();
|
||||
});
|
||||
if (!mounted || requestId != _requestId) return;
|
||||
setState(() => _ready = true);
|
||||
} catch (_) {
|
||||
if (mounted && requestId == _requestId) {
|
||||
setState(() => _failed = true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _VideoPreviewOpenQueue {
|
||||
static const int _maxConcurrent = 2;
|
||||
static final Queue<Future<void> Function()> _pending = Queue();
|
||||
static int _active = 0;
|
||||
|
||||
static Future<void> run(Future<void> Function() task) {
|
||||
final completer = Completer<void>();
|
||||
_pending.add(() async {
|
||||
try {
|
||||
await task();
|
||||
if (!completer.isCompleted) completer.complete();
|
||||
} catch (error, stackTrace) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error, stackTrace);
|
||||
}
|
||||
}
|
||||
});
|
||||
_pump();
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
static void _pump() {
|
||||
while (_active < _maxConcurrent && _pending.isNotEmpty) {
|
||||
final job = _pending.removeFirst();
|
||||
_active++;
|
||||
unawaited(
|
||||
job().whenComplete(() {
|
||||
_active--;
|
||||
_pump();
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _FavoriteButton extends StatelessWidget {
|
||||
|
||||
Reference in New Issue
Block a user