💄 Better full screen attachment display

This commit is contained in:
LittleSheep 2024-07-27 00:20:11 +08:00
parent 33d69908a6
commit 0d279842cf
10 changed files with 197 additions and 54 deletions

View File

@ -1,3 +1,5 @@
import 'package:solian/models/account.dart';
class Attachment { class Attachment {
int id; int id;
DateTime createdAt; DateTime createdAt;
@ -13,7 +15,8 @@ class Attachment {
String destination; String destination;
Map<String, dynamic>? metadata; Map<String, dynamic>? metadata;
bool isMature; bool isMature;
int accountId; Account? account;
int? accountId;
Attachment({ Attachment({
required this.id, required this.id,
@ -30,6 +33,7 @@ class Attachment {
required this.destination, required this.destination,
required this.metadata, required this.metadata,
required this.isMature, required this.isMature,
required this.account,
required this.accountId, required this.accountId,
}); });
@ -48,6 +52,7 @@ class Attachment {
destination: json['destination'], destination: json['destination'],
metadata: json['metadata'], metadata: json['metadata'],
isMature: json['is_mature'], isMature: json['is_mature'],
account: json['account'] != null ? Account.fromJson(json['account']) : null,
accountId: json['account_id'], accountId: json['account_id'],
); );
@ -66,6 +71,7 @@ class Attachment {
'destination': destination, 'destination': destination,
'metadata': metadata, 'metadata': metadata,
'is_mature': isMature, 'is_mature': isMature,
'account': account?.toJson(),
'account_id': accountId, 'account_id': accountId,
}; };
} }

View File

@ -6,7 +6,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:get/get_connect/http/src/request/request.dart'; import 'package:get/get_connect/http/src/request/request.dart';
import 'package:mutex/mutex.dart';
import 'package:solian/controllers/chat_events_controller.dart'; import 'package:solian/controllers/chat_events_controller.dart';
import 'package:solian/providers/websocket.dart'; import 'package:solian/providers/websocket.dart';
import 'package:solian/services.dart'; import 'package:solian/services.dart';
@ -55,7 +54,6 @@ class AuthProvider extends GetConnect {
static const storage = FlutterSecureStorage(); static const storage = FlutterSecureStorage();
TokenSet? credentials; TokenSet? credentials;
Mutex credentialsRefreshMutex = Mutex();
@override @override
void onInit() { void onInit() {
@ -66,9 +64,17 @@ class AuthProvider extends GetConnect {
}); });
} }
Completer<void>? _refreshCompleter;
Future<void> refreshCredentials() async { Future<void> refreshCredentials() async {
if (_refreshCompleter != null) {
await _refreshCompleter!.future;
return;
} else {
_refreshCompleter = Completer<void>();
}
try { try {
credentialsRefreshMutex.acquire();
if (!credentials!.isExpired) return; if (!credentials!.isExpired) return;
final resp = await post('/auth/token', { final resp = await post('/auth/token', {
'refresh_token': credentials!.refreshToken, 'refresh_token': credentials!.refreshToken,
@ -86,10 +92,13 @@ class AuthProvider extends GetConnect {
key: 'auth_credentials', key: 'auth_credentials',
value: jsonEncode(credentials!.toJson()), value: jsonEncode(credentials!.toJson()),
); );
} catch (_) { _refreshCompleter!.complete();
log('Refreshed credentials at ${DateTime.now()}');
} catch (e) {
_refreshCompleter!.completeError(e);
rethrow; rethrow;
} finally { } finally {
credentialsRefreshMutex.release(); _refreshCompleter = null;
} }
} }
@ -124,7 +133,6 @@ class AuthProvider extends GetConnect {
if (credentials!.isExpired) { if (credentials!.isExpired) {
await refreshCredentials(); await refreshCredentials();
log('Refreshed credentials at ${DateTime.now()}');
} }
} }

View File

@ -18,7 +18,7 @@ class RelationshipProvider extends GetxController {
bool hasFriend(Account account) { bool hasFriend(Account account) {
final auth = Get.find<AuthProvider>(); final auth = Get.find<AuthProvider>();
if (auth.userProfile.value!['id'] == account.id) return true; if (auth.userProfile.value!['id'] == account.id) return true;
return _friends.any((x) => x.id == account.id); return _friends.any((x) => x.relatedId == account.id);
} }
Future<Response> listRelation() { Future<Response> listRelation() {

View File

@ -132,6 +132,7 @@ const messagesEnglish = {
'reactAdd': 'React', 'reactAdd': 'React',
'reactCompleted': 'Your reaction has been added', 'reactCompleted': 'Your reaction has been added',
'reactUncompleted': 'Your reaction has been removed', 'reactUncompleted': 'Your reaction has been removed',
'attachmentUploadBy': 'Upload by',
'attachmentAdd': 'Attach attachments', 'attachmentAdd': 'Attach attachments',
'attachmentAddGalleryPhoto': 'Gallery photo', 'attachmentAddGalleryPhoto': 'Gallery photo',
'attachmentAddGalleryVideo': 'Gallery video', 'attachmentAddGalleryVideo': 'Gallery video',

View File

@ -81,7 +81,7 @@ const simplifiedChineseMessages = {
'notifyAllRead': '已读所有通知', 'notifyAllRead': '已读所有通知',
'notifyEmpty': '通知箱为空', 'notifyEmpty': '通知箱为空',
'notifyEmptyCaption': '看起来最近没发生什么呢', 'notifyEmptyCaption': '看起来最近没发生什么呢',
'totalSocialCreditPoints': '社会信用点 async', 'totalSocialCreditPoints': '社会信用点',
'totalPostCount': '总帖数', 'totalPostCount': '总帖数',
'totalUpvote': '获顶数', 'totalUpvote': '获顶数',
'totalDownvote': '获踩数', 'totalDownvote': '获踩数',
@ -121,6 +121,7 @@ const simplifiedChineseMessages = {
'reactAdd': '作出反应', 'reactAdd': '作出反应',
'reactCompleted': '你的反应已被添加', 'reactCompleted': '你的反应已被添加',
'reactUncompleted': '你的反应已被移除', 'reactUncompleted': '你的反应已被移除',
'attachmentUploadBy': '由上传',
'attachmentAdd': '附加附件', 'attachmentAdd': '附加附件',
'attachmentAddGalleryPhoto': '相册照片', 'attachmentAddGalleryPhoto': '相册照片',
'attachmentAddGalleryVideo': '相册视频', 'attachmentAddGalleryVideo': '相册视频',

View File

@ -2,6 +2,7 @@ import 'dart:math' show min;
import 'dart:ui'; import 'dart:ui';
import 'package:carousel_slider/carousel_slider.dart'; import 'package:carousel_slider/carousel_slider.dart';
import 'package:dismissible_page/dismissible_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:solian/models/attachment.dart'; import 'package:solian/models/attachment.dart';
@ -236,16 +237,10 @@ class AttachmentListEntry extends StatelessWidget {
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
const Icon(Icons.close, size: 32), Icon(
const SizedBox(height: 8), Icons.close,
Text( size: 32,
'attachmentLoadFailed'.tr, color: Theme.of(context).colorScheme.onSurface,
style:
const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
Text(
'attachmentLoadFailedCaption'.tr,
textAlign: TextAlign.center,
), ),
], ],
), ),
@ -325,13 +320,12 @@ class AttachmentListEntry extends StatelessWidget {
if (!showMature && item!.isMature) { if (!showMature && item!.isMature) {
onReveal(true); onReveal(true);
} else if (['image'].contains(item!.mimetype.split('/').first)) { } else if (['image'].contains(item!.mimetype.split('/').first)) {
Navigator.of(context, rootNavigator: true).push( context.pushTransparentRoute(
MaterialPageRoute( AttachmentListFullScreen(
builder: (context) => AttachmentListFullScreen(
parentId: parentId, parentId: parentId,
attachment: item!, attachment: item!,
), ),
), rootNavigator: true,
); );
} }
}, },

View File

@ -1,5 +1,11 @@
import 'dart:math' as math;
import 'package:dismissible_page/dismissible_page.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:get/get.dart';
import 'package:solian/models/attachment.dart'; import 'package:solian/models/attachment.dart';
import 'package:solian/widgets/account/account_avatar.dart';
import 'package:solian/widgets/attachments/attachment_item.dart'; import 'package:solian/widgets/attachments/attachment_item.dart';
class AttachmentListFullScreen extends StatefulWidget { class AttachmentListFullScreen extends StatefulWidget {
@ -15,6 +21,30 @@ class AttachmentListFullScreen extends StatefulWidget {
} }
class _AttachmentListFullScreenState extends State<AttachmentListFullScreen> { class _AttachmentListFullScreenState extends State<AttachmentListFullScreen> {
bool _showDetails = true;
Color get _unFocusColor =>
Theme.of(context).colorScheme.onSurface.withOpacity(0.75);
String _formatBytes(int bytes, {int decimals = 2}) {
if (bytes == 0) return '0 Bytes';
const k = 1024;
final dm = decimals < 0 ? 0 : decimals;
final sizes = [
'Bytes',
'KiB',
'MiB',
'GiB',
'TiB',
'PiB',
'EiB',
'ZiB',
'YiB'
];
final i = (math.log(bytes) / math.log(k)).floor().toInt();
return '${(bytes / math.pow(k, i)).toStringAsFixed(dm)} ${sizes[i]}';
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@ -22,17 +52,25 @@ class _AttachmentListFullScreenState extends State<AttachmentListFullScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Material( return DismissiblePage(
color: Theme.of(context).colorScheme.surface, key: Key('attachment-dismissible${widget.attachment.id}'),
direction: DismissiblePageDismissDirection.multi,
onDismissed: () => Navigator.pop(context),
dismissThresholds: const {
DismissiblePageDismissDirection.multi: 0.05,
},
child: GestureDetector( child: GestureDetector(
child: SizedBox( child: Stack(
fit: StackFit.loose,
children: [
SizedBox(
height: MediaQuery.of(context).size.height, height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width, width: MediaQuery.of(context).size.width,
child: InteractiveViewer( child: InteractiveViewer(
boundaryMargin: const EdgeInsets.all(128), boundaryMargin: EdgeInsets.zero,
minScale: 0.1, minScale: 1,
maxScale: 16, maxScale: 16,
panEnabled: true, panEnabled: false,
scaleEnabled: true, scaleEnabled: true,
child: AttachmentItem( child: AttachmentItem(
parentId: widget.parentId, parentId: widget.parentId,
@ -42,8 +80,103 @@ class _AttachmentListFullScreenState extends State<AttachmentListFullScreen> {
), ),
), ),
), ),
Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 300,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [Color(0xFFFFFFFF), Color(0x00FFFFFF)],
),
),
),
)
.animate(target: _showDetails ? 1 : 0)
.fadeIn(curve: Curves.fastEaseInToSlowEaseOut),
Positioned(
bottom: MediaQuery.of(context).padding.bottom,
left: 16,
right: 16,
child: Material(
color: Colors.transparent,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.attachment.account != null)
Row(
children: [
AccountAvatar(
content: widget.attachment.account!.avatar,
radius: 19,
),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'attachmentUploadBy'.tr,
style: Theme.of(context).textTheme.bodySmall,
),
Text(
widget.attachment.account!.nick,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
],
),
const SizedBox(height: 4),
Text(
widget.attachment.alt,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 2),
Wrap(
spacing: 6,
children: [
if (widget.attachment.metadata?['width'] != null &&
widget.attachment.metadata?['height'] != null)
Text(
'${widget.attachment.metadata?['width']}x${widget.attachment.metadata?['height']}',
style: TextStyle(
fontSize: 12,
color: _unFocusColor,
),
),
if (widget.attachment.metadata?['ratio'] != null)
Text(
'${(widget.attachment.metadata?['ratio'] as double).toPrecision(2)}',
style: TextStyle(
fontSize: 12,
color: _unFocusColor,
),
),
Text(
_formatBytes(widget.attachment.size),
style: TextStyle(
fontSize: 12,
color: _unFocusColor,
),
)
],
),
],
),
),
)
.animate(target: _showDetails ? 1 : 0)
.fadeIn(curve: Curves.fastEaseInToSlowEaseOut),
],
),
onTap: () { onTap: () {
Navigator.pop(context); setState(() => _showDetails = !_showDetails);
}, },
), ),
); );

View File

@ -191,7 +191,7 @@ class _AttachmentPublishPopupState extends State<AttachmentPublishPopup> {
} }
} }
String formatBytes(int bytes, {int decimals = 2}) { String _formatBytes(int bytes, {int decimals = 2}) {
if (bytes == 0) return '0 Bytes'; if (bytes == 0) return '0 Bytes';
const k = 1024; const k = 1024;
final dm = decimals < 0 ? 0 : decimals; final dm = decimals < 0 ? 0 : decimals;
@ -353,7 +353,7 @@ class _AttachmentPublishPopupState extends State<AttachmentPublishPopup> {
fontFamily: 'monospace'), fontFamily: 'monospace'),
), ),
Text( Text(
'${fileType[0].toUpperCase()}${fileType.substring(1)} · ${formatBytes(element.size)}', '${fileType[0].toUpperCase()}${fileType.substring(1)} · ${_formatBytes(element.size)}',
style: style:
const TextStyle(fontSize: 12), const TextStyle(fontSize: 12),
), ),

View File

@ -321,6 +321,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "7.0.0" version: "7.0.0"
dismissible_page:
dependency: "direct main"
description:
name: dismissible_page
sha256: "5b2316f770fe83583f770df1f6505cb19102081c5971979806e77f2e507a9958"
url: "https://pub.dev"
source: hosted
version: "1.0.2"
dropdown_button2: dropdown_button2:
dependency: "direct main" dependency: "direct main"
description: description:
@ -992,14 +1000,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.5" version: "1.0.5"
mutex:
dependency: "direct main"
description:
name: mutex
sha256: "8827da25de792088eb33e572115a5eb0d61d61a3c01acbc8bcbe76ed78f1a1f2"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
nm: nm:
dependency: transitive dependency: transitive
description: description:

View File

@ -50,11 +50,11 @@ dependencies:
media_kit_video: ^1.2.4 media_kit_video: ^1.2.4
media_kit_libs_video: ^1.0.4 media_kit_libs_video: ^1.0.4
textfield_tags: ^3.0.1 textfield_tags: ^3.0.1
mutex: ^3.1.0
pasteboard: ^0.2.0 pasteboard: ^0.2.0
desktop_drop: ^0.4.4 desktop_drop: ^0.4.4
badges: ^3.1.2 badges: ^3.1.2
flutter_card_swiper: ^7.0.1 flutter_card_swiper: ^7.0.1
dismissible_page: ^1.0.2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test: