-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathmessage_list.dart
1489 lines (1328 loc) · 55.3 KB
/
message_list.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:math';
import 'package:collection/collection.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_color_models/flutter_color_models.dart';
import 'package:intl/intl.dart' hide TextDirection;
import '../api/model/model.dart';
import '../generated/l10n/zulip_localizations.dart';
import '../model/message_list.dart';
import '../model/narrow.dart';
import '../model/store.dart';
import '../model/typing_status.dart';
import 'action_sheet.dart';
import 'actions.dart';
import 'app_bar.dart';
import 'compose_box.dart';
import 'content.dart';
import 'dialog.dart';
import 'emoji_reaction.dart';
import 'icons.dart';
import 'page.dart';
import 'profile.dart';
import 'sticky_header.dart';
import 'store.dart';
import 'text.dart';
import 'theme.dart';
/// Message-list styles that differ between light and dark themes.
class MessageListTheme extends ThemeExtension<MessageListTheme> {
static final light = MessageListTheme._(
dateSeparator: Colors.black,
dateSeparatorText: const HSLColor.fromAHSL(0.75, 0, 0, 0.15).toColor(),
dmRecipientHeaderBg: const HSLColor.fromAHSL(1, 46, 0.35, 0.93).toColor(),
messageTimestamp: const HSLColor.fromAHSL(0.8, 0, 0, 0.2).toColor(),
recipientHeaderText: const HSLColor.fromAHSL(1, 0, 0, 0.15).toColor(),
senderBotIcon: const HSLColor.fromAHSL(1, 180, 0.08, 0.65).toColor(),
senderName: const HSLColor.fromAHSL(1, 0, 0, 0.2).toColor(),
streamMessageBgDefault: Colors.white,
streamRecipientHeaderChevronRight: Colors.black.withValues(alpha: 0.3),
// From the Figma mockup at:
// https://www.figma.com/file/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?node-id=132-9684
// See discussion about design at:
// https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/flutter.3A.20unread.20marker/near/1658008
// (Web uses a left-to-right gradient from hsl(217deg 64% 59%) to transparent,
// in both light and dark theme.)
unreadMarker: const HSLColor.fromAHSL(1, 227, 0.78, 0.59).toColor(),
unreadMarkerGap: Colors.white.withValues(alpha: 0.6),
// TODO(design) this seems ad-hoc; is there a better color?
unsubscribedStreamRecipientHeaderBg: const Color(0xfff5f5f5),
);
static final dark = MessageListTheme._(
dateSeparator: Colors.white,
dateSeparatorText: const HSLColor.fromAHSL(0.75, 0, 0, 1).toColor(),
dmRecipientHeaderBg: const HSLColor.fromAHSL(1, 46, 0.15, 0.2).toColor(),
messageTimestamp: const HSLColor.fromAHSL(0.8, 0, 0, 0.85).toColor(),
recipientHeaderText: const HSLColor.fromAHSL(0.8, 0, 0, 1).toColor(),
senderBotIcon: const HSLColor.fromAHSL(1, 180, 0.05, 0.5).toColor(),
senderName: const HSLColor.fromAHSL(0.85, 0, 0, 1).toColor(),
streamMessageBgDefault: const HSLColor.fromAHSL(1, 0, 0, 0.15).toColor(),
streamRecipientHeaderChevronRight: Colors.white.withValues(alpha: 0.3),
// 0.75 opacity from here:
// https://www.figma.com/design/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?node-id=807-33998&m=dev
// Discussion, some weeks after the discussion linked on the light variant:
// https://github.com/zulip/zulip-flutter/pull/317#issuecomment-1784311663
// where Vlad includes screenshots that look like they're from there.
unreadMarker: const HSLColor.fromAHSL(0.75, 227, 0.78, 0.59).toColor(),
unreadMarkerGap: Colors.transparent,
// TODO(design) this is ad-hoc and untested; is there a better color?
unsubscribedStreamRecipientHeaderBg: const Color(0xff0a0a0a),
);
MessageListTheme._({
required this.dateSeparator,
required this.dateSeparatorText,
required this.dmRecipientHeaderBg,
required this.messageTimestamp,
required this.recipientHeaderText,
required this.senderBotIcon,
required this.senderName,
required this.streamMessageBgDefault,
required this.streamRecipientHeaderChevronRight,
required this.unreadMarker,
required this.unreadMarkerGap,
required this.unsubscribedStreamRecipientHeaderBg,
});
/// The [MessageListTheme] from the context's active theme.
///
/// The [ThemeData] must include [MessageListTheme] in [ThemeData.extensions].
static MessageListTheme of(BuildContext context) {
final theme = Theme.of(context);
final extension = theme.extension<MessageListTheme>();
assert(extension != null);
return extension!;
}
final Color dateSeparator;
final Color dateSeparatorText;
final Color dmRecipientHeaderBg;
final Color messageTimestamp;
final Color recipientHeaderText;
final Color senderBotIcon;
final Color senderName;
final Color streamMessageBgDefault;
final Color streamRecipientHeaderChevronRight;
final Color unreadMarker;
final Color unreadMarkerGap;
final Color unsubscribedStreamRecipientHeaderBg;
@override
MessageListTheme copyWith({
Color? dateSeparator,
Color? dateSeparatorText,
Color? dmRecipientHeaderBg,
Color? messageTimestamp,
Color? recipientHeaderText,
Color? senderBotIcon,
Color? senderName,
Color? streamMessageBgDefault,
Color? streamRecipientHeaderChevronRight,
Color? unreadMarker,
Color? unreadMarkerGap,
Color? unsubscribedStreamRecipientHeaderBg,
}) {
return MessageListTheme._(
dateSeparator: dateSeparator ?? this.dateSeparator,
dateSeparatorText: dateSeparatorText ?? this.dateSeparatorText,
dmRecipientHeaderBg: dmRecipientHeaderBg ?? this.dmRecipientHeaderBg,
messageTimestamp: messageTimestamp ?? this.messageTimestamp,
recipientHeaderText: recipientHeaderText ?? this.recipientHeaderText,
senderBotIcon: senderBotIcon ?? this.senderBotIcon,
senderName: senderName ?? this.senderName,
streamMessageBgDefault: streamMessageBgDefault ?? this.streamMessageBgDefault,
streamRecipientHeaderChevronRight: streamRecipientHeaderChevronRight ?? this.streamRecipientHeaderChevronRight,
unreadMarker: unreadMarker ?? this.unreadMarker,
unreadMarkerGap: unreadMarkerGap ?? this.unreadMarkerGap,
unsubscribedStreamRecipientHeaderBg: unsubscribedStreamRecipientHeaderBg ?? this.unsubscribedStreamRecipientHeaderBg,
);
}
@override
MessageListTheme lerp(MessageListTheme other, double t) {
if (identical(this, other)) {
return this;
}
return MessageListTheme._(
dateSeparator: Color.lerp(dateSeparator, other.dateSeparator, t)!,
dateSeparatorText: Color.lerp(dateSeparatorText, other.dateSeparatorText, t)!,
dmRecipientHeaderBg: Color.lerp(dmRecipientHeaderBg, other.dmRecipientHeaderBg, t)!,
messageTimestamp: Color.lerp(messageTimestamp, other.messageTimestamp, t)!,
recipientHeaderText: Color.lerp(recipientHeaderText, other.recipientHeaderText, t)!,
senderBotIcon: Color.lerp(senderBotIcon, other.senderBotIcon, t)!,
senderName: Color.lerp(senderName, other.senderName, t)!,
streamMessageBgDefault: Color.lerp(streamMessageBgDefault, other.streamMessageBgDefault, t)!,
streamRecipientHeaderChevronRight: Color.lerp(streamRecipientHeaderChevronRight, other.streamRecipientHeaderChevronRight, t)!,
unreadMarker: Color.lerp(unreadMarker, other.unreadMarker, t)!,
unreadMarkerGap: Color.lerp(unreadMarkerGap, other.unreadMarkerGap, t)!,
unsubscribedStreamRecipientHeaderBg: Color.lerp(unsubscribedStreamRecipientHeaderBg, other.unsubscribedStreamRecipientHeaderBg, t)!,
);
}
}
/// The interface for the state of a [MessageListPage].
///
/// To obtain one of these, see [MessageListPage.ancestorOf].
abstract class MessageListPageState {
/// The narrow for this page's message list.
Narrow get narrow;
/// The controller for this [MessageListPage]'s compose box,
/// if this [MessageListPage] offers a compose box and it has mounted,
/// else null.
ComposeBoxController? get composeBoxController;
/// The active [MessageListView].
///
/// This is null if [MessageList] has not mounted yet.
MessageListView? get model;
}
class MessageListPage extends StatefulWidget {
const MessageListPage({super.key, required this.initNarrow});
static AccountRoute<void> buildRoute({int? accountId, BuildContext? context,
required Narrow narrow}) {
return MaterialAccountWidgetRoute(accountId: accountId, context: context,
page: MessageListPage(initNarrow: narrow));
}
/// The [MessageListPageState] above this context in the tree.
///
/// Uses the inefficient [BuildContext.findAncestorStateOfType];
/// don't call this in a build method.
// If we do find ourselves wanting this in a build method, it won't be hard
// to enable that: we'd just need to add an [InheritedWidget] here.
static MessageListPageState ancestorOf(BuildContext context) {
final state = context.findAncestorStateOfType<_MessageListPageState>();
assert(state != null, 'No MessageListPage ancestor');
return state!;
}
final Narrow initNarrow;
@override
State<MessageListPage> createState() => _MessageListPageState();
}
class _MessageListPageState extends State<MessageListPage> implements MessageListPageState {
@override
late Narrow narrow;
@override
ComposeBoxController? get composeBoxController => _composeBoxKey.currentState?.controller;
final GlobalKey<ComposeBoxState> _composeBoxKey = GlobalKey();
@override
MessageListView? get model => _messageListKey.currentState?.model;
final GlobalKey<_MessageListState> _messageListKey = GlobalKey();
@override
void initState() {
super.initState();
narrow = widget.initNarrow;
}
void _narrowChanged(Narrow newNarrow) {
setState(() {
narrow = newNarrow;
});
}
@override
Widget build(BuildContext context) {
final store = PerAccountStoreWidget.of(context);
final messageListTheme = MessageListTheme.of(context);
final zulipLocalizations = ZulipLocalizations.of(context);
final Color? appBarBackgroundColor;
bool removeAppBarBottomBorder = false;
switch(narrow) {
case CombinedFeedNarrow():
case MentionsNarrow():
case StarredMessagesNarrow():
appBarBackgroundColor = null; // i.e., inherit
case ChannelNarrow(:final streamId):
case TopicNarrow(:final streamId):
final subscription = store.subscriptions[streamId];
appBarBackgroundColor = subscription != null
? colorSwatchFor(context, subscription).barBackground
: messageListTheme.unsubscribedStreamRecipientHeaderBg;
// All recipient headers will match this color; remove distracting line
// (but are recipient headers even needed for topic narrows?)
removeAppBarBottomBorder = true;
case DmNarrow():
appBarBackgroundColor = messageListTheme.dmRecipientHeaderBg;
// All recipient headers will match this color; remove distracting line
// (but are recipient headers even needed?)
removeAppBarBottomBorder = true;
}
List<Widget>? actions;
if (narrow case TopicNarrow(:final streamId)) {
(actions ??= []).add(IconButton(
icon: const Icon(ZulipIcons.message_feed),
tooltip: zulipLocalizations.channelFeedButtonTooltip,
onPressed: () => Navigator.push(context,
MessageListPage.buildRoute(context: context,
narrow: ChannelNarrow(streamId)))));
}
// Insert a PageRoot here, to provide a context that can be used for
// MessageListPage.ancestorOf.
return PageRoot(child: Scaffold(
appBar: ZulipAppBar(
buildTitle: (willCenterTitle) =>
MessageListAppBarTitle(narrow: narrow, willCenterTitle: willCenterTitle),
actions: actions,
backgroundColor: appBarBackgroundColor,
shape: removeAppBarBottomBorder
? const Border()
: null, // i.e., inherit
),
// TODO question for Vlad: for a stream view, should we set the Scaffold's
// [backgroundColor] based on stream color, as in this frame:
// https://www.figma.com/file/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?node-id=132%3A9684&mode=dev
// That's not obviously preferred over the default background that
// we matched to the Figma in 21dbae120. See another frame, which uses that:
// https://www.figma.com/file/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?node-id=147%3A9088&mode=dev
body: Builder(
builder: (BuildContext context) => Column(
// Children are expected to take the full horizontal space
// and handle the horizontal device insets.
// The bottom inset should be handled by the last child only.
children: [
MediaQuery.removePadding(
// Scaffold knows about the app bar, and so has run this
// BuildContext, which is under `body`, through
// MediaQuery.removePadding with `removeTop: true`.
context: context,
// The compose box, when present, pads the bottom inset.
// TODO(#311) If we have a bottom nav, it will pad the bottom
// inset, and this should always be true.
removeBottom: ComposeBox.hasComposeBox(narrow),
child: Expanded(
child: MessageList(
key: _messageListKey,
narrow: narrow,
onNarrowChanged: _narrowChanged,
))),
if (ComposeBox.hasComposeBox(narrow))
ComposeBox(key: _composeBoxKey, narrow: narrow)
]))));
}
}
class MessageListAppBarTitle extends StatelessWidget {
const MessageListAppBarTitle({
super.key,
required this.narrow,
required this.willCenterTitle,
});
final Narrow narrow;
final bool willCenterTitle;
Widget _buildStreamRow(BuildContext context, {
ZulipStream? stream,
}) {
final zulipLocalizations = ZulipLocalizations.of(context);
// A null [Icon.icon] makes a blank space.
final icon = stream != null ? iconDataForStream(stream) : null;
return Row(
mainAxisSize: MainAxisSize.min,
// TODO(design): The vertical alignment of the stream privacy icon is a bit ad hoc.
// For screenshots of some experiments, see:
// https://github.com/zulip/zulip-flutter/pull/219#discussion_r1281024746
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(size: 16, icon),
const SizedBox(width: 4),
Flexible(child: Text(
stream?.name ?? zulipLocalizations.unknownChannelName)),
]);
}
Widget _buildTopicRow(BuildContext context, {
required ZulipStream? stream,
required TopicName topic,
}) {
final store = PerAccountStoreWidget.of(context);
final designVariables = DesignVariables.of(context);
final icon = stream == null ? null
: iconDataForTopicVisibilityPolicy(
store.topicVisibilityPolicy(stream.streamId, topic));
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(topic.displayName, style: const TextStyle(
fontSize: 13,
).merge(weightVariableTextStyle(context)))),
if (icon != null)
Padding(
padding: const EdgeInsetsDirectional.only(start: 4),
child: Icon(icon,
// TODO(design) copies the recipient header in web; is there a better color?
color: designVariables.colorMessageHeaderIconInteractive, size: 14)),
]);
}
@override
Widget build(BuildContext context) {
final zulipLocalizations = ZulipLocalizations.of(context);
switch (narrow) {
case CombinedFeedNarrow():
return Text(zulipLocalizations.combinedFeedPageTitle);
case MentionsNarrow():
return Text(zulipLocalizations.mentionsPageTitle);
case StarredMessagesNarrow():
return Text(zulipLocalizations.starredMessagesPageTitle);
case ChannelNarrow(:var streamId):
final store = PerAccountStoreWidget.of(context);
final stream = store.streams[streamId];
return _buildStreamRow(context, stream: stream);
case TopicNarrow(:var streamId, :var topic):
final store = PerAccountStoreWidget.of(context);
final stream = store.streams[streamId];
return SizedBox(
width: double.infinity,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onLongPress: () {
final someMessage = MessageListPage.ancestorOf(context)
.model?.messages.firstOrNull;
// If someMessage is null, the topic action sheet won't have a
// resolve/unresolve button. That seems OK; in that case we're
// either still fetching messages (and the user can reopen the
// sheet after that finishes) or there aren't any messages to
// act on anyway.
assert(someMessage == null || narrow.containsMessage(someMessage));
showTopicActionSheet(context,
channelId: streamId,
topic: topic,
someMessageIdInTopic: someMessage?.id);
},
child: Column(
crossAxisAlignment: willCenterTitle ? CrossAxisAlignment.center
: CrossAxisAlignment.start,
children: [
_buildStreamRow(context, stream: stream),
_buildTopicRow(context, stream: stream, topic: topic),
])));
case DmNarrow(:var otherRecipientIds):
final store = PerAccountStoreWidget.of(context);
if (otherRecipientIds.isEmpty) {
return Text(zulipLocalizations.dmsWithYourselfPageTitle);
} else {
final names = otherRecipientIds.map(store.userDisplayName);
// TODO show avatars
return Text(
zulipLocalizations.dmsWithOthersPageTitle(names.join(', ')));
}
}
}
}
/// The approximate height of a short message in the message list.
const _kShortMessageHeight = 80;
/// The point at which we fetch more history, in pixels from the start or end.
///
/// When the user scrolls to within this distance of the start (or end) of the
/// history we currently have, we make a request to fetch the next batch of
/// older (or newer) messages.
//
// When the user reaches this point, they're at least halfway through the
// previous batch.
const kFetchMessagesBufferPixels = (kMessageListFetchBatchSize / 2) * _kShortMessageHeight;
/// The message list.
///
/// Takes the full screen width, keeping its contents
/// out of the horizontal insets with transparent [SafeArea] padding.
/// When there is no [ComposeBox], also takes responsibility
/// for dealing with the bottom inset.
class MessageList extends StatefulWidget {
const MessageList({super.key, required this.narrow, required this.onNarrowChanged});
final Narrow narrow;
final void Function(Narrow newNarrow) onNarrowChanged;
@override
State<StatefulWidget> createState() => _MessageListState();
}
class _MessageListState extends State<MessageList> with PerAccountStoreAwareStateMixin<MessageList> {
MessageListView? model;
final ScrollController scrollController = ScrollController();
final ValueNotifier<bool> _scrollToBottomVisibleValue = ValueNotifier<bool>(false);
@override
void initState() {
super.initState();
scrollController.addListener(_scrollChanged);
}
@override
void onNewStore() { // TODO(#464) try to keep using old model until new one gets messages
model?.dispose();
_initModel(PerAccountStoreWidget.of(context));
}
@override
void dispose() {
model?.dispose();
scrollController.dispose();
_scrollToBottomVisibleValue.dispose();
super.dispose();
}
void _initModel(PerAccountStore store) {
model = MessageListView.init(store: store, narrow: widget.narrow);
model!.addListener(_modelChanged);
model!.fetchInitial();
}
void _modelChanged() {
if (model!.narrow != widget.narrow) {
// Either:
// - A message move event occurred, where propagate mode is
// [PropagateMode.changeAll] or [PropagateMode.changeLater]. Or:
// - We fetched a "with" / topic-permalink narrow, and the response
// redirected us to the new location of the operand message ID.
widget.onNarrowChanged(model!.narrow);
}
setState(() {
// The actual state lives in the [MessageListView] model.
// This method was called because that just changed.
});
}
void _handleScrollMetrics(ScrollMetrics scrollMetrics) {
if (scrollMetrics.extentAfter == 0) {
_scrollToBottomVisibleValue.value = false;
} else {
_scrollToBottomVisibleValue.value = true;
}
if (scrollMetrics.extentBefore < kFetchMessagesBufferPixels) {
// TODO: This ends up firing a second time shortly after we fetch a batch.
// The result is that each time we decide to fetch a batch, we end up
// fetching two batches in quick succession. This is basically harmless
// but makes things a bit more complicated to reason about.
// The cause seems to be that this gets called again with maxScrollExtent
// still not yet updated to account for the newly-added messages.
model?.fetchOlder();
}
}
void _scrollChanged() {
_handleScrollMetrics(scrollController.position);
}
bool _handleScrollMetricsNotification(ScrollMetricsNotification notification) {
if (notification.depth > 0) {
// This notification came from some Viewport nested more deeply than the
// one for the message list itself (e.g., from a CodeBlock). Ignore it.
return true;
}
_handleScrollMetrics(notification.metrics);
return true;
}
@override
Widget build(BuildContext context) {
assert(model != null);
if (!model!.fetched) return const Center(child: CircularProgressIndicator());
// Pad the left and right insets, for small devices in landscape.
return SafeArea(
// Don't let this be the place we pad the bottom inset. When there's
// no compose box, we want to let the message-list content
// and the scroll-to-bottom button avoid it.
// TODO(#311) Remove as unnecessary if we do a bottom nav.
// The nav will pad the bottom inset, and an ancestor of this widget
// will have a `MediaQuery.removePadding` with `removeBottom: true`.
bottom: false,
// Horizontally, on wide screens, this Center grows the SafeArea
// to position its padding over the device insets and centers content.
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 760),
child: NotificationListener<ScrollMetricsNotification>(
onNotification: _handleScrollMetricsNotification,
child: Stack(
children: <Widget>[
_buildListView(context),
Positioned(
bottom: 0,
right: 0,
// TODO(#311) SafeArea shouldn't be needed if we have a
// bottom nav; that will pad the bottom inset. Remove it,
// and the mention of bottom-inset handling in
// MessageList's dartdoc.
child: SafeArea(
child: ScrollToBottomButton(
scrollController: scrollController,
visibleValue: _scrollToBottomVisibleValue))),
])))));
}
Widget _buildListView(BuildContext context) {
final length = model!.items.length;
const centerSliverKey = ValueKey('center sliver');
final zulipLocalizations = ZulipLocalizations.of(context);
Widget sliver = SliverStickyHeaderList(
headerPlacement: HeaderPlacement.scrollingStart,
delegate: SliverChildBuilderDelegate(
// To preserve state across rebuilds for individual [MessageItem]
// widgets as the size of [MessageListView.items] changes we need
// to match old widgets by their key to their new position in
// the list.
//
// The keys are of type [ValueKey] with a value of [Message.id]
// and here we use a O(log n) binary search method. This could
// be improved but for now it only triggers for materialized
// widgets. As a simple test, flinging through Combined feed in
// CZO on a Pixel 5, this only runs about 10 times per rebuild
// and the timing for each call is <100 microseconds.
//
// Non-message items (e.g., start and end markers) that do not
// have state that needs to be preserved have not been given keys
// and will not trigger this callback.
findChildIndexCallback: (Key key) {
final valueKey = key as ValueKey<int>;
final index = model!.findItemWithMessageId(valueKey.value);
if (index == -1) return null;
return length - 1 - (index - 3);
},
childCount: length + 3,
(context, i) {
// To reinforce that the end of the feed has been reached:
// https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/flutter.3A.20Mark-as-read/near/1680603
if (i == 0) return const SizedBox(height: 36);
if (i == 1) return MarkAsReadWidget(narrow: widget.narrow);
if (i == 2) return TypingStatusWidget(narrow: widget.narrow);
final data = model!.items[length - 1 - (i - 3)];
return _buildItem(zulipLocalizations, data, i);
}));
if (!ComposeBox.hasComposeBox(widget.narrow)) {
// TODO(#311) If we have a bottom nav, it will pad the bottom inset,
// and this can be removed; also remove mention in MessageList dartdoc
sliver = SliverSafeArea(sliver: sliver);
}
return CustomScrollView(
// TODO: Offer `ScrollViewKeyboardDismissBehavior.interactive` (or
// similar) if that is ever offered:
// https://github.com/flutter/flutter/issues/57609#issuecomment-1355340849
keyboardDismissBehavior: switch (Theme.of(context).platform) {
// This seems to offer the only built-in way to close the keyboard
// on iOS. It's not ideal; see TODO above.
TargetPlatform.iOS => ScrollViewKeyboardDismissBehavior.onDrag,
// The Android keyboard seems to have a built-in close button.
_ => ScrollViewKeyboardDismissBehavior.manual,
},
controller: scrollController,
semanticChildCount: length + 2,
anchor: 1.0,
center: centerSliverKey,
slivers: [
sliver,
// This is a trivial placeholder that occupies no space. Its purpose is
// to have the key that's passed to [ScrollView.center], and so to cause
// the above [SliverStickyHeaderList] to run from bottom to top.
const SliverToBoxAdapter(key: centerSliverKey),
]);
}
Widget _buildItem(ZulipLocalizations zulipLocalizations, MessageListItem data, int i) {
switch (data) {
case MessageListHistoryStartItem():
return Center(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text(zulipLocalizations.noEarlierMessages))); // TODO use an icon
case MessageListLoadingItem():
return const Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: CircularProgressIndicator())); // TODO perhaps a different indicator
case MessageListRecipientHeaderItem():
final header = RecipientHeader(message: data.message, narrow: widget.narrow);
return StickyHeaderItem(allowOverflow: true,
header: header, child: header);
case MessageListDateSeparatorItem():
final header = RecipientHeader(message: data.message, narrow: widget.narrow);
return StickyHeaderItem(allowOverflow: true,
header: header,
child: DateSeparator(message: data.message));
case MessageListMessageItem():
final header = RecipientHeader(message: data.message, narrow: widget.narrow);
return MessageItem(
key: ValueKey(data.message.id),
header: header,
trailingWhitespace: i == 1 ? 8 : 11,
item: data);
}
}
}
class ScrollToBottomButton extends StatelessWidget {
const ScrollToBottomButton({super.key, required this.scrollController, required this.visibleValue});
final ValueNotifier<bool> visibleValue;
final ScrollController scrollController;
Future<void> _navigateToBottom() {
final distance = scrollController.position.pixels;
final durationMsAtSpeedLimit = (1000 * distance / 8000).ceil();
final durationMs = max(300, durationMsAtSpeedLimit);
return scrollController.animateTo(
0,
duration: Duration(milliseconds: durationMs),
curve: Curves.ease);
}
@override
Widget build(BuildContext context) {
final zulipLocalizations = ZulipLocalizations.of(context);
return ValueListenableBuilder<bool>(
valueListenable: visibleValue,
builder: (BuildContext context, bool value, Widget? child) {
return (value && child != null) ? child : const SizedBox.shrink();
},
// TODO: fix hardcoded values for size and style here
child: IconButton(
tooltip: zulipLocalizations.scrollToBottomTooltip,
icon: const Icon(Icons.expand_circle_down_rounded),
iconSize: 40,
// Web has the same color in light and dark mode.
color: const HSLColor.fromAHSL(0.5, 240, 0.96, 0.68).toColor(),
onPressed: _navigateToBottom));
}
}
class TypingStatusWidget extends StatefulWidget {
const TypingStatusWidget({super.key, required this.narrow});
final Narrow narrow;
@override
State<StatefulWidget> createState() => _TypingStatusWidgetState();
}
class _TypingStatusWidgetState extends State<TypingStatusWidget> with PerAccountStoreAwareStateMixin<TypingStatusWidget> {
TypingStatus? model;
@override
void onNewStore() {
model?.removeListener(_modelChanged);
model = PerAccountStoreWidget.of(context).typingStatus
..addListener(_modelChanged);
}
@override
void dispose() {
model?.removeListener(_modelChanged);
super.dispose();
}
void _modelChanged() {
setState(() {
// The actual state lives in [model].
// This method was called because that just changed.
});
}
@override
Widget build(BuildContext context) {
final narrow = widget.narrow;
if (narrow is! SendableNarrow) return const SizedBox();
final store = PerAccountStoreWidget.of(context);
final localizations = ZulipLocalizations.of(context);
final typistIds = model!.typistIdsInNarrow(narrow);
if (typistIds.isEmpty) return const SizedBox();
final text = switch (typistIds.length) {
1 => localizations.onePersonTyping(
store.userDisplayName(typistIds.first)),
2 => localizations.twoPeopleTyping(
store.userDisplayName(typistIds.first),
store.userDisplayName(typistIds.last)),
_ => localizations.manyPeopleTyping,
};
return Padding(
padding: const EdgeInsetsDirectional.only(start: 16, top: 2),
child: Text(text,
style: const TextStyle(
// Web has the same color in light and dark mode.
color: HslColor(0, 0, 53),
fontStyle: FontStyle.italic)));
}
}
class MarkAsReadWidget extends StatefulWidget {
const MarkAsReadWidget({super.key, required this.narrow});
final Narrow narrow;
@override
State<MarkAsReadWidget> createState() => _MarkAsReadWidgetState();
}
class _MarkAsReadWidgetState extends State<MarkAsReadWidget> {
bool _loading = false;
void _handlePress(BuildContext context) async {
if (!context.mounted) return;
setState(() => _loading = true);
await ZulipAction.markNarrowAsRead(context, widget.narrow);
setState(() => _loading = false);
}
@override
Widget build(BuildContext context) {
final zulipLocalizations = ZulipLocalizations.of(context);
final store = PerAccountStoreWidget.of(context);
final unreadCount = store.unreads.countInNarrow(widget.narrow);
final areMessagesRead = unreadCount == 0;
final messageListTheme = MessageListTheme.of(context);
return IgnorePointer(
ignoring: areMessagesRead,
child: MarkAsReadAnimation(
loading: _loading,
hidden: areMessagesRead,
child: SizedBox(width: double.infinity,
// Design referenced from:
// https://www.figma.com/file/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?type=design&node-id=132-9684&mode=design&t=jJwHzloKJ0TMOG4M-0
child: Padding(
// vertical padding adjusted for tap target height (48px) of button
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10 - ((48 - 38) / 2)),
child: FilledButton.icon(
style: FilledButton.styleFrom(
splashFactory: NoSplash.splashFactory,
minimumSize: const Size.fromHeight(38),
textStyle:
// Restate [FilledButton]'s default, which inherits from
// [zulipTypography]…
Theme.of(context).textTheme.labelLarge!
// …then clobber some attributes to follow Figma:
.merge(TextStyle(
fontSize: 18,
letterSpacing: proportionalLetterSpacing(context,
kButtonTextLetterSpacingProportion, baseFontSize: 18),
height: (23 / 18))
.merge(weightVariableTextStyle(context, wght: 400))),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(7)),
).copyWith(
// Give the buttons a constant color regardless of whether their
// state is disabled, pressed, etc. We handle those states
// separately, via MarkAsReadAnimation.
foregroundColor: const WidgetStatePropertyAll(Colors.white),
iconColor: const WidgetStatePropertyAll(Colors.white),
backgroundColor: WidgetStatePropertyAll(messageListTheme.unreadMarker),
),
onPressed: _loading ? null : () => _handlePress(context),
icon: const Icon(Icons.playlist_add_check),
label: Text(zulipLocalizations.markAllAsReadLabel))))));
}
}
class MarkAsReadAnimation extends StatefulWidget {
final bool loading;
final bool hidden;
final Widget child;
const MarkAsReadAnimation({
super.key,
required this.loading,
required this.hidden,
required this.child
});
@override
State<MarkAsReadAnimation> createState() => _MarkAsReadAnimationState();
}
class _MarkAsReadAnimationState extends State<MarkAsReadAnimation> {
bool _isPressed = false;
void _setIsPressed(bool isPressed) {
setState(() {
_isPressed = isPressed;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapDown: (_) => _setIsPressed(true),
onTapUp: (_) => _setIsPressed(false),
onTapCancel: () => _setIsPressed(false),
child: AnimatedScale(
scale: _isPressed ? 0.95 : 1,
duration: const Duration(milliseconds: 100),
curve: Curves.easeOut,
child: AnimatedOpacity(
opacity: widget.hidden ? 0 : widget.loading ? 0.5 : 1,
duration: const Duration(milliseconds: 500),
curve: Curves.easeOut,
child: widget.child)));
}
}
class RecipientHeader extends StatelessWidget {
const RecipientHeader({super.key, required this.message, required this.narrow});
final Message message;
final Narrow narrow;
@override
Widget build(BuildContext context) {
final message = this.message;
return switch (message) {
StreamMessage() => StreamMessageRecipientHeader(message: message, narrow: narrow),
DmMessage() => DmRecipientHeader(message: message, narrow: narrow),
};
}
}
class DateSeparator extends StatelessWidget {
const DateSeparator({super.key, required this.message});
final Message message;
@override
Widget build(BuildContext context) {
// This makes the small-caps text vertically centered,
// to align with the vertically centered divider lines.
const textBottomPadding = 2.0;
final messageListTheme = MessageListTheme.of(context);
final line = BorderSide(width: 0, color: messageListTheme.dateSeparator);
// TODO(#681) use different color for DM messages
return ColoredBox(color: messageListTheme.streamMessageBgDefault,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 2),
child: Row(children: [
Expanded(
child: SizedBox(height: 0,
child: DecoratedBox(
decoration: BoxDecoration(
border: Border(
bottom: line))))),
Padding(padding: const EdgeInsets.fromLTRB(2, 0, 2, textBottomPadding),
child: DateText(
fontSize: 16,
height: (16 / 16),
timestamp: message.timestamp)),
SizedBox(height: 0, width: 12,
child: DecoratedBox(
decoration: BoxDecoration(
border: Border(
bottom: line)))),
])),
);
}
}
class MessageItem extends StatelessWidget {
const MessageItem({
super.key,
required this.item,
required this.header,
this.trailingWhitespace,
});
final MessageListMessageItem item;
final Widget header;
final double? trailingWhitespace;
@override
Widget build(BuildContext context) {
final message = item.message;
final messageListTheme = MessageListTheme.of(context);
return StickyHeaderItem(
allowOverflow: !item.isLastInBlock,
header: header,
child: _UnreadMarker(
isRead: message.flags.contains(MessageFlag.read),
child: ColoredBox(
color: messageListTheme.streamMessageBgDefault,
child: Column(children: [
MessageWithPossibleSender(item: item),
if (trailingWhitespace != null && item.isLastInBlock) SizedBox(height: trailingWhitespace!),
]))));
}
}
/// Widget responsible for showing the read status of a message.
class _UnreadMarker extends StatelessWidget {
const _UnreadMarker({required this.isRead, required this.child});
final bool isRead;
final Widget child;