♻️ Refactored using controller as post editing

This commit is contained in:
2024-11-11 21:30:05 +08:00
parent 1ff4dc2a4b
commit f23ffe61f5
12 changed files with 851 additions and 558 deletions

View File

@ -1,7 +1,6 @@
import 'dart:math' as math;
import 'package:collection/collection.dart';
import 'package:dio/dio.dart';
import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/gestures.dart';
@ -11,9 +10,8 @@ import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:styled_widget/styled_widget.dart';
import 'package:surface/providers/sn_attachment.dart';
import 'package:surface/controllers/post_write_controller.dart';
import 'package:surface/providers/sn_network.dart';
import 'package:surface/types/attachment.dart';
import 'package:surface/types/post.dart';
import 'package:surface/widgets/account/account_image.dart';
import 'package:surface/widgets/loading_indicator.dart';
@ -42,203 +40,37 @@ class PostEditorScreen extends StatefulWidget {
}
class _PostEditorScreenState extends State<PostEditorScreen> {
static const Map<String, String> _kTitleMap = {
'stories': 'writePostTypeStory',
'articles': 'writePostTypeArticle',
};
final PostWriteController _writeController = PostWriteController();
bool _isBusy = false;
bool _isLoading = false;
bool _isFetching = false;
bool get _isLoading => _isFetching || _writeController.isLoading;
SnPublisher? _publisher;
List<SnPublisher>? _publishers;
final List<XFile> _selectedMedia = List.empty(growable: true);
final List<SnAttachment> _attachments = List.empty(growable: true);
Future<void> _fetchPublishers() async {
final sn = context.read<SnNetworkProvider>();
final resp = await sn.client.get('/cgi/co/publishers');
_publishers = List<SnPublisher>.from(
resp.data?.map((e) => SnPublisher.fromJson(e)) ?? [],
);
setState(() {
_publisher = _publishers?.first;
});
}
SnPost? _editingOg;
SnPost? _replyingTo;
SnPost? _repostingTo;
Future<void> _fetchRelatedPost() async {
final sn = context.read<SnNetworkProvider>();
final attach = context.read<SnAttachmentProvider>();
setState(() => _isFetching = true);
try {
setState(() => _isLoading = true);
if (widget.postEditId != null) {
final resp = await sn.client.get('/cgi/co/posts/${widget.postEditId}');
final post = SnPost.fromJson(resp.data);
final attachments = await attach
.getMultiple(post.body['attachments']?.cast<String>() ?? []);
_title = post.body['title'];
_description = post.body['description'];
_contentController.text = post.body['content'] ?? '';
_attachments.addAll(attachments);
_editingOg = post.copyWith(
preload: SnPostPreload(
attachments: attachments,
),
);
}
if (widget.postReplyId != null) {
final resp = await sn.client.get('/cgi/co/posts/${widget.postReplyId}');
final post = SnPost.fromJson(resp.data);
_replyingTo = post.copyWith(
preload: SnPostPreload(
attachments: await attach
.getMultiple(post.body['attachments']?.cast<String>() ?? []),
),
);
}
if (widget.postRepostId != null) {
final resp =
await sn.client.get('/cgi/co/posts/${widget.postRepostId}');
final post = SnPost.fromJson(resp.data);
_repostingTo = post.copyWith(
preload: SnPostPreload(
attachments: await attach
.getMultiple(post.body['attachments']?.cast<String>() ?? []),
),
);
}
} catch (err) {
context.showErrorDialog(err);
} finally {
setState(() => _isLoading = false);
}
}
String? _title;
String? _description;
final TextEditingController _contentController = TextEditingController();
double? _progress;
static const kAttachmentProgressWeight = 0.9;
static const kPostingProgressWeight = 0.1;
void _performAction() async {
if (_isBusy || _publisher == null) return;
final sn = context.read<SnNetworkProvider>();
final attach = context.read<SnAttachmentProvider>();
setState(() {
_progress = 0;
_isBusy = true;
});
// Uploading attachments
try {
for (int i = 0; i < _selectedMedia.length; i++) {
final media = _selectedMedia[i];
final place = await attach.chunkedUploadInitialize(
await media.length(),
media.name,
'interactive',
null,
);
final item = await attach.chunkedUploadParts(
media,
place.$1,
place.$2,
onProgress: (progress) {
// Calculate overall progress for attachments
setState(() {
_progress = ((i + progress) / _selectedMedia.length) *
kAttachmentProgressWeight;
});
},
);
_attachments.add(item);
}
} catch (err) {
if (!mounted) return;
context.showErrorDialog(err);
setState(() => _isBusy = false);
return;
}
setState(() => _progress = kAttachmentProgressWeight);
// Posting the content
try {
final baseProgressVal = _progress!;
await sn.client.request(
[
'/cgi/co/${widget.mode}',
if (widget.postEditId != null) '${widget.postEditId}',
].join('/'),
data: {
'publisher': _publisher!.id,
'content': _contentController.value.text,
'title': _title,
'description': _description,
'attachments': _attachments.map((e) => e.rid).toList(),
if (_replyingTo != null) 'reply_to': _replyingTo!.id,
if (_repostingTo != null) 'repost_to': _repostingTo!.id,
},
onSendProgress: (count, total) {
setState(() {
_progress = baseProgressVal +
(count / total) * (kPostingProgressWeight / 2);
});
},
onReceiveProgress: (count, total) {
setState(() {
_progress = baseProgressVal +
(kPostingProgressWeight / 2) +
(count / total) * (kPostingProgressWeight / 2);
});
},
options: Options(
method: widget.postEditId != null ? 'PUT' : 'POST',
),
final sn = context.read<SnNetworkProvider>();
final resp = await sn.client.get('/cgi/co/publishers');
_publishers = List<SnPublisher>.from(
resp.data?.map((e) => SnPublisher.fromJson(e)) ?? [],
);
if (!mounted) return;
Navigator.pop(context, true);
_writeController.setPublisher(_publishers?.firstOrNull);
} catch (err) {
if (!mounted) return;
context.showErrorDialog(err);
} finally {
setState(() => _isBusy = false);
setState(() => _isFetching = false);
}
}
void _updateMeta() {
showModalBottomSheet<PostMetaResult?>(
showModalBottomSheet(
context: context,
builder: (context) => PostMetaEditor(
initialTitle: _title,
initialDescription: _description,
),
builder: (context) => PostMetaEditor(controller: _writeController),
useRootNavigator: true,
).then((value) {
if (value is PostMetaResult) {
_title = value.title;
_description = value.description;
setState(() {});
}
});
);
}
final _imagePicker = ImagePicker();
@ -246,308 +78,337 @@ class _PostEditorScreenState extends State<PostEditorScreen> {
void _selectMedia() async {
final result = await _imagePicker.pickMultipleMedia();
if (result.isEmpty) return;
_selectedMedia.addAll(result);
_writeController.addAttachments(
result.map((e) => PostWriteMedia.fromFile(e)),
);
setState(() {});
}
@override
void dispose() {
_contentController.dispose();
_writeController.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
if (!_kTitleMap.keys.contains(widget.mode)) {
if (!PostWriteController.kTitleMap.keys.contains(widget.mode)) {
context.showErrorDialog('Unknown post type');
Navigator.pop(context);
}
_fetchRelatedPost();
_fetchPublishers();
_writeController.fetchRelatedPost(
context,
editing: widget.postEditId,
replying: widget.postReplyId,
reposting: widget.postRepostId,
);
}
@override
Widget build(BuildContext context) {
return AppScaffold(
appBar: AppBar(
leading: BackButton(
onPressed: () {
Navigator.pop(context);
},
),
flexibleSpace: Column(
children: [
Text(_title ?? 'untitled'.tr())
.textStyle(Theme.of(context).textTheme.titleLarge!)
.textColor(Colors.white),
Text(_kTitleMap[widget.mode]!)
.tr()
.textColor(Colors.white.withAlpha((255 * 0.9).round())),
],
).padding(top: math.max(MediaQuery.of(context).padding.top, 8)),
actions: [
IconButton(
icon: const Icon(Symbols.tune),
onPressed: _isBusy ? null : _updateMeta,
return ListenableBuilder(
listenable: _writeController,
builder: (context, _) {
return AppScaffold(
appBar: AppBar(
leading: BackButton(
onPressed: () {
Navigator.pop(context);
},
),
flexibleSpace: Column(
children: [
Text(_writeController.title.isNotEmpty
? _writeController.title
: 'untitled'.tr())
.textStyle(Theme.of(context).textTheme.titleLarge!)
.textColor(Colors.white),
Text(PostWriteController.kTitleMap[widget.mode]!)
.tr()
.textColor(Colors.white.withAlpha((255 * 0.9).round())),
],
).padding(top: math.max(MediaQuery.of(context).padding.top, 8)),
actions: [
IconButton(
icon: const Icon(Symbols.tune),
onPressed: _writeController.isBusy ? null : _updateMeta,
),
],
),
],
),
body: Column(
children: [
DropdownButtonHideUnderline(
child: DropdownButton2<SnPublisher>(
isExpanded: true,
hint: Text(
'fieldPostPublisher',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).hintColor,
body: Column(
children: [
DropdownButtonHideUnderline(
child: DropdownButton2<SnPublisher>(
isExpanded: true,
hint: Text(
'fieldPostPublisher',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).hintColor,
),
).tr(),
items: <DropdownMenuItem<SnPublisher>>[
...(_publishers?.map(
(item) => DropdownMenuItem<SnPublisher>(
enabled: _writeController.editingPost == null,
value: item,
child: Row(
children: [
AccountImage(content: item.avatar, radius: 16),
const Gap(8),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(item.nick).textStyle(
Theme.of(context)
.textTheme
.bodyMedium!),
Text('@${item.name}')
.textStyle(Theme.of(context)
.textTheme
.bodySmall!)
.fontSize(12),
],
),
),
],
),
),
) ??
[]),
DropdownMenuItem<SnPublisher>(
value: null,
child: Row(
children: [
CircleAvatar(
radius: 16,
backgroundColor: Colors.transparent,
foregroundColor:
Theme.of(context).colorScheme.onSurface,
child: const Icon(Symbols.add),
),
const Gap(8),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('publishersNew').tr().textStyle(
Theme.of(context).textTheme.bodyMedium!),
],
),
),
],
),
),
],
value: _writeController.publisher,
onChanged: (SnPublisher? value) {
if (value == null) {
GoRouter.of(context)
.pushNamed('accountPublisherNew')
.then((value) {
if (value == true) {
_publishers = null;
_fetchPublishers();
}
});
} else {
_writeController.setPublisher(value);
}
},
buttonStyleData: const ButtonStyleData(
padding: EdgeInsets.only(right: 16),
height: 48,
),
menuItemStyleData: const MenuItemStyleData(
height: 48,
),
),
).tr(),
items: <DropdownMenuItem<SnPublisher>>[
...(_publishers?.map(
(item) => DropdownMenuItem<SnPublisher>(
enabled: _editingOg == null,
value: item,
child: Row(
),
const Divider(height: 1),
Expanded(
child: SingleChildScrollView(
padding: EdgeInsets.only(bottom: 8),
child: Column(
children: [
// Replying Notice
if (_writeController.replyingPost != null)
Column(
children: [
AccountImage(content: item.avatar, radius: 16),
const Gap(8),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(item.nick).textStyle(
Theme.of(context).textTheme.bodyMedium!),
Text('@${item.name}')
.textStyle(Theme.of(context)
.textTheme
.bodySmall!)
.fontSize(12),
Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
minTileHeight: 48,
leading:
const Icon(Symbols.reply).padding(left: 4),
title: Text('postReplyingNotice')
.fontSize(15)
.tr(args: [
'@${_writeController.replyingPost!.publisher.name}'
]),
children: <Widget>[
PostItem(data: _writeController.replyingPost!)
],
),
),
const Divider(height: 1),
],
),
),
) ??
[]),
DropdownMenuItem<SnPublisher>(
value: null,
child: Row(
children: [
CircleAvatar(
radius: 16,
backgroundColor: Colors.transparent,
foregroundColor:
Theme.of(context).colorScheme.onSurface,
child: const Icon(Symbols.add),
),
const Gap(8),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
// Reposting Notice
if (_writeController.repostingPost != null)
Column(
children: [
Text('publishersNew').tr().textStyle(
Theme.of(context).textTheme.bodyMedium!),
Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
minTileHeight: 48,
leading: const Icon(Symbols.forward)
.padding(left: 4),
title: Text('postRepostingNotice')
.fontSize(15)
.tr(args: [
'@${_writeController.repostingPost!.publisher.name}'
]),
children: <Widget>[
PostItem(
data: _writeController.repostingPost!)
],
),
),
const Divider(height: 1),
],
),
),
],
// Editing Notice
if (_writeController.editingPost != null)
Column(
children: [
Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
minTileHeight: 48,
leading: const Icon(Symbols.edit_note)
.padding(left: 4),
title: Text('postEditingNotice')
.fontSize(15)
.tr(args: [
'@${_writeController.editingPost!.publisher.name}'
]),
children: <Widget>[
PostItem(data: _writeController.editingPost!)
],
),
),
const Divider(height: 1),
],
),
// Content Input Area
TextField(
controller: _writeController.contentController,
maxLines: null,
decoration: InputDecoration(
hintText: 'fieldPostContent'.tr(),
hintStyle: TextStyle(fontSize: 14),
isCollapsed: true,
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
),
border: InputBorder.none,
),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
)
]
.expandIndexed(
(idx, ele) => [
if (idx != 0 || _writeController.isRelatedNull)
const Gap(8),
ele,
],
)
.toList(),
),
),
],
value: _publisher,
onChanged: (SnPublisher? value) {
if (value == null) {
GoRouter.of(context)
.pushNamed('accountPublisherNew')
.then((value) {
if (value == true) {
_publisher = null;
_publishers = null;
_fetchPublishers();
}
});
} else {
setState(() {
_publisher = value;
});
}
},
buttonStyleData: const ButtonStyleData(
padding: EdgeInsets.only(right: 16),
height: 48,
),
menuItemStyleData: const MenuItemStyleData(
height: 48,
),
),
),
const Divider(height: 1),
Expanded(
child: SingleChildScrollView(
padding: EdgeInsets.only(bottom: 8),
child: Column(
children: [
// Replying Notice
if (_replyingTo != null)
Column(
children: [
Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
minTileHeight: 48,
leading: const Icon(Symbols.reply).padding(left: 4),
title: Text('postReplyingNotice')
.fontSize(15)
.tr(args: ['@${_replyingTo!.publisher.name}']),
children: <Widget>[PostItem(data: _replyingTo!)],
),
),
const Divider(height: 1),
],
),
// Reposting Notice
if (_repostingTo != null)
Column(
children: [
Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
minTileHeight: 48,
leading:
const Icon(Symbols.forward).padding(left: 4),
title: Text('postRepostingNotice')
.fontSize(15)
.tr(args: ['@${_repostingTo!.publisher.name}']),
children: <Widget>[PostItem(data: _repostingTo!)],
),
),
const Divider(height: 1),
],
),
// Editing Notice
if (_editingOg != null)
Column(
children: [
Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
),
child: ExpansionTile(
minTileHeight: 48,
leading:
const Icon(Symbols.edit_note).padding(left: 4),
title: Text('postEditingNotice')
.fontSize(15)
.tr(args: ['@${_editingOg!.publisher.name}']),
children: <Widget>[PostItem(data: _editingOg!)],
),
),
const Divider(height: 1),
],
),
// Content Input Area
TextField(
controller: _contentController,
maxLines: null,
decoration: InputDecoration(
hintText: 'fieldPostContent'.tr(),
hintStyle: TextStyle(fontSize: 14),
isCollapsed: true,
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
),
border: InputBorder.none,
),
onTapOutside: (_) =>
FocusManager.instance.primaryFocus?.unfocus(),
)
]
.expandIndexed(
(idx, ele) => [
if (idx != 0 ||
![_editingOg, _replyingTo, _repostingTo]
.any((x) => x != null))
const Gap(8),
ele,
],
)
.toList(),
),
),
),
if (_selectedMedia.isNotEmpty)
PostMediaPendingList(
data: _selectedMedia,
onRemove: (idx) {
setState(() {
_selectedMedia.removeAt(idx);
});
},
).padding(bottom: 8),
Material(
elevation: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LoadingIndicator(isActive: _isLoading),
if (_isBusy && _progress != null)
TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: 1),
duration: Duration(milliseconds: 300),
builder: (context, value, _) =>
LinearProgressIndicator(value: value, minHeight: 2),
)
else if (_isBusy)
const LinearProgressIndicator(value: null, minHeight: 2),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
if (_writeController.attachments.isNotEmpty)
PostMediaPendingList(
data: _writeController.attachments,
onRemove: (idx) {
_writeController.removeAttachmentAt(idx);
},
).padding(bottom: 8),
Material(
elevation: 2,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ScrollConfiguration(
behavior: _PostEditorActionScrollBehavior(),
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Row(
children: [
IconButton(
onPressed: _isBusy ? null : _selectMedia,
icon: Icon(
Symbols.add_photo_alternate,
color: Theme.of(context).colorScheme.primary,
),
LoadingIndicator(isActive: _isLoading),
if (_writeController.isBusy &&
_writeController.progress != null)
TweenAnimationBuilder<double>(
tween: Tween(begin: 0, end: _writeController.progress),
duration: Duration(milliseconds: 300),
builder: (context, value, _) =>
LinearProgressIndicator(value: value, minHeight: 2),
)
else if (_writeController.isBusy)
const LinearProgressIndicator(value: null, minHeight: 2),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: ScrollConfiguration(
behavior: _PostEditorActionScrollBehavior(),
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Row(
children: [
IconButton(
onPressed: _writeController.isBusy
? null
: _selectMedia,
icon: Icon(
Symbols.add_photo_alternate,
color:
Theme.of(context).colorScheme.primary,
),
),
],
),
],
),
),
),
),
),
TextButton.icon(
onPressed: (_isBusy || _publisher == null)
? null
: _performAction,
icon: const Icon(Symbols.send),
label: Text('postPublish').tr(),
),
TextButton.icon(
onPressed: (_writeController.isBusy ||
_writeController.publisher == null)
? null
: () => _writeController.post(context),
icon: const Icon(Symbols.send),
label: Text('postPublish').tr(),
),
],
).padding(horizontal: 16),
],
).padding(horizontal: 16),
],
).padding(
bottom: MediaQuery.of(context).padding.bottom,
top: 4,
),
).padding(
bottom: MediaQuery.of(context).padding.bottom,
top: 4,
),
),
],
),
],
),
);
},
);
}
}