Merge pull request #620 from GetStream/feat/limit-attachment-selection

feat(ui): add possibility to limit attachments in `MessageInput`
This commit is contained in:
Salvatore Giordano
2021-08-24 10:51:12 +02:00
committed by GitHub
14 changed files with 327 additions and 272 deletions
+9 -8
View File
@@ -6,14 +6,15 @@
Added `StreamChatThemeData.placeholderUserImage` for building a widget when the `UserAvatar` image Added `StreamChatThemeData.placeholderUserImage` for building a widget when the `UserAvatar` image
is loading is loading
- Added a `backgroundColor` property to the following widgets: - Added a `backgroundColor` property to the following widgets:
- `ChannelHeader` - `ChannelHeader`
- `ChannelListHeader` - `ChannelListHeader`
- `GalleryHeader` - `GalleryHeader`
- `GalleryFooter` - `GalleryFooter`
- `ThreadHeader` - `ThreadHeader`
- Added `MessageInput.attachmentLimit` in order to limit the no. of attachments that can be sent with a single message.
- Added `MessageInput.attachmentButtonBuilder` and `MessageInput.commandButtonBuilder` for more - Added `MessageInput.onAttachmentLimitExceed` callback which will be called when the `attachmentLimit` is exceeded.
customizations. This will override the default error alert behaviour.
- Added `MessageInput.attachmentButtonBuilder` and `MessageInput.commandButtonBuilder` for more customizations.
```dart ```dart
typedef ActionButtonBuilder = Widget Function( typedef ActionButtonBuilder = Widget Function(
@@ -106,7 +106,7 @@ class ChannelPage extends StatelessWidget {
Expanded( Expanded(
child: MessageListView(), child: MessageListView(),
), ),
MessageInput(), MessageInput(attachmentLimit: 3),
], ],
), ),
); );
@@ -308,6 +308,10 @@ abstract class Translations {
/// The label for "Reply to message" /// The label for "Reply to message"
String get replyToMessageLabel; String get replyToMessageLabel;
/// Label for "Attachment limit exceeded:
/// it's not possible to add more than $limit attachments"
String attachmentLimitExceedError(int limit);
} }
/// Default implementation of Translation strings for the stream chat widgets /// Default implementation of Translation strings for the stream chat widgets
@@ -673,4 +677,8 @@ class DefaultTranslations implements Translations {
@override @override
String get slowModeOnLabel => 'Slow mode ON'; String get slowModeOnLabel => 'Slow mode ON';
@override
String attachmentLimitExceedError(int limit) => """
Attachment limit exceeded: it's not possible to add more than $limit attachments""";
} }
@@ -37,6 +37,16 @@ typedef ErrorListener = void Function(
StackTrace? stackTrace, StackTrace? stackTrace,
); );
/// A callback that can be passed to [MessageInput.onAttachmentLimitExceed].
///
/// This callback should not throw.
///
/// It exists merely for showing custom error, and should not be used otherwise.
typedef AttachmentLimitExceedListener = void Function(
int limit,
String error,
);
/// Builder for attachment thumbnails /// Builder for attachment thumbnails
typedef AttachmentThumbnailBuilder = Widget Function( typedef AttachmentThumbnailBuilder = Widget Function(
BuildContext, BuildContext,
@@ -173,9 +183,15 @@ class MessageInput extends StatefulWidget {
this.compressedVideoQuality = VideoQuality.DefaultQuality, this.compressedVideoQuality = VideoQuality.DefaultQuality,
this.compressedVideoFrameRate = 30, this.compressedVideoFrameRate = 30,
this.onError, this.onError,
this.attachmentLimit = 10,
this.onAttachmentLimitExceed,
this.attachmentButtonBuilder, this.attachmentButtonBuilder,
this.commandButtonBuilder, this.commandButtonBuilder,
}) : super(key: key); }) : assert(
initialMessage == null || editMessage == null,
"Can't provide both `initialMessage` and `editMessage`",
),
super(key: key);
/// Message to edit /// Message to edit
final Message? editMessage; final Message? editMessage;
@@ -258,6 +274,14 @@ class MessageInput extends StatefulWidget {
/// A callback for error reporting /// A callback for error reporting
final ErrorListener? onError; final ErrorListener? onError;
/// A limit for the no. of attachments that can be sent with a single message.
final int attachmentLimit;
/// A callback for when the [attachmentLimit] is exceeded.
///
/// This will override the default error alert behaviour.
final AttachmentLimitExceedListener? onAttachmentLimitExceed;
/// Builder for customizing the attachment button. /// Builder for customizing the attachment button.
/// ///
/// The builder contains the default [IconButton] that can be customized by /// The builder contains the default [IconButton] that can be customized by
@@ -293,7 +317,6 @@ class MessageInputState extends State<MessageInput> {
final _imagePicker = ImagePicker(); final _imagePicker = ImagePicker();
late final FocusNode _focusNode; late final FocusNode _focusNode;
bool _inputEnabled = true; bool _inputEnabled = true;
bool _messageIsPresent = false;
bool _commandEnabled = false; bool _commandEnabled = false;
OverlayEntry? _commandsOverlay, _mentionsOverlay, _emojiOverlay; OverlayEntry? _commandsOverlay, _mentionsOverlay, _emojiOverlay;
late Iterable<String> _emojiNames; late Iterable<String> _emojiNames;
@@ -303,9 +326,8 @@ class MessageInputState extends State<MessageInput> {
bool _sendAsDm = false; bool _sendAsDm = false;
bool _openFilePickerSection = false; bool _openFilePickerSection = false;
int _filePickerIndex = 0; int _filePickerIndex = 0;
double _filePickerSize = _kMinMediaPickerSize;
final KeyboardVisibilityController _keyboardVisibilityController = final _keyboardVisibilityController = KeyboardVisibilityController();
KeyboardVisibilityController();
/// The editing controller passed to the input TextField /// The editing controller passed to the input TextField
late final TextEditingController textEditingController; late final TextEditingController textEditingController;
@@ -315,6 +337,7 @@ class MessageInputState extends State<MessageInput> {
bool get _hasQuotedMessage => widget.quotedMessage != null; bool get _hasQuotedMessage => widget.quotedMessage != null;
bool get _messageIsPresent => textEditingController.text.trim().isNotEmpty;
late DateTime? _cooldownStartedAt; late DateTime? _cooldownStartedAt;
int? _timeOut; int? _timeOut;
@@ -602,7 +625,7 @@ class MessageInputState extends State<MessageInput> {
final margin = (widget.sendButtonLocation == SendButtonLocation.inside final margin = (widget.sendButtonLocation == SendButtonLocation.inside
? const EdgeInsets.only(right: 8) ? const EdgeInsets.only(right: 8)
: EdgeInsets.zero) + : EdgeInsets.zero) +
(widget.actionsLocation != ActionsLocation.left (widget.actionsLocation != ActionsLocation.left || _commandEnabled
? const EdgeInsets.only(left: 8) ? const EdgeInsets.only(left: 8)
: EdgeInsets.zero); : EdgeInsets.zero);
return Expanded( return Expanded(
@@ -780,7 +803,6 @@ class MessageInputState extends State<MessageInput> {
.catchError((e) {}); .catchError((e) {});
setState(() { setState(() {
_messageIsPresent = s.trim().isNotEmpty;
_actionsShrunk = s.trim().isNotEmpty && _actionsShrunk = s.trim().isNotEmpty &&
((widget.actions?.length ?? 0) + ((widget.actions?.length ?? 0) +
(widget.showCommandsButton ? 1 : 0) + (widget.showCommandsButton ? 1 : 0) +
@@ -873,7 +895,6 @@ class MessageInputState extends State<MessageInput> {
if (matchedCommandsList.length == 1) { if (matchedCommandsList.length == 1) {
_chosenCommand = matchedCommandsList[0]; _chosenCommand = matchedCommandsList[0];
textEditingController.clear(); textEditingController.clear();
_messageIsPresent = false;
setState(() { setState(() {
_commandEnabled = true; _commandEnabled = true;
}); });
@@ -1020,6 +1041,9 @@ class MessageInputState extends State<MessageInput> {
final _attachmentContainsFile = final _attachmentContainsFile =
_attachments.values.any((it) => it.type == 'file'); _attachments.values.any((it) => it.type == 'file');
final attachmentLimitCrossed =
_attachments.length >= widget.attachmentLimit;
Color _getIconColor(int index) { Color _getIconColor(int index) {
final streamChatThemeData = _streamChatTheme; final streamChatThemeData = _streamChatTheme;
switch (index) { switch (index) {
@@ -1039,15 +1063,21 @@ class MessageInputState extends State<MessageInput> {
: streamChatThemeData.colorTheme.textHighEmphasis : streamChatThemeData.colorTheme.textHighEmphasis
.withOpacity(0.2)); .withOpacity(0.2));
case 2: case 2:
return _attachmentContainsFile && _attachments.isNotEmpty return attachmentLimitCrossed
? streamChatThemeData.colorTheme.textHighEmphasis.withOpacity(0.2) ? streamChatThemeData.colorTheme.textHighEmphasis.withOpacity(0.2)
: streamChatThemeData.colorTheme.textHighEmphasis : _attachmentContainsFile && _attachments.isNotEmpty
.withOpacity(0.5); ? streamChatThemeData.colorTheme.textHighEmphasis
.withOpacity(0.2)
: streamChatThemeData.colorTheme.textHighEmphasis
.withOpacity(0.5);
case 3: case 3:
return _attachmentContainsFile && _attachments.isNotEmpty return attachmentLimitCrossed
? streamChatThemeData.colorTheme.textHighEmphasis.withOpacity(0.2) ? streamChatThemeData.colorTheme.textHighEmphasis.withOpacity(0.2)
: streamChatThemeData.colorTheme.textHighEmphasis : _attachmentContainsFile && _attachments.isNotEmpty
.withOpacity(0.5); ? streamChatThemeData.colorTheme.textHighEmphasis
.withOpacity(0.2)
: streamChatThemeData.colorTheme.textHighEmphasis
.withOpacity(0.5);
default: default:
return Colors.black; return Colors.black;
} }
@@ -1055,7 +1085,7 @@ class MessageInputState extends State<MessageInput> {
return AnimatedContainer( return AnimatedContainer(
duration: const Duration(milliseconds: 300), duration: const Duration(milliseconds: 300),
height: _openFilePickerSection ? _filePickerSize : 0, height: _openFilePickerSection ? _kMinMediaPickerSize : 0,
child: Material( child: Material(
color: _streamChatTheme.colorTheme.inputBg, color: _streamChatTheme.colorTheme.inputBg,
child: Column( child: Column(
@@ -1090,10 +1120,11 @@ class MessageInputState extends State<MessageInput> {
icon: StreamSvgIcon.camera( icon: StreamSvgIcon.camera(
color: _getIconColor(2), color: _getIconColor(2),
), ),
onPressed: _attachmentContainsFile && _attachments.isNotEmpty onPressed: attachmentLimitCrossed ||
(_attachmentContainsFile && _attachments.isNotEmpty)
? null ? null
: () { : () {
pickFile(DefaultAttachmentTypes.image, true); pickFile(DefaultAttachmentTypes.image, camera: true);
}, },
), ),
IconButton( IconButton(
@@ -1101,46 +1132,32 @@ class MessageInputState extends State<MessageInput> {
icon: StreamSvgIcon.record( icon: StreamSvgIcon.record(
color: _getIconColor(3), color: _getIconColor(3),
), ),
onPressed: _attachmentContainsFile && _attachments.isNotEmpty onPressed: attachmentLimitCrossed ||
(_attachmentContainsFile && _attachments.isNotEmpty)
? null ? null
: () { : () {
pickFile(DefaultAttachmentTypes.video, true); pickFile(DefaultAttachmentTypes.video, camera: true);
}, },
), ),
], ],
), ),
GestureDetector( DecoratedBox(
onVerticalDragUpdate: (update) { decoration: BoxDecoration(
setState(() { color: _streamChatTheme.colorTheme.barsBg,
_filePickerSize = (_filePickerSize - update.delta.dy).clamp( borderRadius: const BorderRadius.only(
_kMinMediaPickerSize, topLeft: Radius.circular(16),
MediaQuery.of(context).size.height / 1.7, topRight: Radius.circular(16),
);
});
},
child: DecoratedBox(
decoration: BoxDecoration(
color: _streamChatTheme.colorTheme.barsBg,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
), ),
child: SizedBox( ),
width: double.infinity, child: Center(
child: Center( child: Padding(
child: Padding( padding: const EdgeInsets.all(8),
padding: const EdgeInsets.all(8), child: Container(
child: SizedBox( width: 40,
width: 40, height: 4,
height: 4, decoration: BoxDecoration(
child: DecoratedBox( color: _streamChatTheme.colorTheme.inputBg,
decoration: BoxDecoration( borderRadius: BorderRadius.circular(4),
color: _streamChatTheme.colorTheme.inputBg,
borderRadius: BorderRadius.circular(4),
),
),
),
), ),
), ),
), ),
@@ -1163,7 +1180,7 @@ class MessageInputState extends State<MessageInput> {
if (_attachments.containsKey(media.id)) { if (_attachments.containsKey(media.id)) {
setState(() => _attachments.remove(media.id)); setState(() => _attachments.remove(media.id));
} else { } else {
_addAttachment(media); _addAssetAttachment(media);
} }
}, },
), ),
@@ -1175,15 +1192,13 @@ class MessageInputState extends State<MessageInput> {
); );
} }
void _addAttachment(AssetEntity medium) async { void _addAssetAttachment(AssetEntity medium) async {
final mediaFile = await medium.originFile.timeout( final mediaFile = await medium.originFile.timeout(
const Duration(seconds: 5), const Duration(seconds: 5),
onTimeout: () => medium.originFile, onTimeout: () => medium.originFile,
); );
if (mediaFile == null) { if (mediaFile == null) return;
return;
}
var file = AttachmentFile( var file = AttachmentFile(
path: mediaFile.path, path: mediaFile.path,
@@ -1222,11 +1237,12 @@ class MessageInputState extends State<MessageInput> {
} }
setState(() { setState(() {
_attachments[medium.id] = Attachment( final attachment = Attachment(
id: medium.id, id: medium.id,
file: file, file: file,
type: medium.type == AssetType.image ? 'image' : 'video', type: medium.type == AssetType.image ? 'image' : 'video',
); );
_addAttachments([attachment]);
}); });
} }
@@ -1547,7 +1563,6 @@ class MessageInputState extends State<MessageInput> {
setState(() { setState(() {
_chosenCommand = c; _chosenCommand = c;
_commandEnabled = true; _commandEnabled = true;
_messageIsPresent = false;
}); });
_commandsOverlay?.remove(); _commandsOverlay?.remove();
_commandsOverlay = null; _commandsOverlay = null;
@@ -1755,10 +1770,7 @@ class MessageInputState extends State<MessageInput> {
splashRadius: 24, splashRadius: 24,
onPressed: () async { onPressed: () async {
if (_openFilePickerSection) { if (_openFilePickerSection) {
setState(() { setState(() => _openFilePickerSection = false);
_openFilePickerSection = false;
_filePickerSize = _kMinMediaPickerSize;
});
await Future.delayed(const Duration(milliseconds: 300)); await Future.delayed(const Duration(milliseconds: 300));
} }
@@ -1804,10 +1816,7 @@ class MessageInputState extends State<MessageInput> {
_mentionsOverlay = null; _mentionsOverlay = null;
if (_openFilePickerSection) { if (_openFilePickerSection) {
setState(() { setState(() => _openFilePickerSection = false);
_openFilePickerSection = false;
_filePickerSize = _kMinMediaPickerSize;
});
} else { } else {
showAttachmentModal(); showAttachmentModal();
} }
@@ -1831,87 +1840,91 @@ class MessageInputState extends State<MessageInput> {
}); });
} else { } else {
showModalBottomSheet( showModalBottomSheet(
clipBehavior: Clip.hardEdge, clipBehavior: Clip.hardEdge,
shape: const RoundedRectangleBorder( shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only( borderRadius: BorderRadius.only(
topLeft: Radius.circular(32), topLeft: Radius.circular(32),
topRight: Radius.circular(32), topRight: Radius.circular(32),
),
), ),
context: context, ),
isScrollControlled: true, context: context,
builder: (_) => Column( isScrollControlled: true,
mainAxisSize: MainAxisSize.min, builder: (_) => Column(
children: <Widget>[ mainAxisSize: MainAxisSize.min,
ListTile( children: <Widget>[
title: Text( ListTile(
context.translations.addAFileLabel, title: Text(
style: const TextStyle( context.translations.addAFileLabel,
fontWeight: FontWeight.bold, style: const TextStyle(
), fontWeight: FontWeight.bold,
), ),
), ),
ListTile( ),
leading: const Icon(Icons.image), ListTile(
title: Text(context.translations.uploadAPhotoLabel), leading: const Icon(Icons.image),
onTap: () { title: Text(context.translations.uploadAPhotoLabel),
pickFile(DefaultAttachmentTypes.image); onTap: () {
Navigator.pop(context); pickFile(DefaultAttachmentTypes.image);
}, Navigator.pop(context);
), },
ListTile( ),
leading: const Icon(Icons.video_library), ListTile(
title: Text(context.translations.uploadAVideoLabel), leading: const Icon(Icons.video_library),
onTap: () { title: Text(context.translations.uploadAVideoLabel),
pickFile(DefaultAttachmentTypes.video); onTap: () {
Navigator.pop(context); pickFile(DefaultAttachmentTypes.video);
}, Navigator.pop(context);
), },
if (!kIsWeb) ),
ListTile( ListTile(
leading: const Icon(Icons.camera_alt), leading: const Icon(Icons.insert_drive_file),
title: Text(context.translations.photoFromCameraLabel), title: Text(context.translations.uploadAFileLabel),
onTap: () { onTap: () {
pickFile(DefaultAttachmentTypes.image, true); pickFile(DefaultAttachmentTypes.file);
Navigator.pop(context); Navigator.pop(context);
}, },
), ),
if (!kIsWeb) ],
ListTile( ),
leading: const Icon(Icons.videocam), );
title: Text(context.translations.videoFromCameraLabel),
onTap: () {
pickFile(DefaultAttachmentTypes.video, true);
Navigator.pop(context);
},
),
ListTile(
leading: const Icon(Icons.insert_drive_file),
title: Text(context.translations.uploadAFileLabel),
onTap: () {
pickFile(DefaultAttachmentTypes.file);
Navigator.pop(context);
},
),
],
));
} }
} }
/// Add an attachment to the sending message /// Add an attachment to the sending message
/// Use this to add custom type attachments /// Use this to add custom type attachments
///
/// Note: Only meant to be used from outside the state.
void addAttachment(Attachment attachment) { void addAttachment(Attachment attachment) {
setState(() { setState(() => _addAttachments([attachment]));
_attachments[attachment.id] = attachment.copyWith( }
uploadState: attachment.uploadState,
/// Adds an attachment to the [_attachments] map
void _addAttachments(Iterable<Attachment> attachments) {
final limit = widget.attachmentLimit;
final length = _attachments.length + attachments.length;
if (length > limit) {
final onAttachmentLimitExceed = widget.onAttachmentLimitExceed;
if (onAttachmentLimitExceed != null) {
return onAttachmentLimitExceed(
widget.attachmentLimit,
context.translations.attachmentLimitExceedError(limit),
);
}
return _showErrorAlert(
context.translations.attachmentLimitExceedError(limit),
); );
}); }
for (final attachment in attachments) {
_attachments[attachment.id] = attachment;
}
} }
/// Pick a file from the device /// Pick a file from the device
/// If [camera] is true then the camera will open /// If [camera] is true then the camera will open
// ignore: avoid_positional_boolean_parameters void pickFile(
void pickFile(DefaultAttachmentTypes fileType, [bool camera = false]) async { DefaultAttachmentTypes fileType, {
bool camera = false,
}) async {
setState(() => _inputEnabled = false); setState(() => _inputEnabled = false);
AttachmentFile? file; AttachmentFile? file;
@@ -2009,16 +2022,14 @@ class MessageInputState extends State<MessageInput> {
} }
} }
_attachments[attachment.id] = attachment;
setState(() { setState(() {
_attachments.update( _addAttachments([
attachment.id, attachment.copyWith(
(it) => it.copyWith( file: file,
file: file, extraData: {...attachment.extraData}
extraData: {...it.extraData} ..update('file_size', ((_) => file!.size!)),
..update('file_size', ((_) => file!.size!)), ),
)); ]);
}); });
} }
@@ -2085,7 +2096,6 @@ class MessageInputState extends State<MessageInput> {
widget.onQuotedMessageCleared?.call(); widget.onQuotedMessageCleared?.call();
setState(() { setState(() {
_messageIsPresent = false;
_commandEnabled = false; _commandEnabled = false;
}); });
@@ -2216,7 +2226,8 @@ class MessageInputState extends State<MessageInput> {
child: Text( child: Text(
context.translations.okLabel, context.translations.okLabel,
style: _streamChatTheme.textTheme.bodyBold.copyWith( style: _streamChatTheme.textTheme.bodyBold.copyWith(
color: _streamChatTheme.colorTheme.accentPrimary), color: _streamChatTheme.colorTheme.accentPrimary,
),
), ),
), ),
], ],
@@ -2227,13 +2238,9 @@ class MessageInputState extends State<MessageInput> {
} }
void _parseExistingMessage(Message message) { void _parseExistingMessage(Message message) {
textEditingController.text = message.text!; final messageText = message.text;
_messageIsPresent = true; if (messageText != null) textEditingController.text = messageText;
for (final attachment in message.attachments) { _addAttachments(message.attachments);
_attachments[attachment.id] = attachment.copyWith(
uploadState: attachment.uploadState,
);
}
} }
@override @override
@@ -2252,7 +2259,8 @@ class MessageInputState extends State<MessageInput> {
void didChangeDependencies() { void didChangeDependencies() {
_streamChatTheme = StreamChatTheme.of(context); _streamChatTheme = StreamChatTheme.of(context);
_messageInputTheme = MessageInputTheme.of(context); _messageInputTheme = MessageInputTheme.of(context);
if (widget.editMessage != null && !_initialized) { if ((widget.editMessage != null || widget.initialMessage != null) &&
!_initialized) {
FocusScope.of(context).requestFocus(_focusNode); FocusScope.of(context).requestFocus(_focusNode);
_initialized = true; _initialized = true;
} }
@@ -2260,54 +2268,6 @@ class MessageInputState extends State<MessageInput> {
} }
} }
/// Represents a 2-tuple, or pair.
class Tuple2<T1, T2> {
/// Creates a new tuple value with the specified items.
const Tuple2(this.item1, this.item2);
/// Create a new tuple value with the specified list [items].
factory Tuple2.fromList(List items) {
if (items.length != 2) {
throw ArgumentError('items must have length 2');
}
return Tuple2<T1, T2>(items[0] as T1, items[1] as T2);
}
/// Returns the first item of the tuple
final T1 item1;
/// Returns the second item of the tuple
final T2 item2;
/// Returns a tuple with the first item set to the specified value.
Tuple2<T1, T2> withItem1(T1 v) => Tuple2<T1, T2>(v, item2);
/// Returns a tuple with the second item set to the specified value.
Tuple2<T1, T2> withItem2(T2 v) => Tuple2<T1, T2>(item1, v);
/// Creates a [List] containing the items of this [Tuple2].
///
/// The elements are in item order. The list is variable-length
/// if [growable] is true.
List toList({bool growable = false}) =>
List.from([item1, item2], growable: growable);
@override
String toString() => '[$item1, $item2]';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Tuple2 &&
runtimeType == other.runtimeType &&
item1 == other.item1 &&
item2 == other.item2;
@override
int get hashCode => item1.hashCode ^ item2.hashCode;
}
class _PickerWidget extends StatefulWidget { class _PickerWidget extends StatefulWidget {
const _PickerWidget({ const _PickerWidget({
Key? key, Key? key,
@@ -2345,75 +2305,75 @@ class _PickerWidgetState extends State<_PickerWidget> {
return const Offstage(); return const Offstage();
} }
return FutureBuilder<bool>( return FutureBuilder<bool>(
future: requestPermission, future: requestPermission,
builder: (context, snapshot) { builder: (context, snapshot) {
if (!snapshot.hasData) { if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
} }
if (snapshot.data!) { if (snapshot.data!) {
if (widget.containsFile) { if (widget.containsFile) {
return GestureDetector( return GestureDetector(
onTap: () { onTap: () {
widget.onAddMoreFilesClick(DefaultAttachmentTypes.file); widget.onAddMoreFilesClick(DefaultAttachmentTypes.file);
}, },
child: Container( child: Container(
constraints: const BoxConstraints.expand(), constraints: const BoxConstraints.expand(),
color: widget.streamChatTheme.colorTheme.inputBg, color: widget.streamChatTheme.colorTheme.inputBg,
alignment: Alignment.center, alignment: Alignment.center,
child: Text(
context.translations.addMoreFilesLabel,
style: TextStyle(
color: widget.streamChatTheme.colorTheme.accentPrimary,
fontWeight: FontWeight.bold,
),
),
),
);
}
return MediaListView(
selectedIds: widget.selectedMedias,
onSelect: widget.onMediaSelected,
);
}
return InkWell(
onTap: () async {
PhotoManager.openSetting();
},
child: Container(
color: widget.streamChatTheme.colorTheme.inputBg,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SvgPicture.asset(
'svgs/icon_picture_empty_state.svg',
package: 'stream_chat_flutter',
height: 140,
color: widget.streamChatTheme.colorTheme.disabled,
),
Text(
context.translations.enablePhotoAndVideoAccessMessage,
style: widget.streamChatTheme.textTheme.body.copyWith(
color: widget.streamChatTheme.colorTheme.textLowEmphasis),
textAlign: TextAlign.center,
),
const SizedBox(height: 6),
Center(
child: Text( child: Text(
context.translations.addMoreFilesLabel, context.translations.allowGalleryAccessMessage,
style: TextStyle( style: widget.streamChatTheme.textTheme.bodyBold.copyWith(
color: widget.streamChatTheme.colorTheme.accentPrimary, color: widget.streamChatTheme.colorTheme.accentPrimary,
fontWeight: FontWeight.bold,
), ),
), ),
), ),
); ],
}
return MediaListView(
selectedIds: widget.selectedMedias,
onSelect: widget.onMediaSelected,
);
}
return InkWell(
onTap: () async {
PhotoManager.openSetting();
},
child: Container(
color: widget.streamChatTheme.colorTheme.inputBg,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SvgPicture.asset(
'svgs/icon_picture_empty_state.svg',
package: 'stream_chat_flutter',
height: 140,
color: widget.streamChatTheme.colorTheme.disabled,
),
Text(
context.translations.enablePhotoAndVideoAccessMessage,
style: widget.streamChatTheme.textTheme.body.copyWith(
color:
widget.streamChatTheme.colorTheme.textLowEmphasis),
textAlign: TextAlign.center,
),
const SizedBox(height: 6),
Center(
child: Text(
context.translations.allowGalleryAccessMessage,
style: widget.streamChatTheme.textTheme.bodyBold.copyWith(
color: widget.streamChatTheme.colorTheme.accentPrimary,
),
),
),
],
),
), ),
); ),
}); );
},
);
} }
} }
@@ -340,3 +340,51 @@ Widget wrapAttachmentWidget(
type: MaterialType.transparency, type: MaterialType.transparency,
child: attachmentWidget, child: attachmentWidget,
); );
/// Represents a 2-tuple, or pair.
class Tuple2<T1, T2> {
/// Creates a new tuple value with the specified items.
const Tuple2(this.item1, this.item2);
/// Create a new tuple value with the specified list [items].
factory Tuple2.fromList(List items) {
if (items.length != 2) {
throw ArgumentError('items must have length 2');
}
return Tuple2<T1, T2>(items[0] as T1, items[1] as T2);
}
/// Returns the first item of the tuple
final T1 item1;
/// Returns the second item of the tuple
final T2 item2;
/// Returns a tuple with the first item set to the specified value.
Tuple2<T1, T2> withItem1(T1 v) => Tuple2<T1, T2>(v, item2);
/// Returns a tuple with the second item set to the specified value.
Tuple2<T1, T2> withItem2(T2 v) => Tuple2<T1, T2>(item1, v);
/// Creates a [List] containing the items of this [Tuple2].
///
/// The elements are in item order. The list is variable-length
/// if [growable] is true.
List toList({bool growable = false}) =>
List.from([item1, item2], growable: growable);
@override
String toString() => '[$item1, $item2]';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Tuple2 &&
runtimeType == other.runtimeType &&
item1 == other.item1 &&
item2 == other.item2;
@override
int get hashCode => item1.hashCode ^ item2.hashCode;
}
@@ -384,6 +384,10 @@ class NnStreamChatLocalizations extends GlobalStreamChatLocalizations {
@override @override
String get replyToMessageLabel => 'Reply to Message'; String get replyToMessageLabel => 'Reply to Message';
@override
String attachmentLimitExceedError(int limit) =>
'Attachment limit exceeded, limit: $limit';
@override @override
String get slowModeOnLabel => 'Slow mode ON'; String get slowModeOnLabel => 'Slow mode ON';
} }
@@ -360,6 +360,10 @@ class StreamChatLocalizationsEn extends GlobalStreamChatLocalizations {
@override @override
String get replyToMessageLabel => 'Reply to Message'; String get replyToMessageLabel => 'Reply to Message';
@override
String attachmentLimitExceedError(int limit) =>
'Attachment limit exceeded, limit: $limit';
@override @override
String get slowModeOnLabel => 'Slow mode ON'; String get slowModeOnLabel => 'Slow mode ON';
} }
@@ -365,6 +365,11 @@ class StreamChatLocalizationsEs extends GlobalStreamChatLocalizations {
@override @override
String get replyToMessageLabel => 'Responder al Mensaje'; String get replyToMessageLabel => 'Responder al Mensaje';
@override
String attachmentLimitExceedError(int limit) => '''
No es posible añadir más de $limit archivos adjuntos
''';
@override @override
String get slowModeOnLabel => 'Modo lento activado'; String get slowModeOnLabel => 'Modo lento activado';
} }
@@ -364,6 +364,11 @@ class StreamChatLocalizationsFr extends GlobalStreamChatLocalizations {
@override @override
String get replyToMessageLabel => 'Répondre au Message'; String get replyToMessageLabel => 'Répondre au Message';
@override
String attachmentLimitExceedError(int limit) => '''
Limite de pièces jointes dépassée : il n'est pas possible d'ajouter plus de $limit pièces jointes
''';
@override @override
String get slowModeOnLabel => 'Mode lent activé'; String get slowModeOnLabel => 'Mode lent activé';
} }
@@ -359,6 +359,11 @@ class StreamChatLocalizationsHi extends GlobalStreamChatLocalizations {
@override @override
String get replyToMessageLabel => 'संदेश का जवाब'; String get replyToMessageLabel => 'संदेश का जवाब';
@override
String attachmentLimitExceedError(int limit) => '''
अटैचमेंट लिमिट: $limit अटैचमेंट से अधिक जोड़ना संभव नहीं है
''';
@override @override
String get slowModeOnLabel => 'स्लो मोड चालू'; String get slowModeOnLabel => 'स्लो मोड चालू';
} }
@@ -361,6 +361,11 @@ Il file è troppo grande per essere caricato. Il limite è di $limitInMB MB.''';
@override @override
String get replyToMessageLabel => 'Rispondi al messaggio'; String get replyToMessageLabel => 'Rispondi al messaggio';
@override
String attachmentLimitExceedError(int limit) => '''
Attenzione: il limite massimo di $limit file è stato superato.
''';
@override @override
String get slowModeOnLabel => 'Slowmode attiva'; String get slowModeOnLabel => 'Slowmode attiva';
} }
@@ -349,4 +349,9 @@ class StreamChatLocalizationsJa extends GlobalStreamChatLocalizations {
@override @override
String get slowModeOnLabel => 'スローモードオン'; String get slowModeOnLabel => 'スローモードオン';
@override
String attachmentLimitExceedError(int limit) => '''
添付ファイルの制限を超えました:$limit個のファイル以上を添付することはできません
''';
} }
@@ -347,4 +347,8 @@ class StreamChatLocalizationsKo extends GlobalStreamChatLocalizations {
@override @override
String get slowModeOnLabel => '슬로모드 켜짐'; String get slowModeOnLabel => '슬로모드 켜짐';
@override
String attachmentLimitExceedError(int limit) =>
'첨부 파일 제한 초과: $limit 이상의 첨부 파일을 추가할 수 없습니다';
} }
@@ -177,6 +177,7 @@ void main() {
expect(localizations.galleryPaginationText, isNotNull); expect(localizations.galleryPaginationText, isNotNull);
expect(localizations.fileText, isNotNull); expect(localizations.fileText, isNotNull);
expect(localizations.replyToMessageLabel, isNotNull); expect(localizations.replyToMessageLabel, isNotNull);
expect(localizations.attachmentLimitExceedError(3), isNotNull);
}); });
} }