-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathaction_sheet.dart
1029 lines (891 loc) · 36.3 KB
/
action_sheet.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:ui';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share_plus/share_plus.dart';
import '../api/exception.dart';
import '../api/model/model.dart';
import '../api/route/channels.dart';
import '../api/route/messages.dart';
import '../generated/l10n/zulip_localizations.dart';
import '../model/emoji.dart';
import '../model/internal_link.dart';
import '../model/narrow.dart';
import 'actions.dart';
import 'color.dart';
import 'compose_box.dart';
import 'dialog.dart';
import 'emoji.dart';
import 'emoji_reaction.dart';
import 'icons.dart';
import 'inset_shadow.dart';
import 'message_list.dart';
import 'page.dart';
import 'store.dart';
import 'text.dart';
import 'theme.dart';
import 'topic_list.dart';
void _showActionSheet(
BuildContext context, {
required List<Widget> optionButtons,
}) {
showModalBottomSheet<void>(
context: context,
// Clip.hardEdge looks bad; Clip.antiAliasWithSaveLayer looks pixel-perfect
// on my iPhone 13 Pro but is marked as "much slower":
// https://api.flutter.dev/flutter/dart-ui/Clip.html
clipBehavior: Clip.antiAlias,
useSafeArea: true,
isScrollControlled: true,
builder: (BuildContext _) {
return Semantics(
role: SemanticsRole.menu,
child: SafeArea(
minimum: const EdgeInsets.only(bottom: 16),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
// TODO(#217): show message text
Flexible(child: InsetShadowBox(
top: 8, bottom: 8,
color: DesignVariables.of(context).bgContextMenu,
child: SingleChildScrollView(
padding: const EdgeInsets.only(top: 16, bottom: 8),
child: ClipRRect(
borderRadius: BorderRadius.circular(7),
child: Column(spacing: 1,
children: optionButtons))))),
const ActionSheetCancelButton(),
]))));
});
}
/// A button in an action sheet.
///
/// When built from server data, the action sheet ignores changes in that data;
/// we intentionally don't live-update the buttons on events.
/// If a button's label, action, or position changes suddenly,
/// it can be confusing and make the on-tap behavior unexpected.
/// Better to let the user decide to tap
/// based on information that's comfortably in their working memory,
/// even if we sometimes have to explain (where we handle the tap)
/// that that information has changed and they need to decide again.
///
/// (Even if we did live-update the buttons, it's possible anyway that a user's
/// action can race with a change that's already been applied on the server,
/// because it takes some time for the server to report changes to us.)
abstract class ActionSheetMenuItemButton extends StatelessWidget {
const ActionSheetMenuItemButton({super.key, required this.pageContext});
IconData get icon;
String label(ZulipLocalizations zulipLocalizations);
/// Called when the button is pressed, after dismissing the action sheet.
///
/// If the action may take a long time, this method is responsible for
/// arranging any form of progress feedback that may be desired.
///
/// For operations that need a [BuildContext], see [pageContext].
void onPressed();
/// A context within the [MessageListPage] this action sheet was
/// triggered from.
final BuildContext pageContext;
/// The [MessageListPageState] this action sheet was triggered from.
///
/// Uses the inefficient [BuildContext.findAncestorStateOfType];
/// don't call this in a build method.
MessageListPageState findMessageListPage() {
assert(pageContext.mounted,
'findMessageListPage should be called only when pageContext is known to still be mounted');
return MessageListPage.ancestorOf(pageContext);
}
void _handlePressed(BuildContext context) {
// Dismiss the enclosing action sheet immediately,
// for swift UI feedback that the user's selection was received.
Navigator.of(context).pop();
assert(pageContext.mounted);
onPressed();
}
@override
Widget build(BuildContext context) {
final designVariables = DesignVariables.of(context);
final zulipLocalizations = ZulipLocalizations.of(context);
return MenuItemButton(
trailingIcon: Icon(icon, color: designVariables.contextMenuItemText),
style: MenuItemButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
foregroundColor: designVariables.contextMenuItemText,
splashFactory: NoSplash.splashFactory,
).copyWith(backgroundColor: WidgetStateColor.resolveWith((states) =>
designVariables.contextMenuItemBg.withFadedAlpha(
states.contains(WidgetState.pressed) ? 0.20 : 0.12))),
onPressed: () => _handlePressed(context),
child: Text(label(zulipLocalizations),
style: const TextStyle(fontSize: 20, height: 24 / 20)
.merge(weightVariableTextStyle(context, wght: 600)),
));
}
}
class ActionSheetCancelButton extends StatelessWidget {
const ActionSheetCancelButton({super.key});
@override
Widget build(BuildContext context) {
final designVariables = DesignVariables.of(context);
return TextButton(
style: TextButton.styleFrom(
minimumSize: const Size.fromHeight(44),
padding: const EdgeInsets.all(10),
foregroundColor: designVariables.contextMenuCancelText,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(7)),
splashFactory: NoSplash.splashFactory,
).copyWith(backgroundColor: WidgetStateColor.fromMap({
WidgetState.pressed: designVariables.contextMenuCancelPressedBg,
~WidgetState.pressed: designVariables.contextMenuCancelBg,
})),
onPressed: () {
Navigator.pop(context);
},
child: Text(ZulipLocalizations.of(context).dialogCancel,
style: const TextStyle(fontSize: 20, height: 24 / 20)
.merge(weightVariableTextStyle(context, wght: 600))));
}
}
/// Show a sheet of actions you can take on a channel.
///
/// Needs a [PageRoot] ancestor.
void showChannelActionSheet(BuildContext context, {
required int channelId,
}) {
final pageContext = PageRoot.contextOf(context);
final store = PerAccountStoreWidget.of(pageContext);
final optionButtons = <ActionSheetMenuItemButton>[];
optionButtons.add(
TopicListButton(pageContext: pageContext, channelId: channelId));
final unreadCount = store.unreads.countInChannelNarrow(channelId);
if (unreadCount > 0) {
optionButtons.add(
MarkChannelAsReadButton(pageContext: pageContext, channelId: channelId));
}
_showActionSheet(pageContext, optionButtons: optionButtons);
}
class TopicListButton extends ActionSheetMenuItemButton {
const TopicListButton({
super.key,
required this.channelId,
required super.pageContext,
});
final int channelId;
@override
IconData get icon => ZulipIcons.list;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionTopicList;
}
@override
void onPressed() {
Navigator.push(pageContext,
TopicListPage.buildRoute(
context: pageContext,
streamId: channelId,
));
}
}
class MarkChannelAsReadButton extends ActionSheetMenuItemButton {
const MarkChannelAsReadButton({
super.key,
required this.channelId,
required super.pageContext,
});
final int channelId;
@override
IconData get icon => ZulipIcons.message_checked;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionMarkChannelAsRead;
}
@override
void onPressed() async {
final narrow = ChannelNarrow(channelId);
await ZulipAction.markNarrowAsRead(pageContext, narrow);
}
}
/// Show a sheet of actions you can take on a topic.
///
/// Needs a [PageRoot] ancestor.
///
/// The API request for resolving/unresolving a topic needs a message ID.
/// If [someMessageIdInTopic] is null, the button for that will be absent.
void showTopicActionSheet(BuildContext context, {
required int channelId,
required TopicName topic,
required int? someMessageIdInTopic,
}) {
final pageContext = PageRoot.contextOf(context);
final store = PerAccountStoreWidget.of(pageContext);
final subscription = store.subscriptions[channelId];
final optionButtons = <ActionSheetMenuItemButton>[];
// TODO(server-7): simplify this condition away
final supportsUnmutingTopics = store.zulipFeatureLevel >= 170;
// TODO(server-8): simplify this condition away
final supportsFollowingTopics = store.zulipFeatureLevel >= 219;
final visibilityOptions = <UserTopicVisibilityPolicy>[];
final visibilityPolicy = store.topicVisibilityPolicy(channelId, topic);
if (subscription == null) {
// Not subscribed to the channel; there is no user topic change to be made.
} else if (!subscription.isMuted) {
// Channel is subscribed and not muted.
switch (visibilityPolicy) {
case UserTopicVisibilityPolicy.muted:
visibilityOptions.add(UserTopicVisibilityPolicy.none);
if (supportsFollowingTopics) {
visibilityOptions.add(UserTopicVisibilityPolicy.followed);
}
case UserTopicVisibilityPolicy.none:
case UserTopicVisibilityPolicy.unmuted:
visibilityOptions.add(UserTopicVisibilityPolicy.muted);
if (supportsFollowingTopics) {
visibilityOptions.add(UserTopicVisibilityPolicy.followed);
}
case UserTopicVisibilityPolicy.followed:
visibilityOptions.add(UserTopicVisibilityPolicy.muted);
if (supportsFollowingTopics) {
visibilityOptions.add(UserTopicVisibilityPolicy.none);
}
case UserTopicVisibilityPolicy.unknown:
// TODO(#1074): This should be unreachable as we keep `unknown` out of
// our data structures.
assert(false);
}
} else {
// Channel is muted.
if (supportsUnmutingTopics) {
switch (visibilityPolicy) {
case UserTopicVisibilityPolicy.none:
case UserTopicVisibilityPolicy.muted:
visibilityOptions.add(UserTopicVisibilityPolicy.unmuted);
if (supportsFollowingTopics) {
visibilityOptions.add(UserTopicVisibilityPolicy.followed);
}
case UserTopicVisibilityPolicy.unmuted:
visibilityOptions.add(UserTopicVisibilityPolicy.muted);
if (supportsFollowingTopics) {
visibilityOptions.add(UserTopicVisibilityPolicy.followed);
}
case UserTopicVisibilityPolicy.followed:
visibilityOptions.add(UserTopicVisibilityPolicy.muted);
if (supportsFollowingTopics) {
visibilityOptions.add(UserTopicVisibilityPolicy.none);
}
case UserTopicVisibilityPolicy.unknown:
// TODO(#1074): This should be unreachable as we keep `unknown` out of
// our data structures.
assert(false);
}
}
}
optionButtons.addAll(visibilityOptions.map((to) {
return UserTopicUpdateButton(
currentVisibilityPolicy: visibilityPolicy,
newVisibilityPolicy: to,
narrow: TopicNarrow(channelId, topic),
pageContext: pageContext);
}));
// TODO: check for other cases that may disallow this action (e.g.: time
// limit for editing topics).
if (someMessageIdInTopic != null
// ignore: unnecessary_null_comparison // null topic names soon to be enabled
&& topic.displayName != null) {
optionButtons.add(ResolveUnresolveButton(pageContext: pageContext,
topic: topic,
someMessageIdInTopic: someMessageIdInTopic));
}
final unreadCount = store.unreads.countInTopicNarrow(channelId, topic);
if (unreadCount > 0) {
optionButtons.add(MarkTopicAsReadButton(
channelId: channelId,
topic: topic,
pageContext: context));
}
if (optionButtons.isEmpty) {
// TODO(a11y): This case makes a no-op gesture handler; as a consequence,
// we're presenting some UI (to people who use screen-reader software) as
// though it offers a gesture interaction that it doesn't meaningfully
// offer, which is confusing. The solution here is probably to remove this
// is-empty case by having at least one button that's always present,
// such as "copy link to topic".
return;
}
_showActionSheet(pageContext, optionButtons: optionButtons);
}
class UserTopicUpdateButton extends ActionSheetMenuItemButton {
const UserTopicUpdateButton({
super.key,
required this.currentVisibilityPolicy,
required this.newVisibilityPolicy,
required this.narrow,
required super.pageContext,
});
final UserTopicVisibilityPolicy currentVisibilityPolicy;
final UserTopicVisibilityPolicy newVisibilityPolicy;
final TopicNarrow narrow;
@override IconData get icon {
switch (newVisibilityPolicy) {
case UserTopicVisibilityPolicy.none:
return ZulipIcons.inherit;
case UserTopicVisibilityPolicy.muted:
return ZulipIcons.mute;
case UserTopicVisibilityPolicy.unmuted:
return ZulipIcons.unmute;
case UserTopicVisibilityPolicy.followed:
return ZulipIcons.follow;
case UserTopicVisibilityPolicy.unknown:
// TODO(#1074): This should be unreachable as we keep `unknown` out of
// our data structures.
assert(false);
return ZulipIcons.inherit;
}
}
@override
String label(ZulipLocalizations zulipLocalizations) {
switch ((currentVisibilityPolicy, newVisibilityPolicy)) {
case (UserTopicVisibilityPolicy.muted, UserTopicVisibilityPolicy.none):
return zulipLocalizations.actionSheetOptionUnmuteTopic;
case (UserTopicVisibilityPolicy.followed, UserTopicVisibilityPolicy.none):
return zulipLocalizations.actionSheetOptionUnfollowTopic;
case (_, UserTopicVisibilityPolicy.muted):
return zulipLocalizations.actionSheetOptionMuteTopic;
case (_, UserTopicVisibilityPolicy.unmuted):
return zulipLocalizations.actionSheetOptionUnmuteTopic;
case (_, UserTopicVisibilityPolicy.followed):
return zulipLocalizations.actionSheetOptionFollowTopic;
case (_, UserTopicVisibilityPolicy.none):
// This is unexpected because `UserTopicVisibilityPolicy.muted` and
// `UserTopicVisibilityPolicy.followed` (handled in separate `case`'s)
// are the only expected `currentVisibilityPolicy`
// when `newVisibilityPolicy` is `UserTopicVisibilityPolicy.none`.
assert(false);
return '';
case (_, UserTopicVisibilityPolicy.unknown):
// This case is unreachable (or should be) because we keep `unknown` out
// of our data structures. We plan to remove the `unknown` case in #1074.
assert(false);
return '';
}
}
String _errorTitle(ZulipLocalizations zulipLocalizations) {
switch ((currentVisibilityPolicy, newVisibilityPolicy)) {
case (UserTopicVisibilityPolicy.muted, UserTopicVisibilityPolicy.none):
return zulipLocalizations.errorUnmuteTopicFailed;
case (UserTopicVisibilityPolicy.followed, UserTopicVisibilityPolicy.none):
return zulipLocalizations.errorUnfollowTopicFailed;
case (_, UserTopicVisibilityPolicy.muted):
return zulipLocalizations.errorMuteTopicFailed;
case (_, UserTopicVisibilityPolicy.unmuted):
return zulipLocalizations.errorUnmuteTopicFailed;
case (_, UserTopicVisibilityPolicy.followed):
return zulipLocalizations.errorFollowTopicFailed;
case (_, UserTopicVisibilityPolicy.none):
// This is unexpected because `UserTopicVisibilityPolicy.muted` and
// `UserTopicVisibilityPolicy.followed` (handled in separate `case`'s)
// are the only expected `currentVisibilityPolicy`
// when `newVisibilityPolicy` is `UserTopicVisibilityPolicy.none`.
assert(false);
return '';
case (_, UserTopicVisibilityPolicy.unknown):
// This case is unreachable (or should be) because we keep `unknown` out
// of our data structures. We plan to remove the `unknown` case in #1074.
assert(false);
return '';
}
}
@override void onPressed() async {
try {
await updateUserTopicCompat(
PerAccountStoreWidget.of(pageContext).connection,
streamId: narrow.streamId,
topic: narrow.topic,
visibilityPolicy: newVisibilityPolicy);
} catch (e) {
if (!pageContext.mounted) return;
String? errorMessage;
switch (e) {
case ZulipApiException():
errorMessage = e.message;
// TODO(#741) specific messages for common errors, like network errors
// (support with reusable code)
default:
}
final zulipLocalizations = ZulipLocalizations.of(pageContext);
showErrorDialog(context: pageContext,
title: _errorTitle(zulipLocalizations), message: errorMessage);
}
}
}
class ResolveUnresolveButton extends ActionSheetMenuItemButton {
ResolveUnresolveButton({
super.key,
required this.topic,
required this.someMessageIdInTopic,
required super.pageContext,
}) : _actionIsResolve = !topic.isResolved;
/// The topic that the action sheet was opened for.
///
/// There might not currently be any messages with this topic;
/// see dartdoc of [ActionSheetMenuItemButton].
final TopicName topic;
/// The message ID that was passed when opening the action sheet.
///
/// The message with this ID might currently not exist,
/// or might exist with a different topic;
/// see dartdoc of [ActionSheetMenuItemButton].
final int someMessageIdInTopic;
final bool _actionIsResolve;
@override
IconData get icon => _actionIsResolve ? ZulipIcons.check : ZulipIcons.check_remove;
@override
String label(ZulipLocalizations zulipLocalizations) {
return _actionIsResolve
? zulipLocalizations.actionSheetOptionResolveTopic
: zulipLocalizations.actionSheetOptionUnresolveTopic;
}
@override void onPressed() async {
final zulipLocalizations = ZulipLocalizations.of(pageContext);
final store = PerAccountStoreWidget.of(pageContext);
// We *could* check here if the topic has changed since the action sheet was
// opened (see dartdoc of [ActionSheetMenuItemButton]) and abort if so.
// We simplify by not doing so.
// There's already an inherent race that that check wouldn't help with:
// when you tap the button, an intervening topic change may already have
// happened, just not reached us in an event yet.
// Discussion, including about what web does:
// https://github.com/zulip/zulip-flutter/pull/1301#discussion_r1936181560
try {
await updateMessage(store.connection,
messageId: someMessageIdInTopic,
topic: _actionIsResolve ? topic.resolve() : topic.unresolve(),
propagateMode: PropagateMode.changeAll,
sendNotificationToOldThread: false,
sendNotificationToNewThread: true,
);
} catch (e) {
if (!pageContext.mounted) return;
String? errorMessage;
switch (e) {
case ZulipApiException():
errorMessage = e.message;
// TODO(#741) specific messages for common errors, like network errors
// (support with reusable code)
default:
}
final title = _actionIsResolve
? zulipLocalizations.errorResolveTopicFailedTitle
: zulipLocalizations.errorUnresolveTopicFailedTitle;
showErrorDialog(context: pageContext, title: title, message: errorMessage);
}
}
}
class MarkTopicAsReadButton extends ActionSheetMenuItemButton {
const MarkTopicAsReadButton({
super.key,
required this.channelId,
required this.topic,
required super.pageContext,
});
final int channelId;
final TopicName topic;
@override IconData get icon => ZulipIcons.message_checked;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionMarkTopicAsRead;
}
@override void onPressed() async {
await ZulipAction.markNarrowAsRead(pageContext, TopicNarrow(channelId, topic));
}
}
/// Show a sheet of actions you can take on a message in the message list.
///
/// Must have a [MessageListPage] ancestor.
void showMessageActionSheet({required BuildContext context, required Message message}) {
final pageContext = PageRoot.contextOf(context);
final store = PerAccountStoreWidget.of(pageContext);
// The UI that's conditioned on this won't live-update during this appearance
// of the action sheet (we avoid calling composeBoxControllerOf in a build
// method; see its doc).
// So we rely on the fact that isComposeBoxOffered for any given message list
// will be constant through the page's life.
final messageListPage = MessageListPage.ancestorOf(pageContext);
final isComposeBoxOffered = messageListPage.composeBoxController != null;
final isMessageRead = message.flags.contains(MessageFlag.read);
final markAsUnreadSupported = store.zulipFeatureLevel >= 155; // TODO(server-6)
final showMarkAsUnreadButton = markAsUnreadSupported && isMessageRead;
final optionButtons = [
ReactionButtons(message: message, pageContext: pageContext),
StarButton(message: message, pageContext: pageContext),
if (isComposeBoxOffered)
QuoteAndReplyButton(message: message, pageContext: pageContext),
if (showMarkAsUnreadButton)
MarkAsUnreadButton(message: message, pageContext: pageContext),
CopyMessageTextButton(message: message, pageContext: pageContext),
CopyMessageLinkButton(message: message, pageContext: pageContext),
ShareButton(message: message, pageContext: pageContext),
];
_showActionSheet(pageContext, optionButtons: optionButtons);
}
abstract class MessageActionSheetMenuItemButton extends ActionSheetMenuItemButton {
MessageActionSheetMenuItemButton({
super.key,
required this.message,
required super.pageContext,
}) : assert(pageContext.findAncestorWidgetOfExactType<MessageListPage>() != null);
final Message message;
}
class ReactionButtons extends StatelessWidget {
const ReactionButtons({
super.key,
required this.message,
required this.pageContext,
});
final Message message;
/// A context within the [MessageListPage] this action sheet was
/// triggered from.
final BuildContext pageContext;
void _handleTapReaction({
required EmojiCandidate emoji,
required bool isSelfVoted,
}) {
// Dismiss the enclosing action sheet immediately,
// for swift UI feedback that the user's selection was received.
Navigator.pop(pageContext);
final zulipLocalizations = ZulipLocalizations.of(pageContext);
doAddOrRemoveReaction(
context: pageContext,
doRemoveReaction: isSelfVoted,
messageId: message.id,
emoji: emoji,
errorDialogTitle: isSelfVoted
? zulipLocalizations.errorReactionRemovingFailedTitle
: zulipLocalizations.errorReactionAddingFailedTitle);
}
void _handleTapMore() {
// TODO(design): have emoji picker slide in from right and push
// action sheet off to the left
// Dismiss current action sheet before opening emoji picker sheet.
Navigator.of(pageContext).pop();
showEmojiPickerSheet(pageContext: pageContext, message: message);
}
Widget _buildButton({
required BuildContext context,
required EmojiCandidate emoji,
required bool isSelfVoted,
required bool isFirst,
}) {
final designVariables = DesignVariables.of(context);
return Flexible(child: InkWell(
onTap: () => _handleTapReaction(emoji: emoji, isSelfVoted: isSelfVoted),
splashFactory: NoSplash.splashFactory,
borderRadius: isFirst
? const BorderRadius.only(topLeft: Radius.circular(7))
: null,
overlayColor: WidgetStateColor.resolveWith((states) =>
states.any((e) => e == WidgetState.pressed)
? designVariables.contextMenuItemBg.withFadedAlpha(0.20)
: Colors.transparent),
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 5),
alignment: Alignment.center,
color: isSelfVoted
? designVariables.contextMenuItemBg.withFadedAlpha(0.20)
: null,
child: UnicodeEmojiWidget(
emojiDisplay: emoji.emojiDisplay as UnicodeEmojiDisplay,
notoColorEmojiTextSize: 20.1,
size: 24))));
}
@override
Widget build(BuildContext context) {
assert(EmojiStore.popularEmojiCandidates.every(
(emoji) => emoji.emojiType == ReactionType.unicodeEmoji));
final zulipLocalizations = ZulipLocalizations.of(context);
final store = PerAccountStoreWidget.of(pageContext);
final designVariables = DesignVariables.of(context);
bool hasSelfVote(EmojiCandidate emoji) {
return message.reactions?.aggregated.any((reactionWithVotes) {
return reactionWithVotes.reactionType == ReactionType.unicodeEmoji
&& reactionWithVotes.emojiCode == emoji.emojiCode
&& reactionWithVotes.userIds.contains(store.selfUserId);
}) ?? false;
}
return Container(
decoration: BoxDecoration(
color: designVariables.contextMenuItemBg.withFadedAlpha(0.12)),
child: Row(children: [
Flexible(child: Row(spacing: 1, children: List.unmodifiable(
EmojiStore.popularEmojiCandidates.mapIndexed((index, emoji) =>
_buildButton(
context: context,
emoji: emoji,
isSelfVoted: hasSelfVote(emoji),
isFirst: index == 0))))),
InkWell(
onTap: _handleTapMore,
splashFactory: NoSplash.splashFactory,
borderRadius: const BorderRadius.only(topRight: Radius.circular(7)),
overlayColor: WidgetStateColor.resolveWith((states) =>
states.any((e) => e == WidgetState.pressed)
? designVariables.contextMenuItemBg.withFadedAlpha(0.20)
: Colors.transparent),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(12, 12, 4, 12),
child: Row(children: [
Text(zulipLocalizations.emojiReactionsMore,
textAlign: TextAlign.end,
style: TextStyle(
color: designVariables.contextMenuItemText,
fontSize: 14,
).merge(weightVariableTextStyle(context, wght: 600))),
Icon(ZulipIcons.chevron_right,
color: designVariables.contextMenuItemText,
size: 24),
]),
)),
]),
);
}
}
class StarButton extends MessageActionSheetMenuItemButton {
StarButton({super.key, required super.message, required super.pageContext});
@override IconData get icon => _isStarred ? ZulipIcons.star_filled : ZulipIcons.star;
bool get _isStarred => message.flags.contains(MessageFlag.starred);
@override
String label(ZulipLocalizations zulipLocalizations) {
return _isStarred
? zulipLocalizations.actionSheetOptionUnstarMessage
: zulipLocalizations.actionSheetOptionStarMessage;
}
@override void onPressed() async {
final zulipLocalizations = ZulipLocalizations.of(pageContext);
final op = message.flags.contains(MessageFlag.starred)
? UpdateMessageFlagsOp.remove
: UpdateMessageFlagsOp.add;
try {
final connection = PerAccountStoreWidget.of(pageContext).connection;
await updateMessageFlags(connection, messages: [message.id],
op: op, flag: MessageFlag.starred);
} catch (e) {
if (!pageContext.mounted) return;
String? errorMessage;
switch (e) {
case ZulipApiException():
errorMessage = e.message;
// TODO specific messages for common errors, like network errors
// (support with reusable code)
default:
}
showErrorDialog(context: pageContext,
title: switch(op) {
UpdateMessageFlagsOp.remove => zulipLocalizations.errorUnstarMessageFailedTitle,
UpdateMessageFlagsOp.add => zulipLocalizations.errorStarMessageFailedTitle,
}, message: errorMessage);
}
}
}
/// Fetch and return the raw Markdown content for [messageId],
/// showing an error dialog on failure.
Future<String?> fetchRawContentWithFeedback({
required BuildContext context,
required int messageId,
required String errorDialogTitle,
}) async {
Message? fetchedMessage;
String? errorMessage;
// TODO, supported by reusable code:
// - (?) Retry with backoff on plausibly transient errors.
// - If request(s) take(s) a long time, show snackbar with cancel
// button, like "Still working on quote-and-reply…".
// On final failure or success, auto-dismiss the snackbar.
final zulipLocalizations = ZulipLocalizations.of(context);
try {
fetchedMessage = await getMessageCompat(PerAccountStoreWidget.of(context).connection,
messageId: messageId,
applyMarkdown: false,
);
if (fetchedMessage == null) {
errorMessage = zulipLocalizations.errorMessageDoesNotSeemToExist;
}
} catch (e) {
switch (e) {
case ZulipApiException():
errorMessage = e.message;
// TODO specific messages for common errors, like network errors
// (support with reusable code)
default:
errorMessage = zulipLocalizations.errorCouldNotFetchMessageSource;
}
}
if (!context.mounted) return null;
if (fetchedMessage == null) {
assert(errorMessage != null);
// TODO(?) give no feedback on error conditions we expect to
// flag centrally in event polling, like invalid auth,
// user/realm deactivated. (Support with reusable code.)
showErrorDialog(context: context,
title: errorDialogTitle, message: errorMessage);
}
return fetchedMessage?.content;
}
class QuoteAndReplyButton extends MessageActionSheetMenuItemButton {
QuoteAndReplyButton({super.key, required super.message, required super.pageContext});
@override IconData get icon => ZulipIcons.format_quote;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionQuoteAndReply;
}
@override void onPressed() async {
final zulipLocalizations = ZulipLocalizations.of(pageContext);
final message = this.message;
var composeBoxController = findMessageListPage().composeBoxController;
// The compose box doesn't null out its controller; it's either always null
// (e.g. in Combined Feed) or always non-null; it can't have been nulled out
// after the action sheet opened.
composeBoxController!;
if (
composeBoxController is StreamComposeBoxController
&& composeBoxController.topic.textNormalized == kNoTopicTopic
&& message is StreamMessage
) {
composeBoxController.topic.setTopic(message.topic);
}
// This inserts a "[Quoting…]" placeholder into the content input,
// giving the user a form of progress feedback.
final tag = composeBoxController.content
.registerQuoteAndReplyStart(
zulipLocalizations,
PerAccountStoreWidget.of(pageContext),
message: message,
);
final rawContent = await fetchRawContentWithFeedback(
context: pageContext,
messageId: message.id,
errorDialogTitle: zulipLocalizations.errorQuotationFailed,
);
if (!pageContext.mounted) return;
composeBoxController = findMessageListPage().composeBoxController;
// The compose box doesn't null out its controller; it's either always null
// (e.g. in Combined Feed) or always non-null; it can't have been nulled out
// during the raw-content request.
composeBoxController!.content
.registerQuoteAndReplyEnd(PerAccountStoreWidget.of(pageContext), tag,
message: message,
rawContent: rawContent,
);
if (!composeBoxController.contentFocusNode.hasFocus) {
composeBoxController.contentFocusNode.requestFocus();
}
}
}
class MarkAsUnreadButton extends MessageActionSheetMenuItemButton {
MarkAsUnreadButton({super.key, required super.message, required super.pageContext});
@override IconData get icon => Icons.mark_chat_unread_outlined;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionMarkAsUnread;
}
@override void onPressed() async {
final narrow = findMessageListPage().narrow;
unawaited(ZulipAction.markNarrowAsUnreadFromMessage(pageContext,
message, narrow));
}
}
class CopyMessageTextButton extends MessageActionSheetMenuItemButton {
CopyMessageTextButton({super.key, required super.message, required super.pageContext});
@override IconData get icon => ZulipIcons.copy;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionCopyMessageText;
}
@override void onPressed() async {
// This action doesn't show request progress.
// But hopefully it won't take long at all; and
// fetchRawContentWithFeedback has a TODO for giving feedback if it does.
final zulipLocalizations = ZulipLocalizations.of(pageContext);
final rawContent = await fetchRawContentWithFeedback(
context: pageContext,
messageId: message.id,
errorDialogTitle: zulipLocalizations.errorCopyingFailed,
);
if (rawContent == null) return;
if (!pageContext.mounted) return;
PlatformActions.copyWithPopup(context: pageContext,
successContent: Text(zulipLocalizations.successMessageTextCopied),
data: ClipboardData(text: rawContent));
}
}
class CopyMessageLinkButton extends MessageActionSheetMenuItemButton {
CopyMessageLinkButton({super.key, required super.message, required super.pageContext});
@override IconData get icon => Icons.link;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionCopyMessageLink;
}
@override void onPressed() {
final zulipLocalizations = ZulipLocalizations.of(pageContext);
final store = PerAccountStoreWidget.of(pageContext);
final messageLink = narrowLink(
store,
SendableNarrow.ofMessage(message, selfUserId: store.selfUserId),
nearMessageId: message.id,
);
PlatformActions.copyWithPopup(context: pageContext,
successContent: Text(zulipLocalizations.successMessageLinkCopied),
data: ClipboardData(text: messageLink.toString()));
}
}
class ShareButton extends MessageActionSheetMenuItemButton {
ShareButton({super.key, required super.message, required super.pageContext});
@override
IconData get icon => defaultTargetPlatform == TargetPlatform.iOS
? ZulipIcons.share_ios
: ZulipIcons.share;
@override
String label(ZulipLocalizations zulipLocalizations) {
return zulipLocalizations.actionSheetOptionShare;
}
@override void onPressed() async {
// TODO(#591): Fix iOS bug where if the keyboard was open before the call
// to `showMessageActionSheet`, it reappears briefly between
// the `pop` of the action sheet and the appearance of the share sheet.
//
// (Alternatively we could delay the [NavigatorState.pop] that
// dismisses the action sheet until after the sharing Future settles
// with [ShareResultStatus.success]. But on iOS one gets impatient with
// how slowly our action sheet dismisses in that case.)
final zulipLocalizations = ZulipLocalizations.of(pageContext);
final rawContent = await fetchRawContentWithFeedback(