forked from zulip/zulip-flutter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompose_box.dart
1599 lines (1400 loc) · 54.1 KB
/
compose_box.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:math';
import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mime/mime.dart';
import '../api/exception.dart';
import '../api/model/model.dart';
import '../api/route/messages.dart';
import '../generated/l10n/zulip_localizations.dart';
import '../model/binding.dart';
import '../model/compose.dart';
import '../model/narrow.dart';
import '../model/store.dart';
import 'autocomplete.dart';
import 'color.dart';
import 'dialog.dart';
import 'icons.dart';
import 'inset_shadow.dart';
import 'store.dart';
import 'text.dart';
import 'theme.dart';
/// Compose-box styles that differ between light and dark theme.
///
/// These styles will animate on theme changes (with help from [lerp]).
class ComposeBoxTheme extends ThemeExtension<ComposeBoxTheme> {
static final light = ComposeBoxTheme._(
boxShadow: null,
);
static final dark = ComposeBoxTheme._(
boxShadow: [BoxShadow(
color: DesignVariables.dark.bgTopBar,
offset: const Offset(0, -4),
blurRadius: 16,
spreadRadius: 0,
)],
);
ComposeBoxTheme._({
required this.boxShadow,
});
/// The [ComposeBoxTheme] from the context's active theme.
///
/// The [ThemeData] must include [ComposeBoxTheme] in [ThemeData.extensions].
static ComposeBoxTheme of(BuildContext context) {
final theme = Theme.of(context);
final extension = theme.extension<ComposeBoxTheme>();
assert(extension != null);
return extension!;
}
final List<BoxShadow>? boxShadow;
@override
ComposeBoxTheme copyWith({
List<BoxShadow>? boxShadow,
}) {
return ComposeBoxTheme._(
boxShadow: boxShadow ?? this.boxShadow,
);
}
@override
ComposeBoxTheme lerp(ComposeBoxTheme other, double t) {
if (identical(this, other)) {
return this;
}
return ComposeBoxTheme._(
boxShadow: BoxShadow.lerpList(boxShadow, other.boxShadow, t)!,
);
}
}
const double _composeButtonSize = 44;
/// A [TextEditingController] for use in the compose box.
///
/// Subclasses must ensure that [_update] is called in all exposed constructors.
abstract class ComposeController<ErrorT> extends TextEditingController {
int get maxLengthUnicodeCodePoints;
String get textNormalized => _textNormalized;
late String _textNormalized;
String _computeTextNormalized();
/// Length of [textNormalized] in Unicode code points
/// if it might exceed [maxLengthUnicodeCodePoints], else null.
///
/// Use this instead of [String.length]
/// to enforce a max length expressed in code points.
/// [String.length] is conservative and may cut the user off too short.
///
/// Counting code points ([String.runes])
/// is more expensive than getting the number of UTF-16 code units
/// ([String.length]), so we avoid it when the result definitely won't exceed
/// [maxLengthUnicodeCodePoints].
late int? _lengthUnicodeCodePointsIfLong;
@visibleForTesting
int? get debugLengthUnicodeCodePointsIfLong => _lengthUnicodeCodePointsIfLong;
int? _computeLengthUnicodeCodePointsIfLong() =>
_textNormalized.length > maxLengthUnicodeCodePoints
? _textNormalized.runes.length
: null;
List<ErrorT> get validationErrors => _validationErrors;
late List<ErrorT> _validationErrors;
List<ErrorT> _computeValidationErrors();
ValueNotifier<bool> hasValidationErrors = ValueNotifier(false);
void _update() {
_textNormalized = _computeTextNormalized();
// uses _textNormalized, so comes after _computeTextNormalized()
_lengthUnicodeCodePointsIfLong = _computeLengthUnicodeCodePointsIfLong();
_validationErrors = _computeValidationErrors();
hasValidationErrors.value = _validationErrors.isNotEmpty;
}
@override
void notifyListeners() {
_update();
super.notifyListeners();
}
}
enum TopicValidationError {
mandatoryButEmpty,
tooLong;
String message(ZulipLocalizations zulipLocalizations) {
switch (this) {
case tooLong:
return zulipLocalizations.topicValidationErrorTooLong;
case mandatoryButEmpty:
return zulipLocalizations.topicValidationErrorMandatoryButEmpty;
}
}
}
class ComposeTopicController extends ComposeController<TopicValidationError> {
ComposeTopicController({required this.store}) {
_update();
}
PerAccountStore store;
// TODO(#668): listen to [PerAccountStore] once we subscribe to this value
bool get mandatory => store.realmMandatoryTopics;
// TODO(#307) use `max_topic_length` instead of hardcoded limit
@override final maxLengthUnicodeCodePoints = kMaxTopicLengthCodePoints;
@override
String _computeTextNormalized() {
String trimmed = text.trim();
// TODO(server-10): simplify
if (store.zulipFeatureLevel < 334) {
return trimmed.isEmpty ? kNoTopicTopic : trimmed;
}
return trimmed;
}
/// Whether [textNormalized] would fail a mandatory-topics check
/// (see [mandatory]).
///
/// The term "Vacuous" draws distinction from [String.isEmpty], in the sense
/// that certain strings are not empty but also indicate the absence of a topic.
///
/// See also: https://zulip.com/api/send-message#parameter-topic
bool get isTopicVacuous {
if (textNormalized.isEmpty) return true;
if (textNormalized == kNoTopicTopic) return true;
// TODO(server-10): simplify
if (store.zulipFeatureLevel >= 334) {
return textNormalized == store.realmEmptyTopicDisplayName;
}
return false;
}
@override
List<TopicValidationError> _computeValidationErrors() {
return [
if (mandatory && isTopicVacuous)
TopicValidationError.mandatoryButEmpty,
if (
_lengthUnicodeCodePointsIfLong != null
&& _lengthUnicodeCodePointsIfLong! > maxLengthUnicodeCodePoints
)
TopicValidationError.tooLong,
];
}
void setTopic(TopicName newTopic) {
// ignore: dead_null_aware_expression // null topic names soon to be enabled
value = TextEditingValue(text: newTopic.displayName ?? '');
}
}
enum ContentValidationError {
empty,
tooLong,
quoteAndReplyInProgress,
uploadInProgress;
String message(ZulipLocalizations zulipLocalizations) {
switch (this) {
case ContentValidationError.tooLong:
return zulipLocalizations.contentValidationErrorTooLong;
case ContentValidationError.empty:
return zulipLocalizations.contentValidationErrorEmpty;
case ContentValidationError.quoteAndReplyInProgress:
return zulipLocalizations.contentValidationErrorQuoteAndReplyInProgress;
case ContentValidationError.uploadInProgress:
return zulipLocalizations.contentValidationErrorUploadInProgress;
}
}
}
class ComposeContentController extends ComposeController<ContentValidationError> {
ComposeContentController() {
_update();
}
// TODO(#1237) use `max_message_length` instead of hardcoded limit
@override final maxLengthUnicodeCodePoints = kMaxMessageLengthCodePoints;
int _nextQuoteAndReplyTag = 0;
int _nextUploadTag = 0;
final Map<int, ({int messageId, String placeholder})> _quoteAndReplies = {};
final Map<int, ({String filename, String placeholder})> _uploads = {};
/// A probably-reasonable place to insert Markdown, such as for a file upload.
///
/// Gives the cursor position,
/// or if text is selected, the end of the selection range.
///
/// If there isn't a cursor position or a text selection
/// (e.g., when the input has never been focused),
/// gives the end of the whole text.
///
/// Expressed as a collapsed `TextRange` at the index.
TextRange insertionIndex() {
final TextRange selection = value.selection;
final String text = value.text;
return selection.isValid
? (selection.isCollapsed
? selection
: TextRange.collapsed(selection.end))
: TextRange.collapsed(text.length);
}
/// Inserts [newText] in [text], setting off with an empty line before and after.
///
/// Assumes [newText] is not empty and consists entirely of complete lines
/// (each line ends with a newline).
///
/// Inserts at [insertionIndex]. If that's zero, no empty line is added before.
///
/// If there is already an empty line before or after, does not add another.
void insertPadded(String newText) {
assert(newText.isNotEmpty);
assert(newText.endsWith('\n'));
final i = insertionIndex();
final textBefore = text.substring(0, i.start);
final String paddingBefore;
if (textBefore.isEmpty || textBefore == '\n' || textBefore.endsWith('\n\n')) {
paddingBefore = ''; // At start of input, or just after an empty line.
} else if (textBefore.endsWith('\n')) {
paddingBefore = '\n'; // After a complete but non-empty line.
} else {
paddingBefore = '\n\n'; // After an incomplete line.
}
if (text.substring(i.start).startsWith('\n')) {
final partial = value.replaced(i, paddingBefore + newText);
value = partial.copyWith(selection: TextSelection.collapsed(offset: partial.selection.start + 1));
} else {
value = value.replaced(i, '$paddingBefore$newText\n');
}
}
/// Tells the controller that a quote-and-reply has started.
///
/// Returns an int "tag" that should be passed to registerQuoteAndReplyEnd on
/// success or failure
int registerQuoteAndReplyStart(
ZulipLocalizations zulipLocalizations,
PerAccountStore store, {
required Message message,
}) {
final tag = _nextQuoteAndReplyTag;
_nextQuoteAndReplyTag += 1;
final placeholder = quoteAndReplyPlaceholder(
zulipLocalizations, store, message: message);
_quoteAndReplies[tag] = (messageId: message.id, placeholder: placeholder);
notifyListeners(); // _quoteAndReplies change could affect validationErrors
insertPadded(placeholder);
return tag;
}
/// Tells the controller that a quote-and-reply has ended, with success or error.
///
/// To indicate success, pass [rawContent].
/// If that is null, failure is assumed.
void registerQuoteAndReplyEnd(PerAccountStore store, int tag, {
required Message message,
String? rawContent,
}) {
final val = _quoteAndReplies[tag];
assert(val != null, 'registerQuoteAndReplyEnd called twice for same tag');
final int startIndex = text.indexOf(val!.placeholder);
final replacementText = rawContent == null
? ''
: quoteAndReply(store, message: message, rawContent: rawContent);
if (startIndex >= 0) {
value = value.replaced(
TextRange(start: startIndex, end: startIndex + val.placeholder.length),
replacementText,
);
} else if (replacementText != '') { // insertPadded requires non-empty string
insertPadded(replacementText);
}
_quoteAndReplies.remove(tag);
notifyListeners(); // _quoteAndReplies change could affect validationErrors
}
/// Tells the controller that a file upload has started.
///
/// Returns an int "tag" that should be passed to registerUploadEnd on the
/// upload's success or failure.
int registerUploadStart(String filename, ZulipLocalizations zulipLocalizations) {
final tag = _nextUploadTag;
_nextUploadTag += 1;
final linkText = zulipLocalizations.composeBoxUploadingFilename(filename);
final placeholder = inlineLink(linkText, null);
_uploads[tag] = (filename: filename, placeholder: placeholder);
notifyListeners(); // _uploads change could affect validationErrors
value = value.replaced(insertionIndex(), '$placeholder\n\n');
return tag;
}
/// Tells the controller that a file upload has ended, with success or error.
///
/// To indicate success, pass the URL to be used for the Markdown link.
/// If `url` is null, failure is assumed.
void registerUploadEnd(int tag, Uri? url) {
final val = _uploads[tag];
assert(val != null, 'registerUploadEnd called twice for same tag');
final (:filename, :placeholder) = val!;
final int startIndex = text.indexOf(placeholder);
final replacementRange = startIndex >= 0
? TextRange(start: startIndex, end: startIndex + placeholder.length)
: insertionIndex();
value = value.replaced(
replacementRange,
url == null ? '' : inlineLink(filename, url));
_uploads.remove(tag);
notifyListeners(); // _uploads change could affect validationErrors
}
@override
String _computeTextNormalized() {
return text.trim();
}
@override
List<ContentValidationError> _computeValidationErrors() {
return [
if (textNormalized.isEmpty)
ContentValidationError.empty,
if (
_lengthUnicodeCodePointsIfLong != null
&& _lengthUnicodeCodePointsIfLong! > maxLengthUnicodeCodePoints
)
ContentValidationError.tooLong,
if (_quoteAndReplies.isNotEmpty)
ContentValidationError.quoteAndReplyInProgress,
if (_uploads.isNotEmpty)
ContentValidationError.uploadInProgress,
];
}
}
class _TypingNotifier extends StatefulWidget {
const _TypingNotifier({
required this.destination,
required this.controller,
required this.child,
});
final SendableNarrow destination;
final ComposeBoxController controller;
final Widget child;
@override
State<_TypingNotifier> createState() => _TypingNotifierState();
}
class _TypingNotifierState extends State<_TypingNotifier> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
widget.controller.content.addListener(_contentChanged);
widget.controller.contentFocusNode.addListener(_focusChanged);
WidgetsBinding.instance.addObserver(this);
}
@override
void didUpdateWidget(covariant _TypingNotifier oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller != oldWidget.controller) {
oldWidget.controller.content.removeListener(_contentChanged);
widget.controller.content.addListener(_contentChanged);
oldWidget.controller.contentFocusNode.removeListener(_focusChanged);
widget.controller.contentFocusNode.addListener(_focusChanged);
}
}
@override
void dispose() {
widget.controller.content.removeListener(_contentChanged);
widget.controller.contentFocusNode.removeListener(_focusChanged);
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
void _contentChanged() {
final store = PerAccountStoreWidget.of(context);
(widget.controller.content.text.isEmpty)
? store.typingNotifier.stoppedComposing()
: store.typingNotifier.keystroke(widget.destination);
}
void _focusChanged() {
if (widget.controller.contentFocusNode.hasFocus) {
// Content input getting focus doesn't necessarily mean that
// the user started typing, so do nothing.
return;
}
final store = PerAccountStoreWidget.of(context);
store.typingNotifier.stoppedComposing();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.hidden:
case AppLifecycleState.paused:
case AppLifecycleState.detached:
// Transition to either [hidden] or [paused] signals that
// > [the] application is not currently visible to the user, and not
// > responding to user input.
//
// When transitioning to [detached], the compose box can't exist:
// > The application defaults to this state before it initializes, and
// > can be in this state (applicable on Android, iOS, and web) after
// > all views have been detached.
//
// For all these states, we can conclude that the user is not
// composing a message.
final store = PerAccountStoreWidget.of(context);
store.typingNotifier.stoppedComposing();
case AppLifecycleState.inactive:
// > At least one view of the application is visible, but none have
// > input focus. The application is otherwise running normally.
// For example, we expect this state when the user is selecting a file
// to upload.
case AppLifecycleState.resumed:
}
}
@override
Widget build(BuildContext context) => widget.child;
}
class _ContentInput extends StatelessWidget {
const _ContentInput({
required this.narrow,
required this.controller,
required this.hintText,
});
final Narrow narrow;
final ComposeBoxController controller;
final String hintText;
static double maxHeight(BuildContext context) {
final clampingTextScaler = MediaQuery.textScalerOf(context)
.clamp(maxScaleFactor: 1.5);
final scaledLineHeight = clampingTextScaler.scale(_fontSize) * _lineHeightRatio;
// Reserve space to fully show the first 7th lines and just partially
// clip the 8th line, where the height matches the spec at
// https://www.figma.com/design/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?node-id=3960-5147&node-type=text&m=dev
// > Maximum size of the compose box is suggested to be 178px. Which
// > has 7 fully visible lines of text
//
// The partial line hints that the content input is scrollable.
//
// Using the ambient TextScale means this works for different values of the
// system text-size setting. We clamp to a max scale factor to limit
// how tall the content input can get; that's to save room for the message
// list. The user can still scroll the input to see everything.
return _verticalPadding + 7.727 * scaledLineHeight;
}
static const _verticalPadding = 8.0;
static const _fontSize = 17.0;
static const _lineHeight = 22.0;
static const _lineHeightRatio = _lineHeight / _fontSize;
@override
Widget build(BuildContext context) {
final designVariables = DesignVariables.of(context);
return ComposeAutocomplete(
narrow: narrow,
controller: controller.content,
focusNode: controller.contentFocusNode,
fieldViewBuilder: (context) => ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxHeight(context)),
// This [ClipRect] replaces the [TextField] clipping we disable below.
child: ClipRect(
child: InsetShadowBox(
top: _verticalPadding, bottom: _verticalPadding,
color: designVariables.composeBoxBg,
child: TextField(
controller: controller.content,
focusNode: controller.contentFocusNode,
// Let the content show through the `contentPadding` so that
// our [InsetShadowBox] can fade it smoothly there.
clipBehavior: Clip.none,
style: TextStyle(
fontSize: _fontSize,
height: _lineHeightRatio,
color: designVariables.textInput),
// From the spec at
// https://www.figma.com/design/1JTNtYo9memgW7vV6d0ygq/Zulip-Mobile?node-id=3960-5147&node-type=text&m=dev
// > Compose box has the height to fit 2 lines. This is [done] to
// > have a bigger hit area for the user to start the input. […]
minLines: 2,
maxLines: null,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
// This padding ensures that the user can always scroll long
// content entirely out of the top or bottom shadow if desired.
// With this and the `minLines: 2` above, an empty content input
// gets 60px vertical distance (with no text-size scaling)
// between the top of the top shadow and the bottom of the
// bottom shadow. That's a bit more than the 54px given in the
// Figma, and we can revisit if needed, but it's tricky to get
// that 54px distance while also making the scrolling work like
// this and offering two lines of touchable area.
contentPadding: const EdgeInsets.symmetric(vertical: _verticalPadding),
hintText: hintText,
hintStyle: TextStyle(
color: designVariables.textInput.withFadedAlpha(0.5))))))));
}
}
/// The content input for _StreamComposeBox.
class _StreamContentInput extends StatefulWidget {
const _StreamContentInput({required this.narrow, required this.controller});
final ChannelNarrow narrow;
final StreamComposeBoxController controller;
@override
State<_StreamContentInput> createState() => _StreamContentInputState();
}
class _StreamContentInputState extends State<_StreamContentInput> {
void _topicChanged() {
setState(() {
// The relevant state lives on widget.controller.topic itself.
});
}
void _contentFocusChanged() {
setState(() {
// The relevant state lives on widget.controller.contentFocusNode itself.
});
}
@override
void initState() {
super.initState();
widget.controller.topic.addListener(_topicChanged);
widget.controller.contentFocusNode.addListener(_contentFocusChanged);
}
@override
void didUpdateWidget(covariant _StreamContentInput oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller.topic != oldWidget.controller.topic) {
oldWidget.controller.topic.removeListener(_topicChanged);
widget.controller.topic.addListener(_topicChanged);
}
if (widget.controller.contentFocusNode != oldWidget.controller.contentFocusNode) {
oldWidget.controller.contentFocusNode.removeListener(_contentFocusChanged);
widget.controller.contentFocusNode.addListener(_contentFocusChanged);
}
}
@override
void dispose() {
widget.controller.topic.removeListener(_topicChanged);
widget.controller.contentFocusNode.removeListener(_contentFocusChanged);
super.dispose();
}
/// The topic name to show in the hint text, or null to show no topic.
TopicName? _hintTopic() {
if (widget.controller.topic.isTopicVacuous) {
if (widget.controller.topic.mandatory) {
// The chosen topic can't be sent to, so don't show it.
return null;
}
if (!widget.controller.contentFocusNode.hasFocus) {
// Do not fall back to a vacuous topic unless the user explicitly chooses
// to do so (by skipping topic input and moving focus to content input),
// so that the user is not encouraged to use vacuous topic when they
// have not interacted with the inputs at all.
return null;
}
}
return TopicName(widget.controller.topic.textNormalized);
}
@override
Widget build(BuildContext context) {
final store = PerAccountStoreWidget.of(context);
final zulipLocalizations = ZulipLocalizations.of(context);
final streamName = store.streams[widget.narrow.streamId]?.name
?? zulipLocalizations.unknownChannelName;
final hintTopic = _hintTopic();
final hintDestination = hintTopic == null
// No i18n of this use of "#" and ">" string; those are part of how
// Zulip expresses channels and topics, not any normal English punctuation,
// so don't make sense to translate. See:
// https://github.com/zulip/zulip-flutter/pull/1148#discussion_r1941990585
? '#$streamName'
// ignore: dead_null_aware_expression // null topic names soon to be enabled
: '#$streamName > ${hintTopic.displayName ?? store.realmEmptyTopicDisplayName}';
return _TypingNotifier(
destination: TopicNarrow(widget.narrow.streamId,
TopicName(widget.controller.topic.textNormalized)),
controller: widget.controller,
child: _ContentInput(
narrow: widget.narrow,
controller: widget.controller,
hintText: zulipLocalizations.composeBoxChannelContentHint(hintDestination)));
}
}
class _TopicInput extends StatelessWidget {
const _TopicInput({required this.streamId, required this.controller});
final int streamId;
final StreamComposeBoxController controller;
@override
Widget build(BuildContext context) {
final zulipLocalizations = ZulipLocalizations.of(context);
final designVariables = DesignVariables.of(context);
TextStyle topicTextStyle = TextStyle(
fontSize: 20,
height: 22 / 20,
color: designVariables.textInput.withFadedAlpha(0.9),
).merge(weightVariableTextStyle(context, wght: 600));
return TopicAutocomplete(
streamId: streamId,
controller: controller.topic,
focusNode: controller.topicFocusNode,
contentFocusNode: controller.contentFocusNode,
fieldViewBuilder: (context) => Container(
padding: const EdgeInsets.only(top: 10, bottom: 9),
decoration: BoxDecoration(border: Border(bottom: BorderSide(
width: 1,
color: designVariables.foreground.withFadedAlpha(0.2)))),
child: TextField(
controller: controller.topic,
focusNode: controller.topicFocusNode,
textInputAction: TextInputAction.next,
style: topicTextStyle,
decoration: InputDecoration(
hintText: zulipLocalizations.composeBoxTopicHintText,
hintStyle: topicTextStyle.copyWith(
color: designVariables.textInput.withFadedAlpha(0.5))))));
}
}
class _FixedDestinationContentInput extends StatelessWidget {
const _FixedDestinationContentInput({
required this.narrow,
required this.controller,
});
final SendableNarrow narrow;
final FixedDestinationComposeBoxController controller;
String _hintText(BuildContext context) {
final zulipLocalizations = ZulipLocalizations.of(context);
switch (narrow) {
case TopicNarrow(:final streamId, :final topic):
final store = PerAccountStoreWidget.of(context);
final streamName = store.streams[streamId]?.name
?? zulipLocalizations.unknownChannelName;
return zulipLocalizations.composeBoxChannelContentHint(
// No i18n of this use of "#" and ">" string; those are part of how
// Zulip expresses channels and topics, not any normal English punctuation,
// so don't make sense to translate. See:
// https://github.com/zulip/zulip-flutter/pull/1148#discussion_r1941990585
// ignore: dead_null_aware_expression // null topic names soon to be enabled
'#$streamName > ${topic.displayName ?? store.realmEmptyTopicDisplayName}');
case DmNarrow(otherRecipientIds: []): // The self-1:1 thread.
return zulipLocalizations.composeBoxSelfDmContentHint;
case DmNarrow(otherRecipientIds: [final otherUserId]):
final store = PerAccountStoreWidget.of(context);
final fullName = store.getUser(otherUserId)?.fullName;
if (fullName == null) return zulipLocalizations.composeBoxGenericContentHint;
return zulipLocalizations.composeBoxDmContentHint(fullName);
case DmNarrow(): // A group DM thread.
return zulipLocalizations.composeBoxGroupDmContentHint;
}
}
@override
Widget build(BuildContext context) {
return _TypingNotifier(
destination: narrow,
controller: controller,
child: _ContentInput(
narrow: narrow,
controller: controller,
hintText: _hintText(context)));
}
}
/// Data on a file to be uploaded, from any source.
///
/// A convenience class to represent data from the generic file picker,
/// the media library, and the camera, in a single form.
class _File {
_File({
required this.content,
required this.length,
required this.filename,
required this.mimeType,
});
final Stream<List<int>> content;
final int length;
final String filename;
final String? mimeType;
}
Future<void> _uploadFiles({
required BuildContext context,
required ComposeContentController contentController,
required FocusNode contentFocusNode,
required Iterable<_File> files,
}) async {
assert(context.mounted);
final store = PerAccountStoreWidget.of(context);
final zulipLocalizations = ZulipLocalizations.of(context);
final List<_File> tooLargeFiles = [];
final List<_File> rightSizeFiles = [];
for (final file in files) {
if ((file.length / (1 << 20)) > store.maxFileUploadSizeMib) {
tooLargeFiles.add(file);
} else {
rightSizeFiles.add(file);
}
}
if (tooLargeFiles.isNotEmpty) {
final listMessage = tooLargeFiles
.map((file) => zulipLocalizations.filenameAndSizeInMiB(
file.filename, (file.length / (1 << 20)).toStringAsFixed(1)))
.join('\n');
showErrorDialog(
context: context,
title: zulipLocalizations.errorFilesTooLargeTitle(tooLargeFiles.length),
message: zulipLocalizations.errorFilesTooLarge(
tooLargeFiles.length,
store.maxFileUploadSizeMib,
listMessage));
}
final List<(int, _File)> uploadsInProgress = [];
for (final file in rightSizeFiles) {
final tag = contentController.registerUploadStart(file.filename,
zulipLocalizations);
uploadsInProgress.add((tag, file));
}
if (!contentFocusNode.hasFocus) {
contentFocusNode.requestFocus();
}
for (final (tag, file) in uploadsInProgress) {
final _File(:content, :length, :filename, :mimeType) = file;
Uri? url;
try {
final result = await uploadFile(store.connection,
content: content,
length: length,
filename: filename,
contentType: mimeType,
);
url = Uri.parse(result.uri);
} catch (e) {
if (!context.mounted) return;
// TODO(#741): Specifically handle `413 Payload Too Large`
// TODO(#741): On API errors, quote `msg` from server, with "The server said:"
showErrorDialog(context: context,
title: zulipLocalizations.errorFailedToUploadFileTitle(filename),
message: e.toString());
} finally {
contentController.registerUploadEnd(tag, url);
}
}
}
abstract class _AttachUploadsButton extends StatelessWidget {
const _AttachUploadsButton({required this.controller});
final ComposeBoxController controller;
IconData get icon;
String tooltip(ZulipLocalizations zulipLocalizations);
/// Request files from the user, in the way specific to this upload type.
///
/// Subclasses should manage the interaction completely, e.g., by catching and
/// handling any permissions-related exceptions.
///
/// To signal exiting the interaction with no files chosen,
/// return an empty [Iterable] after showing user feedback as appropriate.
Future<Iterable<_File>> getFiles(BuildContext context);
void _handlePress(BuildContext context) async {
final files = await getFiles(context);
if (files.isEmpty) {
return; // Nothing to do (getFiles handles user feedback)
}
// https://github.com/dart-lang/linter/issues/4007
// ignore: use_build_context_synchronously
if (!context.mounted) {
return;
}
await _uploadFiles(
context: context,
contentController: controller.content,
contentFocusNode: controller.contentFocusNode,
files: files);
}
@override
Widget build(BuildContext context) {
final designVariables = DesignVariables.of(context);
final zulipLocalizations = ZulipLocalizations.of(context);
return SizedBox(
width: _composeButtonSize,
child: IconButton(
icon: Icon(icon, color: designVariables.foreground.withFadedAlpha(0.5)),
tooltip: tooltip(zulipLocalizations),
onPressed: () => _handlePress(context)));
}
}
Future<Iterable<_File>> _getFilePickerFiles(BuildContext context, FileType type) async {
FilePickerResult? result;
try {
result = await ZulipBinding.instance
.pickFiles(allowMultiple: true, withReadStream: true, type: type);
} catch (e) {
if (!context.mounted) return [];
final zulipLocalizations = ZulipLocalizations.of(context);
if (e is PlatformException && e.code == 'read_external_storage_denied') {
// Observed on Android. If Android's error message tells us whether the
// user has checked "Don't ask again", it seems the library doesn't pass
// that on to us. So just always prompt to check permissions in settings.
// If the user hasn't checked "Don't ask again", they can always dismiss
// our prompt and retry, and the permissions request will reappear,
// letting them grant permissions and complete the upload.
showSuggestedActionDialog(context: context,
title: zulipLocalizations.permissionsNeededTitle,
message: zulipLocalizations.permissionsDeniedReadExternalStorage,
actionButtonText: zulipLocalizations.permissionsNeededOpenSettings,
onActionButtonPress: () {
AppSettings.openAppSettings();
});
} else {
showErrorDialog(context: context,
title: zulipLocalizations.errorDialogTitle,
message: e.toString());
}
return [];
}
if (result == null) {
return []; // User cancelled; do nothing
}
return result.files.map((f) {
assert(f.readStream != null); // We passed `withReadStream: true` to pickFiles.
final mimeType = lookupMimeType(
// Seems like the path shouldn't be required; we still want to look for
// matches on `headerBytes`. Thankfully we can still do that, by calling
// lookupMimeType with the empty string as the path. That's a value that
// doesn't map to any particular type, so the path will be effectively
// ignored, as desired. Upstream comment:
// https://github.com/dart-lang/mime/issues/11#issuecomment-2246824452
f.path ?? '',
headerBytes: f.bytes?.take(defaultMagicNumbersMaxLength).toList(),
);
return _File(
content: f.readStream!,
length: f.size,
filename: f.name,
mimeType: mimeType,
);
});
}
class _AttachFileButton extends _AttachUploadsButton {
const _AttachFileButton({required super.controller});
@override
IconData get icon => ZulipIcons.attach_file;
@override
String tooltip(ZulipLocalizations zulipLocalizations) =>
zulipLocalizations.composeBoxAttachFilesTooltip;
@override
Future<Iterable<_File>> getFiles(BuildContext context) async {
return _getFilePickerFiles(context, FileType.any);
}
}
class _AttachMediaButton extends _AttachUploadsButton {
const _AttachMediaButton({required super.controller});
@override
IconData get icon => ZulipIcons.image;
@override
String tooltip(ZulipLocalizations zulipLocalizations) =>
zulipLocalizations.composeBoxAttachMediaTooltip;
@override
Future<Iterable<_File>> getFiles(BuildContext context) async {
// TODO(#114): This doesn't give quite the right UI on Android.
return _getFilePickerFiles(context, FileType.media);
}
}
class _AttachFromCameraButton extends _AttachUploadsButton {
const _AttachFromCameraButton({required super.controller});
@override
IconData get icon => ZulipIcons.camera;
@override
String tooltip(ZulipLocalizations zulipLocalizations) =>
zulipLocalizations.composeBoxAttachFromCameraTooltip;
@override
Future<Iterable<_File>> getFiles(BuildContext context) async {
final zulipLocalizations = ZulipLocalizations.of(context);
final XFile? result;
try {
// Ideally we'd open a platform interface that lets you choose between
// taking a photo and a video. `image_picker` doesn't yet have that
// option: https://github.com/flutter/flutter/issues/89159
// so just stick with images for now. We could add another button for