♻️ Refactored post draft system

This commit is contained in:
2025-06-25 02:15:45 +08:00
parent b89cffeb18
commit 47c31ddec2
19 changed files with 776 additions and 1844 deletions

View File

@ -1,7 +1,6 @@
import 'dart:developer';
import 'package:collection/collection.dart';
import 'package:dio/dio.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
@ -15,6 +14,7 @@ import 'package:island/services/compose_storage_db.dart';
import 'package:island/widgets/alert.dart';
import 'package:pasteboard/pasteboard.dart';
import 'dart:async';
import 'dart:developer';
class ComposeState {
final ValueNotifier<List<UniversalFile>> attachments;
@ -40,10 +40,10 @@ class ComposeState {
required this.draftId,
});
void startAutoSave(WidgetRef ref) {
void startAutoSave(WidgetRef ref, {int postType = 0}) {
_autoSaveTimer?.cancel();
_autoSaveTimer = Timer.periodic(const Duration(seconds: 3), (_) {
ComposeLogic.saveDraft(ref, this);
ComposeLogic.saveDraftWithoutUpload(ref, this, postType: postType);
});
}
@ -96,9 +96,11 @@ class ComposeLogic {
);
}
static ComposeState createStateFromDraft(ComposeDraftModel draft) {
static ComposeState createStateFromDraft(SnPost draft) {
return ComposeState(
attachments: ValueNotifier<List<UniversalFile>>([]),
attachments: ValueNotifier<List<UniversalFile>>(
draft.attachments.map((e) => UniversalFile.fromAttachment(e)).toList(),
),
titleController: TextEditingController(text: draft.title),
descriptionController: TextEditingController(text: draft.description),
contentController: TextEditingController(text: draft.content),
@ -110,29 +112,247 @@ class ComposeLogic {
);
}
static Future<void> saveDraft(WidgetRef ref, ComposeState state, {int postType = 0}) async {
final hasContent =
state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty ||
state.contentController.text.trim().isNotEmpty;
final hasAttachments = state.attachments.value.isNotEmpty;
if (!hasContent && !hasAttachments) {
return; // Don't save empty posts
}
static Future<void> saveDraft(WidgetRef ref, ComposeState state) async {
try {
// Check if the auto-save timer is still active (widget not disposed)
if (state._autoSaveTimer == null) {
return; // Widget has been disposed, don't save
return;
}
final draft = ComposeDraftModel(
// Upload any local attachments first
final baseUrl = ref.watch(serverUrlProvider);
final token = await getToken(ref.watch(tokenProvider));
if (token == null) throw ArgumentError('Token is null');
for (int i = 0; i < state.attachments.value.length; i++) {
final attachment = state.attachments.value[i];
if (attachment.data is! SnCloudFile) {
try {
final cloudFile =
await putMediaToCloud(
fileData: attachment,
atk: token,
baseUrl: baseUrl,
filename: attachment.data.name ?? (postType == 1 ? 'Article media' : 'Post media'),
mimetype:
attachment.data.mimeType ??
ComposeLogic.getMimeTypeFromFileType(attachment.type),
).future;
if (cloudFile != null) {
// Update attachments list with cloud file
final clone = List.of(state.attachments.value);
clone[i] = UniversalFile(data: cloudFile, type: attachment.type);
state.attachments.value = clone;
}
} catch (err) {
log('[ComposeLogic] Failed to upload attachment: $err');
// Continue with other attachments even if one fails
}
}
}
final draft = SnPost(
id: state.draftId,
title: state.titleController.text,
description: state.descriptionController.text,
content: state.contentController.text,
attachments: state.attachments.value,
language: null,
editedAt: null,
publishedAt: DateTime.now(),
visibility: state.visibility.value,
lastModified: DateTime.now(),
content: state.contentController.text,
type: postType,
meta: null,
viewsUnique: 0,
viewsTotal: 0,
upvotes: 0,
downvotes: 0,
repliesCount: 0,
threadedPostId: null,
threadedPost: null,
repliedPostId: null,
repliedPost: null,
forwardedPostId: null,
forwardedPost: null,
attachments:
state.attachments.value
.map((e) => e.data)
.whereType<SnCloudFile>()
.toList(),
publisher: SnPublisher(
id: '',
type: 0,
name: '',
nick: '',
picture: null,
background: null,
account: null,
accountId: null,
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
realmId: null,
verification: null,
),
reactions: [],
tags: [],
categories: [],
collections: [],
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
);
await ref.read(composeStorageNotifierProvider.notifier).saveDraft(draft);
} catch (e) {
log('[ComposeLogic] Failed to save draft, error: $e');
// Silently fail for auto-save to avoid disrupting user experience
}
}
static Future<void> saveDraftWithoutUpload(WidgetRef ref, ComposeState state, {int postType = 0}) async {
final hasContent =
state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty ||
state.contentController.text.trim().isNotEmpty;
final hasAttachments = state.attachments.value.isNotEmpty;
if (!hasContent && !hasAttachments) {
return; // Don't save empty posts
}
try {
if (state._autoSaveTimer == null) {
return;
}
final draft = SnPost(
id: state.draftId,
title: state.titleController.text,
description: state.descriptionController.text,
language: null,
editedAt: null,
publishedAt: DateTime.now(),
visibility: state.visibility.value,
content: state.contentController.text,
type: postType,
meta: null,
viewsUnique: 0,
viewsTotal: 0,
upvotes: 0,
downvotes: 0,
repliesCount: 0,
threadedPostId: null,
threadedPost: null,
repliedPostId: null,
repliedPost: null,
forwardedPostId: null,
forwardedPost: null,
attachments:
state.attachments.value
.map((e) => e.data)
.whereType<SnCloudFile>()
.toList(),
publisher: SnPublisher(
id: '',
type: 0,
name: '',
nick: '',
picture: null,
background: null,
account: null,
accountId: null,
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
realmId: null,
verification: null,
),
reactions: [],
tags: [],
categories: [],
collections: [],
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
);
await ref.read(composeStorageNotifierProvider.notifier).saveDraft(draft);
} catch (e) {
log('[ComposeLogic] Failed to save draft without upload, error: $e');
}
}
static Future<void> saveDraftManually(
WidgetRef ref,
ComposeState state,
BuildContext context,
) async {
try {
final draft = SnPost(
id: state.draftId,
title: state.titleController.text,
description: state.descriptionController.text,
language: null,
editedAt: null,
publishedAt: DateTime.now(),
visibility: state.visibility.value,
content: state.contentController.text,
type: 0,
meta: null,
viewsUnique: 0,
viewsTotal: 0,
upvotes: 0,
downvotes: 0,
repliesCount: 0,
threadedPostId: null,
threadedPost: null,
repliedPostId: null,
repliedPost: null,
forwardedPostId: null,
forwardedPost: null,
attachments: [], // TODO: Handle attachments
publisher: SnPublisher(
id: '',
type: 0,
name: '',
nick: '',
picture: null,
background: null,
account: null,
accountId: null,
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
realmId: null,
verification: null,
),
reactions: [],
tags: [],
categories: [],
collections: [],
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
deletedAt: null,
);
await ref.read(composeStorageNotifierProvider.notifier).saveDraft(draft);
if (context.mounted) {
showSnackBar(context, 'draftSaved'.tr());
}
} catch (e) {
log('[ComposeLogic] Failed to save draft manually, error: $e');
if (context.mounted) {
showSnackBar(context, 'draftSaveFailed'.tr());
}
}
}
@ -146,7 +366,7 @@ class ComposeLogic {
}
}
static Future<ComposeDraftModel?> loadDraft(WidgetRef ref, String draftId) async {
static Future<SnPost?> loadDraft(WidgetRef ref, String draftId) async {
try {
return ref
.read(composeStorageNotifierProvider.notifier)
@ -282,6 +502,20 @@ class ComposeLogic {
}) async {
if (state.submitting.value) return;
// Don't submit empty posts (no content and no attachments)
final hasContent =
state.titleController.text.trim().isNotEmpty ||
state.descriptionController.text.trim().isNotEmpty ||
state.contentController.text.trim().isNotEmpty;
final hasAttachments = state.attachments.value.isNotEmpty;
if (!hasContent && !hasAttachments) {
if (context.mounted) {
showSnackBar(context, 'postContentEmpty'.tr());
}
return; // Don't submit empty posts
}
try {
state.submitting.value = true;
@ -329,7 +563,7 @@ class ComposeLogic {
if (postType == 1) {
// Delete article draft
await ref
.read(articleStorageNotifierProvider.notifier)
.read(composeStorageNotifierProvider.notifier)
.deleteDraft(state.draftId);
} else {
// Delete regular post draft
@ -381,7 +615,7 @@ class ComposeLogic {
if (isPaste && isModifierPressed) {
handlePaste(state);
} else if (isSave && isModifierPressed) {
saveDraft(ref, state);
saveDraftManually(ref, state, context);
} else if (isSubmit && isModifierPressed && !state.submitting.value) {
performAction(
ref,

View File

@ -7,208 +7,168 @@ import 'package:island/services/compose_storage_db.dart';
import 'package:material_symbols_icons/symbols.dart';
class DraftManagerSheet extends HookConsumerWidget {
final bool isArticle;
final Function(String draftId)? onDraftSelected;
const DraftManagerSheet({
super.key,
this.isArticle = false,
this.onDraftSelected,
});
const DraftManagerSheet({super.key, this.onDraftSelected});
@override
Widget build(BuildContext context, WidgetRef ref) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final isLoading = useState(true);
final drafts =
isArticle
? ref.watch(articleStorageNotifierProvider)
: ref.watch(composeStorageNotifierProvider);
final drafts = ref.watch(composeStorageNotifierProvider);
final sortedDrafts = useMemoized(() {
if (isArticle) {
final draftList = drafts.values.cast<ArticleDraftModel>().toList();
draftList.sort((a, b) => b.lastModified.compareTo(a.lastModified));
return draftList;
} else {
final draftList = drafts.values.cast<ComposeDraftModel>().toList();
draftList.sort((a, b) => b.lastModified.compareTo(a.lastModified));
return draftList;
}
// Track loading state based on drafts being loaded
useEffect(() {
// Set loading to false after drafts are loaded
// We consider drafts loaded when the provider has been initialized
Future.microtask(() {
if (isLoading.value) {
isLoading.value = false;
}
});
return null;
}, [drafts]);
final sortedDrafts = useMemoized(
() {
final draftList = drafts.values.toList();
draftList.sort((a, b) => b.updatedAt!.compareTo(a.updatedAt!));
return draftList;
},
[
drafts.length,
drafts.values.map((e) => e.updatedAt!.millisecondsSinceEpoch).join(),
],
);
return Scaffold(
appBar: AppBar(
title: Text(isArticle ? 'articleDrafts'.tr() : 'postDrafts'.tr()),
),
body: Column(
children: [
if (sortedDrafts.isEmpty)
Expanded(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Symbols.draft,
size: 64,
color: colorScheme.onSurface.withOpacity(0.3),
appBar: AppBar(title: Text('drafts'.tr())),
body:
isLoading.value
? const Center(child: CircularProgressIndicator())
: Column(
children: [
if (sortedDrafts.isEmpty)
Expanded(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Symbols.draft,
size: 64,
color: colorScheme.onSurface.withOpacity(0.3),
),
const Gap(16),
Text(
'noDrafts'.tr(),
style: theme.textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withOpacity(0.6),
),
),
],
),
),
)
else
Expanded(
child: ListView.builder(
itemCount: sortedDrafts.length,
itemBuilder: (context, index) {
final draft = sortedDrafts[index];
return _DraftItem(
draft: draft,
onTap: () {
Navigator.of(context).pop();
onDraftSelected?.call(draft.id);
},
onDelete: () async {
await ref
.read(composeStorageNotifierProvider.notifier)
.deleteDraft(draft.id);
},
);
},
),
),
const Gap(16),
Text(
'noDrafts'.tr(),
style: theme.textTheme.bodyLarge?.copyWith(
color: colorScheme.onSurface.withOpacity(0.6),
if (sortedDrafts.isNotEmpty) ...[
const Divider(),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () async {
final confirmed = await showDialog<bool>(
context: context,
builder:
(context) => AlertDialog(
title: Text('clearAllDrafts'.tr()),
content: Text(
'clearAllDraftsConfirm'.tr(),
),
actions: [
TextButton(
onPressed:
() => Navigator.of(
context,
).pop(false),
child: Text('cancel'.tr()),
),
TextButton(
onPressed:
() => Navigator.of(
context,
).pop(true),
child: Text('confirm'.tr()),
),
],
),
);
if (confirmed == true) {
await ref
.read(
composeStorageNotifierProvider.notifier,
)
.clearAllDrafts();
}
},
icon: const Icon(Symbols.delete_sweep),
label: Text('clearAll'.tr()),
),
),
],
),
),
],
),
),
)
else
Expanded(
child: ListView.builder(
itemCount: sortedDrafts.length,
itemBuilder: (context, index) {
final draft = sortedDrafts[index];
return _DraftItem(
draft: draft,
isArticle: isArticle,
onTap: () {
Navigator.of(context).pop();
final draftId =
isArticle
? (draft as ArticleDraftModel).id
: (draft as ComposeDraftModel).id;
onDraftSelected?.call(draftId);
},
onDelete: () async {
final draftId =
isArticle
? (draft as ArticleDraftModel).id
: (draft as ComposeDraftModel).id;
if (isArticle) {
await ref
.read(articleStorageNotifierProvider.notifier)
.deleteDraft(draftId);
} else {
await ref
.read(composeStorageNotifierProvider.notifier)
.deleteDraft(draftId);
}
},
);
},
),
),
if (sortedDrafts.isNotEmpty) ...[
const Divider(),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () async {
final confirmed = await showDialog<bool>(
context: context,
builder:
(context) => AlertDialog(
title: Text('clearAllDrafts'.tr()),
content: Text('clearAllDraftsConfirm'.tr()),
actions: [
TextButton(
onPressed:
() => Navigator.of(context).pop(false),
child: Text('cancel'.tr()),
),
TextButton(
onPressed:
() => Navigator.of(context).pop(true),
child: Text('confirm'.tr()),
),
],
),
);
if (confirmed == true) {
if (isArticle) {
await ref
.read(articleStorageNotifierProvider.notifier)
.clearAllDrafts();
} else {
await ref
.read(composeStorageNotifierProvider.notifier)
.clearAllDrafts();
}
}
},
icon: const Icon(Symbols.delete_sweep),
label: Text('clearAll'.tr()),
),
),
],
),
),
],
],
),
);
}
}
class _DraftItem extends StatelessWidget {
final dynamic draft; // ComposeDraft or ArticleDraft
final bool isArticle;
final dynamic draft;
final VoidCallback? onTap;
final VoidCallback? onDelete;
const _DraftItem({
required this.draft,
required this.isArticle,
this.onTap,
this.onDelete,
});
const _DraftItem({required this.draft, this.onTap, this.onDelete});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final String title;
final String content;
final DateTime lastModified;
final String visibility;
if (isArticle) {
final articleDraft = draft as ArticleDraftModel;
title =
articleDraft.title.isNotEmpty ? articleDraft.title : 'untitled'.tr();
content =
articleDraft.content.isNotEmpty
? articleDraft.content
: (articleDraft.description.isNotEmpty
? articleDraft.description
: 'noContent'.tr());
lastModified = articleDraft.lastModified;
visibility = _parseArticleVisibility(articleDraft.visibility);
} else {
final postDraft = draft as ComposeDraftModel;
title = postDraft.title.isNotEmpty ? postDraft.title : 'untitled'.tr();
content =
postDraft.content.isNotEmpty
? postDraft.content
: (postDraft.description.isNotEmpty
? postDraft.description
: 'noContent'.tr());
lastModified = postDraft.lastModified;
visibility = _parseArticleVisibility(postDraft.visibility);
}
final title = draft.title ?? 'untitled'.tr();
final content = draft.content ?? (draft.description ?? 'noContent'.tr());
final preview =
content.length > 100 ? '${content.substring(0, 100)}...' : content;
final timeAgo = _formatTimeAgo(lastModified);
final timeAgo = _formatTimeAgo(draft.updatedAt!);
final visibility = _parseVisibility(draft.visibility);
return Card(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
@ -223,7 +183,7 @@ class _DraftItem extends StatelessWidget {
Row(
children: [
Icon(
isArticle ? Symbols.article : Symbols.post_add,
draft.type == 1 ? Symbols.article : Symbols.post_add,
size: 20,
color: colorScheme.primary,
),
@ -316,7 +276,7 @@ class _DraftItem extends StatelessWidget {
}
}
String _parseArticleVisibility(int visibility) {
String _parseVisibility(int visibility) {
switch (visibility) {
case 0:
return 'public'.tr();

View File

@ -162,8 +162,8 @@ class PostItem extends HookConsumerWidget {
Spacer(),
Text(
isFullPost
? item.publishedAt.formatSystem()
: item.publishedAt.formatRelative(context),
? item.publishedAt?.formatSystem() ?? ''
: item.publishedAt?.formatRelative(context) ?? '',
).fontSize(11).alignment(Alignment.bottomRight),
const Gap(4),
],
@ -213,12 +213,14 @@ class PostItem extends HookConsumerWidget {
content: item.content!,
linesMargin:
item.type == 0
? EdgeInsets.only(bottom: 4)
? EdgeInsets.only(bottom: 8)
: null,
),
// Show truncation hint if post is truncated
if (item.isTruncated && !isFullPost)
_PostTruncateHint(),
_PostTruncateHint().padding(
bottom: item.attachments.isNotEmpty ? 8 : null,
),
if ((item.repliedPost != null ||
item.forwardedPost != null) &&
showReferencePost)
@ -234,7 +236,7 @@ class PostItem extends HookConsumerWidget {
MediaQuery.of(context).size.width * 0.9,
kWideScreenWidth - 160,
),
).padding(top: 4),
),
// Render embed links
if (item.meta?['embeds'] != null)
...((item.meta!['embeds'] as List<dynamic>)
@ -248,7 +250,8 @@ class PostItem extends HookConsumerWidget {
MediaQuery.of(context).size.width * 0.85,
kWideScreenWidth - 160,
),
).padding(top: 4),
margin: EdgeInsets.only(top: 8),
),
)),
],
),
@ -323,7 +326,6 @@ Widget _buildReferencePost(BuildContext context, SnPost item) {
final isReply = item.repliedPost != null;
return Container(
margin: const EdgeInsets.only(top: 8, bottom: 8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5),

View File

@ -153,7 +153,7 @@ class PostItemCreator extends HookConsumerWidget {
),
const Gap(8),
Text(
item.publishedAt.formatSystem(),
item.publishedAt?.formatSystem() ?? '',
style: TextStyle(
fontSize: 12,
color: Theme.of(context).colorScheme.secondary,
@ -291,7 +291,7 @@ class PostItemCreator extends HookConsumerWidget {
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Created: ${item.createdAt.formatSystem()}',
'Created: ${item.createdAt?.formatSystem() ?? ''}',
style: TextStyle(
fontSize: 12,
color: Theme.of(context).colorScheme.secondary,